KatInterview

Simulate a Printer Queue with Priority Levels

Stacks & QueuesAuto-graded · 15 test cases
MediumAuto-gradedStacks & Queuesqueuesimulationgreedy

Last updated

Tests queue simulation by processing print jobs where higher-priority jobs preempt lower-priority ones, requiring candidates to track position and reorder the queue correctly.

Printer Queue Simulation

A shared office printer processes jobs using the following rules:

  1. The printer inspects the job at the front of the queue.
  2. If any job remaining in the queue (including the front job itself) has a strictly higher priority, the front job is moved to the back of the queue.
  3. Otherwise, the front job is printed (removed from the queue).
  4. This repeats until the queue is empty.

Each print job has an id (unique non-negative integer) and a priority (integer 1–10, where 10 is highest).

You are given a list of jobs as [id, priority] pairs in their initial queue order (index 0 is the front), and a target job id.

Return the 1-based position in the print order at which the job with the given target_id is printed.

Constraints

  • 1 ≤ len(jobs) ≤ 2000
  • Each job is represented as a two-element list [id, priority].
  • 0 ≤ id ≤ 10^6; all ids are unique.
  • 1 ≤ priority ≤ 10
  • target_id is guaranteed to be the id of one of the jobs in the list.
  • The function must return the exact 1-based print position of the target job.

Examples

Example 1

Input: printer_queue_position([[1, 3], [2, 5], [3, 3], [4, 1]], 1)

Output: 3

Example 2

Input: printer_queue_position([[10, 2], [20, 2], [30, 2]], 20)

Output: 2

Example 3

Input: printer_queue_position([[7, 1], [8, 10], [9, 1]], 7)

Output: 3

Hints

Hint 1

Use a collections.deque so you can cheaply pop from the front and append to the back.

Hint 2

To efficiently check 'is there any job with higher priority still in the queue?', maintain a sorted structure or frequency count of current priorities.

Hint 3

Increment a counter each time a job is actually printed; when the printed job's id equals target_id, return that counter.