Code Lab

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

Common elements of two lists

MoyenMap and Set10 min

Write a function commonElements(listA, listB) that returns the elements that are in both lists: their intersection.

  • listA and listB are arrays of strings. They can be empty and can have duplicates.
  • Return a new array with every common element once, even if it occurs several times in one or both lists.
  • Order: the order of the first occurrence in listA.
  • Case matters: 'ann' and 'Ann' are different elements.
  • If there are no common elements, return an empty array.

A Set helps to check fast whether a value is in a list and to remember what is already in the result.

Exemples

commonElements(['ann', 'bob', 'carl', 'dan'], ['dan', 'eve', 'bob'])

Renvoie [ 'bob', 'dan' ]

commonElements(['ann', 'ann', 'bob'], ['ann'])

Renvoie [ 'ann' ]

commonElements(['ann'], ['Ann'])

Renvoie []

Posé chez Ness Digital · Source

Chargement de l'éditeur...
  1. EntréecommonElements([ 'ann', 'bob', 'carl', 'dan' ], [ 'dan', 'eve', 'bob' ])
    Attendu[ 'bob', 'dan' ]
  2. EntréecommonElements([ 'red', 'green' ], [ 'blue', 'green' ])
    Attendu[ 'green' ]
  3. EntréecommonElements([ 'a', 'b' ], [ 'c', 'd' ])
    Attendu[]

Les tests cachés se lancent à la soumission