Longest Consecutive Sequence
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Find the length of the longest run of consecutive integers (like 4,5,6,7) present in the list, in O(n).
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1How can you tell, in one step, that a number starts a run?
- Hint 2A number starts a run exactly when (number - 1) is not in the list.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Students stand scattered with roll-number badges. A chain is roll numbers 4, 5, 6, 7 standing in a row of consecutive numbers. To find the longest chain you do not start counting from every student. You ask each one: "Is student number (yours - 1) here?" If yes, you are in the middle of a chain, skip. If no, you are the head of a chain: count forward 5? 6? 7? until a number is missing.
- The obvious way
Sort and scan: O(n log n). Or extend a run from every number by searching a list: O(n²).
- The key insight
Put all numbers in a set. A number whose predecessor is in the set is in the middle of a chain: skip it. A number without a predecessor is a chain head: walk forward while the next number exists. Every number is walked over at most once, so it is O(n).
- The algorithm
- Put all numbers in a set.
- For each number: is its predecessor in the set? Then it is mid-chain, skip.
- Otherwise it is a head: count how far the chain goes forward (number+1, number+2, ...).
- Keep the longest chain length seen.
Watch it run
Examplenumbers = [100, 4, 200, 1, 3, 2]
100: is 99 here? No, so 100 is a head. Is 101 here? No. Chain length 1.
longest = 1
Where people slip
- Loop over the set, not the list, so duplicates do not repeat work.
- Without the predecessor check it becomes O(n²).
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def longest_consecutive(nums):
present = set(nums)
longest = 0
for number in present:
if number - 1 in present: # not the head of a chain
continue
length = 1
while number + length in present: # walk forward along the chain
length += 1
longest = max(longest, length)
return longestNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.