Magicsheet logo

Score of a String

Easy
25%
Updated 8/1/2025

Score of a String

What is this problem about?

The Score of a String interview question asks you to compute a "score" for a given string. The score is the sum of the absolute differences between the ASCII values of all adjacent character pairs. For example, for "hello", you compute |h-e| + |e-l| + |l-l| + |l-o| and sum those values. This is a simple string traversal and arithmetic problem.

Why is this asked in interviews?

Microsoft, Meta, Amazon, Google, and Bloomberg ask this as a beginner-level warm-up that tests character-to-ASCII conversion, adjacent element comparison, and cumulative sum computation. It validates coding fluency with ord() (or equivalent) and basic loop logic. Despite its simplicity, it distinguishes candidates who write clean, readable code from those who over-complicate straightforward tasks.

Algorithmic pattern used

The pattern is linear scan with adjacent pair processing. Iterate from index 0 to len(s) - 2. For each index i, compute abs(ord(s[i]) - ord(s[i+1])) and add to the running total. Return the total. In Python, this is elegantly expressed as sum(abs(ord(a) - ord(b)) for a, b in zip(s, s[1:])).

Example explanation

Input: "hello"

Adjacent pairs:

  • h(104) and e(101): |104 - 101| = 3.
  • e(101) and l(108): |101 - 108| = 7.
  • l(108) and l(108): |108 - 108| = 0.
  • l(108) and o(111): |108 - 111| = 3.

Score = 3 + 7 + 0 + 3 = 13.

Input: "zaz":

  • z(122) and a(97): |122 - 97| = 25.
  • a(97) and z(122): |97 - 122| = 25.

Score = 50.

Common mistakes candidates make

  • Forgetting the absolute value — character differences can be negative without abs().
  • Iterating to len(s) instead of len(s) - 1, causing an index-out-of-bounds error when accessing s[i+1].
  • Using character comparison (>, <) instead of ord() for numeric values.
  • Confusing this with Hamming distance (which counts differing bits between same-length strings).

Interview preparation tip

For the Score of a String coding problem, the string interview pattern is the simplest adjacent-pair traversal. In Python, the zip(s, s[1:]) idiom elegantly pairs adjacent characters without index arithmetic. Interviewers at Meta and Google use this as a 2-minute warm-up — solve it instantly with the zip idiom and offer to discuss follow-ups: "What if we wanted the maximum single adjacent difference?" (just use max instead of sum).

Similar Questions