Beam Search and Nucleus Decoding
Updated
Problem statement
Implement two next-token decoding strategies for one finite language-model simulation: beam search and nucleus (top-p) sampling. Return the best beam sentence and one nucleus-sampled sentence.
Follow the rules below exactly, so every run gives the same answer.
Model and stopping
tokensis a distinct vocabulary. Its final entry is<eos>;startTokenis the initial context and is not emitted.percentages[i][j]gives the integer percentage for tokenjafter tokeni. Every row sums to100.- Generate at most
maxTokenstransitions. Generating<eos>ends a path and contributes its probability, but does not appear in the sentence. An unfinished path at the cutoff is valid. Join emitted tokens with one space; an immediate<eos>produces the empty string.
Beam search
- Start with one empty path of probability
1. On each transition expand every unfinished path through every positive-probability token; carry finished paths unchanged. The path score is the raw product of its transition probabilities. - From the combined pool retain at most
beamWidthpaths by descending exact probability, then ascending sentence text. If both still tie, finished precedes unfinished, then compare the last token text. Finished paths occupy beam slots. - Stop when all retained paths are finished or
maxTokenstransitions have occurred. The first retained path is the beam result. Do not renormalize over the beam or add a length penalty.
Nucleus sampling
- At each transition sort positive-probability next tokens by descending percentage, then ascending token text; treat
<eos>as the empty text for tie-breaking. Keep the shortest prefix whose total percentage is at leasttopP. - Renormalize within that prefix.
draws[step]stands in for a random draw. Use the valuedraws[step] / 10000. Walk the kept tokens in the same order and choose the first whose cumulative renormalized probability is strictly greater than the draw. Continue from the selected token unless it is<eos>.
Return a two-element string array: [bestBeamSentence, nucleusSentence]. Compare the percentages and draws as whole numbers, so there is no rounding. Do not return a greedy result or any probability.
Function
decodeBeamAndNucleus(tokens: String[], percentages: int[][], startToken: int, maxTokens: int, beamWidth: int, topP: int, draws: int[]) → String[]Examples
Example 1
tokens = ["start","a","b","<eos>"]percentages = [[0,60,40,0],[0,0,50,50],[0,0,0,100],[0,0,0,100]]startToken = 0maxTokens = 3beamWidth = 2topP = 60draws = [0,0,0]return = ["b","a"]Beam search retains the finished b path at probability 0.4 ahead of either a path at 0.3. The nucleus first contains only a; on its second step the zero draw selects the tied <eos>.
Example 2
tokens = ["seed","apple","berry","<eos>"]percentages = [[0,40,35,25],[0,0,0,100],[0,0,0,100],[0,0,0,100]]startToken = 0maxTokens = 2beamWidth = 2topP = 75draws = [9999,0]return = ["apple","berry"]Beam search returns apple with probability 0.4. The first nucleus retains apple and berry to reach 75%; the first draw chooses berry.
Example 3
tokens = ["seed","go","<eos>"]percentages = [[0,20,80],[0,0,100],[0,0,100]]startToken = 0maxTokens = 2beamWidth = 2topP = 50draws = [0,0]return = ["",""]Both strategies can select <eos> immediately. The generated sentence is then empty, so the returned strings are empty.
Constraints
2 <= tokens.length <= 8. Ordinary tokens are distinct lowercase words of length1..8; the final token is exactly<eos>.percentagesis square with one row per token; entries are integers from0to100, and every row sums to100.0 <= startToken < tokens.length - 1;1 <= maxTokens <= 6;1 <= beamWidth <= 12;1 <= topP <= 100.draws.length == maxTokensand each draw is an integer in0..9999.- The
<eos>row is never queried after termination. Scores can be compared exactly with a common fixed denominator of100^maxTokens, which fits signed64-bit arithmetic under these bounds.
More Microsoft Onsite Interview questions
- Bad Request AlertsONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Capping Portfolio WeightsCapstone Investment Advisors · OA
- Macaron Order PriceOpenAI · OAOpenAI interview questions
- Meeting Rooms III: Most Booked RoomGoogle · ONSITE INTERVIEWGoogle interview questions
- Deterministic K-Means AssignmentsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Vectorized K-Means AssignmentsSambaNova Systems · ONSITE INTERVIEWSambaNova Systems interview questions
- Fixed-Round K-Means AssignmentsNVIDIA · ONSITE INTERVIEWNVIDIA interview questions
- Retrieve Vectors by Cosine SimilarityHarvey · ONSITE INTERVIEWHarvey interview questions
- Expected Value of Modified DiceJane Street · ONSITE INTERVIEWJane Street interview questions
- Merge Sort Report with a Noisy ComparatorMercor · ONSITE INTERVIEWMercor interview questions
- Group-Relative Policy AdvantagesAmazon · ONSITE INTERVIEW
Microsoft interview experiences
- Microsoft OA Questions, October 2026: 4 Experiences
- Microsoft Experienced SWE Phone Screen: 1 Experience
- Microsoft Explore and Student SWE: 12 Experiences (Part 6 of 6)
- Microsoft SWE Intern, Early 2025: 41 Experiences (Part 5 of 6)
- Microsoft SWE Intern, Mid 2025: 42 Experiences (Part 4 of 6)
- Microsoft SWE Intern, Late 2025: 47 Experiences (Part 3 of 6)