Introduction

Hello! Are you ready for an exciting voyage into the wonderful realm of strings and data structures? Today, we will assist Alice, an aspiring cryptographer, with an intriguing string manipulation task. She loves playing with strings and has come up with a unique string encoding scheme. I assure you this will be an enlightening journey that will stretch your programming muscles. Let's get started!

Task Statement

Alice has devised a unique way of encoding words. She takes a word and replaces each character with the next character in the alphabetical order. In other words, given a string word, for each character, if it is not z, she replaces it with the character that comes next alphabetically. For the character z, she replaces it with a.

Another element of Alice's algorithm involves frequency analysis. After shifting the characters, she counts the frequency of each character in the new string. Then, she creates an association of each character with its frequency and ASCII value. Each character maps to a number, which is a product of the ASCII value of the character and its frequency. Our task is to construct a list containing these products, sorted in descending order.

Example

For the input string "banana", the output should be [294, 222, 99].

The string "banana" will be shifted to "cbobob".

Calculating the product of frequency and ASCII value for each character:

  • The ASCII value for c is 99; it appears once in the string, so its product is 99 * 1 = 99.
  • The ASCII value for b is 98; it appears three times in the string, so its product is 98 * 3 = 294.
  • The ASCII value for o is 111; it appears twice in the string, so its product is 111 * 2 = 222.

Collecting these products into a list gives [99, 294, 222]. Sorting this list in descending order results in [294, 222, 99].

Solution Building: Step 1 - Mapping each character to the next alphabetical character

Our first step involves mapping each character of the input string to the next alphabetical character. In Kotlin, we use a StringBuilder for mutable strings, which allows us to efficiently append each shifted character. To achieve this, we iterate over each character of the input string using Kotlin's forEach method. If a character is not z, we replace it with the next alphabetical character using letter + 1. If it is z, we replace it with a.

Here's the updated function in Kotlin:

fun characterFrequencyEncoding(word: String): String {
    val nextString = StringBuilder()
    word.forEach { letter ->
        nextString.append(if (letter == 'z') 'a' else (letter + 1))
    }
    return nextString.toString()
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal