We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Score of a String

Number: 3379

Difficulty: Easy

Paid? No

Companies: Google, Meta, Microsoft, Amazon, Bloomberg


Problem Description

We are given a string s consisting of lowercase English letters. The score of s is defined as the sum of the absolute differences between the ASCII values of every pair of adjacent characters. The goal is to calculate and return the score of the string.


Key Insights

  • The task requires comparing each character with its adjacent neighbor.
  • Compute the difference between ASCII values using a built-in method (such as ord in Python).
  • A single linear iteration over the string is sufficient given the problem's constraints.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), as no additional data structures are used beyond basic variables.


Solution

The solution involves iterating over the string from the first character to the second last character. At each step, compute the absolute difference between the ASCII values of the current character and the next. Summing these differences yields the final score. The algorithm is efficient since it makes just one pass through the string, and it utilizes constant extra space.


Code Solutions

# Define a function to compute the score of the string.
def score_of_string(s):
    # Initialize the score counter.
    score = 0
    # Iterate through the string until the second last character.
    for i in range(len(s) - 1):
        # Add the absolute difference between consecutive characters (by their ASCII values).
        score += abs(ord(s[i]) - ord(s[i + 1]))
    return score

# Example usage:
if __name__ == "__main__":
    s = "hello"
    print(score_of_string(s))  # Expected output: 13
← Back to All Questions