3110. Score of a String - Explanation
Description
You are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
Return the score of s.
Example 1:
Input: s = "code"
Output: 24Explanation: The ASCII values of the characters in the given string are: 'c' = 99, 'o' = 111, 'd' = 100, and 'e' = 101. The score of s will be: |111 - 99| + |100 - 111| + |101 - 100|.
Example 2:
Input: s = "neetcode"
Output: 65Constraints:
2 <= s.length <= 100sis made up of lowercase English letters.
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- String iteration - Traversing through characters in a string using indices
- ASCII values - Converting characters to their numeric ASCII codes for comparison
- Absolute value - Computing the non-negative difference between two numbers
1. Iteration
Intuition
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.
Algorithm
- Initialize a variable
resto store the running total. - Iterate through the string from index
0ton - 2:- For each position
i, compute the absolute difference between the ASCII values ofs[i]ands[i + 1]. - Add this difference to
res.
- For each position
- Return
resas the final answer.
Time & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
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].
Sign in to join the discussion