Queue Rotation
PHP
Hard
5 views
Problem Description
Commands: PUSH x, POP, ROTATE k (move first to end k times). Print final queue (space-separated).
Input Format
First line q. Next q lines.
Output Format
Final queue line.
Sample Test Case
Input:
6
PUSH 1
PUSH 2
PUSH 3
ROTATE 2
POP
PUSH 4
Official Solution
<?php
$inputLines=preg_split('/\\R/', trim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$q=intval($inputLines[0]);
$qarr=[]; $head=0;
for($i=1;$i<=$q;$i++){
$parts=preg_split('/\\s+/', trim($inputLines[$i] ?? ''), 2);
$cmd=$parts[0] ?? '';
if($cmd==='PUSH') $qarr[] = $parts[1] ?? '';
elseif($cmd==='POP'){
if($head<count($qarr)) $head++;
}elseif($cmd==='ROTATE'){
$k=intval($parts[1] ?? 0);
$len=count($qarr)-$head;
if($len>0){
$k = $k % $len;
for($t=0;$t<$k;$t++){
$first=$qarr[$head];
$head++;
$qarr[]=$first;
}
}
}
}
$res=array_slice($qarr,$head);
echo implode(' ',$res);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!