Score of a String (LeetCode 3110): Solution and Explanation

Easy
String

The score of a string is the sum of the absolute differences between the character codes of each pair of neighbouring characters. Given a lowercase string of length 2 to 100, return its score.

Intuition

Picture the alphabet laid out on a ruler, with each letter at its ASCII code. Reading the string left to right means hopping from one letter to the next on that ruler.

The score is simply the total distance travelled. Each hop only depends on two neighbouring letters, so nothing needs to be remembered beyond the running total.

Approach: Single pass over adjacent pairs

  1. Set score = 0.
  2. For every index i from 1 to n - 1, add abs(s[i] - s[i - 1]) using the character codes.
  3. Return score.

Step-by-step example

s = "hello"
  1. The codes are h = 104, e = 101, l = 108, l = 108, o = 111.
  2. h to e: |101 - 104| = 3, score = 3.
  3. e to l: |108 - 101| = 7, score = 10.
  4. l to l: the same letter, 0, score stays 10.
  5. l to o: |111 - 108| = 3, score = 13. Return 13.

Code: Python, Java, C++

1class Solution:
2    def scoreOfString(self, s: str) -> int:
3        score = 0
4        for i in range(1, len(s)):
5            score += abs(ord(s[i]) - ord(s[i - 1]))
6        return score
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each of the n - 1 neighbouring pairs is looked at once.

Space

O(1)

Only the running score and the loop index are stored.

Other approaches

Zip the string with itself shifted by one (time O(n), space O(n))

In Python, sum(abs(ord(a) - ord(b)) for a, b in zip(s, s[1:])) does the same scan in one line. It builds a sliced copy of the string.

Precompute codes into an array (time O(n), space O(n))

Convert the string to an int array first, then sum the absolute differences. Same result with an extra array and no real benefit.

Common mistakes

  • Forgetting the absolute value. Going from 'z' down to 'a' is a hop of 25, not -25.
  • Starting the loop at 0 and reading s[i - 1], which reads before the string (or wraps to the last character in Python).
  • Comparing every pair of characters instead of only neighbours, which gives a different and much larger number.

Frequently asked questions

Does the order of the two characters in a pair matter?

No. The absolute value makes |a - b| equal to |b - a|, so a hop has the same length in either direction.

Can the score overflow a 32-bit integer?

No. Each hop is at most 25 for lowercase letters and there are at most 99 hops, so the score is at most 2475.

Why is the answer for "zaz" 50?

'z' is 122 and 'a' is 97. The string makes two hops of 25 each, one down and one back up, for a total of 50.