Sort by Frequency
PHP
Medium
4 views
Problem Description
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.
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!
No comments yet. Start the discussion!