Tutorialspoint
Problem
Solution
Submissions

Decode Ways

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to determine the number of ways to decode a string of digits. A message containing letters from A-Z can be encoded into numbers using the mapping: 'A' -> 1, 'B' -> 2, ..., 'Z' -> 26. To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse mapping. For example, "11106" can be mapped to "AAJF" (1 1 10 6) or "KJF" (11 10 6). Return the number of ways to decode the given string.

Example 1
  • Input: s = "12"
  • Output: 2
  • Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
Example 2
  • Input: s = "226"
  • Output: 3
  • Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Constraints
  • 1 ≤ s.length ≤ 100
  • s contains only digits and may contain leading zero(s)
  • Time Complexity: O(n)
  • Space Complexity: O(n)
StringsNumberGoogleGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming to solve this problem
  • Create a dp array where dp[i] represents the number of ways to decode the substring s[0...i-1]
  • For each position, check if the current digit is valid (not '0') and if the last two digits form a valid number (between 10 and 26)
  • Handle the special case of '0' carefully, as it can't be decoded on its own
  • The final answer is dp[n], where n is the length of the string

Steps to solve by this approach:

 Step 1: Handle edge cases - empty string or string starting with '0'.
 Step 2: Create a dp array of size n+1 to store the number of ways to decode each prefix of the string.
 Step 3: Initialize dp[0] = 1 (base case - one way to decode empty string) and dp[1] = 1 if s[0] is not '0'.
 Step 4: For each position i from 2 to n:
 Step 5: If the current digit s[i-1] is not '0', add dp[i-1] to dp[i] (can be decoded independently).
 Step 6: Check if the last two digits form a valid number between 10 and 26. If yes, add dp[i-2] to dp[i].
 Step 7: Return dp[n] which represents the total number of ways to decode the entire string.

Submitted Code :