PHP Program to Sort by Frequency with Explanation
PHP
Medium
PHP Arrays
34 views
1 min read
97 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around sort, frequency, line. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Sort array values by frequency (desc), and by value (asc) when tie.
Input Format
First n. Next line n integers.
Output Format
One line sorted.
Constraints
n
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);
$a=[]; $freq=[];
for($k=0;$k<$n;$k++){
$v=intval($tokens[$i++] ?? 0);
$a[]=$v;
if(!isset($freq[$v])) $freq[$v]=0;
$freq[$v]++;
}
usort($a,function($x,$y) use ($freq){
$fx=$freq[$x]; $fy=$freq[$y];
if($fx===$fy) return $x <=> $y;
return $fy <=> $fx;
});
echo implode(' ',array_map('strval',$a));
?>
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
Sort array values by frequency (desc), and by value (asc) when tie.
Input / Output
Input
First n. Next line n integers.
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);
$a=[]; $freq=[];
for($k=0;$k<$n;$k++){
$v=intval($tokens[$i++] ?? 0);
$a[]=$v;
if(!isset($freq[$v])) $freq[$v]=0;
$freq[$v]++;
}
usort($a,function($x,$y) use ($freq){
$fx=$freq[$x]; $fy=$freq[$y];
if($fx===$fy) return $x <=> $y;
return $fy <=> $fx;
});
echo implode(' ',array_map('strval',$a));
?>
Solutions (0)
No solutions submitted yet. Be the first!