DSA interview question
A game logs the levels players have completed, in no particular order and with repeats, and the achievements screen wants the longest streak of consecutive level numbers a player has cleared (such as 1, 2, 3, 4) no matter what order they played them in. Sorting and scanning is O(n log n). The O(n) trick uses a hash set: only start counting from numbers that begin a streak (their predecessor isn't in the set), and walk upwards from there. Every number is then visited a constant number of times.
Example: [100, 4, 200, 1, 3, 2] → 4 (the sequence 1, 2, 3, 4).
int longestConsecutive(const vector<int>& nums); // length of the longest run of consecutive integers
Input nums | Output | Explanation |
|---|---|---|
[100, 4, 200, 1, 3, 2] | 4 | 1, 2, 3, 4 |
[0, 3, 7, 2, 5, 8, 4, 6, 0, 1] | 9 | 0 through 8; the duplicate 0 doesn't matter |
[1, 2, 0, 1] | 3 | 0, 1, 2 |
[-1, -2, 5] | 2 | -2, -1 |
[9] | 1 | |
[] | 0 |
(Confirm: the elements don't need to be adjacent in the array; duplicates count once; O(n) time is expected.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in