Code Lab

Mode entretien. Minuteur de 10 min, sans indices ni autocomplétion

Duplicate numbers in an array

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

Exemples

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

Renvoie [ 1, 2 ]

findDuplicates([4, 4, 4])

Renvoie [ 4 ]

findDuplicates([7, 8, 9])

Renvoie []

Posé chez Cognizant · Source

Chargement de l'éditeur...
  1. EntréefindDuplicates([ 1, 2, 3, 2, 1, 5 ])
    Attendu[ 1, 2 ]
  2. EntréefindDuplicates([ 5, 6, 5 ])
    Attendu[ 5 ]
  3. EntréefindDuplicates([ 7, 8, 9 ])
    Attendu[]

Les tests cachés se lancent à la soumission