Score of a String - Problem

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.

For example, if we have the string "hello", we calculate:

  • |ASCII('h') - ASCII('e')| = |104 - 101| = 3
  • |ASCII('e') - ASCII('l')| = |101 - 108| = 7
  • |ASCII('l') - ASCII('l')| = |108 - 108| = 0
  • |ASCII('l') - ASCII('o')| = |108 - 111| = 3

The total score would be 3 + 7 + 0 + 3 = 13.

Goal: Return the score of the given string s.

Input & Output

example_1.py β€” Basic Example
$ Input: s = "hello"
β€Ί Output: 13
πŸ’‘ Note: The adjacent character differences are: |'h'-'e'| = |104-101| = 3, |'e'-'l'| = |101-108| = 7, |'l'-'l'| = |108-108| = 0, |'l'-'o'| = |108-111| = 3. Total: 3+7+0+3 = 13
example_2.py β€” Single Character
$ Input: s = "z"
β€Ί Output: 0
πŸ’‘ Note: A single character has no adjacent characters, so the score is 0
example_3.py β€” Same Characters
$ Input: s = "aaa"
β€Ί Output: 0
πŸ’‘ Note: All characters are the same, so all adjacent differences are |'a'-'a'| = 0. Total: 0+0 = 0

Constraints

  • 2 ≀ s.length ≀ 100
  • s consists only of lowercase English letters
  • ASCII values of lowercase letters range from 97 ('a') to 122 ('z')

Visualization

Tap to expand
πŸ”οΈ ASCII Mountain Trail Visualizationh104me101ml108ml108mo111m↕3m↕7m↕0m↕3mElevation Changesh β†’ e: |104-101| = 3me β†’ l: |101-108| = 7ml β†’ l: |108-108| = 0ml β†’ o: |108-111| = 3mTotal Effort: 13mSum of all elevation changesπŸšΆβ€β™‚οΈ Hiker traverses trail once, measuring elevation changes between consecutive checkpoints
Understanding the Visualization
1
Map Characters to Elevations
Each character becomes a checkpoint with ASCII value as elevation
2
Calculate Elevation Changes
Find absolute difference between consecutive checkpoint elevations
3
Sum Total Effort
Add all elevation changes to get total hiking effort (score)
Key Takeaway
🎯 Key Insight: We only need to visit each character once and calculate the ASCII difference with its immediate neighbor, making this an optimal O(n) solution.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 10
58.0K Views
Medium Frequency
~5 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen