Code Lab

Common characters of two strings

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

Examples

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

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

commonCharacters('Hello', 'World')

Returns [ 'l', 'o' ]

commonCharacters('abc', 'xyz')

Returns []

Asked at Synechron · Source

Loading the editor...
  1. InputcommonCharacters('Java With Collections', 'Java Selenium')
    Expected[ 'a', 'e', 'i', 'j', 'l', 'n', 's', 'v' ]
  2. InputcommonCharacters('Hello', 'World')
    Expected[ 'l', 'o' ]
  3. InputcommonCharacters('abc', 'xyz')
    Expected[]

Hidden tests run on Submit.