#3110
Score of a String
EasyStringArrayString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution is essentially the same as the brute force approach but emphasizes that we can compute the score in a single pass through the string, making it efficient and straightforward.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a variable 'score' to 0.
- 2Step 2: Iterate through the string from the first character to the second last character.
- 3Step 3: For each character, compute the absolute difference with the next character and add it to 'score'.
- 4Step 4: Return the 'score' after the loop.
solution.py5 lines
1def score_of_string(s):
2 score = 0
3 for i in range(len(s) - 1):
4 score += abs(ord(s[i]) - ord(s[i + 1]))
5 return scoreℹ
Complexity note: The time complexity remains O(n) as we still only loop through the string once. The space complexity is O(1) since we are using a fixed amount of space for the score variable.
- 1The score is based on the absolute differences of ASCII values, which can be computed in a single pass.
- 2Understanding ASCII values helps in visualizing the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.