← Uber bank

Uber · Question 68 · Dynamic Programming

Decode Ways

Dynamic ProgrammingPythoncode⏱ O(n)💾 O(n)
Product-based

Problem

Given a digit string, return the number of ways to decode it using mapping '1' → 'A', ..., '26' → 'Z'.

Approach

DP:  If last digit is valid (1 – 9), add dp[i - 1]  If last two digits are 10 – 26, add dp[i - 2]

Time O(n)Space O(n)

How it works

  1. 1dp[i] counts ways for the prefix.
  2. 2A valid single digit extends dp[i-1].
  3. 3A valid pair 10-26 extends dp[i-2].

Sample input / output

Input:
226
Output:
3

Constraints

1 <= s.length <= 100; digits only; leading-zero rules apply.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 3Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyes↻ repeat↻ repeatyesnoSTARTsn = len(s)dp = [0] * (n + 1)dp[0] = 1dp[1] = 0 if s[0] == '0'else 1for i in range(2, n +1)one = int(s[i - 1:i])two = int(s[i - 2:i])if 1 <= one <= 9dp[i] += dp[i - 1]if 10 <= two <= 26dp[i] += dp[i - 2]RETURN dp[n]DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)s = next(it)print(numDecodings(s))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/22

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits