Skip to content

Crack SDE

Most of the content are generated by AI, with human being reviewed, edited, and revised

Menu
  • Home
  • Daily English Story
  • Tech Interviews
  • Cloud Native
  • DevOps
  • Artificial Intelligence
Menu

LeetCode 347 – Top K Frequent Elements

Posted on 02/15/202502/15/2025 by user

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1: Input: nums = [1,1,1,2,2,3], k = 2, Output: [1,2]
Example 2: Input: nums = [1], k = 1, Output: [1]

For LeetCode 347 – Top K Frequent Elements. We will aim to achieve an O(n log k) time complexity, which is the most efficient for this problem.

Key steps to solve this problem:

  1. Count the frequency of each element in the array using a map.
  2. Use a min-heap (priority queue) to keep track of the top k frequent elements. The heap will store pairs of (element, frequency).
  3. Extract the top k elements from the heap.

Code implementation:

package main

import (
	"container/heap"
	"fmt"
)

// Define a type for the min-heap
type Element struct {
	num   int
	freq  int
}

type MinHeap []Element

// Implementing heap.Interface methods
func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].freq < h[j].freq }
func (h MinHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *MinHeap) Push(x interface{}) {
	*h = append(*h, x.(Element))
}

func (h *MinHeap) Pop() interface{} {
	old := *h
	n := len(old)
	item := old[n-1]
	*h = old[0 : n-1]
	return item
}

func topKFrequent(nums []int, k int) []int {
	// Step 1: Build frequency map
	freqMap := make(map[int]int)
	for _, num := range nums {
		freqMap[num]++
	}

	// Step 2: Use a min-heap to store the top k frequent elements
	minHeap := &MinHeap{}
	heap.Init(minHeap)

	// Step 3: Iterate through the frequency map and maintain the heap
	for num, freq := range freqMap {
		heap.Push(minHeap, Element{num, freq})
		if minHeap.Len() > k {
			heap.Pop(minHeap) // Remove the element with the least frequency
		}
	}

	// Step 4: Extract the top k frequent elements from the heap
	result := make([]int, k)
	for i := 0; i < k; i++ {
		result[i] = heap.Pop(minHeap).(Element).num
	}

	return result
}

func main() {
	// Test the function with an example
	nums := []int{1,1,1,2,2,3}
	k := 2
	result := topKFrequent(nums, k)
	fmt.Println(result) // Output: [1, 2]
}

Explanation:

  1. Frequency Map:
    • We first create a frequency map freqMap to count how often each number appears in the input array nums.
  2. Min-Heap:
    • We then use a min-heap to keep track of the top k frequent elements. A heap allows us to efficiently access and remove the least frequent element in O(log k) time.
  3. Heap Operations:
    • We push each element from the frequency map into the heap. If the size of the heap exceeds k, we pop the smallest element (which is the least frequent element so far).
  4. Result Extraction:
    • After maintaining the heap with the top k frequent elements, we extract the elements from the heap into the result array.

Time Complexity:

  • Building the frequency map: O(n), where n is the number of elements in nums.
  • Heap operations: For each unique element in the frequency map, we perform heap operations (push and pop). In the worst case, the heap size is k, so each operation takes O(log k) time. There are at most n unique elements, so the heap operations take O(n log k) time.
  • Final extraction: O(k) to extract k elements from the heap.

Thus, the overall time complexity is O(n log k).

Space Complexity:

  • O(n) for the frequency map.
  • O(k) for the heap. Hence, the total space complexity is O(n + k).

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Related

Recent Posts

  • LC#622 Design Circular Queue
  • Started with OpenTelemetry in Go
  • How Prometheus scrap works, and how to find the target node and get the metrics files
  • How to collect metrics of container, pods, node and cluster in k8s?
  • LC#200 island problem

Recent Comments

  1. another user on A Journey of Resilience

Archives

  • May 2025
  • April 2025
  • February 2025
  • July 2024
  • April 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023

Categories

  • Artificial Intelligence
  • Cloud Computing
  • Cloud Native
  • Daily English Story
  • Database
  • DevOps
  • Golang
  • Java
  • Leetcode
  • Startups
  • Tech Interviews
©2025 Crack SDE | Design: Newspaperly WordPress Theme
Manage Cookie Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
View preferences
{title} {title} {title}