↓Skip to main content
  1. LeetCode/

LeetCode 448: Find All Numbers Disappeared in an Array

·1 min· ·
LeetCode Easy Array Hash-Table
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-24

  • Submissions: Accepted ×2

Approach
#

Values lie in 1..n, so the array can serve as its own hash table (Hash Table Template 2): for each x, make nums[abs(x) - 1] negative to mark x as seen, using abs since the cell may already be negative. Afterward every i with nums[i] > 0 means i + 1 is missing, with O(1) extra space.

My Attempts
#

Both submissions passed on the first try, the first already using this negative-marking approach.

Solution
#

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        for x in nums:
            i = abs(x) - 1
            nums[i] = -abs(nums[i])
        return [i + 1 for i, x in enumerate(nums) if x > 0]

Complexity
#

Time O(n), space O(1) excluding output.

Mistakes to Avoid
#

  • Take abs when reading; the cell may already be negative.
  • Mark with -abs(...) so a value seen twice does not flip back to positive.

Interview Explanation
#

With values in 1 to n, I use the array as its own hash table, negating cell x - 1 for each x; positions still positive, plus one, are the missing numbers. Extra space O(1).

Related

LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate
LeetCode 219: Contains Duplicate II
·2 mins
LeetCode Easy Array Hash-Table Sliding-Window
LeetCode 219 note: a hash map stores each value’s last index; only the most recent occurrence needs a distance check
LeetCode 169: Majority Element
·2 mins
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 note: Boyer-Moore voting, where different values cancel in pairs and the survivor is the one appearing more than half the time
LeetCode 1: Two Sum
·2 mins
LeetCode Easy Array Hash-Table
LeetCode 1 note: store seen numbers in a hash map while scanning and look up target - x; checking before storing prevents using one element twice
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them