MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Book Borrowing with Explanation

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

Problem Statement

Commands: ADD book, BORROW book, RETURN book. Track if a book is available. BORROW unavailable prints FAIL.

Input Format

First line q. Next q lines.

Output Format

Outputs for BORROW.

Constraints

q

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php class Library{ private $avail=[]; function add($b){ $this->avail[$b]=true; } function borrow($b){ if(isset($this->avail[$b]) && $this->avail[$b]===true){ $this->avail[$b]=false; return 'OK'; } return 'FAIL'; } function ret($b){ if(isset($this->avail[$b])) $this->avail[$b]=true; } } $inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN))); if(!$inputLines || trim($inputLines[0])==='') exit; $q=intval($inputLines[0]); $lib=new Library(); $output=[]; for($i=1;$i<=$q;$i++){ $tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''), 2); $cmd=$tokens[0] ?? ''; $arg=$tokens[1] ?? ''; if($cmd==='ADD') $lib->add($arg); elseif($cmd==='BORROW') $output[]=$lib->borrow($arg); elseif($cmd==='RETURN') $lib->ret($arg); } echo implode(PHP_EOL,$output); ?>

Output Example

Input:
6 ADD Dune BORROW Dune BORROW Dune RETURN Dune BORROW Dune BORROW Other
Output:
OK FAIL OK FAIL

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