DDSA Solutions

3498. Reverse Degree of a String

Problem Overview

Reverse degree scores each character by how far it sits from the end of the alphabet, then weights that score by its 1-based index.

Intuition

Reverse degree scores each character by how far it sits from the end of the alphabet, then weights that score by its 1-based index. Summing those products in one left-to-right pass is the whole answer.

Algorithm

  1. 1Initialize ans to 0.
  2. 2For each index i from 0 to n-1, let reversePos = 26 - (s[i] - a).
  3. 3Add reversePos * (i + 1) to ans.
  4. 4Return ans.

Example Walkthrough

Input: s = "abc"

  1. 1.a contributes 26 * 1 = 26.
  2. 2.b contributes 25 * 2 = 50.
  3. 3.c contributes 24 * 3 = 72, for a total of 148.

Output: 148

Common Pitfalls

  • Positions are 1-indexed in the formula, so multiply by i + 1.
  • Reverse rank of a is 26, of z is 1.
  • No sorting or extra structures are needed; a single pass is enough.
  • Use int carefully only if constraints grow; current constraints fit in 32-bit.
3498.cs
C#
// Approach: For each 1-indexed position i, add (26 - (s[i]-'a')) * i.
// That is the letter's reverse alphabet rank times its position.
// Complexity: O(n) time, O(1) extra space. Already optimal.
public class Solution
{
    public int ReverseDegree(string s)
    {
        int ans = 0;
        for (int i = 0; i < s.Length; i++)
            ans += (26 - (s[i] - 'a')) * (i + 1);
        return ans;
    }
}
Was this solution helpful?

Related Problems