How to implement K stacks in an array, with best storage usage (stacks should be dynamic)?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, if you’re only worried about space usage, and don’t care that stack operations can take
O(N), you can use the array’s first few cells to manage the stacks:Array[0]– the end of stack 0Array[1]– the end of stack 1…
Array[K-1]= the end of stack KStack
nstarts atArray[n-1]and ends atArray[n](exclusive - [Array[n-1], Array[n]) ).If Array[n-1]==Array[n]the stack is empty. The first stack starts at K, so at firstArray[0]..Array[K-1] = KWhen you push into a stack, just move all the elements in the stacks below it, and adjust the pointers respectively.
It’ll get you the memory constraint you need.