Score of a String

Easy

10 min read

April 10, 2025

Problem Statement

Given a string s consisting of lowercase English letters, return the sum of absolute differences between the ASCII values of each pair of adjacent letters in the string.

For example, if s = "abc", you should return 2 because:

  • ASCII('a') = 97, ASCII('b') = 98 → |97 - 98| = 1
  • ASCII('b') = 98, ASCII('c') = 99 → |98 - 99| = 1 So the result is 1 + 1 = 2.

Understanding the Problem

In this problem, we are given a string of lowercase English letters. The task is to calculate the sum of the absolute differences of the ASCII values of each adjacent letter pair.

For instance:

  • For the string s = "abc", the ASCII difference between 'a' and 'b' is |97 - 98| = 1, and between 'b' and 'c' is |98 - 99| = 1. Thus, the total sum would be 1 + 1 = 2.

Solution Approach

To solve this, I used a simple approach where I:

  1. First convert each character in the string to its corresponding ASCII value.
  2. Store the ASCII values in an array.
  3. Calculate the sum of the absolute differences between adjacent ASCII values.

This method is straightforward, and it involves iterating through the string and performing constant-time operations for each character. The time complexity of this approach is O(n), where n is the length of the string.

Code Implementation

/**
* @param {string} s
* @return {number}
*/
var scoreOfString = function(s) {
const ASCII = {
a: 97,
b: 98,
c: 99,
d: 100,
e: 101,
f: 102,
g: 103,
h: 104,
i: 105,
j: 106,
k: 107,
l: 108,
m: 109,
n: 110,
o: 111,
p: 112,
q: 113,
r: 114,
s: 115,
t: 116,
u: 117,
v: 118,
w: 119,
x: 120,
y: 121,
z: 122,
};
  const temp = [];
let sum = 0;

for (let i = 0; i < s.length; i++) {
temp.push(ASCII[s[i]]);
}

for (let j = 0; j < temp.length - 1; j++) {
sum += Math.abs(temp[j] - temp[j + 1]);
}

return sum;
};

Time and Space Complexity

O(n)

Testing

Result of score of a string
Score of a String — Result

Takeaways

This problem provides a simple example of how string manipulation can be combined with numeric operations like absolute differences. While the solution is relatively straightforward, it’s essential to understand how we can work with ASCII values and apply basic arithmetic operations to solve real-world problems efficiently.