3498. Reverse Degree of a String
- String
- Simulation
TIME
O(n)
SPACE
O(1)
Intuition
The definition is already the algorithm. The only translation needed is from a character to its reversed-alphabet position: 'a' is offset 0 from 'a' and should map to 26, 'z' is offset 25 and should map to 1, so the value is 26 - offset.
Approach
- Walk the string with a 0-based index
i. - For character
c, computeweight = 26 - (ord(c) - ord('a'))andposition = i + 1. - Accumulate
weight * position.
Complexity
- Time: O(n)
- Space: O(1)
Edge Cases
- Single character
"a"→ 26,"z"→ 1 - All
'z'→ sum of positionsn(n+1)/2 - Maximum value:
n = 1000, all'a'→26 * 1000 * 1001 / 2 = 13,013,000, fits in a 32-bitint
Code
class Solution:
def reverseDegree(self, s: str) -> int:
"""
3498. Reverse Degree of a String
Time: O(n)
Space: O(1)
"""
total = 0
for i, ch in enumerate(s):
weight = 26 - (ord(ch) - ord("a"))
total += weight * (i + 1)
return total/**
* 3498. Reverse Degree of a String
* Time: O(n)
* Space: O(1)
*/
class Solution {
public int reverseDegree(String s) {
int total = 0;
for (int i = 0; i < s.length(); i++) {
int weight = 26 - (s.charAt(i) - 'a');
total += weight * (i + 1);
}
return total;
}
}