Solved LeetCode problem: Find the Two Sneaky Numbers with boolean array

✨ Today marks Day 7 of my LeetCode streak! I solved a fun and logical problem that reminded me how important simple ideas like arrays and booleans can be in solving tricky questions. 💡 Problem: Find the Two Sneaky Numbers In the town of Digitville, there’s a list called nums that should contain all integers from 0 to n - 1 exactly once. But two numbers decided to appear twice, making the list longer! 😅 My task was to find those two sneaky numbers and bring peace back to Digitville. 📘 Example: Input: nums = [0,3,2,1,3,2] Output: [2,3] Explanation: Numbers 2 and 3 appear twice in the array. 🧠 My Thought Process: At first, I thought of sorting the array and checking adjacent elements, but that would take O(n log n) time. Then I realized I could just keep track of which numbers I’ve seen using a boolean array — whenever I see a number again, that’s one of the sneaky ones! Since n ≤ 100, a simple O(n) solution works perfectly here. 💻 Code (Java): class Solution { public int[] getSneakyNumbers(int[] nums) { int n = nums.length - 2; boolean[] seen = new boolean[n]; int[] result = new int[2]; int idx = 0; for (int num : nums) { if (seen[num]) { result[idx++] = num; if (idx == 2) break; } else { seen[num] = true; } } return result; } } 🔍 Dry Run Example: nums = [0,3,2,1,3,2] Start → seen = [F,F,F,F] See 0 → mark as true See 3 → mark as true See 2 → mark as true See 1 → mark as true See 3 again → duplicate #1 See 2 again → duplicate #2 ✅ Output → [3,2] (order doesn’t matter) ⚙️ Complexity: Time: O(n) Space: O(n) Simple, clean, and efficient! 🎯 Key Learnings: Reinforced how boolean arrays can efficiently handle duplicates. Learned to identify when sorting isn’t needed — sometimes direct logic is faster. Keeping things simple often gives the most elegant solutions. 🗓️ LeetCode Streak: Day 7 / Small Steps → Big Progress 🚀 Each day I’m learning new ways to look at problems — this one taught me simplicity is power 💪 #LeetCode #100DaysOfCode #Java #DSA #ProblemSolving #LearningJourney #CodingPractice #DeveloperLife

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories