Skip to main content

Scoring a String: Or How I Accidentally Did ASCII Math Again

Published 2 min readMarkdown
Part of seriesDSA - Breakdown

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 <= 100

  • s is made up of lowercase English letters.

My Approach

  1. Initialize a variable to store the score

  2. Loop from index 0 to len(s) - 2

  3. For each index:

    • convert current and next character to ASCII

    • take absolute difference

    • add to score

  4. 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.

No comments yet. Be the first to comment.