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.
s1ands2are strings. They can be empty and can have spaces, digits and punctuation.- Only the Latin letters
a-zcount. Spaces, digits and other characters are never in the result. Letters with accents, likeé, are not ina-zand 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...
- Input
commonCharacters('Java With Collections', 'Java Selenium')Expected[ 'a', 'e', 'i', 'j', 'l', 'n', 's', 'v' ] - Input
commonCharacters('Hello', 'World')Expected[ 'l', 'o' ] - Input
commonCharacters('abc', 'xyz')Expected[]
Hidden tests run on Submit