Skip to content

Is Beautiful String

A string is said to be beautiful if each letter in the string appears at most as many times as the previous letter in the alphabet within the string; ie: b occurs no more times than a; c occurs no more times than b; etc. Note that letter a has no previous letter.

Given a string, check whether it is beautiful.

Example

  • For inputString = "bbbaacdafe", the output should be

    is_beautiful_string(inputString) = true

    This string contains 3 as, 3 bs, 1 c, 1 d, 1 e, and 1 f (and 0 of every other letter), so since there aren't any letters that appear more frequently than the previous letter, this string qualifies as beautiful.

  • For inputString = "aabbb", the output should be

    is_beautiful_string(inputString) = false

    Since there are more bs than as, this string is not beautiful.

  • For inputString = "bbc", the output should be

    is_beautiful_string(inputString) = false

    Although there are more bs than cs, this string is not beautiful because there are no as, so therefore there are more bs than as.

Input/Output

  • [input] string inputString

    A string of lowercase English letters.

Solution

py
import string


def is_beautiful_string(input_string):
    count_dict = sorted([
        (k, input_string.count(k))
        for k in set((input_string))
    ])

    if(count_dict[0][0] != 'a'):
        return False

    for i in range(len(count_dict) - 1):
        if(
            ord(count_dict[i+1][0]) - ord(count_dict[i][0]) != 1
            or
            count_dict[i+1][1] > count_dict[i][1]
        ):
            return False

    return True


print(is_beautiful_string('bcdeff'))
print(is_beautiful_string('aabb'))
js
function isBeautifulString(inputString) {
  const charMap = {};
  const charCode = 'a'.charCodeAt(0);
  for (let i = 0; i < 26; i++) {
    charMap[String.fromCharCode(charCode + i)] = 0;
  }
  for (let i = 0; i < inputString.length; i++) {
    charMap[inputString[i]]++;
  }
  const charMapKeys = Object.keys(charMap);
  for (let i = 0; i < charMapKeys.length - 1; i++) {
    if (charMap[charMapKeys[i]] < charMap[charMapKeys[i + 1]]) {
      return false;
    }
  }
  return true;
}

console.log(isBeautifulString('bcdeff'));
console.log(isBeautifulString('aabb'));
console.log(isBeautifulString('bbc'));

my thoughts are neither my employer's nor my wife's