Shortest Document Snippet Containing Every Query Term
Last updated: November 29, 2026
Quick Overview
Given a document as a list of word tokens and a search query as a list of terms (possibly repeated), return the start and end indices of the shortest contiguous span of tokens that contains every query term at least as many times as it appears in the query.
Microsoft
November 29, 20260
0
0 solved
Given a document as a list of word tokens and a search query as a list of terms (possibly repeated), return the start and end indices of the shortest contiguous span of tokens that contains every query term at least as many times as it appears in the query.
Bing's result captions highlight a compact snippet where the query terms appear close together, and this question models that step. Microsoft interviewers use it to test the minimum window technique: expanding until valid, shrinking while valid, and tracking multiplicity without rescanning counts.
What the Interviewer Expects
- Explains expand-then-shrink two pointers and why it finds the optimum
- Tracks a single missing counter instead of comparing whole count maps
- Handles repeated query terms and case normalization
- Returns None when no snippet exists
- Runs in O(n + m) time
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Snippets should prefer spans that start at sentence boundaries: how would you score them?
- The document is indexed with positional postings lists per term: how would you solve it without scanning every token?
- Allow stemming so 'scaling' matches 'scale'.
- Return the top 3 non-overlapping snippets.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Tokens and query terms are compared case-insensitively. If a term appears twice in the query, the snippet must contain it twice. Return (lo, hi) inclusive indices of the shortest valid span, earlies...
High-Level Design
Classic minimum window: move hi right adding tokens until the window covers the query, then move lo right as long as it still covers, recording the best window each time. Every optimal window is f...