Sobes.tech
Junior — Middle

Do you have experience working with the Heap data structure?

sobes.tech AI

Answer from AI

Yes, I have experience working with the Heap data structure in Go. The standard library in Go includes the "container/heap" package, which provides an interface for implementing heaps (usually min-heaps or max-heaps).

A heap is a binary tree that allows efficient retrieval of the minimum (or maximum) element in O(1) and insertion or deletion of elements in O(log n).

Example of using a min-heap in Go:

package main

import (
    "container/heap"
    "fmt"
)

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x interface{}) {
    *h = append(*h, x.(int))
}

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

func main() {
    h := &IntHeap{2, 1, 5}
    heap.Init(h)
    heap.Push(h, 3)
    fmt.Printf("min: %d\n", (*h)[0])
    for h.Len() > 0 {
        fmt.Printf("%d ", heap.Pop(h))
    }
}

This example demonstrates creating a min-heap, adding elements, and extracting the minimum element.

Do you have experience working with the Heap data… - sobes.tech