Code Lab

Mode entretien. Minuteur de 15 min, sans indices ni autocomplétion

Most and least frequent character

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

Exemples

mostAndLeastFrequent('hello world')

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

mostAndLeastFrequent('abba')

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

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

Renvoie { most: null, least: null }

Posé chez Cognizant · Source

Chargement de l'éditeur...
  1. EntréemostAndLeastFrequent('hello world')
    Attendu{ most: 'l', least: 'h' }
  2. EntréemostAndLeastFrequent('')
    Attendu{ most: null, least: null }

Les tests cachés se lancent à la soumission