Code Lab

Indexes of duplicate numbers

HardMap and Set15 min

Write a function duplicateIndices(numbers) that finds where every duplicate number stands in an array.

  • numbers is an array of integers. They can be positive, negative or 0.
  • Return a Map. Each key is a number that occurs more than once. Its value is an array of all its indexes in numbers, from small to large.
  • Indexes start at 0, as usual in JavaScript.
  • A number that occurs only once is not in the Map.
  • If there are no duplicates (also for an empty array), return an empty Map.
  • Key order is not checked.

Examples

duplicateIndices([3, 1, 3, 2, 1, 3])

Returns Map(2) { 3 => [ 0, 2, 5 ], 1 => [ 1, 4 ] }

duplicateIndices([7, 8, 7])

Returns Map(1) { 7 => [ 0, 2 ] }

duplicateIndices([1, 2, 3])

Returns Map(0) {}

Asked at ServiceNow · Source

Loading the editor...
  1. InputduplicateIndices([ 3, 1, 3, 2, 1, 3 ])
    ExpectedMap(2) { 3 => [ 0, 2, 5 ], 1 => [ 1, 4 ] }
  2. InputduplicateIndices([ 7, 8, 7 ])
    ExpectedMap(1) { 7 => [ 0, 2 ] }
  3. InputduplicateIndices([ 1, 2, 3 ])
    ExpectedMap(0) {}

Hidden tests run on Submit.