Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Stack with getMax and max

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Stack with getMax and max. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Razorpay payment workflows may need to process events in stack order while also immediately removing the event with the highest priority. Design a stack that supports normal LIFO operations, constant-time maximum lookup, and efficient removal of the maximum value.

Implement process_stack(operations). Each operation is represented as an array:

  • ["push", value]: Push an integer onto the stack.
  • ["pop"]: Remove and return the top value.
  • ["getMax"]: Return the current maximum without removing it.
  • ["max"]: Remove and return one occurrence of the current maximum. If duplicates exist, any occurrence may be removed.

Return an array containing the results of every pop, getMax, and max operation, in execution order. Inputs will not request pop, getMax, or max when the stack is empty.

Use a max-heap to locate maximum values and a doubly linked representation to unlink a maximum node without scanning the stack. Each pushed value is a distinct node, even when values are equal.

Constraints

  • 1 <= operations.length <= 2 * 10^5
  • -10^9 <= value <= 10^9
  • The total number of pushed values is at most 10^5
  • Every read or removal operation is valid for the current stack state
  • Duplicate values are allowed

Function Signature

def process_stack(operations):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output