3498 LeetCode problem solution
LeetCode problem link: 3498. Reverse Degree of a String
LeetCode 3498 problem description
This is Easy level problem
Given a string s, calculate its reverse degree.
The reverse degree is calculated as follows:
1. For each character, multiply its position in the reversed alphabet ('a' = 26, 'b' = 25, ..., 'z' = 1) with its position in the string (1-indexed).
2. Sum these products for all characters in the string.
Return the reverse degree of s.
Example 1:
Input: s = "abc"
Output: 148
Explanation:
The reversed degree is 26 + 50 + 72 = 148.
Example 2:
Input: s = "zaza"
Output: 160
Explanation:
The reverse degree is 1 + 52 + 3 + 104 = 160.
Constraints:
1 <= s.length <= 1000scontains only lowercase English letters.
LeetCode 3498 problem: solution explanation
We need to iterate through the string once and calculate each character's contribution to the result.
The reversed alphabet position can be calculated directly as 'z' - s[i] + 1, where 'a' becomes 26 and 'z' becomes 1.
Multiply this value by i + 1 because string positions are 1-indexed and then add each product to the final sum.
LeetCode 3498 problem: complexity
Time complexity: O(n)
Space complexity: O(1)
LeetCode 3498 C++ solution
class Solution {
public:
int reverseDegree(string s) {
int ans = 0;
for(int i = 0; i < s.size(); i++) ans += ('z' - s[i] + 1) * (i + 1);
return ans;
}
};LeetCode 3498 Java solution
In Java, just like in C++, we can directly subtract char values, so 'z' - s.charAt(i) + 1 gives 26 for 'a', 25 for 'b', ..., and 1 for 'z'.
class Solution {
public int reverseDegree(String s) {
int ans = 0;
for(int i = 0; i < s.length(); i++) ans += ('z' - s.charAt(i) + 1) * (i + 1);
return ans;
}
}LeetCode 3498 JavaScript solution
Here 123 is ASCII code of z: z = 'z'.charCodeAt(0) + 1, and 97, for example, is ASCII code of a. And so on. Then:
'a' = 123 - 97 = 26
'b' = 123 - 98 = 25
...
'z' = 123 - 122 = 1var reverseDegree = function(s) {
let ans = 0;
for(let i = 0; i < s.length; i++) ans += (123 - s.charCodeAt(i)) * (i + 1);
return ans;
};LeetCode 3498 TypeScript solution
function reverseDegree(s: string): number {
let ans = 0;
for(let i = 0; i < s.length; i++) ans += (123 - s.charCodeAt(i)) * (i + 1);
return ans;
}LeetCode 3498 Python solution
class Solution:
def reverseDegree(self, s: str) -> int:
ans = 0
for i, char in enumerate(s): ans += (123 - ord(char)) * (i + 1)
return ans