Reverse Degree of a String (LeetCode 3498): Solution and Explanation
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
- Set
total = 0. - For each index
i, computerev = 26 - (s[i] - 'a'). - Add
rev * (i + 1)tototal. - Return
total.
Step-by-step example
s = "abc"
- 'a' is 0 places after 'a', so rev = 26. Position 1 gives 26, total = 26.
- 'b' has rev = 25. Position 2 gives 50, total = 76.
- 'c' has rev = 24. Position 3 gives 72, total = 148.
- 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 total1class Solution {
2 public int reverseDegree(String s) {
3 int total = 0;
4 for (int i = 0; i < s.length(); i++) {
5 int rev = 26 - (s.charAt(i) - 'a');
6 total += rev * (i + 1);
7 }
8 return total;
9 }
10}1class Solution {
2public:
3 int reverseDegree(string s) {
4 int total = 0;
5 for (int i = 0; i < (int) s.size(); i++) {
6 int rev = 26 - (s[i] - 'a');
7 total += rev * (i + 1);
8 }
9 return total;
10 }
11};Time and space complexity
O(n)
Each character is visited once and costs a constant amount of arithmetic.
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'), not25 - (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.