π PHP Pattern: How I Beat 100% with a Simple "Ordered Frequency Match" Trick
TL;DR: I solved a problem that required picking the top k
largest elements while maintaining their original input order β no sorting, no heap, just native PHP and smart looping. Itβs a neat trick I now use in real-world projects too!
π― The Problem
Given an array of numbers, return the top k
largest elements, but preserve their original input order.
Example:
$nums = [3, 1, 5, 10, 2];
$k = 3;
Expected Output:
[5, 10, 2]
Why? Because those are the top 3 largest, and they appear in that order in the original list.
π Naive Solutions
Most solutions either:
- Sort the array and lose original order
- Use complex heap structures (like
SplPriorityQueue
) - Or re-sort by index after slicing top values
All of them work. But I wanted better β faster and cleaner.
π‘ The Insight
We can:
- Copy the original array
- Sort to get the top
k
- Count those values
- Walk the original array again and "stock out" each value as needed
β The Final Code
function maxSubsequence($nums, $k) {
if ($k === count($nums)) return $nums;
$copy = $nums;
rsort($copy);
$freq = array_count_values(array_splice($copy, 0, $k));
$result = [];
foreach ($nums as $num) {
if (!empty($freq[$num])) {
$result[] = $num;
$freq[$num]--;
if (count($result) === $k) break;
}
}
return $result;
}
π§ Pattern Name: Ordered Frequency Match
Think of this like a controlled inventory:
- You have a "stock" of top elements
- You want to consume them, but in original order
- So you match frequency and reduce it as you go
β¨ Summary: Where to Apply This Pattern
Pattern Need | Apply This? |
---|---|
Top K elements + original order | β Yes |
Frequency controlled loop | β Yes |
"Use only if available" | β Yes |
Limited quota-based logic | β Yes |
Stack/history simulation with limit | β οΈ Maybe |
π Real-World Uses
- Show top-selling items in catalog order
- Enforce cart limits (e.g. 2 max discounted items)
- Apply user quotas in original login order
- Filter search history against top terms
β Why This Rocks
- No fancy data structures
- Native PHP β fast and readable
- Preserves original order
- Beats 100% in LeetCode (true story!)
π Final Thoughts
Donβt underestimate simple patterns.
This one is a mix of:
array_count_values()
- Controlled iteration
- Smart early breaks (
count($res) === $k
)
And it works like a charm!
π¬ Drop a comment if youβve used similar tricks in your projects!
Or if you want me to show this in Laravel, JavaScript, or React state-based filtering.
Top comments (0)