Optimizing Longest Consecutive Sequence with HashSet

🚀 𝐃𝐚𝐲 86/100 – 𝐋𝐨𝐧𝐠𝐞𝐬𝐭 𝐂𝐨𝐧𝐬𝐞𝐜𝐮𝐭𝐢𝐯𝐞 𝐒𝐞𝐪𝐮𝐞𝐧𝐜𝐞 Today’s problem was Longest Consecutive Sequence — a great example of optimizing from brute force to an efficient solution using hashing. 🔍 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠: Sorting would take O(n log n), but we can solve this in O(n) using a HashSet. 💡  𝐂𝐨𝐫𝐞 𝐈𝐝𝐞𝐚: Store all elements in a set for O(1) lookup Only start counting when the current number is the start of a sequence 𝐖𝐡𝐲 𝐢𝐭 𝐰𝐨𝐫𝐤𝐬? This ensures we only count each sequence once, avoiding unnecessary repeated work. ⚡ 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Add all elements to a HashSet Iterate through the set: If (num - 1) doesn’t exist → start a sequence Keep increasing and count streak Track maximum length ⏱️ 𝐓𝐢𝐦𝐞 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: 𝐎(𝐧) 📦 𝐒𝐩𝐚𝐜𝐞 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: 𝐎(𝐧) #Day86 #100DaysOfCode #Java #DSA #LeetCode #HashSet #CodingJourney

  • graphical user interface, text, email

To view or add a comment, sign in

Explore content categories