3498. Reverse Degree of a String
Problem Description
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
.
Intuition
The problem requires calculating a unique value, referred to as the reverse degree, for a given string. Understanding this requires two key observations:
-
Reversed Alphabet Position: For each character in the string, determine its position in the reversed alphabet. For instance,
'a'
has the reverse position of 26,'b'
is 25, continuing to'z'
which is 1. This can be simply calculated using26 - (ord(c) - ord('a'))
whereord()
is a function that gives the ASCII value of a character. -
Weighting by Position: Each character's reverse position is weighted by its position in the string itself (1-indexed). This means the earlier a character appears, the more it influences the final sum due to multiplication by its positional index.
By iterating over each character, computing the reverse position, and multiplying by the character's position in the string, we can sum these results to find the reverse degree. The approach is direct as it involves iterating over the string once, making the solution efficient with a time complexity of (O(n)), where (n) is the length of the string. The space complexity is (O(1)) since we only use a fixed amount of additional space regardless of input size.
Solution Approach
The solution employs a simple iterative approach to calculate the reverse degree. Here's how the algorithm is implemented:
-
Initialization: Start by initializing a variable
ans
to 0. This will be used to accumulate the sum of the products of character positions and their corresponding reverse alphabet positions. -
Enumeration Over the String: Use Python's
enumerate()
to iterate over each characterc
in the strings
, also retrieving its positioni
(1-indexed). -
Calculate Reverse Position: For each character, determine its position in the reversed alphabet using the formula
x = 26 - (ord(c) - ord('a'))
. This utilizes theord()
function to convert the character to its ASCII value and then transforms it to the desired reversed position. -
Compute Product and Accumulate: Multiply the reverse position
x
by the character's positioni
and add this product toans
. -
Return the Result: After processing all characters, return the accumulated sum
ans
, which represents the reverse degree.
The entire operation processes each character in a single pass with constant space usage, ensuring efficiency. The implementation effectively captures the described logic:
class Solution:
def reverseDegree(self, s: str) -> int:
ans = 0
for i, c in enumerate(s, 1):
x = 26 - (ord(c) - ord("a"))
ans += i * x
return ans
This solution is optimal for this problem due to its straightforward iteration and calculation, making it both time and space-efficient.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's consider the string s = "abc"
to demonstrate the calculation of its reverse degree using the given solution approach.
-
Initialize the accumulator: Start with
ans = 0
. -
Enumerate through the string:
-
First Character:
c = 'a'
,i = 1
(position in string)- Compute the reverse position:
[ x = 26 - (ord('a') - ord('a')) = 26 ] - Calculate product and update the sum: [ ans += 1 \times 26 = 26 ]
- Compute the reverse position:
-
Second Character:
c = 'b'
,i = 2
(position in string)- Compute the reverse position:
[ x = 26 - (ord('b') - ord('a')) = 25 ] - Calculate product and update the sum: [ ans += 2 \times 25 = 50 ]
- New
ans
value:
[ ans = 26 + 50 = 76 ]
- Compute the reverse position:
-
Third Character:
c = 'c'
,i = 3
(position in string)- Compute the reverse position:
[ x = 26 - (ord('c') - ord('a')) = 24 ] - Calculate product and update the sum: [ ans += 3 \times 24 = 72 ]
- New
ans
value:
[ ans = 76 + 72 = 148 ]
- Compute the reverse position:
-
-
Result: After processing all characters, the final accumulated value
ans
is 148. Thus, the reverse degree of the string "abc" is 148.
The overall procedure highlights how each character's position and reverse alphabet position are used to accumulate the total reverse degree in a single pass.
Solution Implementation
1class Solution:
2 def reverseDegree(self, s: str) -> int:
3 # Initialize the final answer to zero
4 ans = 0
5
6 # Enumerate over the string, starting index at 1
7 for i, char in enumerate(s, 1):
8 # Calculate the distance from 'z' (reverse position in alphabet)
9 reverse_position = 26 - (ord(char) - ord('a'))
10 # Accumulate the weighted reverse position
11 ans += i * reverse_position
12
13 # Return the final accumulated result
14 return ans
15
1class Solution {
2 public int reverseDegree(String s) {
3 int length = s.length(); // Get the length of the string
4 int totalSum = 0; // Initialize the sum result to 0
5
6 // Loop through each character in the string using 1-based index
7 for (int i = 1; i <= length; ++i) {
8 // Calculate the reverse alphabetic value of the current character
9 int reverseValue = 26 - (s.charAt(i - 1) - 'a');
10
11 // Compute the weighted sum using the 1-based index and the reverse value
12 totalSum += i * reverseValue;
13 }
14
15 return totalSum; // Return the computed sum
16 }
17}
18
1#include <string>
2using namespace std;
3
4class Solution {
5public:
6 int reverseDegree(string s) {
7 int n = s.length(); // Get the length of the string
8 int ans = 0; // Initialize the answer variable to accumulate the result
9
10 // Iterate over each character in the string
11 for (int i = 1; i <= n; ++i) {
12 // Calculate x by reversing the alphabet position of the character
13 int x = 26 - (s[i - 1] - 'a');
14 // Multiply the position (i) with x and add to ans
15 ans += i * x;
16 }
17
18 return ans; // Return the accumulated result
19 }
20};
21
1// Function to calculate the "reverse degree" of a string based on letter positions.
2function reverseDegree(s: string): number {
3 let ans = 0; // Initialize the result accumulator to 0.
4
5 // Loop through each character in the string.
6 for (let i = 1; i <= s.length; ++i) {
7 // Calculate the reverse position of the character in the alphabet.
8 const x = 26 - (s.charCodeAt(i - 1) - 'a'.charCodeAt(0));
9
10 // Accumulate the weighted reverse position.
11 ans += i * x;
12 }
13
14 return ans; // Return the calculated reverse degree.
15}
16
Time and Space Complexity
The time complexity of the function reverseDegree
is O(n)
, where n
is the length of the input string s
. This is because the function iterates over each character of the string once, performing a constant amount of work for each character.
The space complexity of the function is O(1)
, as it uses a fixed amount of additional space that does not depend on the size of the input string. The only additional variables used are the integer ans
and the loop variables i
and c
, which occupy constant space.
Learn more about how to find time and space complexity quickly.
How would you design a stack which has a function min
that returns the minimum element in the stack, in addition to push
and pop
? All push
, pop
, min
should have running time O(1)
.
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!