Iterator Over K-Letter Combinations in Lexicographic Order
Last updated: November 29, 2026
Quick Overview
Design an iterator over all length-k combinations of the characters of a sorted string of distinct letters, returned in lexicographic order, with next() and has_next() methods.
0
0
0 solved
Design an iterator over all length-k combinations of the characters of a sorted string of distinct letters, returned in lexicographic order, with next() and has_next() methods.
A Google technical screen that turns backtracking into an on-demand iterator. The interviewer checks whether you can produce the next combination in place without precomputing all C(n, k) results, which matters when callers stop early.
What the Interviewer Expects
- Stores only the current index tuple, not the full list
- Advances by finding the rightmost index that can be incremented and resetting the tail
- Implements has_next correctly at the last combination
- States O(k) per next and O(k) memory
- Contrasts with a precomputed list or a Python generator
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
- How would you support a reset() method?
- How would you skip directly to the m-th combination?
- What changes if the input has repeated letters and you want distinct combinations?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Constructor:
CombinationIterator(chars, k), chars sorted and distinct, 1 <= k <= len(chars) <= 15. next()returns the next combination as a string;has_next()returns whether one remains.- ...
High-Level Design
Represent the current combination by indices idx[0] < idx[1] < ... < idx[k-1], starting at [0, 1, ..., k-1]. This is exactly the state a backtracking DFS would hold on its stack, made explicit.
T...