DEV Community

Cover image for DSA Pattern: Ordered Frequency Match
Al Amin
Al Amin

Posted on • Edited on

DSA Pattern: Ordered Frequency Match

πŸš€ 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;
Enter fullscreen mode Exit fullscreen mode

Expected Output:

[5, 10, 2]
Enter fullscreen mode Exit fullscreen mode

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:

  1. Copy the original array
  2. Sort to get the top k
  3. Count those values
  4. 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;
}
Enter fullscreen mode Exit fullscreen mode

🧠 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)