Reverse Degree of a String (LeetCode 3498): Solution and Explanation

Easy
String
Simulation

Number the alphabet backwards so 'a' is 26 and 'z' is 1. The reverse degree of a lowercase string is the sum, over every character, of that reversed value times the character's 1-indexed position. Return it.

Intuition

Each character contributes independently: its reversed alphabet value times its position. Nothing about one character changes another's contribution.

The reversed value is just 26 minus the letter's distance from 'a', so it takes one subtraction. A single left-to-right pass with a running total is all the problem needs.

Approach: One weighted pass

  1. Set total = 0.
  2. For each index i, compute rev = 26 - (s[i] - 'a').
  3. Add rev * (i + 1) to total.
  4. Return total.

Step-by-step example

s = "abc"
  1. 'a' is 0 places after 'a', so rev = 26. Position 1 gives 26, total = 26.
  2. 'b' has rev = 25. Position 2 gives 50, total = 76.
  3. 'c' has rev = 24. Position 3 gives 72, total = 148.
  4. Every letter is counted. Return 148.

Code: Python, Java, C++

1class Solution:
2    def reverseDegree(self, s: str) -> int:
3        total = 0
4        for i, ch in enumerate(s):
5            rev = 26 - (ord(ch) - ord('a'))
6            total += rev * (i + 1)
7        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is visited once and costs a constant amount of arithmetic.

Space

O(1)

Only the running total and the loop index are stored.

Other approaches

Lookup table (time O(n), space O(1))

Precompute a 26-entry array of reversed values and index it with ch - 'a'. It does the same work with a table read instead of a subtraction.

Generator expression (time O(n), space O(1))

In Python, sum((123 - ord(c)) * (i + 1) for i, c in enumerate(s)) computes the same sum in one line, since 123 - ord('a') is 26.

Common mistakes

  • Using 0-indexed positions. The first letter has weight 1, not 0, so multiply by i + 1.
  • Getting the reversal off by one: 'a' is 26 and 'z' is 1, so the formula is 26 - (ch - 'a'), not 25 - (ch - 'a').
  • Using the normal alphabet order ('a' = 1) out of habit.

Frequently asked questions

Can the total overflow a 32-bit integer?

No. The largest possible value is 26 times the sum of 1..1000, which is 26 * 500500 = 13,013,000.

Why is "zaza" worth 160?

'z' is worth 1 and 'a' is worth 26. The products are 1*1, 26*2, 1*3 and 26*4, which add up to 1 + 52 + 3 + 104 = 160.

Is there a closed form?

Not a useful one, because each letter can be anything. You have to read every character, so O(n) is optimal.