Skip to content

Instantly share code, notes, and snippets.

@ja7ad
Created January 5, 2026 07:51
Show Gist options
  • Select an option

  • Save ja7ad/672ce649f94a03c1091903cf1be07012 to your computer and use it in GitHub Desktop.

Select an option

Save ja7ad/672ce649f94a03c1091903cf1be07012 to your computer and use it in GitHub Desktop.
An algorithmic challenge to filter and sort the most frequent words from a slice, prioritizing frequency and then lexicographical order.
package main
import (
"fmt"
"reflect"
"sort"
)
// Challenge: Top K Frequent Words
//
// Objective:
// Given an array of strings `words` and an integer `k`, return the `k` most frequent strings.
//
// Sorting Rules:
// 1. Sort by frequency from highest to lowest.
// 2. If two words have the same frequency, sort them by lexicographical order (alphabetically).
//
// Example:
// Input: ["i", "love", "coding", "i", "love", "go"], k = 2
// Output: ["i", "love"]
// Explanation: "i" and "love" are the two most frequent words.
// Note: "i" comes before "love" due to higher frequency? No, both have 2. "i" comes before "love" alphabetically.
func TopKFrequent(words []string, k int) []string {
// TODO: Implement the logic here
return []string{}
}
func main() {
// --- Test Case 1 ---
input1 := []string{"i", "love", "golang", "i", "love", "coding"}
k1 := 2
expected1 := []string{"i", "love"}
// Both have count 2. 'i' comes before 'love' alphabetically.
// --- Test Case 2 ---
input2 := []string{"orange", "apple", "banana", "apple", "orange", "apple", "banana"}
k2 := 3
expected2 := []string{"apple", "banana", "orange"}
// apple: 3, banana: 2, orange: 2. (banana comes before orange alphabetically)
fmt.Println("--- Running Tests ---")
// Execution & Validation for Case 1
result1 := TopKFrequent(input1, k1)
if reflect.DeepEqual(result1, expected1) {
fmt.Println("✅ Test 1 Passed")
} else {
fmt.Printf("❌ Test 1 Failed.\n Expected: %v\n Got: %v\n", expected1, result1)
}
// Execution & Validation for Case 2
result2 := TopKFrequent(input2, k2)
if reflect.DeepEqual(result2, expected2) {
fmt.Println("✅ Test 2 Passed")
} else {
fmt.Printf("❌ Test 2 Failed.\n Expected: %v\n Got: %v\n", expected2, result2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment