Leetcode "Decode Ways" problem and recursion error
Question:
I am trying to solve the Leetcode Decode Ways problem (https://leetcode.com/problems/decode-ways/). Consider a string with upper case elements from the English alphabet represented by numbers.
So A
maps to 1
, B
maps to 2
, and so on until Z
maps to 26
. Given a string of numbers, how many ways can one decode it to a string of alphabets?
For example, 11106
can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06)
is invalid because 06
cannot be mapped into F
since 6
is different from 06
.
I run into a maximum recursion depth error in Python, even for very short input strings. My solution is below:
def numDecodings(s):
## Case of empty string
if len(s)== 0:
return 1
## Error cases if a zero is in a weird place
for idx, i in enumerate(s):
if idx == 0 and s[idx]=="0":
return 0
if idx > 1 and s[idx-1] not in "12" and s[idx]==0:
return 0
## Recursion
def subProblem(substring):
if len(substring) == 1:
res = 1
else:
res = subProblem(substring[1:])
if (len(substring) > 1) and (substring[0] == "1") or (substring[0] == "2" and (substring[1] in "0123456")):
res += subProblem(substring[2:])
return res
return subProblem(s)
What is causing the unbounded recursion?
Answers:
You aren’t accounting for the case when substring
is empty.
Therefore subProblem()
endlessly calls itself with an empty string as an argument.
I am trying to solve the Leetcode Decode Ways problem (https://leetcode.com/problems/decode-ways/). Consider a string with upper case elements from the English alphabet represented by numbers.
So A
maps to 1
, B
maps to 2
, and so on until Z
maps to 26
. Given a string of numbers, how many ways can one decode it to a string of alphabets?
For example, 11106
can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06)
is invalid because 06
cannot be mapped into F
since 6
is different from 06
.
I run into a maximum recursion depth error in Python, even for very short input strings. My solution is below:
def numDecodings(s):
## Case of empty string
if len(s)== 0:
return 1
## Error cases if a zero is in a weird place
for idx, i in enumerate(s):
if idx == 0 and s[idx]=="0":
return 0
if idx > 1 and s[idx-1] not in "12" and s[idx]==0:
return 0
## Recursion
def subProblem(substring):
if len(substring) == 1:
res = 1
else:
res = subProblem(substring[1:])
if (len(substring) > 1) and (substring[0] == "1") or (substring[0] == "2" and (substring[1] in "0123456")):
res += subProblem(substring[2:])
return res
return subProblem(s)
What is causing the unbounded recursion?
You aren’t accounting for the case when substring
is empty.
Therefore subProblem()
endlessly calls itself with an empty string as an argument.