MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Queue Class with Explanation

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

Problem Statement

Implement a Queue class with enqueue/dequeue. DEQ on empty prints EMPTY.

Input Format

First line q. Next q lines: ENQ x or DEQ.

Output Format

Outputs for DEQ.

Constraints

q

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php class Queue{ private $a=[]; private $h=0; function enq($x){ $this->a[]=$x; } function deq(){ if($this->h>=count($this->a)) return null; $v=$this->a[$this->h]; $this->h++; return $v; } } $inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN))); if(!$inputLines || trim($inputLines[0])==='') exit; $q=intval($inputLines[0]); $qu=new Queue(); $output=[]; for($i=1;$i<=$q;$i++){ $tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''), 2); $cmd=$tokens[0] ?? ''; if($cmd==='ENQ') $qu->enq($tokens[1] ?? ''); else{ $v=$qu->deq(); $output[] = ($v===null)?'EMPTY':$v; } } echo implode(PHP_EOL,$output); ?>

Output Example

Input:
6 DEQ ENQ 1 ENQ 2 DEQ DEQ DEQ
Output:
EMPTY 1 2 EMPTY

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 Next