5. Find All Duplicates in an Array

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

Example 1:

Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]

Example 2:

Input: nums = [1,1,2]
Output: [1]

Example 3:

Input: nums = [1]
Output: []

Solution: (Hashset)

Basic solution extra space of O(n)

Solution: (Optimized)

Approach: when find a number i, flip the number at position i-1 to negative. if the number at position i-1 is already negative, i is the number that occurs twice.

class Solution
{
public:
    vector<int> findDuplicates(vector<int> &nums)
    {

        vector<int> res;

        for (int i = 0; i < nums.size(); i++)
        {

            int idx = abs(nums[i]) - 1;
            if (nums[idx] < 0)
            {
                res.push_back(idx+1);
            }
            nums[idx] = nums[idx] * -1;
        }

        return res;
    }
};

Time Complexity: O(n) , Space Complexity: O(1)

Last updated