PHP Program to Top K Frequent Numbers with Explanation
PHP
Hard
PHP Functions
32 views
1 min read
104 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around line, frequent, one. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Given n numbers and k, print the k most frequent numbers. If frequencies tie, smaller number first.
Input Format
One line: n k. Next line n integers.
Output Format
One line k integers.
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);
$k=intval($tokens[$i++] ?? 0);
$freq=[];
for($t=0;$t<$n;$t++){
$v=intval($tokens[$i++] ?? 0);
if(!isset($freq[$v])) $freq[$v]=0;
$freq[$v]++;
}
function topK($freq,$k){
$arr=[];
foreach($freq as $v=>$c) $arr[] = [$v,$c];
usort($arr,function($a,$b){
if($a[1]===$b[1]) return $a[0] <=> $b[0];
return $b[1] <=> $a[1];
});
$output=[];
for($i=0;$i<min($k,count($arr));$i++) $output[] = strval($arr[$i][0]);
return $output;
}
$res=topK($freq,$k);
echo implode(' ',$res);
?>
Output Example
Input:
8 3
1 2 2 3 3 3 4 4
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 n numbers and k, print the k most frequent numbers. If frequencies tie, smaller number first.
Input / Output
Input
One line: n k. Next line n integers.
Output
One line k integers.
Examples
Input:
8 3
1 2 2 3 3 3 4 4
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);
$k=intval($tokens[$i++] ?? 0);
$freq=[];
for($t=0;$t<$n;$t++){
$v=intval($tokens[$i++] ?? 0);
if(!isset($freq[$v])) $freq[$v]=0;
$freq[$v]++;
}
function topK($freq,$k){
$arr=[];
foreach($freq as $v=>$c) $arr[] = [$v,$c];
usort($arr,function($a,$b){
if($a[1]===$b[1]) return $a[0] <=> $b[0];
return $b[1] <=> $a[1];
});
$output=[];
for($i=0;$i<min($k,count($arr));$i++) $output[] = strval($arr[$i][0]);
return $output;
}
$res=topK($freq,$k);
echo implode(' ',$res);
?>
Solutions (0)
No solutions submitted yet. Be the first!