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.

Return the score of s.

Input & Output

Example 1 — Basic Case
$ Input: s = "hello"
Output: 13
💡 Note: Adjacent differences: |'h'-'e'| = |104-101| = 3, |'e'-'l'| = |101-108| = 7, |'l'-'l'| = |108-108| = 0, |'l'-'o'| = |108-111| = 3. Sum = 3+7+0+3 = 13
Example 2 — Two Characters
$ Input: s = "zab"
Output: 26
💡 Note: |'z'-'a'| = |122-97| = 25, |'a'-'b'| = |97-98| = 1. Sum = 25+1 = 26
Example 3 — Single Character
$ Input: s = "a"
Output: 0
💡 Note: Single character has no adjacent pairs, so score is 0

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists of lowercase English letters only

Visualization

Tap to expand
Score of a String - Infographic INPUT String s = "hello" h 104 e 101 l 108 l 108 o 111 idx 0 idx 1 idx 2 idx 3 idx 4 Adjacent Pairs: (h,e) (e,l) (l,l) (l,o) Score Formula: sum of |ASCII[i+1] - ASCII[i]| ALGORITHM STEPS 1 Initialize score = 0 2 Single Pass Loop for i = 0 to len-2 3 Calculate Diff diff = |s[i+1] - s[i]| 4 Accumulate score += diff Iteration Details: i=0: |101-104| = 3 i=1: |108-101| = 7 i=2: |108-108| = 0 i=3: |111-108| = 3 Total: 3+7+0+3 = 13 FINAL RESULT Output: 13 OK Score computed in single pass O(n) Score Breakdown: 3 7 0 3 =13 Key Insight: The optimized single pass approach iterates through the string exactly once, computing the absolute difference between each adjacent pair of characters. Time complexity is O(n), space is O(1). TutorialsPoint - Score of a String | Optimized Single Pass with Early Termination
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~5 min Avg. Time
450 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