Easy dsa arrays

Find All Numbers Disappeared in an Array

The 30 second answer

Values are between one and n, so each value can point at an index. For every value I flip the number at index value minus one to negative. Afterwards, any index that is still positive means that value plus one never appeared. That is linear time and no extra space apart from the output, though it temporarily modifies the input.

Could you say this in an interview?

Problem An array of length n contains values from 1 to n, some repeated. Return every value in 1..n that doesn't appear. Original: LeetCode 448: Find All Numbers Disappeared in an Array.

Understanding the prompt Values map one-to-one onto indices 0..nāˆ’1. The follow-up asks for no extra space besides the returned list.

Pattern recognition A value range of 1..n plus O(1) space is index marking, a form of cyclic sort.

Brute force A boolean array or HashSet of seen values: O(n) extra space.

Optimal For each x, mark index |x| āˆ’ 1 negative. Use Math.abs, because the value may already have been flipped. Indices that stay positive are the missing values minus one.

Alternatives Cyclic sort: swap each value into its home index, then scan for mismatches.

Java solution

import java.util.ArrayList;

public class DisappearedNumbers {
    static ArrayList<Integer> findDisappeared(int[] nums) {
        for (int x : nums) {
            int idx = Math.abs(x) - 1;
            if (nums[idx] > 0) nums[idx] = -nums[idx];
        }
        var missing = new ArrayList<Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) missing.add(i + 1);
        }
        return missing;
    }

    public static void main(String[] args) {
        System.out.println(findDisappeared(new int[] {4, 3, 2, 7, 8, 2, 3, 1})); // [5, 6]
        System.out.println(findDisappeared(new int[] {1, 1}));                   // [2]
        System.out.println(findDisappeared(new int[] {1}));                      // []
    }
}

Complexity O(n) time. O(1) extra space besides the output.

Edge cases

  • All values present returns an empty list.
  • All values the same.
  • Modifying the input: say so, and restore the signs afterwards if the caller needs the array.

Follow-ups

  • Find all duplicates (LeetCode 442): an index that is already negative reveals a duplicate.
  • First missing positive with arbitrary values: see the next question.

Tests [4,3,2,7,8,2,3,1] returns [5,6]. [1,1] returns 2. 1 returns [].

How to say it in the interview "Values are 1 to n, so each value names an index. I flip the sign at that index to mark it seen. Any index left positive is a missing number. O(n) time, no extra memory, but I'm mutating the input, so I'd mention restoring it."

Sources (2)
  1. LeetCode 448: Find All Numbers Disappeared in an Arrayleetcode.com
  2. Java SE 17 API: Math.abs(int)docs.oracle.com