Code Lab

Most and least frequent character

HardMap and Set15 min

Write a function mostAndLeastFrequent(text) that finds the character that occurs most often in a string and the character that occurs least often.

  • text is a string. It can be empty.
  • Whitespace (spaces, tabs, line breaks) is not counted. Letters, digits and punctuation are counted.
  • Case matters: 'a' and 'A' are different characters.
  • Return an object { most, least }: most is the character with the highest frequency, least the character with the lowest frequency.
  • If several characters have the same frequency, the one that first appears earlier in the text wins.
  • If there are no characters to count (empty string or only whitespace), return { most: null, least: null }. Use null, not undefined.
  • You can count with a map.

Examples

mostAndLeastFrequent('hello world')

Returns { most: 'l', least: 'h' }

mostAndLeastFrequent('abba')

Returns { most: 'a', least: 'a' }

a and b both occur twice. a comes first, so it wins both times.
mostAndLeastFrequent('')

Returns { most: null, least: null }

Asked at Cognizant · Source

Loading the editor...
  1. InputmostAndLeastFrequent('hello world')
    Expected{ most: 'l', least: 'h' }
  2. InputmostAndLeastFrequent('')
    Expected{ most: null, least: null }

Hidden tests run on Submit.