3498. Reverse Degree of a String LeetCode Solution

In this guide, you will get 3498. Reverse Degree of a String LeetCode Solution with the best time and space complexity. The solution to Reverse Degree of a String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Reverse Degree of a String solution in C++
  4. Reverse Degree of a String solution in Java
  5. Reverse Degree of a String solution in Python
  6. Additional Resources
3498. Reverse Degree of a String LeetCode Solution image

Problem Statement of Reverse Degree of a String

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.

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 <= 1000
s contains only lowercase English letters.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

3498. Reverse Degree of a String LeetCode Solution in C++

class Solution {
 public:
  int reverseDegree(string s) {
    int ans = 0;
    for (int i = 0; i < s.length(); ++i) {
      const int reversePos = 26 - (s[i] - 'a');
      ans += reversePos * (i + 1);
    }
    return ans;
  }
};
/* code provided by PROGIEZ */

3498. Reverse Degree of a String LeetCode Solution in Java

class Solution {
  public int reverseDegree(String s) {
    int ans = 0;
    for (int i = 0; i < s.length(); ++i) {
      final int reversePos = 26 - (s.charAt(i) - 'a');
      ans += reversePos * (i + 1);
    }
    return ans;
  }
}
// code provided by PROGIEZ

3498. Reverse Degree of a String LeetCode Solution in Python

class Solution:
  def reverseDegree(self, s: str) -> int:
    return sum((26 - (ord(c) - ord('a'))) * (i + 1)
               for i, c in enumerate(s))
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.