Find All Duplicates in an Array
Find All Duplicates in an Array

Find All Duplicates in an Array

LeetCode Question 442

25 views
0
0

LeetCode Problem 448 – Find All Numbers Disappeared in an Array

Problem Link: Link


Problem Statement

You are given an array nums of length n, where each element nums[i] lies in the range [1, n].

Your task is to return all numbers in the range [1, n] that do not appear in the array.

Example 1

Input

nums = [4, 3, 2, 7, 8, 2, 3, 1]

Output

[5, 6]

Example 2

Input

nums = [1, 1]

Output

[2]

Constraints

  1. n == nums.length
  2. 1 ≤ n ≤ 10⁵
  3. 1 ≤ nums[i] ≤ n


Approach

The goal is to identify numbers within the range 1 to n that are missing from the given array.

One straightforward way to solve this problem is by using a HashMap to track the presence of each number:

  1. Traverse the array and store each element in a HashMap.
  2. Iterate through the range 1 to n.
  3. For each number, check whether it exists in the HashMap.
  4. If a number is not present, add it to the result list.

This approach ensures that:

  1. Each element is processed only once.
  2. Lookup operations are efficient.

Time and Space Complexity

  1. Time Complexity: O(n)
  2. Space Complexity: O(n) (due to the HashMap)


Solution Code (Java)

public List<Integer> findDisappearedNumbers(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
List<Integer> result = new ArrayList<>();

// Store all elements in the HashMap
for (int num : nums) {
map.put(num, 0);
}

// Check for missing numbers in the range [1, n]
for (int i = 1; i <= nums.length; i++) {
if (!map.containsKey(i)) {
result.add(i);
}
}

return result;
}


Final Notes

While this solution is simple and easy to understand, it uses additional space.

LeetCode also offers a constant space solution by modifying the input array in-place, which is worth exploring for optimization.

Ai Assistant Kas