Decode Ways

Algorithms
Medium
Stripe
97.7K views

A message containing letters A-Z is being encoded to numbers. Given a non-empty string `s` containing only digits, determine the total number of ways to decode it.

Why Interviewers Ask This

Stripe asks 'Decode Ways' to evaluate a candidate's mastery of dynamic programming and their ability to handle edge cases involving zero handling and invalid sequences. This problem tests whether you can recognize overlapping subproblems and construct an optimal solution without redundant calculations, reflecting Stripe's need for engineers who write efficient, bug-free code under pressure.

How to Answer This Question

1. Clarify constraints immediately: confirm the string contains only digits and identify if leading zeros or empty strings are possible inputs. 2. Identify the recurrence relation: analyze how a single digit (1-9) or two digits (10-26) contribute to the total ways at any index. 3. Choose your DP strategy: decide between a recursive approach with memoization or an iterative bottom-up approach using space optimization. 4. Handle edge cases explicitly: discuss how to treat '0' when it cannot stand alone and must be part of '10' or '20'. 5. Walk through a concrete example like '226' step-by-step to demonstrate your logic before writing code. 6. Analyze time and space complexity: explain why your solution is O(n) time and O(1) space, highlighting efficiency for large inputs typical in fintech systems.

Key Points to Cover

  • Recognizing that this is a classic Dynamic Programming problem requiring state tracking
  • Explicitly handling the edge case where '0' cannot be decoded on its own
  • Validating the two-digit combination range strictly between 10 and 26
  • Demonstrating space optimization by reducing the DP array to two variables
  • Articulating the O(n) time and O(1) space complexity clearly

Sample Answer

To solve the Decode Ways problem efficiently, I would use a dynamic programming approach. First, I'd validate the input; if the string starts with '0', the answer is immediately zero since no valid mapping exists. For th…

Common Mistakes to Avoid

  • Forgetting to check if the string starts with '0', which makes the entire sequence invalid
  • Incorrectly including numbers greater than 26 as valid two-digit combinations
  • Using recursion without memoization, leading to exponential time complexity TLE
  • Overlooking the case where '0' appears in the middle of the string (e.g., '10')
  • Failing to initialize base cases correctly for the first one or two characters

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 57 Stripe questions