Algo-Sim › Arrays & Hashing

Find All Numbers Disappeared in an Array

Easy · Arrays & Hashing · step through it in Java, Python and C++ on your own input

Values are 1..n: swap each one to index v − 1, then every index not holding its own number is missing.

Problem

An array nums of length n holds values from 1 to n; some appear twice and others not at all. Return every number in 1..n that does not appear. Aim for O(n) time and no extra space besides the returned list.

Constraints

Edge cases to test

Follow-up questions

Can you do it without moving values?
Mark presence by negating nums[|v| − 1]; indices still positive are missing. O(n) time, O(1) extra, and one more pass restores the signs.
What if you can’t modify the input?
Use a boolean array or bitset of size n: O(n) time, O(n) bits.

Solution

Java

public List<Integer> findDisappearedNumbers(int[] nums) {
    int i = 0;
    while (i < nums.length) {
        int home = nums[i] - 1;
        if (nums[i] != nums[home]) {
            int t = nums[i]; nums[i] = nums[home]; nums[home] = t;
        } else {
            i++;
        }
    }
    List<Integer> missing = new ArrayList<>();
    for (int j = 0; j < nums.length; j++) {
        if (nums[j] != j + 1) missing.add(j + 1);
    }
    return missing;
}

Python

def find_disappeared_numbers(nums):
    i = 0
    while i < len(nums):
        home = nums[i] - 1
        if nums[i] != nums[home]:
            nums[i], nums[home] = nums[home], nums[i]
        else:
            i += 1
    missing = []
    for j in range(len(nums)):
        if nums[j] != j + 1: missing.append(j + 1)
    return missing

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> findDisappearedNumbers(vector<int> &nums) {
        int i = 0;
        while (i < (int)nums.size()) {
            int home = nums[i] - 1;
            if (nums[i] != nums[home]) {
                swap(nums[i], nums[home]);
            } else {
                i++;
            }
        }
        vector<int> missing = {};
        for (int j = 0; j < (int)nums.size(); j++) {
            if (nums[j] != j + 1) missing.push_back(j + 1);
        }
        return missing;
    }
};

More Arrays & Hashing problems