Code Lab

Duplicate numbers in an array

MediumMap and Set10 min

Write a function findDuplicates(numbers) that returns the duplicate numbers of an array: the numbers that occur more than once.

  • numbers is an array of integers. They can be positive, negative or 0.
  • Return a new array of numbers.
  • Every duplicate number is in the result once, even if it occurs three or more times.
  • Order: by the first occurrence of the number in numbers. [1, 2, 3, 2, 1, 5] gives [1, 2], not [2, 1]. Do not sort the result.
  • If there are no duplicates (also for an empty array), return an empty array.
  • Do not change the input array.

A set or a map helps you remember which numbers you have already seen.

Examples

findDuplicates([1, 2, 3, 2, 1, 5])

Returns [ 1, 2 ]

findDuplicates([4, 4, 4])

Returns [ 4 ]

findDuplicates([7, 8, 9])

Returns []

Asked at Cognizant · Source

Loading the editor...
  1. InputfindDuplicates([ 1, 2, 3, 2, 1, 5 ])
    Expected[ 1, 2 ]
  2. InputfindDuplicates([ 5, 6, 5 ])
    Expected[ 5 ]
  3. InputfindDuplicates([ 7, 8, 9 ])
    Expected[]

Hidden tests run on Submit.