NC-go
LeetCode cheat sheet — Go standard library reference.
slices pkg.go.dev ↗
// --- Iteration ---
for v := range slices.Values(s) // iter.Seq over values
for i, v := range slices.All(s) // iter.Seq2 forward
for i, v := range slices.Backward(s) // iter.Seq2 reverse
for chunk := range slices.Chunk(s, 2) // sub-slices of up to n elements
// --- Search ---
slices.Contains(s, 2)
slices.ContainsFunc(s, func(n int) bool { return n > 5 })
slices.Index(s, 8) // first index or -1
slices.IndexFunc(s, func(n int) bool { return n > 5 })
n, found := slices.BinarySearch(s, "Bill") // s must be sorted
n, found = slices.BinarySearchFunc(s, "bill", strings.Compare)
// --- Comparison ---
slices.Equal(s1, s2)
slices.EqualFunc(s1, s2, func(a, b string) bool { ... })
slices.Compare(s1, s2) // -1, 0, 1
slices.CompareFunc(s1, s2, func(a, b string) int { ... })
// --- Sorting ---
slices.Sort(s)
slices.SortFunc(s, func(a, b string) int { return strings.Compare(a, b) })
slices.SortStableFunc(s, func(a, b string) int { ... })
slices.IsSorted(s)
slices.IsSortedFunc(s, func(a, b string) int { ... })
sorted := slices.Sorted(seq) // iter.Seq → new sorted slice
sorted = slices.SortedFunc(seq, cmp)
// --- Min / Max ---
slices.Max(s)
slices.MaxFunc(s, func(a, b T) int { ... })
slices.Min(s)
slices.MinFunc(s, func(a, b T) int { ... })
// --- Building / Collecting ---
s2 := slices.Clone(s) // shallow copy
s = slices.Grow(s, 10) // ensure cap for 10 more elements
s = slices.Clip(s) // trim cap to len
concat := slices.Concat(s1, s2, s3)
s = slices.Collect(seq) // iter.Seq → new slice
s = slices.AppendSeq(s, seq) // append iter.Seq values to s
// --- Modification ---
s = slices.Insert(s, 1, "Bill", "Billie") // insert at index
s = slices.Delete(s, 1, 4) // delete [1,4)
s = slices.DeleteFunc(s, func(v string) bool { return v == "x" })
s = slices.Replace(s, 1, 3, "Bill", "Billie", "Cat") // replace [1,3)
slices.Reverse(s)
s = slices.Compact(s) // remove consecutive duplicates
s = slices.CompactFunc(s, func(a, b string) bool { ... })
// --- Native slice essentials ---
s := make([]int, 5) // len=5, cap=5
s := make([]int, 0, 10) // len=0, cap=10
s = append(s, 1, 2, 3)
s = append(s, other...) // spread append
s[1:3] // sub-slice [1,3), shares memory
copy(dst, src) // copy min(len(dst),len(src)) elements; returns n
len(s)
cap(s)
// 2D slice:
grid := make([][]int, rows)
for i := range grid { grid[i] = make([]int, cols) }
// Stack (using slice):
stack = append(stack, v) // push
v, stack = stack[len(stack)-1], stack[:len(stack)-1] // pop
// Queue (using slice):
queue = append(queue, v) // enqueue
v, queue = queue[0], queue[1:] // dequeue (use container/list for perf)
maps pkg.go.dev ↗
// --- Iteration ---
for k, v := range maps.All(m)
for k := range maps.Keys(m)
for v := range maps.Values(m)
for _, k := range slices.Sorted(maps.Keys(m)) { ... } // sorted keys
// --- Building / Collecting ---
m2 := maps.Clone(m)
maps.Copy(dst, src) // merge src into dst, overwriting conflicts
m := maps.Collect(seq) // iter.Seq2[K,V] → new map
maps.Insert(m, seq) // add pairs from iter.Seq2 into m
m := maps.Collect(slices.All(s)) // []T → map[int]T
// --- Comparison ---
maps.Equal(m1, m2)
maps.EqualFunc(m1, m2, func(v1, v2 T) bool { ... })
// --- Deletion ---
delete(m, key) // built-in: delete single key
maps.DeleteFunc(m, func(k K, v V) bool { return v == 0 })
// --- Native map essentials ---
m := make(map[string]int)
m := map[string]int{"a": 1}
m[key] = val
val := m[key] // zero value if missing
val, ok := m[key] // ok=false if missing
delete(m, key)
len(m)
iter pkg.go.dev ↗
// --- Types ---
type iter.Seq[V any] // func(yield func(V) bool)
type iter.Seq2[K, V any] // func(yield func(K, V) bool)
// --- Range over ---
for v := range seq { ... }
for k, v := range seq2 { ... }
// --- Pull-style (manual control) ---
next, stop := iter.Pull(seq)
defer stop()
v, ok := next() // ok=false when exhausted
next2, stop2 := iter.Pull2(seq2)
defer stop2()
k, v, ok := next2()
strings pkg.go.dev ↗
// --- Search ---
strings.Contains(s, "foo")
strings.ContainsAny(s, "aeiou")
strings.ContainsRune(s, 'x')
strings.ContainsFunc(s, unicode.IsDigit)
strings.HasPrefix(s, "Go")
strings.HasSuffix(s, "er")
strings.Index(s, "sub") // first index or -1
strings.LastIndex(s, "sub")
strings.IndexByte(s, 'x')
strings.IndexRune(s, 'k')
strings.IndexAny(s, "aeiou")
strings.IndexFunc(s, unicode.IsUpper)
strings.LastIndexFunc(s, unicode.IsNumber)
strings.Count(s, "e") // non-overlapping occurrences
// --- Split / Cut ---
strings.Split(s, ",")
strings.SplitN(s, ",", 2) // at most 2 parts
strings.SplitAfter(s, ",") // keep separator at end of each part
strings.Fields(s) // split on any whitespace
strings.FieldsFunc(s, unicode.IsSpace)
// iterator variants (no allocation):
for part := range strings.SplitSeq(s, ",") { ... }
for word := range strings.FieldsSeq(s) { ... }
for line := range strings.Lines(s) { ... }
before, after, found := strings.Cut(s, "=") // split around first sep
after, found = strings.CutPrefix(s, "Go")
before, found = strings.CutSuffix(s, "er")
// --- Transform ---
strings.ToUpper(s)
strings.ToLower(s)
strings.Replace(s, "old", "new", 2) // n=-1 = all
strings.ReplaceAll(s, "old", "new")
strings.Map(func(r rune) rune { return r + 1 }, s)
strings.Repeat(s, 3)
strings.Join([]string{"a", "b", "c"}, ", ")
r := strings.NewReplacer("<", "<", ">", ">")
r.Replace(s) // efficient multi-substitution
// --- Trim ---
strings.TrimSpace(s)
strings.Trim(s, "!¡") // any char in cutset, both ends
strings.TrimLeft(s, "!¡")
strings.TrimRight(s, "!¡")
strings.TrimPrefix(s, "Go")
strings.TrimSuffix(s, "er")
strings.TrimFunc(s, unicode.IsPunct)
// --- Compare ---
strings.Compare(a, b) // -1, 0, 1
strings.EqualFold(s, t) // case-insensitive ==
// --- Builder ---
var b strings.Builder
b.Grow(64)
b.WriteString("hello")
b.WriteByte(' ')
b.WriteRune('世')
b.Len()
b.Reset()
result := b.String()
// --- Reader ---
r := strings.NewReader(s)
r.Len() // unread bytes remaining
strconv pkg.go.dev ↗
// --- int ↔ string ---
n, err := strconv.Atoi("42")
s := strconv.Itoa(42)
n, err = strconv.ParseInt("FF", 16, 64) // base, bitSize
n, err = strconv.ParseUint("255", 10, 64)
s = strconv.FormatInt(255, 16) // → "ff"
s = strconv.FormatInt(255, 2) // → "11111111"
s = strconv.FormatUint(255, 10)
// --- float ↔ string ---
f, err := strconv.ParseFloat("3.14", 64)
s = strconv.FormatFloat(3.14, 'f', 2, 64) // "3.14"
// format chars: 'f' decimal 'e' scientific 'g' shortest 'b' binary exponent
// --- bool ↔ string ---
b, err := strconv.ParseBool("true") // "1","t","T","TRUE","true" → true
s = strconv.FormatBool(true) // → "true"
// --- quote / unquote ---
s = strconv.Quote("hello\nworld") // → `"hello\nworld"`
s2, err = strconv.Unquote(`"hello"`)
// --- append variants (no allocation) ---
buf = strconv.AppendInt(buf, 255, 16)
buf = strconv.AppendFloat(buf, 3.14, 'f', 2, 64)
math pkg.go.dev ↗
// --- Constants ---
math.MaxInt math.MinInt
math.MaxInt32 math.MinInt32
math.MaxFloat64
math.Pi math.E math.Phi
// --- Rounding ---
math.Floor(x) // round down
math.Ceil(x) // round up
math.Round(x) // round to nearest (half away from zero)
math.Trunc(x) // round toward zero
// --- Arithmetic ---
math.Abs(x)
math.Sqrt(x)
math.Cbrt(x) // cube root
math.Pow(x, y)
math.Exp(x) // e^x
math.Exp2(x) // 2^x
math.Mod(x, y) // floating-point remainder
math.Remainder(x, y) // IEEE 754 remainder
math.Hypot(x, y) // sqrt(x²+y²), overflow-safe
// --- Log ---
math.Log(x) // natural
math.Log2(x)
math.Log10(x)
math.Log1p(x) // accurate Log(1+x) for small x
// --- Min / Max ---
math.Max(x, y)
math.Min(x, y)
math.Dim(x, y) // max(x-y, 0)
// --- Special values ---
math.Inf(1) // +Inf
math.Inf(-1) // -Inf
math.NaN()
math.IsInf(x, 1) // 1=+Inf, -1=-Inf, 0=either
math.IsNaN(x)
math.Signbit(x) // true if negative
// --- Trig (geometry problems) ---
math.Sin(x) math.Cos(x) math.Tan(x)
math.Asin(x) math.Acos(x) math.Atan(x)
math.Atan2(y, x) // angle from origin to (x,y)
math/bits pkg.go.dev ↗
// --- Bit counting ---
bits.OnesCount(x) // popcount — number of set bits
bits.OnesCount8/16/32/64(x)
bits.Len(x) // bits needed: floor(log2(x))+1; Len(0)=0
bits.Len8/16/32/64(x)
bits.LeadingZeros(x) // count of leading 0s
bits.LeadingZeros64(x)
bits.TrailingZeros(x) // index of lowest set bit
bits.TrailingZeros64(x)
// --- Rotation / Reversal ---
bits.RotateLeft(x, k) // rotate left by k; negative k = rotate right
bits.RotateLeft64(x, k)
bits.Reverse(x) // reverse all bits
bits.ReverseBytes(x) // reverse byte order
// --- Overflow-safe arithmetic ---
sum, carry := bits.Add64(x, y, 0)
diff, borrow := bits.Sub64(x, y, 0)
hi, lo := bits.Mul64(x, y) // full 128-bit product
quo, rem := bits.Div64(0, x, y)
// --- Common bitmask patterns ---
x & (x-1) // clear lowest set bit
x & (-x) // isolate lowest set bit
x | (x+1) // set lowest clear bit
1 << k // bit mask for position k
x >> k & 1 // test bit k
x | (1 << k) // set bit k
x &^ (1 << k) // clear bit k (&^ is AND NOT)
x ^ (1 << k) // toggle bit k
unicode pkg.go.dev ↗
// --- Classification ---
unicode.IsDigit(r) // 0-9 and Unicode decimal digits
unicode.IsLetter(r)
unicode.IsLower(r)
unicode.IsUpper(r)
unicode.IsTitle(r)
unicode.IsSpace(r) // \t \n \r \f \v space and Unicode spaces
unicode.IsPunct(r)
unicode.IsNumber(r) // broader: includes ², ③, etc.
unicode.IsMark(r)
unicode.IsControl(r)
unicode.IsPrint(r)
unicode.IsGraphic(r)
// --- Conversion ---
unicode.ToUpper(r)
unicode.ToLower(r)
unicode.ToTitle(r)
// --- ASCII fast-paths (avoid unicode overhead) ---
r >= 'a' && r <= 'z' // is lowercase ASCII
r >= 'A' && r <= 'Z' // is uppercase ASCII
r >= '0' && r <= '9' // is ASCII digit
r - 'a' + 'A' // to upper (ASCII only)
r - 'A' + 'a' // to lower (ASCII only)
int(r - '0') // digit rune → int value
sort pkg.go.dev ↗
// --- Convenience (in-place) ---
sort.Ints(a)
sort.Float64s(a)
sort.Strings(a)
// --- Custom comparator ---
sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
sort.SliceStable(s, func(i, j int) bool { ... }) // preserves equal order
sort.Sort(data) // data implements sort.Interface
sort.Stable(data)
// sort.Interface:
type sort.Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
// --- Check ---
sort.IntsAreSorted(a)
sort.IsSorted(data)
// --- Search (binary, monotone predicate) ---
i := sort.Search(n, func(i int) bool { return arr[i] >= target })
// returns smallest i in [0,n) where f(i)=true; returns n if none found
// arr must be sorted / predicate must be false-then-true
i := sort.SearchInts(a, v) // shorthand
i = sort.SearchFloat64s(a, v)
i = sort.SearchStrings(a, v)
// --- Reverse ---
sort.Sort(sort.Reverse(sort.IntSlice(a)))
container/heap pkg.go.dev ↗
// Implement heap.Interface (5 methods):
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] } // flip > for max-heap
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *MinHeap) Pop() any {
old := *h; n := len(old)
x := old[n-1]; *h = old[:n-1]; return x
}
// Usage:
h := &MinHeap{3, 1, 4, 1, 5}
heap.Init(h) // O(n) heapify
heap.Push(h, 2)
top := heap.Pop(h).(int) // removes and returns min
(*h)[0] // peek min without removing
heap.Remove(h, i) // remove element at index i
heap.Fix(h, i) // re-heapify after modifying element at i
// Pair/struct heap pattern:
type Item struct { val, priority int }
type PQ []Item
func (h PQ) Less(i, j int) bool { return h[i].priority < h[j].priority }
// ... rest of interface same as above
container/list pkg.go.dev ↗
// Doubly linked list — classic for LRU Cache
l := list.New()
e1 := l.PushBack(1) // append; returns *Element
e2 := l.PushFront(0) // prepend; returns *Element
l.PushBackList(other) // append all of other
l.PushFrontList(other)
l.InsertBefore(99, e1) // insert 99 before e1
l.InsertAfter(99, e1) // insert 99 after e1
l.MoveToFront(e1)
l.MoveToBack(e1)
l.MoveBefore(e1, e2)
l.MoveAfter(e1, e2)
l.Remove(e1) // remove element, returns e1.Value
l.Len()
l.Front() // first *Element or nil
l.Back() // last *Element or nil
e.Value // interface{} — cast: e.Value.(int)
e.Next()
e.Prev()
// Forward iteration:
for e := l.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value.(int))
}
// Backward:
for e := l.Back(); e != nil; e = e.Prev() { ... }