Code Lab

Modo entrevista. Temporizador de 10 min, sin pistas y sin autocompletado

Common characters of two strings

MediaMap and Set10 min

Write a function commonCharacters(s1, s2) that finds the letters that occur in both strings: their intersection.

  • s1 and s2 are strings. They can be empty and can have spaces, digits and punctuation.
  • Only the Latin letters a-z count. Spaces, digits and other characters are never in the result. Letters with accents, like é, are not in a-z and do not count either.
  • Case does not matter (case insensitive): 'J' in one string and 'j' in the other is a common letter.
  • Return an array of letters in lower case. Every letter is in it once, even if it occurs many times.
  • Sort the array in alphabetical order.
  • If there are no common letters, return an empty array.

A Set of the letters of each string makes this short.

Ejemplos

commonCharacters('Java With Collections', 'Java Selenium')

Devuelve [ 'a', 'e', 'i', 'j', 'l', 'n', 's', 'v' ]

commonCharacters('Hello', 'World')

Devuelve [ 'l', 'o' ]

commonCharacters('abc', 'xyz')

Devuelve []

Preguntada en Synechron · Fuente

Cargando el editor…
  1. EntradacommonCharacters('Java With Collections', 'Java Selenium')
    Esperado[ 'a', 'e', 'i', 'j', 'l', 'n', 's', 'v' ]
  2. EntradacommonCharacters('Hello', 'World')
    Esperado[ 'l', 'o' ]
  3. EntradacommonCharacters('abc', 'xyz')
    Esperado[]

Las pruebas ocultas se ejecutan al enviar