Magicsheet logo

Decode Ways II

Hard
45.1%
Updated 6/1/2025

Asked by 2 Companies

Decode Ways II

What is this problem about?

The Decode Ways II interview question is a significantly harder extension of the original problem. In addition to digits '0'-'9', the string can contain the wildcard character ''. An '' can represent any digit from '1' to '9'. You need to find the total number of ways to decode this string, modulo 10^9 + 7. This Decode Ways II coding problem requires handling a large number of conditional combinations.

Why is this asked in interviews?

Meta and PhonePe use this to test a candidate's mastery of Dynamic Programming and combinatorics. It evaluates if you can meticulously account for every possible replacement of '*' in both single-digit and two-digit decoding scenarios. It’s a test of high-level logical rigor and ability to manage modular arithmetic in a complex DP transition.

Algorithmic pattern used

This follows the String, Dynamic Programming interview pattern.

  • Similar to the basic version, dp[i] depends on dp[i-1] and dp[i-2].
  • Single Character (s[i-1]):
    • If '*', there are 9 ways (1-9).
    • If '1'-'9', there is 1 way.
    • If '0', there are 0 ways.
  • Double Character (s[i-2, i-1]):
    • If "**": 15 ways (11-19, 21-26).
    • If "*digit": depends if digit <= 6 (2 ways: '1' or '2') or > 6 (1 way: '1').
    • If "digit*": depends if digit is '1' (9 ways) or '2' (6 ways).

Example explanation

Input: "1*"

  1. Single digit '1': 1 way. dp[1] = 1.
  2. Now consider the full string:
    • Decoding "" as single: '' can be 1-9 (9 ways). Total = 9 * dp[1] = 9.
    • Decoding "1*" as double: can be 11, 12, 13, 14, 15, 16, 17, 18, 19 (9 ways). Total = 9 * dp[0] = 9.
  3. Final: 9 + 9 = 18 ways.

Common mistakes candidates make

  • Combinatorial errors: Miscounting the number of valid two-digit combinations involving ''. For example, thinking "2" has 9 ways (forgetting 27, 28, 29 are invalid).
  • Modulo placement: Forgetting to apply the modulo at every addition, which can lead to integer overflow before the final result.
  • Space complexity: Not realizing that O(1) space is possible by only keeping track of the previous two DP values.

Interview preparation tip

Use a helper function to calculate the number of ways to decode one or two characters. This keeps your main DP loop clean and makes it much easier to debug the specific logic for wildcards.

Similar Questions