The Two Sneaky Numbers of Digitville

easy array hash table counting

Problem

A list nums was meant to hold every integer from 0 to n − 1 exactly once, but two mischievous numbers each sneaked in one extra time, so nums.length == n + 2. Find those two repeated numbers and return them in an array of size two (in any order).

Inputnums = [0, 1, 1, 0]
Output[0, 1]
Here n = 2, so values 0 and 1 should each appear once — but both appear twice, so they are the two sneaky numbers.

def getSneakyNumbers(nums):
    n = len(nums) - 2          # values range over 0 .. n-1
    count = [0] * n            # count[v] = times we've seen v
    res = []
    for v in nums:
        count[v] += 1          # tally this value
        if count[v] == 2:      # second sighting -> sneaky
            res.append(v)
    return res                 # exactly two numbers collected
function getSneakyNumbers(nums) {
  const n = nums.length - 2;        // values range over 0 .. n-1
  const count = new Array(n).fill(0); // count[v] = times seen
  const res = [];
  for (const v of nums) {
    count[v]++;                     // tally this value
    if (count[v] === 2) {           // second sighting -> sneaky
      res.push(v);
    }
  }
  return res;                       // exactly two numbers collected
}
int[] getSneakyNumbers(int[] nums) {
    int n = nums.length - 2;        // values range over 0 .. n-1
    int[] count = new int[n];       // count[v] = times seen
    int[] res = new int[2];
    int idx = 0;
    for (int v : nums) {
        count[v]++;                 // tally this value
        if (count[v] == 2) {        // second sighting -> sneaky
            res[idx++] = v;
        }
    }
    return res;                     // exactly two numbers collected
}
vector<int> getSneakyNumbers(vector<int>& nums) {
    int n = nums.size() - 2;        // values range over 0 .. n-1
    vector<int> count(n, 0);        // count[v] = times seen
    vector<int> res;
    for (int v : nums) {
        count[v]++;                 // tally this value
        if (count[v] == 2) {        // second sighting -> sneaky
            res.push_back(v);
        }
    }
    return res;                     // exactly two numbers collected
}
Time: O(n) Space: O(n)