Count ways to decode digit string
Company: Snapchat
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's skill in dynamic programming and combinatorial reasoning about string partitioning, testing competency in counting valid decodings under constraint handling and edge-case analysis.
Constraints
- 1 <= len(s) <= 100
- s consists only of characters '0'-'9'
- The result fits in a 32-bit signed integer
Examples
Input: ("12",)
Expected Output: 2
Explanation: "AB" (1 2) or "L" (12).
Input: ("226",)
Expected Output: 3
Explanation: "BZ" (2 26), "VF" (22 6), "BBF" (2 2 6).
Input: ("0",)
Expected Output: 0
Explanation: A lone '0' is not a valid code.
Input: ("06",)
Expected Output: 0
Explanation: Leading zero: '0' cannot start a number and '06' is not in [10,26].
Input: ("10",)
Expected Output: 1
Explanation: Only "J" (10); '1' '0' fails because '0' alone is invalid.
Input: ("100",)
Expected Output: 0
Explanation: The second '0' has no valid one- or two-digit decode, so the whole string fails.
Input: ("27",)
Expected Output: 1
Explanation: 27 > 26, so only the split "B" "G" (2 7) works.
Input: ("2101",)
Expected Output: 1
Explanation: Only 2 10 1 -> "BJA"; the embedded '0' forces the pairing 1 0 = 10.
Input: ("1",)
Expected Output: 1
Explanation: Single digit '1' decodes to "A".
Input: ("11106",)
Expected Output: 2
Explanation: 1 1 10 6 ("AAJF") and 11 10 6 ("KJF"); the '0' must pair with the preceding '1'.
Input: ("111111111111111111111111111111111111111111111",)
Expected Output: 1836311903
Explanation: 45 ones; the count follows the Fibonacci recurrence and reaches 1836311903, near the 32-bit signed limit.
Hints
- Let dp[i] be the number of ways to decode the prefix s[:i]. The answer is dp[n].
- From position i you may take one digit (valid only if s[i-1] != '0') contributing dp[i-1], or two digits (valid only if 10 <= s[i-2:i] <= 26) contributing dp[i-2].
- Any '0' that cannot pair with a preceding 1 or 2 makes the whole string undecodable, so the count drops to 0.
- Only dp[i-1] and dp[i-2] are needed, so two rolling variables give O(1) space.