Maximizing Letter-Weighted String Scores

Medium · Coding & Algorithms · Data Scientist · Online Assessment

Problem Statement

Every English letter 'a' through 'z' may be given a unique integer value from {1, 2, ..., 26}. Letter matching ignores case ('A' and 'a' receive the same value), while spaces, digits, punctuation marks, and any characters outside ASCII 'a'–'z' / 'A'–'Z' contribute 0.

Under a chosen mapping, a string's total score equals the sum, over all 26 English letters, of each letter's assigned value multiplied by how many times that letter occurs in the string.

Implement:

def maximum_beauty(lines: List[str]) -> List[int]:

Given a list of strings lines, pick an optimal 1..26 letter mapping independently for each string in lines so that each string achieves its highest possible total score, and return those maximum scores in order.

Examples

Example 1

  • Input: lines = ["MmNnnPPPP"]
  • Output: [227]
  • Explanation: Folding uppercase and lowercase together yields 'p': 4, 'n': 3, and 'm': 2. Assigning 'p' -> 26, 'n' -> 25, and 'm' -> 24 achieves 4 * 26 + 3 * 25 + 2 * 24 = 104 + 75 + 48 = 227.

Example 2

  • Input: lines = ["Data, stats & math! 2026"]
  • Output: [318]
  • Explanation: Skipping spaces, punctuation, and digits leaves 13 English letters with counts 'a': 4, 't': 4, 's': 2, 'd': 1, 'h': 1, 'm': 1. Pairing those sorted counts with 26, 25, 24, 23, 22, 21 gives 4 * 26 + 4 * 25 + 2 * 24 + 1 * (23 + 22 + 21) = 318.

Example 3

  • Input: lines = ["ZzZz!", "Go, go!"]
  • Output: [104, 102]
  • Explanation: Each string selects its own mapping independently: "ZzZz!" assigns 'z' -> 26 for 4 * 26 = 104, while "Go, go!" assigns 26 and 25 to 'g' and 'o' for 2 * 26 + 2 * 25 = 102.

Constraints

  • 0 <= len(lines) <= 1,000
  • 0 <= len(lines[i]) <= 10,000
  • Only ASCII letters 'a'–'z' and 'A'–'Z' are scored; all other characters contribute 0.
  • Each string in lines chooses its 1..26 letter mapping independently of all other strings.

Step-by-step walkthrough

  1. Understand the problem and rules

    For each input string, we may map every ASCII English letter a–z to its own unique integer in 1..26:

    • Case-insensitive: 'M' and 'm' represent the exact same letter and share one assigned value.
    • Skip non-letters: spaces, punctuation, digits, and non-ASCII characters add 0.
    • Independent per line: lines is a list of strings, and for each string we choose whichever 1..26 letter mapping maximizes that string's weighted total:
    score(line) = sum over letters a..z of (frequency(letter) * value(letter))
    

    For "MmNnnPPPP", the letter tallies are 'p': 4, 'n': 3, 'm': 2. Assigning 'p' -> 26, 'n' -> 25, 'm' -> 24 produces 4 * 26 + 3 * 25 + 2 * 24 = 227.

  2. Why brute-force permutation search is hopeless

    A permutation is an ordering of the numbers 1, 2, ..., 26 with no repeats. Trying every possible way to hand 1..26 to the 26 letters means checking 26! permutations — roughly 4 * 10^26 possibilities, which would take longer than the age of the universe.

    Even if we notice that letters with 0 occurrences should get the smallest leftover numbers and only permute the k largest values (26, 25, ..., 27 - k) among the k distinct letters present in the line, a sentence containing all 26 letters still has 26! orderings. We need a direct rule that tells us the best assignment without searching.

  3. Greedy exchange argument: pair highest counts with `26, 25, 24, ...`

    Suppose somebody hands us an assignment where a more frequent letter x received a smaller value than a less frequent letter y:

    freq(x) > freq(y),   but   val(x) < val(y)
    

    What happens to the total sum if we swap the values assigned to x and y?

    Before swap:  freq(x) * val(x) + freq(y) * val(y)
    After swap:   freq(x) * val(y) + freq(y) * val(x)
    
    Change = After - Before
           = freq(x) * (val(y) - val(x)) - freq(y) * (val(y) - val(x))
           = (freq(x) - freq(y)) * (val(y) - val(x))
    

    Because freq(x) - freq(y) > 0 and val(y) - val(x) > 0, their product is strictly positive — swapping always increases the score! (And if freq(x) == freq(y), the change is 0, so ties can go in either order.)

    Therefore, the maximum sum is always achieved by sorting the letter frequencies from largest to smallest and pairing them with 26, 25, 24, ...:

    "MmNnnPPPP":
      Sorted frequencies:   4 ('p')    3 ('n')    2 ('m')    0 (other 23 letters)
      Assigned values:     26         25         24         23 .. 1
      Products:           104    +    75    +    48    +     0                   = 227
    

    Notice we do not even need to remember which letter had frequency 4 — only the sorted list of frequencies matters!

  4. Count only English letters `a–z` safely

    We keep a fixed list counts of 26 zeros (index 0 for 'a'/'A' through index 25 for 'z'/'Z'), using Python's ord(ch) (which returns a character's numeric ASCII code, where 'a'..'z' and 'A'..'Z' each form 26 consecutive integers).

    Why check "a" <= ch <= "z" and "A" <= ch <= "Z" explicitly instead of ch.isalpha() or ch.lower()?

    • "é".isalpha() is True in Python because 'é' is a Unicode letter, even though it is not in a–z.
    • "K".lower() (the Unicode Kelvin sign, U+212A) turns into ASCII 'k'! Checking raw ASCII ranges first avoids both traps.
    def count_english_letters(line: str) -> List[int]:
        """Count occurrences of each English letter a-z (case-insensitive), ignoring everything else."""
        # counts[i]: frequency of letter chr(ord('a') + i), e.g. counts[0] for 'a'/'A', counts[25] for 'z'/'Z'.
        counts = [0] * 26
    
        for ch in line:
            # Check explicit ASCII ranges rather than `ch.isalpha()` or `ch.lower()` so accented
            # letters ('é') and Unicode lookalikes (such as Kelvin sign 'K') are safely ignored.
            if "a" <= ch <= "z":
                counts[ord(ch) - ord("a")] += 1
            elif "A" <= ch <= "Z":
                counts[ord(ch) - ord("A")] += 1
    
        return counts
    
  5. Sort counts descending, pair with `26..1`, and trace Example 2

    Once we have the 26 counts for a line, we sort them in descending order (reverse=True) and multiply them by 26, 25, 24, ..., stopping early as soon as freq == 0:

    def max_line_beauty(line: str) -> int:
        # Phase 1: Tally how many times each letter a-z appears in this line.
        counts = count_english_letters(line)
    
        # Phase 2: Sort frequencies largest-first so the most frequent letters receive the highest beauties.
        counts.sort(reverse=True)
    
        # Phase 3: Greedily pair sorted counts with 26, 25, 24, ... (rearrangement inequality).
        total_beauty = 0
        next_beauty = 26
        for freq in counts:
            # Once we hit 0, all remaining letters also have frequency 0 and add nothing to the sum.
            if freq == 0:
                break
            total_beauty += freq * next_beauty
            next_beauty -= 1
    
        return total_beauty
    

    Let's verify Example 2: "Data, stats & math! 2026". Skipping spaces, punctuation, and 2026, the 13 English letters have these counts:

    Count 4 (2 letters: a, t)       -> 4 * (26 + 25)       = 4 * 51 = 204
    Count 2 (1 letter:  s)          -> 2 * 24              = 2 * 24 =  48
    Count 1 (3 letters: d, h, m)    -> 1 * (23 + 22 + 21)  = 1 * 66 =  66
    Remaining 20 letters have count 0 -> stop!
    ----------------------------------------------------------------------
    Total maximum score                                             = 318
    
  6. Complete solution

    Apply max_line_beauty independently to each string in lines:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_english_letters(line: str) -> List[int]:
        """Count occurrences of each English letter a-z (case-insensitive), ignoring everything else."""
        # counts[i]: frequency of letter chr(ord('a') + i), e.g. counts[0] for 'a'/'A', counts[25] for 'z'/'Z'.
        counts = [0] * 26
    
        for ch in line:
            # Check explicit ASCII ranges rather than `ch.isalpha()` or `ch.lower()` so accented
            # letters ('é') and Unicode lookalikes (such as Kelvin sign 'K') are safely ignored.
            if "a" <= ch <= "z":
                counts[ord(ch) - ord("a")] += 1
            elif "A" <= ch <= "Z":
                counts[ord(ch) - ord("A")] += 1
    
        return counts
    
    
    def max_line_beauty(line: str) -> int:
        # Phase 1: Tally how many times each letter a-z appears in this line.
        counts = count_english_letters(line)
    
        # Phase 2: Sort frequencies largest-first so the most frequent letters receive the highest beauties.
        counts.sort(reverse=True)
    
        # Phase 3: Greedily pair sorted counts with 26, 25, 24, ... (rearrangement inequality).
        total_beauty = 0
        next_beauty = 26
        for freq in counts:
            # Once we hit 0, all remaining letters also have frequency 0 and add nothing to the sum.
            if freq == 0:
                break
            total_beauty += freq * next_beauty
            next_beauty -= 1
    
        return total_beauty
    
    
    def maximum_beauty(lines: List[str]) -> List[int]:
        # Each line chooses its own independent letter-to-beauty assignment.
        results: List[int] = []
        for line in lines:
            results.append(max_line_beauty(line))
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine you run a bakery that sold a known tally of each pastry today, and you get to assign point tags 1 through 26 (one unique tag per pastry) afterward to maximize today's total score. You would naturally put 26 on your top-selling pastry, 25 on second place, 24 on third place, and leave 1, 2, ... for pastries nobody ordered. Choosing letter weights works the exact same way via a greedy algorithm (a strategy that makes the locally best choice at each step) backed by an exchange argument (proving optimality by showing that swapping any out-of-order pair improves the score — also known in math as the rearrangement inequality, which states that a sum of pairwise products is maximized when both sequences are sorted in the same direction).

Why do naive approaches fail? Exhaustively testing every permutation (every distinct ordering of 1..26 across a..z) checks 26! (~4 * 10^26) mappings, which is completely infeasible. Meanwhile, handing out 26, 25, 24, ... in order of first appearance in the string fails whenever a rarer letter appears before a more frequent one — for "MmNnnPPPP", first-appearance order gives 'm' -> 26, 'n' -> 25, 'p' -> 24 (2*26 + 3*25 + 4*24 = 223), missing the optimal 227.

Here is the step-by-step calculation on "MmNnnPPPP":

1. Count letters a-z (case-insensitive):  'm' -> 2,  'n' -> 3,  'p' -> 4,  others -> 0
2. Sort non-zero counts descending:       [4, 3, 2]
3. Multiply by 26, 25, 24:                4 * 26 + 3 * 25 + 2 * 24 = 104 + 75 + 48 = 227

Complexity

  • Time: O(L) per line of length L (O(total characters) across all lines). Scanning the L characters of a line updates the 26-slot counter array in O(1) per character using ord (Python's built-in function returning a character's numeric code point), and sorting a fixed list of 26 integers always performs a constant O(1) number of comparisons (26 * log2(26) is ~122, independent of L).
  • Space: O(1) auxiliary space per line (plus O(len(lines)) for the returned results list), since counts always holds exactly 26 integers regardless of how long a line is.

Edge cases

  • Empty string "" or letterless string ("123 !? :)"): Every slot in counts stays 0, the loop breaks immediately on freq == 0, and the score is 0.
  • Empty input list []: Returns [].
  • Mixed uppercase and lowercase ("aAaA"): All four characters map to index 0 ('a'), giving 4 * 26 = 104 rather than splitting into 'A': 2 and 'a': 2 (2*26 + 2*25 = 102).
  • Frequency ties ("aabbc"): Sorted counts are [2, 2, 1]; whichever of 'a' or 'b' gets 26 and 25, 2*26 + 2*25 + 1*24 = 126 is identical.
  • All 26 letters once ("abcdefghijklmnopqrstuvwxyz"): Every count is 1, so the sum is 26 + 25 + ... + 1 = 26 * 27 / 2 = 351.
  • Non-ASCII Unicode letters ("café", Kelvin sign "K"): Ignored because "a" <= ch <= "z" and "A" <= ch <= "Z" accept strictly ASCII English letters.

Common mistakes

  • Forgetting to fold uppercase and lowercase together: Counting 'N' and 'n' separately splits one letter's count across two smaller multipliers (224 instead of 227 on "MmNnnPPPP").
  • Counting spaces, digits, or symbols: Including spaces and digits in "Data, stats & math! 2026" inflates non-letter tallies and hands 26 to ' ' instead of a real letter.
  • Using ch.isalpha() or ch.lower() without an ASCII check: ch.isalpha() accepts accented characters like 'é', and "\u212a".lower() converts the Kelvin symbol into ASCII 'k', overcounting non-a..z characters.
  • Sharing one assignment across all lines instead of resetting per line: Each string in lines chooses its own optimal 1..26 mapping independently (as in Example 3).
  • Sorting ascending instead of descending: Pairing the largest count with 1 instead of 26 minimizes rather than maximizes the sum.

Follow-up questions

  • How would your solution change if every string in the input list had to share one common letter-to-weight mapping to maximize the combined score across all strings? Because the sum over all lines of freq_in_line(c) * weight(c) equals total_freq_across_all_lines(c) * weight(c), you would accumulate one shared 26-element counts array across every line first, sort those 26 global totals descending once, and pair them with 26, 25, ..., 1 (or store assigned_weight[letter] if you still need to return each individual line's score under that shared mapping).
  • Under the same distinct 1-to-26 assignment rules, how would you find the minimum possible score of a string? Every letter a–z must still receive a distinct integer in 1..26, so letters with 0 occurrences happily absorb the largest numbers (26, 25, ...) at 0 cost! For the letters that do appear (freq > 0), the exchange argument reverses: pair the largest nonzero frequency with 1, the second largest with 2, and so on ("MmNnnPPPP" has minimum score 4*1 + 3*2 + 2*3 = 16).
  • If the character set contained K symbols (for instance, K = 100,000 token IDs) instead of 26 English letters, how would you keep each line's runtime fast? Allocating and sorting a K-element array per short line would waste O(K log K) time when a line of length L contains at most U <= L distinct symbols. Instead, count only the symbols present in the line with a hash map in O(L) average time, sort just those U nonzero frequencies descending in O(U log U) time, and multiply them by K, K - 1, ..., K - U + 1, giving O(L + U log U) time and O(U) extra space per line.

Follow-up questions

Similar questions

More Bank of America interview questions

All 11 Bank of America questions →