Scoring a String: Or How I Accidentally Did ASCII Math Again
Ever looked at a string and thought:
“Yes, today I will subtract characters from each other.”
No?
Well, LeetCode did.
Today’s problem is deceptively simple, which makes it dangerous — because you either:
overthink it, or
feel suspicious about how easy it is.
Let’s break it down.
Problem Statement- 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: 24
Explanation: 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: 65
Constraints:
2 <= s.length <= 100sis made up of lowercase English letters.
My Approach
Initialize a variable to store the score
Loop from index
0tolen(s) - 2For each index:
convert current and next character to ASCII
take absolute difference
add to score
Return the result
class Solution:
def scoreOfString(self, s: str) -> int:
ans = 0
for i in range(len(s) - 1):
ans += abs(ord(s[i]) - ord(s[i + 1]))
return ans
⏱️ Complexity Analysis
Time Complexity:
O(n)Space Complexity:
O(1)
Efficient and boring — the best kind of correct.
Comments
Join the discussionNo comments yet. Be the first to comment.
DSA - Breakdown
Cracking DSA! My LeetCode solutions for interview prep of major patterns. Step-by-step problem-solving & code analysis.