MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Task Manager (Priority Queue) with Explanation

PHP Hard PHP OOP Basics 31 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around priority queue, pop, task. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Commands: ADD name p, POP. POP removes and prints the task with highest priority; if tie, the one added earlier. If empty, print EMPTY.

Input Format

First line q. Next q lines.

Output Format

Outputs for POP.

Constraints

q

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php class TaskManager{ private $queue; private $order=0; function __construct(){ $this->queue=new SplPriorityQueue(); $this->queue->setExtractFlags(SplPriorityQueue::EXTR_DATA); } function addTask($name,$priority){ $this->queue->insert($name, [$priority, -$this->order]); $this->order++; } function popTask(){ if($this->queue->isEmpty()) return null; return $this->queue->extract(); } } $inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN))); if(!$inputLines || trim($inputLines[0])==='') exit; $q=intval($inputLines[0]); $tasks=new TaskManager(); $output=[]; for($lineNo=1;$lineNo<=$q;$lineNo++){ $tokens=preg_split('/\\s+/', trim($inputLines[$lineNo] ?? '')); $cmd=$tokens[0] ?? ''; if($cmd==='ADD'){ $tasks->addTask($tokens[1] ?? '', intval($tokens[2] ?? 0)); }else{ $name=$tasks->popTask(); $output[] = ($name===null) ? 'EMPTY' : $name; } } echo implode(PHP_EOL,$output); ?>

Output Example

Input:
7 POP ADD clean 2 ADD build 5 ADD test 5 POP POP POP
Output:
EMPTY build test clean

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev