Two Pointers & Sliding Window Interview Questions
Two-pointer and sliding-window questions turn quadratic scans into single linear passes, and are the standard follow-up to a hash-map solution.
The two-pointer family covers any technique where indices move through a sequence in a coordinated way. Two pointers converging from the ends solve sorted-array problems in linear time with no extra memory; a sliding window maintains a contiguous range with a running aggregate, expanding and contracting to satisfy a constraint. Both replace a nested loop with a single pass.
What interviewers probe
Interviewers use these as the constant-space follow-up after a hash-map answer, so recognising when the input is sorted — or can be sorted cheaply — is the trigger to watch for. For sliding windows, the part that separates a fluent answer is stating the invariant the window maintains, and being explicit about when the window shrinks rather than discovering it through trial and error at the whiteboard.
Practice two pointers & sliding window
9 coding · 4/3/2 easy/medium/hard
Two Pointers & Sliding Window interview questions — FAQ
When can I use two pointers instead of a hash map?
When the input is sorted, or when sorting it does not break the problem. Two pointers then achieve the same linear scan in constant extra space, which is exactly what the interviewer's follow-up question is asking for.
What makes a sliding window question hard?
Deciding when to shrink the window. The expansion step is usually obvious; the contraction condition is where the logic lives, and stating it as an invariant before coding prevents most of the bugs.