Solved Longest Consecutive Sequence with HashSet in Java

🔥 Day 35/100 of #100DaysOfCode - Finding Longest Sequence! Today's Problem: Longest Consecutive Sequence Task: Find the length of the longest consecutive elements sequence in an unsorted array. Solution: Used a HashSet for O(1) lookups! First added all elements to the set, then for each number, checked if it's the start of a sequence (no num-1 in set). If yes, counted consecutive numbers ahead. Key Insights: O(n) time complexity by only checking sequence starters HashSet eliminates duplicates and provides fast lookups Avoids O(n log n) sorting approach Smart Optimization: Only begins counting from sequence starting points Each number is processed at most twice (visited in set iteration + sequence counting) Handles duplicates and empty arrays gracefully Elegant solution that transforms an O(n²) brute force into O(n) using smart data structure choice! 💡 #100DaysOfCode #LeetCode #Java #Algorithms #HashSet #Arrays #CodingInterview

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories