Skip to content
Reverse Degree of a String

Reverse Degree of a String

June 29, 2026

Platform: LeetCode
Difficulty Level: Easy
Link: reverse degree of a string

Problem

Input

  • s: string

Goal

  • Return reverse degree of s

Constraints

  • 1 <= s.length <= 1000
  • s contains only lowercase english letters

Concept

Consider alphabet positions:
a = 1, b = 2, c = 3, d = 4, e = 5. . . . . . x = 24, y = 25, z = 26.

Consider reversed alphabet positions:
a = 26, b = 25, c = 24, d = 23, e = 22 . . . . . . x = 3, y = 2, z = 1.

Consider 1-indexed string:
s = ‘abc’
Index: a -> 1, b -> 2, c -> 3

Reverse Degree of string is the sum of the products of reversed alphabet position and position in the string.

So Reverse Degree of s is:

ReverseDegree(s)=i=1ni(27pos(si))forsi{a, b, c, , z} \text{ReverseDegree}(s) = \sum_{i=1}^{n} i \cdot (27 - \mathrm{pos}(s_i)) \quad \text{for} \quad s_i \in \{\text{a, b, c, } \dots, \text{ z}\}

Here,
n n -> length of the string
i i -> position of the character in the string
pos(si) \mathrm{pos}(s_i) -> postion of the character in the alphabet series
(27pos(si)) (27 - \mathrm{pos}(s_i)) -> position of the character in the reverse alphabet series

For s = ‘abc’,
ReverseDegree = 1 * (27 - 1) + 2 * (27 - 2) + 3 * (27 - 3) = 26 + 50 + 72 = 148

Examples

Example 1:

Input: s = “abc”

Output: 148

Example 2:

Input: s = “zaza”

Output: 160

Solution

reverse_degree.py
class Solution:
    def reverseDegree(self, s: str) -> int:
        rd = 0

        for i in range(len(s)):
            pos_str = i + 1 # here i starts from 0
            pos_rev_series = 27 - (ord(s[i]) - 96)
            
            rd = rd + pos_str * pos_rev_series
        
        return rd

Here, ord() is a function in python that returns the ASCII value of the input character.

Considering the constraint that the string will only contain lowercase english letters a-z, the ASCII values will be in the range [97, 122].

Subtracting 96 from the ASCII values,
a = 97 - 96 = 1, b = 98 - 96 = 2, c = 99 - 96 = 3, …… y = 121 - 96 = 25, z = 122 - 96 = 26
This will give us the positions in the range [1, 26].

Since we want the positions in reverse order, we subtract the positions from 27.
a = 27 - 1 = 26, b = 27 - 2 = 25, c = 27 - 3 = 24, …… y = 27 - 25 = 2, z = 27 - 1 = 26
This will give the position in the range [26, 1].

Complexity Analysis

Let n be the length of the string.

Time

  • traversing the characters of the string once = O(n) O(n)

Time = O(n) O(n)

Space

  • no extra space used

Space = O(1) O(1)

Comments

  • Important part here is to understand ASCII values.
Last updated on • DharminChothani