Reverse Degree of a String
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given a string s, calculate its reverse degree.
The reverse degree is calculated as follows:
- For each character, multiply its position in the reversed alphabet (
'a'= 26,'b'= 25, ...,'z'= 1) with its position in the string (1-indexed). - Sum these products for all characters in the string.
Return the reverse degree of s.
Examples
Example 1
Input: s = "abc"
Output: 148
Explanation:
Letter | Index in Reversed Alphabet | Index in String | Product
---|---|---|---
`'a'` | 26 | 1 | 26
`'b'` | 25 | 2 | 50
`'c'` | 24 | 3 | 72
The reversed degree is `26 + 50 + 72 = 148`.
Example 2
Input: s = "zaza"
Output: 160
Explanation:
Letter | Index in Reversed Alphabet | Index in String | Product
---|---|---|---
`'z'` | 1 | 1 | 1
`'a'` | 26 | 2 | 52
`'z'` | 1 | 3 | 3
`'a'` | 26 | 4 | 104
The reverse degree is `1 + 52 + 3 + 104 = 160`.
Constraints
1 <= s.length <= 1000scontains only lowercase English letters.
Solution
Method 1 - Direct Calculation
Intuition
For each character, its reverse alphabet index is 26 - (ord(c) - ord('a')). Multiply this by its 1-based position and sum for all characters.
Approach
Iterate through the string, for each character at position i (1-indexed), compute (26 - (ord(c) - ord('a'))) * i, and sum up.
Code
C++
class Solution {
public:
int reverseDegree(string s) {
int res = 0;
for (int i = 0; i < s.size(); ++i) {
int rev = 26 - (s[i] - 'a');
res += rev * (i + 1);
}
return res;
}
};
Go
func reverseDegree(s string) int {
res := 0
for i := 0; i < len(s); i++ {
rev := 26 - int(s[i]-'a')
res += rev * (i + 1)
}
return res
}
Java
class Solution {
public int reverseDegree(String s) {
int res = 0;
for (int i = 0; i < s.length(); i++) {
int rev = 26 - (s.charAt(i) - 'a');
res += rev * (i + 1);
}
return res;
}
}
Kotlin
class Solution {
fun reverseDegree(s: String): Int {
var res = 0
for (i in s.indices) {
val rev = 26 - (s[i] - 'a')
res += rev * (i + 1)
}
return res
}
}
Python
class Solution:
def reverseDegree(self, s: str) -> int:
return sum((26 - (ord(c) - ord('a'))) * (i + 1) for i, c in enumerate(s))
Rust
impl Solution {
pub fn reverse_degree(s: String) -> i32 {
s.chars().enumerate().map(|(i, c)| (26 - (c as u8 - b'a') as i32) * (i as i32 + 1)).sum()
}
}
TypeScript
function reverseDegree(s: string): number {
let res = 0;
for (let i = 0; i < s.length; i++) {
const rev = 26 - (s.charCodeAt(i) - 'a'.charCodeAt(0));
res += rev * (i + 1);
}
return res;
}
Complexity
- ⏰ Time complexity:
O(n)— single pass through the string. - 🧺 Space complexity:
O(1)— only a few variables are used.