genericheap

package module
v0.0.0-...-6dfc88c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 26, 2025 License: MIT Imports: 2 Imported by: 0

README

Go Generic Heap

A clean, generic heap implementation for Go that makes heap operations simple and type-safe. Perfect for coding interviews and production use.

Go Version License Go Report Card

Features

  • 🚀 Generic: Works with any type using Go 1.21+ generics
  • 🔒 Type-safe: No interface{} casting needed
  • ⚡ Simple API: Just define your comparison function
  • 🎯 Interview-friendly: Perfect for coding interviews
  • 📦 Zero dependencies: Uses only Go standard library
  • 🧪 Well-tested: Comprehensive test coverage

Installation

go get github.com/SachinHg/go-generic-heap

Quick Start

package main

import (
    "fmt"
    "github.com/SachinHg/go-generic-heap"
)

func main() {
    // Max heap (highest values first)
    maxHeap := genericheap.IntHeap(true)
    maxHeap.PushItem(100)
    maxHeap.PushItem(70)
    maxHeap.PushItem(90)
    
    fmt.Println(maxHeap.Peek()) // 100
    
    // Min heap (lowest values first)
    minHeap := genericheap.IntHeap(false)
    minHeap.PushItem(100)
    minHeap.PushItem(70)
    minHeap.PushItem(90)
    
    fmt.Println(minHeap.Peek()) // 70
}

Usage Examples

Custom Struct Heaps
type PriceEntry struct {
    Commodity string
    Price     int
}

// Max heap by price
priceHeap := genericheap.New[PriceEntry](func(a, b PriceEntry) bool {
    return a.Price > b.Price
})

priceHeap.PushItem(PriceEntry{"Gold", 100})
priceHeap.PushItem(PriceEntry{"Silver", 70})

fmt.Println(priceHeap.Peek()) // {Commodity: "Gold", Price: 100}
Complex Priority Heaps
type Task struct {
    Name     string
    Priority int
    Deadline int
}

// Higher priority first, then earlier deadline
taskHeap := genericheap.New[Task](func(a, b Task) bool {
    if a.Priority != b.Priority {
        return a.Priority > b.Priority
    }
    return a.Deadline < b.Deadline
})
Built-in Type Heaps
// Integer heaps
intMaxHeap := genericheap.IntHeap(true)   // Max heap
intMinHeap := genericheap.IntHeap(false)  // Min heap

// Float heaps
floatMaxHeap := genericheap.FloatHeap(true)   // Max heap
floatMinHeap := genericheap.FloatHeap(false) // Min heap

// String heaps
stringMaxHeap := genericheap.StringHeap(true)   // Max heap
stringMinHeap := genericheap.StringHeap(false) // Min heap

API Reference

Core Functions
Function Description
New[T](less func(a, b T) bool) *Heap[T] Create new heap with comparison function
IntHeap(max bool) *Heap[int] Create integer heap (true=max, false=min)
FloatHeap(max bool) *Heap[float64] Create float heap
StringHeap(max bool) *Heap[string] Create string heap
ComparableHeap[T cmp.Ordered](max bool) *Heap[T] Create heap for comparable types
Heap Operations
Method Description Time Complexity
PushItem(item T) Add item to heap O(log n)
PopItem() T Remove and return top item O(log n)
Peek() T Get top item without removing O(1)
IsEmpty() bool Check if heap is empty O(1)
Size() int Get number of elements O(1)
Clear() Remove all elements O(1)
ToSlice() []T Get copy of all elements O(n)

Interview Examples

Commodity Prices (Max Heap)
priceHeap := genericheap.New[PriceEntry](func(a, b PriceEntry) bool {
    return a.Price > b.Price
})
Task Scheduling (Priority + Deadline)
taskHeap := genericheap.New[Task](func(a, b Task) bool {
    if a.Priority != b.Priority {
        return a.Priority > b.Priority
    }
    return a.Deadline < b.Deadline
})
Court Booking (Min Heap by Next Free Time)
courtHeap := genericheap.New[Court](func(a, b Court) bool {
    return a.NextFree < b.NextFree
})

Why This Package?

The Problem

Go's standard container/heap package requires manual implementation of the heap interface:

// Traditional approach - verbose and error-prone
type MaxHeap []int
func (h MaxHeap) Len() int            { return len(h) }
func (h MaxHeap) Less(i, j int) bool  { return h[i] > h[j] }
func (h MaxHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x interface{})  { *h = append(*h, x.(int)) }
func (h *MaxHeap) Pop() interface{}   { /* complex implementation */ }
The Solution

With this package, you get clean, type-safe heap operations:

// Clean approach - simple and type-safe
maxHeap := genericheap.IntHeap(true)
maxHeap.PushItem(100)
maxHeap.PushItem(70)
fmt.Println(maxHeap.Peek()) // 100

Performance

  • Time Complexity: O(log n) for insert/delete, O(1) for peek
  • Space Complexity: O(n) for storage
  • Zero Runtime Overhead: Generics are compile-time only
  • Memory Efficient: No unnecessary allocations

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Built with Go 1.21+ generics
  • Uses Go's standard container/heap package internally
  • Inspired by the need for cleaner heap implementations in coding interviews

Star History

Star History Chart

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Heap

type Heap[T any] struct {
	// contains filtered or unexported fields
}

Heap is a generic heap implementation that works with any comparable type

func ComparableHeap

func ComparableHeap[T cmp.Ordered](max bool) *Heap[T]

ComparableHeap creates a heap for any comparable type Uses Go's built-in cmp.Compare for comparison For max heap: ComparableHeap[T](true) - larger values first For min heap: ComparableHeap[T](false) - smaller values first

func FloatHeap

func FloatHeap(max bool) *Heap[float64]

FloatHeap creates a heap for floats For max heap: FloatHeap(true) - higher values first For min heap: FloatHeap(false) - lower values first

func IntHeap

func IntHeap(max bool) *Heap[int]

IntHeap creates a heap for integers For max heap: IntHeap(true) - higher values first For min heap: IntHeap(false) - lower values first

func New

func New[T any](less func(a, b T) bool) *Heap[T]

New creates a new heap with the given comparison function For max heap: func(a, b T) bool { return a > b } For min heap: func(a, b T) bool { return a < b }

func PriorityHeap

func PriorityHeap[T any](priority func(a, b T) bool) *Heap[T]

PriorityHeap creates a heap for items with priority The comparison function should return true if a has higher priority than b

func StringHeap

func StringHeap(max bool) *Heap[string]

StringHeap creates a heap for strings For max heap: StringHeap(true) - lexicographically larger first For min heap: StringHeap(false) - lexicographically smaller first

func (*Heap[T]) Clear

func (h *Heap[T]) Clear()

Clear removes all elements from the heap

func (*Heap[T]) IsEmpty

func (h *Heap[T]) IsEmpty() bool

IsEmpty returns true if the heap is empty

func (*Heap[T]) Len

func (h *Heap[T]) Len() int

Len returns the number of elements in the heap

func (*Heap[T]) Less

func (h *Heap[T]) Less(i, j int) bool

Less compares two elements using the provided comparison function

func (*Heap[T]) Peek

func (h *Heap[T]) Peek() T

Peek returns the top item without removing it

func (*Heap[T]) Pop

func (h *Heap[T]) Pop() interface{}

Pop removes and returns the top element from the heap

func (*Heap[T]) PopItem

func (h *Heap[T]) PopItem() T

PopItem removes and returns the top item from the heap (type-safe wrapper)

func (*Heap[T]) Push

func (h *Heap[T]) Push(x interface{})

Push adds an element to the heap

func (*Heap[T]) PushItem

func (h *Heap[T]) PushItem(item T)

PushItem adds an item to the heap (type-safe wrapper)

func (*Heap[T]) Size

func (h *Heap[T]) Size() int

Size returns the number of elements in the heap

func (*Heap[T]) Swap

func (h *Heap[T]) Swap(i, j int)

Swap swaps two elements in the heap

func (*Heap[T]) ToSlice

func (h *Heap[T]) ToSlice() []T

ToSlice returns a copy of all elements in the heap

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL