Top K Frequent Elements

Returns the k most frequent elements in the array.

Medium

Examples

Example 1: [1,1,1,2,2,3], k=2 → [1,2]

Implementation

Ruby


  # 🔝 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)

Complexity Analysis

Time Complexity: O(n log n)
Space Complexity: O(n)

Patterns & Techniques

Problem Details

Category: Array Hashing Examples
Difficulty: Medium
Module: ArrayHashingExamples
Method: top_k_frequent
← Back to Array Hashing Examples