π LeetCode #128: Longest Consecutive Sequence β From Sorting to HashSet & a Big Realization
This one looked simple.
I read the problem, understood the examples, and thought:
"Alright, sort the array and count consecutive numbers. Easy."
π I sketched out the logic in my notebook and wrote the code.
β±οΈ Submitted it β boom:
β
Beat over 90% in time and memory.
But I couldnβt stop there. Because I know my solution is O(n log n)
π Enter: The Discussion Section
I saw people talking about a HashSet-based O(n) solution.
Wait, O(n)? Without sorting?
That grabbed my attention. I didnβt know much about unordered_set internals, so I dug in.
Saw how using a HashSet could eliminate the need for sorting entirely.
Understood how it could help track sequences more efficiently β by checking only where a sequence starts.
π€― Mind-Blown Moment
Then I saw a solution with two loops⦠yet it still claimed to be O(n).
At first, that didnβt make sense. But then I realized:
The inner loop only runs once per unique number β never repeats work.
So overall time complexity remains linear. Elegant!
π‘ Key Takeaways
π Donβt skip the Discussions tab β itβll challenge your assumptions.
π§ Understanding HashSet behavior unlocks powerful optimizations.
βοΈ Writing logic by hand helps internalize edge cases and control flow.
π Nested loops β O(nΒ²) β it depends how the data is traversed.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.