Code Lab

Modo entrevista. Cronômetro de 10 min, sem dicas e sem autocompletar

Check two arrays for a common element

MédiaMap and Set10 min

Write a function hasCommonElement(a, b) that checks if two arrays have at least one equal element. In other words, it checks that their intersection is not empty.

  • Every element of a and b is a number or a string. The arrays can be empty and can have repeated elements.
  • Return a boolean: true if some element of a is also in b, otherwise false.
  • Compare with strict equality ===: the number 1 and the string '1' are different, and 'a' and 'A' are different.
  • The equal elements can be at any positions in the two arrays.
  • If one of the arrays is empty, return false.

A set of the elements of b makes the check fast for long arrays.

Exemplos

hasCommonElement([1, 2, 3], [3, 4])

Retorna true

hasCommonElement([1, 2], [3, 4])

Retorna false

hasCommonElement([1, 2], ['1'])

Retorna false

Fonte

Carregando o editor...
  1. EntradahasCommonElement([ 1, 2, 3 ], [ 3, 4 ])
    Esperadotrue
  2. EntradahasCommonElement([ 1, 2 ], [ 3, 4 ])
    Esperadofalse
  3. EntradahasCommonElement([], [ 1, 2 ])
    Esperadofalse

Os testes ocultos rodam no envio