author avatar BooleanStack

3110. Score Of A String

Master string traversal and ASCII manipulation by calculating the score of a string - a perfect introduction to linear algorithms.

3110. Score of a String: A Gateway to ASCII Manipulation

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.

Real-World Analogy: The Hiking Trail

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.

Interactive Visualization: Calculating the Score

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.

String Score Calculator

Click 'Start' to begin calculation
h
104
[0]
e
101
[1]
l
108
[2]
l
108
[3]
o
111
[4]

How It Works

  1. For each adjacent pair of characters in the string, calculate the absolute difference of their ASCII values.
  2. Sum all these differences to get the total score.
  3. Formula: score = |s[0] - s[1]| + |s[1] - s[2]| + ... + |s[n-2] - s[n-1]|

Core Concepts

To knock this problem out, you really only need three tools in your belt:

  1. ASCII Values: Computers store characters as integers. ‘a’ isn’t just a letter; it’s the number 97. ‘b’ is 98, and ‘z’ is 122.
    • Python: Use ord('a')
    • Java: Cast it like (int) 'a'
    • C++: Just treat 'a' like a number (it does this implicitly)
  2. Adjacent Pairs: We need to look at s[i] and its neighbor s[i+1]. If you have a string of length NN, you’re going to have exactly N1N-1 comparisons.
  3. Absolute Difference: This is just the distance between two numbers. It doesn’t care about direction. The distance from 10 to 5 is 5, and from 5 to 10 is also 5.

Mathematical Definition: Score = i=0n2ASCII(s[i])ASCII(s[i+1])\sum_{i=0}^{n-2} | \text{ASCII}(s[i]) - \text{ASCII}(s[i+1]) |

Step-by-Step Walkthrough

Let’s walk through the logic manually with s = "hello" so there are no surprises when we write the code.

  1. Initialize: Start with score = 0.
  2. Pair 1 (‘h’, ‘e’):
    • ‘h’ is 104, ‘e’ is 101.
    • Difference = 104101=3|104 - 101| = 3.
    • Current Score = 3.
  3. Pair 2 (‘e’, ‘l’):
    • ‘e’ is 101, ‘l’ is 108.
    • Difference = 101108=7|101 - 108| = 7.
    • Current Score = 3 + 7 = 10.
  4. Pair 3 (‘l’, ‘l’):
    • Both are 108.
    • Difference is 0 (flat ground).
    • Current Score = 10 + 0 = 10.
  5. Pair 4 (‘l’, ‘o’):
    • ‘l’ is 108, ‘o’ is 111.
    • Difference = 108111=3|108 - 111| = 3.
    • Final Score = 10 + 3 = 13.

Final Score: 13

Implementation

The strategy here is a Linear Scan (O(N)O(N)). 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;
  }
}

Visualizing the Comparison

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.

String Score Comparison

hello
h
104
e
101
l
108
l
108
o
111
Score:
13
world
w
119
o
111
r
114
l
108
d
100
Score:
25
abc
a
97
b
98
c
99
Score:
2

Ranking (Lowest to Highest Score)

1
abc2
2
hello13
3
world25

About This Visualization

  • Compare scores of multiple strings side by side
  • Lower scores indicate characters that are closer together in ASCII values
  • Higher scores indicate larger jumps between adjacent characters
  • The ranking shows strings ordered from lowest to highest score

Complexity Analysis

We can’t skip the efficiency check (interviewers love this part).

Time Complexity: O(N)O(N) - We visit every character exactly once.

Space Complexity: O(1)O(1) - Constant extra space.

Optimization and Variations

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.

String Score Optimizer

Character Analysis

e
ASCII: 101
×1
h
ASCII: 104
×1
l
ASCII: 108
×2
o
ASCII: 111
×1

Optimization Strategy

  • Key Insight: To minimize the score, adjacent characters should have ASCII values as close as possible.
  • Optimal Solution: Sort the string alphabetically. This ensures characters are ordered by their ASCII values.
  • Why it works: Sorting minimizes the differences between consecutive characters.
  • Example: "hello" → "ehllo" reduces jumps between characters significantly.

Pythonic Approach: pairwise

If 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))

Common Pitfalls

Here is where most people trip up on this problem.

⚠️ The Classic Trap: Off-by-One Errors (IndexOutOfBounds)

Other things to watch out for:

  1. Forgetting Absolute Value: ('a' - 'z') gives you -25. If you forget abs(), you’ll end up subtracting from your score instead of adding the distance.
  2. Edge Cases: The constraints usually say the string will have at least 2 characters. But in a real interview, you should always ask: “What happens if the string is empty or has just one letter?” (Usually, the score would be 0).

Practical Applications

So, why should you care about this besides passing a coding test?

  1. Delta Encoding: This is actually how a lot of data compression works. Instead of storing big raw numbers like [100, 102, 105], we just store the changes: [100, +2, +3]. Smaller numbers take up less space.
  2. Signal Processing: Measuring the sum of absolute differences is a quick way to check how “bumpy” or volatile a signal is. A low score means a smooth line; a high score means lots of noise.
  3. Bioinformatics: When comparing DNA sequences, we often convert nucleotides to numbers to figure out how “far apart” two genetic sequences are.

Conclusion

“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.

Similar Posts