Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Implement a Priority Queue

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

Your question is Implement a Priority Queue. 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

Nio Robotics uses priority-based scheduling for robot tasks. Implement a priority queue that always returns the task with the smallest priority value, while preserving insertion order when priorities are equal.

Create a function that processes a sequence of operations and returns the results of all query operations.

Formal Specification

Implement priority_queue(operations).

Each operation is one of the following lists:

  • ['push', value, priority]: Insert value with an integer priority. Lower values represent higher priority.
  • ['pop']: Remove and return the highest-priority value. Return None if the queue is empty.
  • ['peek']: Return the highest-priority value without removing it. Return None if the queue is empty.
  • ['is_empty']: Return True if the queue contains no values, otherwise return False.

Return a list containing the result of every pop, peek, and is_empty operation in their original order. The queue must be stable: values with equal priorities are returned in insertion order.

Constraints

  • 1 <= len(operations) <= 10^5
  • Values are integers or strings
  • Priorities are integers in [-10^9, 10^9]
  • At most 10^5 values are present at any time
  • Equal-priority values must be returned in insertion order

Function Signature

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