0

I was solving the Game of Two Stack problem on HackerRank and I am unsure of why my recursive python algorithm is failing some of the test cases.

https://www.hackerrank.com/challenges/game-of-two-stacks

My code is

def twoStacks(maxSum, a, b):
    # Write your code here
    res, a_index, b_index = 0, 0, 0
    return recur(res, a_index, b_index, maxSum, a, b)
    
def recur(res, a_i, b_i, maxSum, a, b):
    if maxSum < 0:
        return res-1
    res += 1
    if a_i < len(a) and b_i < len(b):
        return max(recur(res, a_i+1, b_i, maxSum - a[a_i], a, b),recur(res, a_i, b_i+1, maxSum - b[b_i], a, b))
    elif a_i < len(a):
        return recur(res, a_i+1, b_i, maxSum - a[a_i], a, b)
    elif b_i < len(b):
        return recur(res, a_i, b_i+1, maxSum - b[b_i], a, b)
    return res-1

My intention is to increment pointers (a_index and b_index) to simulate the popping of the top element from the stack. The recursive function will terminate when maxSum is less than 0. While the pointers are less than the length of their respective stacks, I will check the possibility of popping from either stack A or B.

I am failing test case 8-13 due to runtime error and test case 2-3 due to timeout. I understand there are other algorithms to solve this problem, but would like to understand why my recursive answer is incorrect.

Ryan Pan
  • 1
  • 1
  • Is it possible that you are getting a stack overflow error? Check this question: https://stackoverflow.com/questions/3323001/what-is-the-maximum-recursion-depth-in-python-and-how-to-increase-it?rq=1 – Pete Jan 13 '23 at 21:28
  • What is your runtime error? It's easy to easy why your run out of time. You solve "I've taken one from A and one from B" separately from "I've taken one from B and one' from A". It gets worse and worse the deeper you go. – Frank Yellin Jan 13 '23 at 21:29
  • This problem can be solved a lot simpler. How many can I take from A if I don't take any from B. Now let me take one from B; how many A's do I have to put back. I'll take another from B; how many more A's do I have to put back. – Frank Yellin Jan 13 '23 at 21:31
  • Thank you for all your response and for helping me to understand the constraints of my code better. I will try the approach suggested! – Ryan Pan Jan 14 '23 at 04:16

0 Answers0