The Two Sneaky Numbers of Digitville - Problem

In the town of Digitville, there was a list of numbers called nums containing integers from 0 to n - 1. Each number was supposed to appear exactly once in the list, however, two mischievous numbers sneaked in an additional time, making the list longer than usual.

As the town detective, your task is to find these two sneaky numbers. Return an array of size two containing the two numbers (in any order), so peace can return to Digitville.

Input & Output

Example 1 — Basic Case
$ Input: nums = [0,1,1,0]
Output: [0,1]
💡 Note: The numbers 0 and 1 each appear twice in the array. Both are duplicates that sneaked in.
Example 2 — Different Numbers
$ Input: nums = [0,1,2,3,2,1]
Output: [1,2]
💡 Note: Numbers 1 and 2 each appear twice. They are the sneaky duplicates we need to find.
Example 3 — Edge Case
$ Input: nums = [7,1,2,3,4,5,6,0,8,9,7,8]
Output: [7,8]
💡 Note: In this larger array, numbers 7 and 8 appear twice each, making them the duplicates.

Constraints

  • 2 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ nums.length - 3

Visualization

Tap to expand
The Two Sneaky Numbers of Digitville INPUT nums = [0, 1, 1, 0] 0 idx 0 1 idx 1 1 idx 2 0 idx 3 Red = Sneaky duplicates! Expected: n=4, nums 0 to 3 Actual length: 4 (has dups) Two numbers appear twice making list longer ALGORITHM STEPS 1 Initialize HashSet seen = {} (empty set) 2 Initialize Result sneaky = [] (empty list) 3 Iterate Array For each num in nums: 4 Check and Add If in seen: add to sneaky Else: add to seen Single Pass Trace: num=0: seen={} --> add 0 num=1: seen={0} --> add 1 num=1: seen={0,1} --> SNEAKY! num=0: seen={0,1} --> SNEAKY! Result: sneaky=[1,0] FINAL RESULT Sneaky Numbers Found: 0 1 Output: [0, 1] Verification: 0 appears at idx 0 and 3 1 appears at idx 1 and 2 OK Peace restored to Digitville! Key Insight: A HashSet provides O(1) lookup time. When we encounter a number already in the set, we've found a duplicate! Single pass through array gives O(n) time complexity with O(n) space for the HashSet. No sorting needed! TutorialsPoint - The Two Sneaky Numbers of Digitville | Single Pass Hash Set Approach
Asked in
Amazon 25 Microsoft 18
33.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen