We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Reverse Degree of a String

Number: 3811

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a string s, calculate its reverse degree. For each character in s, multiply its 1-indexed position in the string by its position in the reversed alphabet (where 'a' is 26, 'b' is 25, …, 'z' is 1). Sum these products to obtain the reverse degree of the string.


Key Insights

  • The reversed alphabetical value for a character can be computed using (27 - normal alphabetical position), where normal alphabetical position is (ord(character) - ord('a') + 1) for example.
  • Multiply each character's reversed value by its position (starting from 1) in the string.
  • A single pass through the string is sufficient to calculate the result.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string because we iterate through the string once. Space Complexity: O(1), since only a few extra variables are used, independent of the length of the string.


Solution

The solution involves iterating over the characters in the string while tracking the index (starting from 1). For each character, determine its reversed alphabetical rank by calculating (27 - (normal alphabetical position)). Multiply this value by the character's index in the string and accumulate the result in a sum. Finally, return the sum as the reverse degree of the string.


Code Solutions

# Python solution for reverse degree of a string.

def reverse_degree_of_string(s):
    total = 0  # Initialize sum for the reverse degree.
    # Iterate through each character along with its 1-indexed position.
    for index, char in enumerate(s, start=1):
        # Calculate normal position: 'a' -> 1, 'b' -> 2, ..., 'z' -> 26.
        normal_position = ord(char) - ord('a') + 1
        # Calculate reversed position: 'a' -> 26, 'b' -> 25, ..., 'z' -> 1.
        reversed_position = 27 - normal_position
        # Multiply the reversed position with the index and accumulate.
        total += index * reversed_position
    return total

# Example usage:
print(reverse_degree_of_string("abc"))  # Expected output: 148.
← Back to All Questions