PHP Program to Merge Two Sorted Arrays with Explanation
PHP
Medium
PHP Functions
49 views
1 min read
105 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around merge, two, sorted. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Given two sorted arrays, merge them using a function and print the merged list.
Input Format
Line1 n m. Line2 n ints. Line3 m ints.
Output Format
One line merged.
Constraints
n+m
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$i=0;
$n=intval($tokens[$i++] ?? 0);
$m=intval($tokens[$i++] ?? 0);
$a=[]; $b=[];
for($k=0;$k<$n;$k++) $a[] = intval($tokens[$i++] ?? 0);
for($k=0;$k<$m;$k++) $b[] = intval($tokens[$i++] ?? 0);
function merge2($a,$b){
$i=0; $j=0; $output=[];
while($i<count($a) && $j<count($b)){
if($a[$i]<=$b[$j]) $output[]=$a[$i++];
else $output[]=$b[$j++];
}
while($i<count($a)) $output[]=$a[$i++];
while($j<count($b)) $output[]=$b[$j++];
return $output;
}
$res=merge2($a,$b);
echo implode(' ',array_map('strval',$res));
?>
Output Example
Input:
3 4
1 4 9
2 3 8 10
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).
Solution Guide
Problem
Given two sorted arrays, merge them using a function and print the merged list.
Input / Output
Input
Line1 n m. Line2 n ints. Line3 m ints.
Examples
Input:
3 4
1 4 9
2 3 8 10
Details
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).
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$i=0;
$n=intval($tokens[$i++] ?? 0);
$m=intval($tokens[$i++] ?? 0);
$a=[]; $b=[];
for($k=0;$k<$n;$k++) $a[] = intval($tokens[$i++] ?? 0);
for($k=0;$k<$m;$k++) $b[] = intval($tokens[$i++] ?? 0);
function merge2($a,$b){
$i=0; $j=0; $output=[];
while($i<count($a) && $j<count($b)){
if($a[$i]<=$b[$j]) $output[]=$a[$i++];
else $output[]=$b[$j++];
}
while($i<count($a)) $output[]=$a[$i++];
while($j<count($b)) $output[]=$b[$j++];
return $output;
}
$res=merge2($a,$b);
echo implode(' ',array_map('strval',$res));
?>
Solutions (0)
No solutions submitted yet. Be the first!