23. Total Decoding Messages
The problem can be found at the following link: Question Link
Problem Description
A message containing letters A-Z is encoded using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"Given a numeric string digits, return the total number of ways the message can be decoded.
Examples
Example 1:
Input:
digits = "123"Output:
3Explanation:
"123" can be decoded as:
"ABC"(1, 2, 3)"LC"(12, 3)"AW"(1, 23)
Example 2:
Input:
Output:
Explanation:
"90" is not a valid encoding because '0' cannot be decoded.
Example 3:
Input:
Output:
Explanation:
"05" is not valid because leading zero makes it an invalid encoding.
Constraints:
$(1 \leq \text{digits.length} \leq 10^3)$
My Approach:
Optimized Space Dynamic Programming
Algorithm Steps:
Edge Case Handling: If
digits[0] == '0', return 0 because it cannot be decoded.Use Two Variables (
prev2andprev1):prev1: Stores the number of ways to decode up to indexi-1.prev2: Stores the number of ways to decode up to indexi-2.
Iterate Over the String:
If
digits[i]is not'0', addprev1to the current count.If
digits[i-1]digits[i]forms a valid number (10-26), addprev2.
Update
prev2andprev1for the next iteration.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(N), as we iterate through the string once.
Expected Auxiliary Space Complexity: O(1), since we use only two variables.
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
π Visitor Count
Last updated