Score of a String Solution in Python

Problem Description

Welcome to the whimsical world of string scoring! Imagine you have a string, and you want to know how “different” it is from itself. Sounds absurd, right? But that’s exactly what the “Score of a String” problem is all about!

In this LeetCode challenge, you’re tasked with calculating the score of a string based on the absolute differences between the ASCII values of adjacent characters. Think of it as a string’s way of expressing its emotional turmoil—each character is just trying to get by, and the score reflects how much they clash with their neighbors.

For example, if your string is “abc”, the score would be calculated as:

  • |a – b| + |b – c| = |97 – 98| + |98 – 99| = 1 + 1 = 2

So, if you ever find yourself in a heated argument with your string, just remember: it’s all about the score!

Code Solution


class Solution:
    def scoreOfString(self, s: str) -> int:
        return sum(abs(ord(a) - ord(b))
                   for a, b in itertools.pairwise(s))

Approach

The approach here is straightforward yet elegant. We utilize Python’s itertools.pairwise to generate pairs of adjacent characters in the string. For each pair, we calculate the absolute difference of their ASCII values using the ord() function. Finally, we sum up all these differences to get the final score. It’s like a math quiz for your string, and it’s acing it!

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the length of the string. We traverse the string once to compute the score.
Space Complexity O(1), as we are using a constant amount of space for our calculations.

Real-World Example

Imagine you’re at a party, and you’re trying to figure out how well you get along with your friends based on their personalities. Each friend represents a character in your string, and the score reflects how much you vibe (or clash) with them. If your friends are all chill and laid-back, your score will be low. But if you have a friend who’s always trying to one-up you, well, that score is going to skyrocket!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in Python