The Two Sneaky Numbers of Digitville
EasyUpdated: Aug 2, 2025
Practice on:
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.
Examples
Example 1
Input: nums = [0,1,1,0]
Output: [0,1]
Explanation:
The numbers 0 and 1 each appear twice in the array.
Example 2
Input: nums = [0,3,2,1,3,2]
Output: [2,3]
Explanation:
The numbers 2 and 3 each appear twice in the array.
Example 3
Input: nums = [7,1,5,4,3,4,6,0,9,5,8,2]
Output: [4,5]
Explanation:
The numbers 4 and 5 each appear twice in the array.
Constraints
2 <= n <= 100nums.length == n + 20 <= nums[i] < n- The input is generated such that
numscontains exactly two repeated elements.
Solution
Method 1 - Count Occurrences
We count the occurrences of each number using a hash table or array. The two numbers that appear twice are the answer.
Code
C++
#include <vector>
using namespace std;
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
int n = nums.size();
vector<int> cnt(n, 0), res;
for (int x : nums) ++cnt[x];
for (int i = 0; i < n; ++i) if (cnt[i] == 2) res.push_back(i);
return res;
}
};
Java
import java.util.*;
class Solution {
public int[] findDuplicates(int[] nums) {
int n = nums.length;
int[] cnt = new int[n];
for (int x : nums) cnt[x]++;
int[] res = new int[2];
int idx = 0;
for (int i = 0; i < n; ++i) if (cnt[i] == 2) res[idx++] = i;
return res;
}
}
Python
from typing import List
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
from collections import Counter
count = Counter(nums)
return [x for x in count if count[x] == 2]
Rust
use std::collections::HashMap;
impl Solution {
pub fn find_duplicates(nums: Vec<i32>) -> Vec<i32> {
let mut count = std::collections::HashMap::new();
for &x in &nums {
*count.entry(x).or_insert(0) += 1;
}
count.into_iter().filter(|&(_, v)| v == 2).map(|(k, _)| k).collect()
}
}
TypeScript
function findDuplicates(nums: number[]): number[] {
const count = new Map<number, number>();
for (const x of nums) count.set(x, (count.get(x) ?? 0) + 1);
return Array.from(count.entries()).filter(([k, v]) => v === 2).map(([k]) => k);
}
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(n)