← Home

442. Find All Duplicates in an Array

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
442

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 442. Find All Duplicates in an Array, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • use extra space

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findDuplicates.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//use extra space
02//Runtime: 224 ms, faster than 5.24% of C++ online submissions for Find All Duplicates in an Array.
03//Memory Usage: 27.9 MB, less than 5.00% of C++ online submissions for Find All Duplicates in an Array.
04
05class Solution {
06public:
07    vector<int> findDuplicates(vector<int>& nums) {
08        map<int, int> count;
09        vector<int> ans;
10        for(int num : nums){
11            if(count.find(num) == count.end()){
12                count[num] = 1;
13            }else{
14                count[num]++;
15                ans.push_back(num);
16            }
17        }
18        return ans;
19    }
20};
21
22//https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/92395/C%2B%2B-beats-98
23//without extra space, O(N)
24//Runtime: 112 ms, faster than 89.64% of C++ online submissions for Find All Duplicates in an Array.
25//Memory Usage: 14.9 MB, less than 90.00% of C++ online submissions for Find All Duplicates in an Array.
26
27class Solution {
28public:
29    vector<int> findDuplicates(vector<int>& nums) {
30        vector<int> ans;
31        for(int _num : nums){
32            //1<=num<=nums.size(), so this is always valid
33            //use the array itself to record whether "num" has occurred
34            //nums[j] may be negative because there could exist i where i < j && nums[i]-1 == abs(nums[j])
35            //so here we revert it to its original value
36            int num = abs(_num);
37            nums[num-1] *= -1;
38            if(nums[num-1] > 0){
39                ans.push_back(num);
40            }
41        }
42        return ans;
43    }
44};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.