Reverse Degree of a String - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "abc"
Output: 148
💡 Note: a=26×1=26, b=25×2=50, c=24×3=72. Total: 26+50+72=148
Example 2 — Single Character
$ Input: s = "z"
Output: 1
💡 Note: z has reverse value 1, position 1: 1×1=1
Example 3 — Repeated Characters
$ Input: s = "aa"
Output: 78
💡 Note: First a: 26×1=26, second a: 26×2=52. Total: 26+52=78

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters only

Visualization

Tap to expand
Reverse Degree of a String INPUT String s = "abc" 'a' pos: 1 'b' pos: 2 'c' pos: 3 Reverse Alphabet Values 'a' = 26 'b' = 25 'c' = 24 Formula: rev_val = 27 - (char - 'a' + 1) sum += rev_val * position ALGORITHM STEPS 1 Initialize sum = 0 Set result to zero 2 Process 'a' at pos 1 26 * 1 = 26 3 Process 'b' at pos 2 25 * 2 = 50 4 Process 'c' at pos 3 24 * 3 = 72 Calculation Summary Char Rev Pos Product 'a' 26 1 26 'b' 25 2 50 'c' 24 3 72 FINAL RESULT Sum of all products: 26 + 50 + 72 = 148 OK - Output: 148 Reverse Degree Calculated return 148; Key Insight: The reverse alphabet value can be calculated as: rev_value = 27 - (char_code - 'a' + 1) = 26 - (char_code - 'a') This gives 'a'=26, 'b'=25, ..., 'z'=1. Multiply each by its 1-indexed position and sum all products. Time Complexity: O(n) where n is the length of the string. Space Complexity: O(1). TutorialsPoint - Reverse Degree of a String | Formula-Based Calculation
Asked in
Google 15 Microsoft 12
12.0K Views
Medium Frequency
~8 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen