Score of a String — Solution in Python, Java & C++
Score of a String solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on strings.
Score of a String is an easy coding problem on strings, asked in Amazon and TCS interviews.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
The score of a string is the sum of the absolute differences between the ASCII values of every pair of adjacent characters.
Given a string s, return its score.
Example 1
Input: s = "hello"
Output: 13
Explanation: |h-e| + |e-l| + |l-l| + |l-o| = 3 + 7 + 0 + 3 = 13.
Example 2
Input: s = "zaz"
Output: 50
Explanation: |z-a| + |a-z| = 25 + 25 = 50.
Example 3
Input: s = "a"
Output: 0
Explanation: No adjacent pairs exist.
Constraints
1 <= s.length <= 100s consists of lowercase English letters.
Hints for Score of a String
Hint 1
Walk the string comparing each character with its predecessor.
Hint 2
Use the character codes, not the characters themselves.
Hint 3
A single-character string has no pairs and therefore scores 0.
How to solve Score of a String
The score is a straight sum over adjacent pairs, so one pass with a running total does the job.
Approach
- Start the total at 0.
- For
ifrom 1 ton-1, add|code(s[i]) - code(s[i-1])|. - Return the total.
Why it works
There are exactly n - 1 adjacent pairs and each contributes independently, so the loop covers the definition exactly.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Starting the loop at 0 reads index
-1. - Forgetting the absolute value lets differences cancel out.
Reference solution
Python
def scoreOfString(s: str) -> int:
return sum(abs(ord(s[i]) - ord(s[i - 1])) for i in range(1, len(s)))Java
public static int scoreOfString(String s) {
int total = 0;
for (int i = 1; i < s.length(); i++) {
total += Math.abs(s.charAt(i) - s.charAt(i - 1));
}
return total;
}C++
int scoreOfString(string s) {
int total = 0;
for (int i = 1; i < (int) s.size(); i++) {
total += abs(s[i] - s[i - 1]);
}
return total;
}JavaScript
var scoreOfString = function(s) {
let total = 0;
for (let i = 1; i < s.length; i++) {
total += Math.abs(s.charCodeAt(i) - s.charCodeAt(i - 1));
}
return total;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings