Master string traversal and ASCII manipulation by calculating the score of a string - a perfect introduction to linear algorithms.
We usually think of strings as text—words, sentences, maybe a bit of JSON. But deep down, your computer just sees a sequence of numbers. LeetCode problem 3110. Score of a String is a great little exercise that peels back that text layer to show you the raw numerical machinery underneath.
The problem asks us to calculate the “score” of a string. In plain English, we need to sum up the absolute differences between the ASCII values of side-by-side characters. It’s categorized as an Easy problem, and honestly, it is. But it’s also a fantastic way to get comfortable with data encoding and linear traversal without getting bogged down in complex logic.
If the math sounds dry, let’s swap the “score” for something tangible: a hiking trail.
Analogy: Imagine each character’s ASCII value is the elevation (height) of a checkpoint on a mountain. The “Score” is simply the total vertical effort of your hike. It doesn’t matter if you’re climbing up a steep hill or scrambling down a ravine (absolute difference); every meter of elevation change burns energy and adds to your total effort.
It’s always easier to see this in action. Let’s look at what happens with a simple string like “hello.” Watch how we grab pairs of neighbors and calculate the gap between them.
To knock this problem out, you really only need three tools in your belt:
ord('a')(int) 'a''a' like a number (it does this implicitly)s[i] and its neighbor s[i+1]. If you have a string of length , you’re going to have exactly comparisons.Mathematical Definition: Score =
Let’s walk through the logic manually with s = "hello" so there are no surprises when we write the code.
score = 0.Final Score: 13
The strategy here is a Linear Scan (). We just walk down the string once, checking each character against the next one in line.
class Solution {
public int scoreOfString(String s) {
int score = 0;
// Iterate from 0 up to the second-to-last character
// We stop at length() - 1 to avoid IndexOutOfBounds when accessing i+1
for (int i = 0; i < s.length() - 1; i++) {
// s.charAt returns a char, which is implicitly promoted to int for subtraction
// Math.abs handles the absolute value
score += Math.abs(s.charAt(i) - s.charAt(i + 1));
}
return score;
}
} Sometimes it helps to see the data flow. The visualization below tracks the raw ASCII values alongside the accumulating score, so you can see exactly how the volatility of the characters impacts the final number.
We can’t skip the efficiency check (interviewers love this part).
Time Complexity: - We visit every character exactly once.
Space Complexity: - Constant extra space.
score and one for the iterator i. It doesn’t matter if the string is 5 characters or 5 million; the memory usage stays the same.While the standard loop is the “correct” answer, different languages have their own flavor. The visualization below highlights how we can optimize the perception of the data flow, even if the underlying complexity stays linear.
pairwiseIf you’re using Python 3.10+, you can look extra fancy by using itertools.pairwise. It handles the “neighbor” logic for you:
from itertools import pairwise
class Solution:
def scoreOfString(self, s: str) -> int:
return sum(abs(ord(a) - ord(b)) for a, b in pairwise(s))
Here is where most people trip up on this problem.
⚠️ The Classic Trap: Off-by-One Errors (IndexOutOfBounds)
for i in range(len(s)) and then trying to access s[i+1].len(s) - 1). Why? Because the very last character in the string has no neighbor to its right. If you try to shake hands with a ghost, your program crashes.Other things to watch out for:
('a' - 'z') gives you -25. If you forget abs(), you’ll end up subtracting from your score instead of adding the distance.So, why should you care about this besides passing a coding test?
[100, 102, 105], we just store the changes: [100, +2, +3]. Smaller numbers take up less space.“Score of a String” isn’t the hardest problem you’ll ever solve, but it’s a solid sanity check for your understanding of loops and character encoding. If you can master this, you’re setting yourself up for success with harder string algorithms like Edit Distance later on.
Just remember the hiking analogy: whether the trail goes up or down, your legs still feel the burn. In this algorithm, every step counts.