InterviewLegend

Parsing & Sliding Windows

Alex Chen12 min readGuide updated 276 real interview reports
In this lesson
  • Pack words to an exact line width, with the one-word line and the left-justified last line handled
  • Parse JSON by recursive descent and name each leaf by its dotted path
  • Keep a running window maximum in one linear pass with a deque of indices
  • Rework each solution for the follow-up where the input arrives as a stream, one piece at a time

These are the Hard problems from MongoDB's array and string questions. Text Justification packs words greedily, and all of its difficulty is in the space arithmetic. Parse JSON reads the text that a shell command or a mongoimport run starts from, before anything becomes BSON. Sliding Window Maximum computes the rolling $max that a $setWindowFields stage returns. Each one is scored the way MongoDB scores everything else, on code that runs and handles its edge cases, and you'll often be asked to explain your reasoning as you write. In every follow-up the input arrives as a stream, one piece at a time, so be ready to rework your solution to hold only what it needs.

For what MongoDB scores and the three shapes behind the Medium problems in this group, see Arrays, Strings & Hashing.

Asked at MongoDB

1

Text Justification: Greedy Lines, Then Pad

HardFrequently asked
Problem
Given an array of words words and a width maxWidth, lay the words out so that every line is exactly maxWidth characters long. Pack greedily. Each line takes as many words as fit with at least one space between them. Then spread the leftover spaces across the gaps as evenly as possible, and when they do not divide evenly, the gaps on the left receive one more than the gaps on the right.

The last line is left-justified, with a single space between its words and spaces appended to reach maxWidth. A line holding only one word gets the same treatment, since it has no gap to widen. Every word is at most maxWidth characters long and words holds at least one word.

Input encoding. Each test case is a JSON array [words, maxWidth]. The function returns the list of lines in order, each exactly maxWidth characters long.
Inputwords = ["This","is","an","example","of","text","justification."]maxWidth = 16Output["This is an","example of text","justification. "]

The first line has 8 letters, so 8 spaces over two gaps, four each. The last line is left-justified and padded.

How this uses the pattern

Two phases per line. First, greedily extend the line while the next word still fits, counting one space per gap. Then compute the spare space and divide it across the gaps, handing the remainder to the leftmost ones.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Text Justification: Greedy Lines, Then Pad

Loading...
Click "Run" to execute your code
The MongoDB angle
Tied with a Premium question as the most-reported Hard in MongoDB interviews, and the one with no algorithm in it. It's scored on what MongoDB's prep page lists, code that works on the edge cases, which is why a problem with an obvious greedy keeps getting asked. Three edge cases make it hard. A line holding one word has no gap, so its spare space goes to the right. A line that fits exactly has nothing to distribute, and the last line stays left-justified however many words it holds. Karat screens focus on array and string manipulation and add spoken questions on top, so expect to explain the space arithmetic as you write.
Take it further
The usual follow-up is memory. Words arrive as a stream, say from a file too large to load, and the caller wants each line as soon as it's complete. The greedy pack only needs the words of the current line, so a generator holds those and nothing else. You can't tell that a line is the last one until the stream runs out, so the final flush is the one that left-justifies. A lighter variant asks only for the number of lines, which drops the padding and keeps the counter.
2

Parse JSON: A Recursive-Descent Reader

HardSignature problem
Problem
A document arrives as text long before it is a document. Given text, one JSON document as a string, read it and return a flattened view of every leaf inside it, in the order the fields appear in the source.

Each leaf becomes one entry of the form path:kind=value, with no spaces anywhere in it. A path is the chain of field names from the root joined with .. An array element contributes its position as a segment, so items.1.sku names the sku field of the second element of items.

The kind is one of str, num, bool, null, obj, or arr. A string renders as its decoded characters, and a number as its text copied verbatim out of the source. The three literals render as the word true, false, or null. An empty subdocument renders as {}, and an empty array as [].

An empty subdocument and an empty array count as leaves themselves, because nothing underneath them exists to report. The document {} therefore has no leaves at all and returns an empty list.

When text is not one well-formed JSON object, return the single-element list ["ERROR"].

The grammar, enforced strictly. The root is an object. A number is an optional minus sign, then 0 alone or a digit run that does not start with 0, then an optional . with at least one digit after it. Then comes an optional e or E with an optional sign and at least one digit. That makes 01, 1., +1, and 1e all malformed. Space, tab, carriage return, and newline may sit between tokens, and anything but whitespace after the closing brace is malformed.

Escapes are scoped to \", \\, \/, \n, \r, and \t. The rarer ones JSON allows, \b and \f and the \uXXXX form, stay out of the input here, so treat any escape outside that list as malformed. A raw character below code point 32 sitting inside a string is malformed too.

Field names hold only letters, digits, and underscores, and no object repeats a field name.

Input encoding. Each test case is a JSON array [text], a single string holding the whole document. The function returns a list of strings.
Inputtext = '{"_id":1,"tags":["a","b"]}'Output["_id:num=1","tags.0:str=a","tags.1:str=b"]

The _id field is a number at the root. Each tag is a string whose path carries its position in the array.

How this uses the pattern

One function per grammar rule, each taking the text and a position and handing back the position just past what it consumed. The value reader dispatches on a single character into the object, array, string, number, or literal reader, and the object and array readers call back into it. Thread the dotted path down as an argument and append finished leaves to a shared list, so the walk and the formatting happen in one pass.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Parse JSON: A Recursive-Descent Reader

Loading...
Click "Run" to execute your code
The MongoDB angle
MongoDB stores BSON, which is typed, ordered and length-prefixed, and almost nothing writes BSON by hand. A shell command, a mongoimport run or a driver call starts from JSON text, and a convert-a-JSON-string-to-an-object problem is among the Hard problems tagged to this company. The output shape asked for here is MongoDB's own naming, since items.1.sku is how a query or an index key reaches a field inside an array.

Types matter for the same reason they do in BSON, where the number 3 and the string "3" are different values. Rejecting bad input matters more. A reader that accepts {"a":01} or a trailing comma would let corrupt data into a collection.
Take it further
The usual follow-up is size. A single document can reach MongoDB's sixteen-megabyte limit, and a bulk import reads a file far larger. So you may be asked what changes when the text arrives as a stream you can't index backward into. Every grammar function stays the same, and you swap the position argument for a reader that peeks one character ahead and consumes it, which is all recursive descent needs from its input. The second follow-up is depth, since a deeply nested document can exhaust the call stack. The production answer is an explicit stack of parser states plus a hard depth limit instead of recursion.
3

Sliding Window Maximum: Monotonic Deque

HardCommonly asked
Problem
Given an integer array nums and a window size k, return the largest value inside each contiguous window of length k. The window slides one position at a time from the left end of the array to the right. An array of length n produces n - k + 1 windows, and the answer lists their maxima in window order.

Rescanning each window costs O(n * k). Aim for O(n) total time with extra space proportional to k. Assume 1 <= k <= len(nums) and that values can be negative.

Input encoding. Each test case is a JSON array [nums, k]. The function returns the list of window maxima.
Inputnums = [1,3,-1,-3,5,3,6,7]k = 3Output[3,3,5,5,6,7]

The windows are [1,3,-1], [3,-1,-3], [-1,-3,5], [-3,5,3], [5,3,6], [3,6,7].

How this uses the pattern

Hold a deque of candidate indices whose values decrease from front to back. Before pushing a new index, drop every index at the back whose value it beats, and drop the front once it falls outside the window.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Sliding Window Maximum: Monotonic Deque

Loading...
Click "Run" to execute your code
The MongoDB angle
Reported less often than the top problems on MongoDB's tag list, but it belongs to the array and hashing family that comes up most. Rolling maxima are built into the product. A $setWindowFields stage computes $max over a span of documents relative to the current one, and a time-series collection answers peak-per-interval queries from ordered data in one pass. The server avoids the naive version for the same reason the deque exists: re-reading k documents at every position turns a linear pass into quadratic work. Two edge cases break implementations here. Storing values instead of indices leaves no way to tell that the current maximum has left the window, and recording a maximum before the first full window shifts the whole answer by one position.
Take it further
The usual follow-up is the stream. Values arrive one at a time with no known end, and the caller wants the current window maximum after each one. The deque already holds what that needs, since it only stores indices that could still win a future window. The change is to emit after each push instead of collecting into a list. A harder variant asks for the maximum over the last T milliseconds instead of the last k values. That swaps the index comparison for a timestamp comparison and lets the window hold any number of entries.

Key Takeaways

  • ✓Text Justification is a greedy pack plus exact space math. Test one-word lines, exact fits and the last line, which stays left-justified.
  • ✓Parse JSON with one function per grammar rule, each returning the position after what it read. Pass the dotted path down as an argument.
  • ✓Sliding Window Maximum keeps a deque of indices with falling values. Record the first maximum only once k values are in.
  • ✓All three follow-ups turn the input into a stream: emit lines as they finish, peek one character ahead, report each window maximum.
MongoDB interview guide

Know what MongoDB asks before you walk in.

31 coding · 5 system design · 17 behavioral questions

Get Premium$49 a year · Instant access
Or start freeNo card.

Get their questions first.

Arrays, Strings & HashingHad your MongoDB interview?How we research

InterviewLegend is independent and not affiliated with or endorsed by any company it covers.