Score of a String

Easy · Arrays & Hashing · Explanation and code example

Iteration

How it works

The score of a string is defined as the sum of absolute differences between adjacent characters' ASCII values. Since we need to compare each character with its neighbor, we simply walk through the string once, computing the difference between consecutive characters and accumulating the result in res.

Steps

  1. Initialize a variable res to store the running total.
  2. Iterate through the string from index 0 to n - 2:
    • For each position i, compute the absolute difference between the ASCII values of s[i] and s[i + 1].
    • Add this difference to res.
  3. Return res as the final answer.

Complexity

  • Time complexity: O(n)
  • Space complexity: O(1)

Things to watch for

Off-by-One Error in Loop Bounds

A frequent mistake is iterating to n instead of n - 1, causing an index out of bounds error when accessing s[i + 1]. Since you compare adjacent pairs, the loop should run from 0 to len(s) - 2 inclusive, processing n - 1 pairs for a string of length n.

Forgetting Absolute Value

Some solutions subtract ASCII values without taking the absolute value, resulting in negative contributions to the score. The problem requires the sum of absolute differences, so always wrap the subtraction with abs() to handle cases where s[i] > s[i + 1].

Python code example

class Solution:
    def scoreOfString(self, s: str) -> int:
        res = 0
        for i in range(len(s) - 1):
            res += abs(ord(s[i]) - ord(s[i + 1]))
        return res

C++ code example

class Solution {
public:
    int scoreOfString(string s) {
        int res = 0;
        for (int i = 0; i < s.length() - 1; i++) {
            res += abs(s[i] - s[i + 1]);
        }
        return res;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations