3110. Score of a String
Problem Description
You are given a string s
. Your task is to calculate the score of this string.
The score is calculated by:
- Looking at each pair of adjacent characters in the string
- Finding the ASCII value of each character
- Computing the absolute difference between these ASCII values
- Summing up all these absolute differences
For example, if you have a string "abc":
- The ASCII value of 'a' is 97, 'b' is 98, and 'c' is 99
- The absolute difference between 'a' and 'b' is
|97 - 98| = 1
- The absolute difference between 'b' and 'c' is
|98 - 99| = 1
- The total score would be
1 + 1 = 2
The solution uses Python's pairwise
function to iterate through consecutive pairs of characters, ord
to get ASCII values, and calculates the sum of absolute differences between each pair.
Intuition
The problem asks us to find the sum of absolute differences between adjacent characters' ASCII values. This is a straightforward simulation problem where we need to process the string character by character.
The key insight is that we need to:
- Process each adjacent pair of characters exactly once
- Convert each character to its ASCII value
- Calculate the absolute difference
- Sum all these differences
Since we're dealing with adjacent pairs, if we have a string of length n
, we'll have n-1
pairs to process. For example, in "hello" we have pairs: (h,e), (e,l), (l,l), (l,o).
The natural approach is to iterate through the string and for each position i
from 0 to n-2
, calculate |ord(s[i]) - ord(s[i+1])|
and accumulate the sum.
Python's pairwise
function elegantly handles the pairing of adjacent elements, eliminating the need for manual index management. By combining it with map(ord, s)
to convert all characters to ASCII values first, we can then simply calculate the absolute difference for each pair and sum them up in a single expression.
This leads to a clean one-liner solution: iterate through pairs of ASCII values and sum their absolute differences.
Solution Approach
The solution follows a simulation approach where we directly compute what the problem asks for - the sum of absolute differences between adjacent characters' ASCII values.
Implementation Details:
-
Convert characters to ASCII values: We use
map(ord, s)
to transform each character in the string to its corresponding ASCII value. Theord()
function returns the Unicode/ASCII code point of a character. -
Create adjacent pairs: The
pairwise()
function from Python's itertools (available in Python 3.10+) takes an iterable and returns successive overlapping pairs. For example, if we have ASCII values[97, 98, 99]
for "abc",pairwise
would give us pairs(97, 98)
and(98, 99)
. -
Calculate absolute differences: For each pair
(a, b)
returned bypairwise
, we computeabs(a - b)
to get the absolute difference between the ASCII values. -
Sum all differences: The
sum()
function aggregates all these absolute differences to produce the final score.
The entire solution is expressed as a single line using a generator expression:
sum(abs(a - b) for a, b in pairwise(map(ord, s)))
This approach has:
- Time Complexity:
O(n)
wheren
is the length of the string, as we traverse the string once - Space Complexity:
O(1)
as we only use a constant amount of extra space (the generator expression doesn't create intermediate lists)
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with the string s = "hello"
.
Step 1: Convert characters to ASCII values
- 'h' → 104
- 'e' → 101
- 'l' → 108
- 'l' → 108
- 'o' → 111
So we have the sequence: [104, 101, 108, 108, 111]
Step 2: Create adjacent pairs using pairwise
The pairwise
function gives us:
- Pair 1: (104, 101) for ('h', 'e')
- Pair 2: (101, 108) for ('e', 'l')
- Pair 3: (108, 108) for ('l', 'l')
- Pair 4: (108, 111) for ('l', 'o')
Step 3: Calculate absolute differences for each pair
- Pair 1: |104 - 101| = 3
- Pair 2: |101 - 108| = 7
- Pair 3: |108 - 108| = 0
- Pair 4: |108 - 111| = 3
Step 4: Sum all differences Total score = 3 + 7 + 0 + 3 = 13
The one-liner solution sum(abs(a - b) for a, b in pairwise(map(ord, s)))
performs all these steps:
map(ord, s)
converts "hello" to ASCII valuespairwise(...)
creates the 4 adjacent pairsabs(a - b) for a, b in ...
calculates each absolute differencesum(...)
adds them all up to get 13
Solution Implementation
1class Solution:
2 def scoreOfString(self, s: str) -> int:
3 """
4 Calculate the score of a string by summing the absolute differences
5 between ASCII values of adjacent characters.
6
7 Args:
8 s: Input string
9
10 Returns:
11 The sum of absolute differences between adjacent character ASCII values
12 """
13 # Import pairwise from itertools (available in Python 3.10+)
14 from itertools import pairwise
15
16 # Convert each character to its ASCII value using ord()
17 ascii_values = map(ord, s)
18
19 # Create pairs of adjacent ASCII values and calculate absolute differences
20 # pairwise creates consecutive pairs: (s[0], s[1]), (s[1], s[2]), etc.
21 score = sum(abs(a - b) for a, b in pairwise(ascii_values))
22
23 return score
24
1class Solution {
2 /**
3 * Calculates the score of a string by summing the absolute differences
4 * between ASCII values of consecutive characters.
5 *
6 * @param s The input string to calculate the score for
7 * @return The total score of the string
8 */
9 public int scoreOfString(String s) {
10 // Initialize the result variable to store the total score
11 int totalScore = 0;
12
13 // Iterate through the string starting from the second character
14 for (int i = 1; i < s.length(); ++i) {
15 // Get the previous character (at index i-1)
16 char previousChar = s.charAt(i - 1);
17
18 // Get the current character (at index i)
19 char currentChar = s.charAt(i);
20
21 // Calculate the absolute difference between ASCII values of consecutive characters
22 int difference = Math.abs(previousChar - currentChar);
23
24 // Add the difference to the total score
25 totalScore += difference;
26 }
27
28 // Return the final calculated score
29 return totalScore;
30 }
31}
32
1class Solution {
2public:
3 int scoreOfString(string s) {
4 // Initialize the score to store the sum of absolute differences
5 int score = 0;
6
7 // Iterate through the string starting from the second character
8 for (int i = 1; i < s.size(); ++i) {
9 // Calculate the absolute difference between ASCII values of consecutive characters
10 // and add it to the running score
11 score += abs(s[i] - s[i - 1]);
12 }
13
14 // Return the final score
15 return score;
16 }
17};
18
1/**
2 * Calculates the score of a string by summing the absolute differences
3 * between ASCII values of consecutive characters
4 * @param s - The input string to calculate the score for
5 * @returns The total score of the string
6 */
7function scoreOfString(s: string): number {
8 // Initialize the score accumulator
9 let totalScore: number = 0;
10
11 // Iterate through the string starting from the second character
12 for (let i: number = 1; i < s.length; i++) {
13 // Calculate the absolute difference between current and previous character's ASCII values
14 const currentCharCode: number = s.charCodeAt(i);
15 const previousCharCode: number = s.charCodeAt(i - 1);
16 const difference: number = Math.abs(currentCharCode - previousCharCode);
17
18 // Add the difference to the total score
19 totalScore += difference;
20 }
21
22 // Return the final calculated score
23 return totalScore;
24}
25
Time and Space Complexity
The time complexity is O(n)
, where n
is the length of the string s
. This is because:
map(ord, s)
iterates through all characters in the string once:O(n)
pairwise()
creates pairs of consecutive elements, requiring a single pass:O(n-1)
sum()
iterates through all pairs to calculate the sum:O(n-1)
- The
abs(a - b)
operation for each pair isO(1)
Overall, the algorithm makes a linear pass through the string, resulting in O(n)
time complexity.
The space complexity is O(1)
. Although pairwise()
and map()
create iterators, they don't store all elements in memory simultaneously. The iterators process elements one at a time, using only constant extra space for:
- The current pair of characters being processed
- The running sum accumulator
- Temporary variables for the absolute difference calculation
Therefore, the space usage remains constant regardless of the input string length.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Python Version Compatibility Issue
The pairwise
function is only available in Python 3.10+. If you're using an older Python version or submitting to a platform that doesn't support Python 3.10+, the code will fail with an ImportError
.
Solution: Implement your own pairwise logic using zip:
class Solution:
def scoreOfString(self, s: str) -> int:
# Works in all Python versions
return sum(abs(ord(s[i]) - ord(s[i+1])) for i in range(len(s) - 1))
Or using zip with slicing:
class Solution:
def scoreOfString(self, s: str) -> int:
# Create pairs using zip
return sum(abs(ord(a) - ord(b)) for a, b in zip(s, s[1:]))
2. Edge Case: Empty or Single Character String
While the current solution handles single character strings correctly (returns 0), you might forget to consider these edge cases when implementing alternative solutions.
Solution: Always validate input:
class Solution:
def scoreOfString(self, s: str) -> int:
if len(s) <= 1:
return 0
return sum(abs(ord(s[i]) - ord(s[i+1])) for i in range(len(s) - 1))
3. Misunderstanding ASCII vs Unicode
Some developers might assume all characters will be standard ASCII (0-127), but Python's ord()
returns Unicode code points which can be much larger for non-ASCII characters.
Solution: The current approach using abs()
handles this correctly regardless of the character range, but be aware that the problem constraints should specify the character set if this matters.
4. Off-by-One Errors in Manual Iteration
When implementing without pairwise
, a common mistake is iterating through all indices including the last one, causing an IndexError.
Wrong approach:
# This will cause IndexError
for i in range(len(s)): # Should be range(len(s) - 1)
diff = abs(ord(s[i]) - ord(s[i+1]))
Correct approach:
for i in range(len(s) - 1): # Stop before the last character
diff = abs(ord(s[i]) - ord(s[i+1]))
What does the following code do?
1def f(arr1, arr2):
2 i, j = 0, 0
3 new_arr = []
4 while i < len(arr1) and j < len(arr2):
5 if arr1[i] < arr2[j]:
6 new_arr.append(arr1[i])
7 i += 1
8 else:
9 new_arr.append(arr2[j])
10 j += 1
11 new_arr.extend(arr1[i:])
12 new_arr.extend(arr2[j:])
13 return new_arr
14
1public static List<Integer> f(int[] arr1, int[] arr2) {
2 int i = 0, j = 0;
3 List<Integer> newArr = new ArrayList<>();
4
5 while (i < arr1.length && j < arr2.length) {
6 if (arr1[i] < arr2[j]) {
7 newArr.add(arr1[i]);
8 i++;
9 } else {
10 newArr.add(arr2[j]);
11 j++;
12 }
13 }
14
15 while (i < arr1.length) {
16 newArr.add(arr1[i]);
17 i++;
18 }
19
20 while (j < arr2.length) {
21 newArr.add(arr2[j]);
22 j++;
23 }
24
25 return newArr;
26}
27
1function f(arr1, arr2) {
2 let i = 0, j = 0;
3 let newArr = [];
4
5 while (i < arr1.length && j < arr2.length) {
6 if (arr1[i] < arr2[j]) {
7 newArr.push(arr1[i]);
8 i++;
9 } else {
10 newArr.push(arr2[j]);
11 j++;
12 }
13 }
14
15 while (i < arr1.length) {
16 newArr.push(arr1[i]);
17 i++;
18 }
19
20 while (j < arr2.length) {
21 newArr.push(arr2[j]);
22 j++;
23 }
24
25 return newArr;
26}
27
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!