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' -> 24achieves4 * 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
13English letters with counts'a': 4,'t': 4,'s': 2,'d': 1,'h': 1,'m': 1. Pairing those sorted counts with26, 25, 24, 23, 22, 21gives4 * 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' -> 26for4 * 26 = 104, while"Go, go!"assigns26and25to'g'and'o'for2 * 26 + 2 * 25 = 102.
Constraints
0 <= len(lines) <= 1,0000 <= len(lines[i]) <= 10,000- Only ASCII letters
'a'–'z'and'A'–'Z'are scored; all other characters contribute0. - Each string in
lineschooses its1..26letter mapping independently of all other strings.
Step-by-step walkthrough
Understand the problem and rules
For each input string, we may map every ASCII English letter
a–zto its own unique integer in1..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:
linesis a list of strings, and for each string we choose whichever1..26letter 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' -> 24produces4 * 26 + 3 * 25 + 2 * 24 = 227.- Case-insensitive:
Why brute-force permutation search is hopeless
A permutation is an ordering of the numbers
1, 2, ..., 26with no repeats. Trying every possible way to hand1..26to the26letters means checking26!permutations — roughly4 * 10^26possibilities, which would take longer than the age of the universe.Even if we notice that letters with
0occurrences should get the smallest leftover numbers and only permute theklargest values (26, 25, ..., 27 - k) among thekdistinct letters present in the line, a sentence containing all26letters still has26!orderings. We need a direct rule that tells us the best assignment without searching.Greedy exchange argument: pair highest counts with `26, 25, 24, ...`
Suppose somebody hands us an assignment where a more frequent letter
xreceived a smaller value than a less frequent lettery:freq(x) > freq(y), but val(x) < val(y)What happens to the total sum if we swap the values assigned to
xandy?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) > 0andval(y) - val(x) > 0, their product is strictly positive — swapping always increases the score! (And iffreq(x) == freq(y), the change is0, 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 = 227Notice we do not even need to remember which letter had frequency
4— only the sorted list of frequencies matters!Count only English letters `a–z` safely
We keep a fixed list
countsof26zeros (index 0for'a'/'A'throughindex 25for'z'/'Z'), using Python'sord(ch)(which returns a character's numeric ASCII code, where'a'..'z'and'A'..'Z'each form26consecutive integers).Why check
"a" <= ch <= "z"and"A" <= ch <= "Z"explicitly instead ofch.isalpha()orch.lower()?"é".isalpha()isTruein Python because'é'is a Unicode letter, even though it is not ina–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 countsSort counts descending, pair with `26..1`, and trace Example 2
Once we have the
26counts for a line, we sort them in descending order (reverse=True) and multiply them by26, 25, 24, ..., stopping early as soon asfreq == 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_beautyLet's verify Example 2:
"Data, stats & math! 2026". Skipping spaces, punctuation, and2026, the13English 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 = 318Complete solution
Apply
max_line_beautyindependently to each string inlines: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 lengthL(O(total characters)across all lines). Scanning theLcharacters of a line updates the26-slot counter array inO(1)per character usingord(Python's built-in function returning a character's numeric code point), and sorting a fixed list of26integers always performs a constantO(1)number of comparisons (26 * log2(26)is ~122, independent ofL). - Space:
O(1)auxiliary space per line (plusO(len(lines))for the returnedresultslist), sincecountsalways holds exactly26integers regardless of how long a line is.
Edge cases
- Empty string
""or letterless string ("123 !? :)"): Every slot incountsstays0, the loop breaks immediately onfreq == 0, and the score is0. - Empty input list
[]: Returns[]. - Mixed uppercase and lowercase (
"aAaA"): All four characters map to index0('a'), giving4 * 26 = 104rather than splitting into'A': 2and'a': 2(2*26 + 2*25 = 102). - Frequency ties (
"aabbc"): Sorted counts are[2, 2, 1]; whichever of'a'or'b'gets26and25,2*26 + 2*25 + 1*24 = 126is identical. - All
26letters once ("abcdefghijklmnopqrstuvwxyz"): Every count is1, so the sum is26 + 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 (224instead of227on"MmNnnPPPP"). - Counting spaces, digits, or symbols: Including spaces and digits in
"Data, stats & math! 2026"inflates non-letter tallies and hands26to' 'instead of a real letter. - Using
ch.isalpha()orch.lower()without an ASCII check:ch.isalpha()accepts accented characters like'é', and"\u212a".lower()converts the Kelvin symbol into ASCII'k', overcounting non-a..zcharacters. - Sharing one assignment across all lines instead of resetting per line: Each string in
lineschooses its own optimal1..26mapping independently (as in Example 3). - Sorting ascending instead of descending: Pairing the largest count with
1instead of26minimizes 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)equalstotal_freq_across_all_lines(c) * weight(c), you would accumulate one shared26-elementcountsarray across every line first, sort those26global totals descending once, and pair them with26, 25, ..., 1(or storeassigned_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–zmust still receive a distinct integer in1..26, so letters with0occurrences happily absorb the largest numbers (26, 25, ...) at0cost! For the letters that do appear (freq > 0), the exchange argument reverses: pair the largest nonzero frequency with1, the second largest with2, and so on ("MmNnnPPPP"has minimum score4*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 wasteO(K log K)time when a line of lengthLcontains at mostU <= Ldistinct symbols. Instead, count only the symbols present in the line with a hash map inO(L)average time, sort just thoseUnonzero frequencies descending inO(U log U)time, and multiply them byK, K - 1, ..., K - U + 1, givingO(L + U log U)time andO(U)extra space per line.
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?
- Under the same distinct 1-to-26 assignment rules, how would you find the minimum possible score of a string?
- 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?
Similar questions
- Spelled-Out Number Phrase to Integer
- Walking Through Your Algorithm Design, Complexity, and Trade-Offs
- Dispense Sorted Currency Change from Decimal Totals
- Quantitative Internship Four-Part Behavioral Assessment
- Earning Trust and Partnership With a Key Stakeholder
- Four-Part Data Science Screen: Ownership, Modeling, Rigor, and Trust
More Bank of America interview questions
- Earning Trust and Partnership With a Key Stakeholder Medium
- Four-Part Data Science Screen: Ownership, Modeling, Rigor, and Trust Medium
- Quantitative Analysis of a Macro Capital-Allocation Trend Medium Pro
- Dispense Sorted Currency Change from Decimal Totals Easy Pro
- Self-Directed Impact, Diagnostic Rigor, and Cross-Team Alignment Medium Pro
- Quantitative Internship Four-Part Behavioral Assessment Medium Pro
- Spelled-Out Number Phrase to Integer Medium Pro
- Walking Through Your Algorithm Design, Complexity, and Trade-Offs Medium Pro
- Foundations of Probability, Statistical Estimation, Regularized Regression, and PCA Medium Pro
- Data Science Behavioral Portfolio: Ownership, Rigor, and Partnership Medium Pro