File: sum-of-digits-of-string-after-convert/solution.py

Date: 2026-06-06

Time: 19:22

sum-of-digits-of-string-after-convert/solution.py

Purpose

This file implements LeetCode problem 1945: *Sum of Digits of String After Convert*. It owns the complete solution and its test suite in a single module — consistent with the repo's convention of co-locating solution and tests per problem directory.

The problem: given a lowercase string s, replace each letter with its 1-indexed alphabet position (a=1, ..., z=26), concatenate those numbers into a single numeric string, then repeatedly sum that string's digits k times. Return the final integer.

Key Components

Solution.getLucky(self, s: str, k: int) -> int — The core algorithm. Contract:

TestGetLucky — Seven unit tests covering LeetCode's three examples, single-character edge cases ('a' and 'z'), a repeated-character case ('zzzz'), and a convergence test with high k.

Flow

The algorithm has two phases:

1. Convert (line 14): Each character maps to its alphabet position via ord(c) - ord('a') + 1, producing strings like "26" for 'z'. These are concatenated — not summed — so "zbax" becomes "2621124", not [26, 2, 1, 24].

2. Transform (lines 15–17): The first digit-sum happens immediately on numstr (line 15). The remaining k - 1 transforms loop over the digits of the running result integer. This split avoids converting back to string unnecessarily on the first pass — numstr is already a string, so summing its digits directly is natural.

After a single digit-sum, the result is at most 9 * len(numstr). For the maximum input (1000 characters of 'z'), numstr has 2000 digits, so the first sum is at most 18,000 — a 5-digit number. The second sum is at most 45. By the third iteration the value is a single digit and stays fixed, which is why testhighk with k=10 works correctly.

Patterns

Dependencies

Imports: Only unittest from stdlib — no external dependencies.

Imported by: The testsolution.py files listed in the context don't actually import this file — they're test files for *other* problems that happen to share the same structural pattern. The sum-of-digits-of-string-after-convert/testsolution.py is the one that tests this code (likely importing Solution from it).

Invariants

Error Handling

None. The code trusts its inputs per LeetCode convention — no validation, no exceptions. Invalid input (empty string, uppercase, non-alpha) produces silently wrong results rather than errors.

Topics to Explore

Beliefs