DEV Community

Kyle Grah
Kyle Grah

Posted on

🐹 Series: Leetcoding in Go β€” slices.Backward()

As Go engineers, we take pride in the language and our experience with it. Yet, many Go developers default to Python in technical interviews, often believing it's more interview-friendly.

But if you're applying to a Go-heavy team, there's no better way to win over your future coworkers than by showing you're fluent in Go β€” even under pressure.

There's a common perception that interviewing in Go puts you at a disadvantage compared to interviewing in Python. Python has built-ins such as reversed()β€”great for saving time and lines of code.

slices.Backward(): https://pkg.go.dev/slices#Backward (introduced in 1.23)

The following is a valid solution to leetcode 347: https://leetcode.com/problems/top-k-frequent-elements/description/

This solution:

  • Tracks frequencies in a single map pass
  • Groups numbers into frequency β€œbuckets”
  • Uses slices.Backward() to iterate from highest frequency down
  • Stops early once k results are collected
import "slices"

func topKFrequent(nums []int, k int) []int {
    frequencies := make(map[int]int)

    for _, n := range nums {
        frequencies[n]++
    }

    buckets := make([][]int, len(nums)+1)
    for n, freq := range frequencies {
        buckets[freq] = append(buckets[freq], n)
    }

    results := make([]int, 0, k) 

// Reverse-iterate the buckets slice. Comparable to Python's reversed.
    for _, b := range slices.Backward(buckets) {
        if len(results) == k {
            return results
        }

        if len(b) <= k-len(results) {
            results = append(results, b...)
        } else {
            results = append(results, b[:k-len(results)]...)
        }
    }

    return results
}
Enter fullscreen mode Exit fullscreen mode

Compared to for i := len(nums) - 1; i >= 0; i-- {}, using slices.Backward() is easier to read, more expressive of intent, and shows fluency with Go’s modern standard library.

Top comments (0)