Longest Consecutive Sequence in O(n) Time with HashSet

🚀 Day 70 of #100DaysOfCode Today’s problem was a very popular array + hashing challenge — Longest Consecutive Sequence 🔢 📌 Problem Summary Given an unsorted array of integers, find the length of the longest consecutive elements sequence. The solution must run in O(n) time. 🧠 My Approach: HashSet Optimization Insert all elements into a HashSet for O(1) lookups Only start counting when the current number is the start of a sequence (i.e., num - 1 does NOT exist in the set) Expand forward while consecutive numbers exist Track and update the maximum sequence length This avoids unnecessary re-counting and keeps the solution efficient. ⚙️ Time & Space Complexity ⏱ Time: O(n) 💾 Space: O(n) (HashSet) 🔥 Key Learning Identifying a valid starting point is crucial for optimal solutions. Hashing combined with smart traversal can turn brute-force ideas into clean O(n) logic. Day 70 done ✔️ Onward to Day 71 🚀 #Day70 #100DaysOfCode #LeetCode #Java #HashSet #Arrays #DSA #ProblemSolving #CodingJourney

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories