Returns the k most frequent elements in the array.
[1,1,1,2,2,3], k=2 → [1,2]
# 🔝 4. Top K Frequent Elements
# Returns the k most frequent elements in the array.
# Builds a frequency hash, sorts it in descending order, and returns the top k keys.
# Time Complexity: O(n log n)
# Why:
# Building frequency hash: O(n)
# Sorting the hash: O(n log n)
# Extracting top k: **O(k)` but dominated by the sort.
def top_k_frequent(nums, k)
freq = nums.tally
freq.sort_by { |_, count| -count }.map(&:first).take(k)
O(n log n)
O(n)