Java

import java.util.ArrayList;
import java.util.List;

/**

 Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

 Find all the elements that appear twice in this array.

 Could you do it without extra space and in O(n) runtime?

 Example:
 Input:
 [4,3,2,7,8,2,3,1]

 Output:
 [2,3]

 */

public class Find_All_Duplicates_in_an_Array {

    class Solution {
        public List<Integer> findDuplicates(int[] nums) {

            List<Integer> result = new ArrayList<>();

            if (nums == null || nums.length == 0) {
                return result;
            }

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

                // 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.

                int index = Math.abs(nums[i]) - 1;

                if (nums[index] < 0) {
                    result.add(index + 1);
//                    nums[i] *= (-1);
                }

                nums[index] *= (-1);
            }

            return result;
        }
    }
}

Java

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> duplicates = new ArrayList<Integer>();
        for (int num : nums) {
            num = Math.abs(num);
            if (nums[num - 1] < 0)
                duplicates.add(num);
            else
                nums[num - 1] *= -1;
        }
        return duplicates;
    }
}

All Problems

All Solutions