Level: BeginnerGo Programs

Go Coding Interview Programs: LRU, Sliding Window and DP

Updated 20 min read
Go Coding Interview Programs featured image: LRU cache and DP output

Go coding interview programs are the problems companies give you in a live coding round, where you must write correct code, explain it and state its speed. In this post, you will write fourteen of the most asked problems with their exact output and the logic explained in comments, covering an LRU cache, sliding window, two pointers, intervals and dynamic programming.

This post closes the Go Programs series, so it uses ideas from every level. Make sure you are comfortable with the Go map programs, Go linked list programs and Go sorting programs. All programs were tested on Go 1.27.

What are Go Coding Interview Programs?

Go coding interview programs are short, self-contained problems with a clear input and output. The interviewer cares about three things: a correct answer, a clean explanation and a good time and space complexity.

Think of a driving test. Driving from A to B is not enough. The examiner also watches how you check mirrors, signal and park. In an interview, how you reach the answer matters as much as the answer.

Why Go Coding Interview Programs Matter

Most product companies still run at least one data structure round, even for backend roles.

  • Patterns repeat: about ten patterns cover most questions you will see.
  • Go is a good fit: slices, maps and simple syntax keep solutions short.
  • Real work: caches, rate limits and interval merges appear in real backend code.
  • Confidence: practising the common set makes new problems feel familiar.

How to Solve Go Coding Interview Programs

Use the same five steps for every problem. First, repeat the problem and ask about edge cases. Next, write a slow but correct idea. Then find the pattern that makes it faster. After that, write the code while you talk. Finally, test it with a small example and state the Big O.

Go coding interview programs diagram showing the five steps to solve a coding problem
Clarify, start simple, find the pattern, code while talking, then test and state the complexity.

The table below maps common question words to the pattern that usually solves them.

If the question saysTry this patternExample in this post
Longest or shortest substringSliding windowProgram 2
Sorted array, pair or tripleTwo pointersPrograms 7 to 9
Overlapping rangesSort, then mergeProgram 5
Number of ways or minimum costDynamic programmingPrograms 10 to 12
Get and put in O(1)Map plus linked listProgram 1

Design Go Coding Interview Programs

These first Go coding interview programs ask you to design a small data structure, which is common in backend rounds.

Program 1: LRU Cache

package main

import (
    "container/list"
    "fmt"
)

// entry is one key and value stored in the cache.
type entry struct {
    key, value int
}

// LRU keeps the most recently used items at the front of a list.
// The map finds a list element in O(1), the list reorders in O(1).
type LRU struct {
    capacity int
    order    *list.List            // a doubly linked list from the standard library
    items    map[int]*list.Element // key -> its element in the list
}

// NewLRU creates an empty cache that can hold capacity items.
func NewLRU(capacity int) *LRU {
    return &LRU{capacity: capacity, order: list.New(), items: map[int]*list.Element{}}
}

// Get returns the value for key, or -1 if the key is not in the cache.
func (cache *LRU) Get(key int) int {
    element, ok := cache.items[key] // ok is true if the key was found
    if !ok {
        return -1
    }
    cache.order.MoveToFront(element) // just used, so it becomes the newest
    // element.Value has type any, so .(*entry) turns it back into our entry
    return element.Value.(*entry).value
}

// Put adds or updates a key. When full, it removes the oldest item first.
func (cache *LRU) Put(key, value int) {
    element, ok := cache.items[key]
    if ok {
        element.Value.(*entry).value = value // key exists: update it
        cache.order.MoveToFront(element)
        return
    }
    if cache.order.Len() == cache.capacity {
        oldest := cache.order.Back() // least recently used is at the back
        cache.order.Remove(oldest)
        delete(cache.items, oldest.Value.(*entry).key) // delete removes a map key
    }
    cache.items[key] = cache.order.PushFront(&entry{key, value})
}

func main() {
    cache := NewLRU(2)
    cache.Put(1, 100)
    cache.Put(2, 200)
    fmt.Println(cache.Get(1)) // 1 is now the newest
    cache.Put(3, 300)         // full: removes 2, the oldest
    fmt.Println(cache.Get(2), cache.Get(3), cache.Get(1))
}
100
-1 300 100

The map jumps straight to an item, and the list keeps the items in order of use. Each Get moves the item to the front, so the back always holds the oldest one. Every Get and Put is O(1), and LRU cache is one of the most asked Go coding interview programs. The entry stores its own key, so when we remove the oldest list element we know which map key to delete too.

Program 2: Longest Substring Without Repeating Characters

package main

import "fmt"

// longest uses a sliding window [left, right] with no repeated bytes.
func longest(text string) int {
    lastSeen := map[byte]int{} // character -> last index where we saw it
    best := 0
    left := 0
    for right := 0; right < len(text); right++ {
        char := text[right]
        lastIndex, found := lastSeen[char] // found is true if we saw char before
        if found && lastIndex >= left {
            left = lastIndex + 1 // jump past the old copy of char
        }
        lastSeen[char] = right
        best = max(best, right-left+1) // window size is right-left+1
    }
    return best
}

func main() {
    for _, text := range []string{"abcabcbb", "bbbbb", "pwwkew", ""} {
        fmt.Printf("%q -> %d\n", text, longest(text)) // %q prints the text in quotes
    }
}
"abcabcbb" -> 3
"bbbbb" -> 1
"pwwkew" -> 3
"" -> 0

The right index grows the window one character at a time. If that character is already inside the window, left jumps just past its old copy. The window only moves forward, so each character is checked a fixed number of times. That makes it O(n) instead of checking every substring.

Program 3: Maximum Subarray Sum (Kadane’s Method)

package main

import "fmt"

// maxSubarray keeps the best sum ending here, and the best sum seen so far.
func maxSubarray(numbers []int) int {
    current := numbers[0]
    best := numbers[0]
    for _, number := range numbers[1:] { // [1:] skips the first item
        // either start fresh at number, or add it to the old run
        current = max(number, current+number)
        best = max(best, current)
    }
    return best
}

func main() {
    fmt.Println(maxSubarray([]int{-2, 1, -3, 4, -1, 2, 1, -5, 4}))
    fmt.Println(maxSubarray([]int{-3, -1, -2}))
}
6
-1

current is the best sum of a run that ends at this number. best remembers the biggest current you have seen. The best run is [4 -1 2 1]. If a running sum turns worse than the current value alone, we drop it and start again, which is the whole trick.

Array Go Coding Interview Programs

These Go coding interview programs work on arrays, using maps, sorting, prefix products and two pointers.

Program 4: Two Sum with a Map

package main

import "fmt"

// twoSum returns the positions of two numbers that add up to target.
func twoSum(numbers []int, target int) (int, int) {
    seen := map[int]int{} // number -> the index where we saw it
    for index, number := range numbers {
        need := target - number           // the partner this number needs
        partnerIndex, found := seen[need] // found is true if the partner came earlier
        if found {
            return partnerIndex, index
        }
        seen[number] = index // remember this number for later ones
    }
    return -1, -1 // no pair adds up to target
}

func main() {
    fmt.Println(twoSum([]int{2, 7, 11, 15}, 9))
    fmt.Println(twoSum([]int{3, 2, 4}, 6))
    fmt.Println(twoSum([]int{1, 2}, 10))
}
0 1
1 2
-1 -1

For each number, you work out the partner it needs to reach the target. If the map already holds that partner, you have the answer. If not, you save the current number and move on. One pass with a map makes this O(n) instead of checking every pair.

Program 5: Merge Overlapping Intervals

package main

import (
    "cmp"
    "fmt"
    "slices"
)

// merge sorts by start time, then joins any interval that overlaps the last one.
func merge(intervals [][2]int) [][2]int {
    // Step 1: sort by start. cmp.Compare returns -1, 0 or 1 to say which is first.
    slices.SortFunc(intervals, func(first, second [2]int) int {
        return cmp.Compare(first[0], second[0])
    })
    // Step 2: walk through and join overlaps
    var merged [][2]int
    for _, current := range intervals {
        last := len(merged) - 1
        if last >= 0 && current[0] <= merged[last][1] {
            merged[last][1] = max(merged[last][1], current[1]) // overlap: stretch the end
        } else {
            merged = append(merged, current) // no overlap: start a new interval
        }
    }
    return merged
}

func main() {
    meetings := [][2]int{{8, 10}, {1, 3}, {2, 6}, {15, 18}, {9, 12}}
    fmt.Println(merge(meetings))
}
[[1 6] [8 12] [15 18]]

First the meetings are sorted by start time. Then each meeting either stretches the last merged one or starts a new one. After sorting, any overlap must be with the last merged interval. This is O(n log n) because of the sort.

Program 6: Product of Array Except Self

package main

import "fmt"

// productExceptSelf multiplies everything to the left, then everything
// to the right, without using division.
func productExceptSelf(numbers []int) []int {
    result := make([]int, len(numbers)) // make creates a slice of zeros
    // Step 1: left to right, store the product of all items before i
    leftProduct := 1
    for i := 0; i < len(numbers); i++ {
        result[i] = leftProduct
        leftProduct *= numbers[i]
    }
    // Step 2: right to left, multiply by the product of all items after i
    rightProduct := 1
    for i := len(numbers) - 1; i >= 0; i-- {
        result[i] *= rightProduct
        rightProduct *= numbers[i]
    }
    return result
}

func main() {
    fmt.Println(productExceptSelf([]int{1, 2, 3, 4}))
    fmt.Println(productExceptSelf([]int{2, 0, 5}))
}
[24 12 8 6]
[0 10 0]

The first loop stores the product of everything to the left of each spot. The second loop multiplies in everything to the right. Division would fail when the input has a zero, as in the second example. Two passes with running products avoid that problem.

Program 7: Check a Palindrome with Two Pointers

package main

import "fmt"

// isPalindrome checks if a word reads the same from both ends.
func isPalindrome(word string) bool {
    left := 0              // starts at the first letter
    right := len(word) - 1 // starts at the last letter
    for left < right {
        if word[left] != word[right] {
            return false // the two ends do not match
        }
        left++  // move in from the left
        right-- // move in from the right
    }
    return true
}

func main() {
    for _, word := range []string{"level", "racecar", "golang", "noon"} {
        fmt.Println(word, isPalindrome(word))
    }
}
level true
racecar true
golang false
noon true

This is the easiest two pointer program. One pointer starts at each end, and both move towards the middle. If any pair of letters differs, the word is not a palindrome. Programs 8 and 9 use the same idea with a smarter rule for which pointer moves.

Program 8: Container With Most Water (Two Pointers)

package main

import "fmt"

// maxArea starts with the widest container and moves the shorter wall inwards.
func maxArea(heights []int) int {
    left := 0
    right := len(heights) - 1
    best := 0
    for left < right {
        width := right - left
        area := width * min(heights[left], heights[right]) // water is limited by the shorter wall
        best = max(best, area)
        if heights[left] < heights[right] {
            left++ // moving the taller wall can never help
        } else {
            right--
        }
    }
    return best
}

func main() {
    fmt.Println(maxArea([]int{1, 8, 6, 2, 5, 4, 8, 3, 7}))
}
49

You start with the two outer walls, which give the widest container. Each step moves the shorter wall inwards, because only a taller wall could hold more water. The walls at index 1 (height 8) and index 8 (height 7) are 7 apart, so the area is 7 times 7. Two pointers turn an O(n squared) search into O(n).

Program 9: Three Sum to Zero

package main

import (
    "fmt"
    "slices"
)

// threeSum sorts, fixes one number, then uses two pointers for the other two.
func threeSum(numbers []int) [][]int {
    slices.Sort(numbers)
    var result [][]int
    for i := 0; i < len(numbers)-2; i++ {
        if i > 0 && numbers[i] == numbers[i-1] {
            continue // skip duplicate first numbers
        }
        left := i + 1
        right := len(numbers) - 1
        for left < right {
            sum := numbers[i] + numbers[left] + numbers[right]
            if sum < 0 {
                left++ // too small, so take a bigger number
            } else if sum > 0 {
                right-- // too big, so take a smaller number
            } else {
                result = append(result, []int{numbers[i], numbers[left], numbers[right]})
                for left < right && numbers[left] == numbers[left+1] {
                    left++ // skip duplicate second numbers
                }
                left++
                right--
            }
        }
    }
    return result
}

func main() {
    fmt.Println(threeSum([]int{-1, 0, 1, 2, -1, -4}))
}
[[-1 -1 2] [-1 0 1]]

The outer loop fixes the first number. The two pointers then search the rest for a pair that brings the sum to zero. Sorting lets us skip duplicates easily and move the pointers with a clear rule. Many Go coding interview programs start with a sort for this reason. The total cost is O(n squared), which is the best known for this problem.

Dynamic Programming Go Coding Interview Programs

Dynamic programming (DP) means solving a big problem by saving the answers to smaller ones. These Go coding interview programs show the three most asked DP shapes.

Go coding interview programs coin change table filled from small amounts to the target
Each cell stores the fewest coins for that amount, built from cells already filled.

Program 10: Climbing Stairs

package main

import "fmt"

// ways counts how many ways you can climb steps stairs, taking 1 or 2 at a time.
// ways(n) = ways(n-1) + ways(n-2), which is the Fibonacci pattern.
func ways(steps int) int {
    twoBack := 1 // ways to reach step 0
    oneBack := 1 // ways to reach step 1
    for i := 2; i <= steps; i++ {
        current := twoBack + oneBack
        twoBack = oneBack // slide both answers forward by one step
        oneBack = current
    }
    return oneBack
}

func main() {
    for _, steps := range []int{1, 2, 3, 5, 10} {
        fmt.Print(ways(steps), " ")
    }
    fmt.Println()
}
1 2 3 8 89

To stand on step n, your last move came from step n-1 or n-2. So the answer for a step is the sum of the two answers before it. We only need the last two answers, so memory is O(1).

Program 11: Coin Change (Fewest Coins)

package main

import "fmt"

// coinChange fills dp[a] = fewest coins that make amount a.
func coinChange(coins []int, amount int) int {
    dp := make([]int, amount+1) // dp[0] is 0: no coins make amount 0
    for a := 1; a <= amount; a++ {
        dp[a] = amount + 1 // a value bigger than any real answer
        for _, coin := range coins {
            // use coin on top of the best answer for a-coin, if that is better
            if coin <= a && dp[a-coin]+1 < dp[a] {
                dp[a] = dp[a-coin] + 1
            }
        }
    }
    if dp[amount] > amount {
        return -1 // the amount cannot be made
    }
    return dp[amount]
}

func main() {
    fmt.Println(coinChange([]int{1, 2, 5}, 11))
    fmt.Println(coinChange([]int{2}, 3))
    fmt.Println(coinChange([]int{1, 5, 10, 20}, 36))
}
3
-1
4

The table dp is filled from amount 1 up to the target. For each amount a, you try every coin and reuse the answer already saved for a minus that coin. For 11, the answer is 5 + 5 + 1. A greedy “biggest coin first” approach fails for some coin sets, which is why interviewers ask for DP here.

Program 12: Longest Common Subsequence

package main

import "fmt"

// lcs builds a table where dp[i][j] is the answer for first[:i] and second[:j].
func lcs(first, second string) int {
    // Step 1: make a table with one extra row and column of zeros
    dp := make([][]int, len(first)+1)
    for i := range dp {
        dp[i] = make([]int, len(second)+1)
    }
    // Step 2: fill it row by row
    for i := 1; i <= len(first); i++ {
        for j := 1; j <= len(second); j++ {
            if first[i-1] == second[j-1] {
                dp[i][j] = dp[i-1][j-1] + 1 // same letter: extend the diagonal
            } else {
                dp[i][j] = max(dp[i-1][j], dp[i][j-1]) // skip a letter from one side
            }
        }
    }
    return dp[len(first)][len(second)]
}

func main() {
    fmt.Println(lcs("abcde", "ace"), lcs("golang", "gopher"), lcs("abc", "xyz"))
}
3 2 0

Each cell compares one letter from each word. When the letters match, you add 1 to the cell up and to the left. The common subsequence of “abcde” and “ace” is “ace”. The diff tool and Git use the same idea to compare file versions.

Backend Go Coding Interview Programs

Program 13: Token Bucket Rate Limiter

package main

import "fmt"

// Bucket allows bursts up to capacity, and refills rate tokens per second.
// Time is passed in as seconds so the output is the same on every run.
type Bucket struct {
    capacity float64 // the most tokens the bucket can hold
    tokens   float64 // tokens left right now
    rate     float64 // tokens added per second
    lastTime float64 // when we last refilled
}

// Allow reports whether a request at time now may pass.
func (bucket *Bucket) Allow(now float64) bool {
    // Step 1: refill for the time that passed, but never above capacity
    passed := now - bucket.lastTime
    bucket.tokens = min(bucket.capacity, bucket.tokens+passed*bucket.rate)
    bucket.lastTime = now
    // Step 2: spend one token if there is one
    if bucket.tokens >= 1 {
        bucket.tokens--
        return true
    }
    return false
}

func main() {
    bucket := &Bucket{capacity: 3, tokens: 3, rate: 1} // 3 requests at once, then 1 per second
    for _, now := range []float64{0, 0, 0, 0, 0.5, 1.2, 4} {
        // %.1f prints one digit after the point, %v prints the value as it is
        fmt.Printf("t=%.1f allowed=%v\n", now, bucket.Allow(now))
    }
}
t=0.0 allowed=true
t=0.0 allowed=true
t=0.0 allowed=true
t=0.0 allowed=false
t=0.5 allowed=false
t=1.2 allowed=true
t=4.0 allowed=true

At the start, the bucket is full, so the first three requests pass at once. A fourth request then finds the bucket empty and is refused. By t=1.2, the bucket has refilled to 1.2 tokens, so one request passes. In real code, pass time.Now() instead, or use the golang.org/x/time/rate package.

Program 14: Move Zeroes to the End In Place

package main

import "fmt"

// moveZeroes copies every non-zero value forward, then fills the rest with 0.
func moveZeroes(numbers []int) {
    writeIndex := 0 // next position to write a non-zero value
    for _, number := range numbers {
        if number != 0 {
            numbers[writeIndex] = number
            writeIndex++
        }
    }
    // every spot after the last non-zero value becomes 0
    for i := writeIndex; i < len(numbers); i++ {
        numbers[i] = 0
    }
}

func main() {
    numbers := []int{0, 1, 0, 3, 12}
    moveZeroes(numbers) // the slice is changed in place
    fmt.Println(numbers)
}
[1 3 12 0 0]

The loop reads every value, but it only writes the non-zero ones, at writeIndex. After that, the second loop fills the leftover spots with zeros. The order of the non-zero values stays the same, and no extra slice is used, which interviewers check for in Go coding interview programs. This read pointer and write pointer pattern also removes duplicates from sorted arrays.

Brute Force vs Optimal in Go Coding Interview Programs

Interviewers want to see both the simple idea and the better one. The table below compares them for problems in this post.

ProblemBrute forceOptimal
Longest unique substringO(n cubed), check allO(n), sliding window
Maximum subarrayO(n squared), all rangesO(n), Kadane
Container with most waterO(n squared), all pairsO(n), two pointers
Three sumO(n cubed), all triplesO(n squared), sort plus two pointers
Coin changeExponential, try all mixesO(amount x coins), DP

A simple rule helps: say the brute force idea first in one sentence, then improve it. This shows clear thinking even before you write code.

Common Mistakes in Go Coding Interview Programs

  • Coding before clarifying: ask about empty input, negatives and duplicates first.
  • Forgetting edge cases: test an empty slice, one item and all equal items.
  • Relying on map order: sort keys when the output order matters.
  • Integer overflow: large sums may need int64, and Go int is 64-bit on most servers.
  • Silent coding: talk through your idea so the interviewer can follow and help.

Best Practices for Go Coding Interview Programs

  • Learn the patterns, not individual answers: window, two pointers, BFS, DP and heaps.
  • Use the standard library: slices.Sort, min, max and container/list save time.
  • Name variables clearly, like left, right and best.
  • State time and space Big O at the end without being asked.
  • Practise on a timer, about 25 minutes per problem.

Go Coding Interview Programs Interview Questions and Answers

These are the follow-up questions interviewers ask most, and they build on the Go coding interview programs above. Each code answer is complete, with real output from Go 1.27.

Concept Questions on Go Coding Interview Programs

Q1. What is Big O notation?

It describes how the work grows as the input grows. O(n) means double the input roughly doubles the work, while O(n squared) means double the input gives about four times the work.

Q2. What is the difference between memoization and tabulation?

Memoization is top-down: a recursive function saves answers in a map. Tabulation is bottom-up: a loop fills a table from small cases, as in Programs 11 and 12.

Q3. What does this program print?

package main

import "fmt"

// fib returns the nth Fibonacci number and saves each answer in memo.
func fib(number int, memo map[int]int) int {
    if number < 2 {
        return number
    }
    saved, ok := memo[number] // ok is true if we solved this one before
    if ok {
        return saved // already solved, reuse it
    }
    memo[number] = fib(number-1, memo) + fib(number-2, memo)
    return memo[number]
}

func main() {
    memo := map[int]int{}
    fmt.Println(fib(50, memo), len(memo))
}
12586269025 49

Without the memo, fib(50) would take billions of calls. With it, each value from 2 to 50 is computed once, which is 49 entries.

Coding Questions

Q4. How do you find the single number when every other number appears twice?

package main

import "fmt"

func main() {
    numbers := []int{4, 1, 2, 1, 2}
    result := 0
    for _, number := range numbers {
        result ^= number // ^ is XOR; a ^ a is 0, so pairs cancel out
    }
    fmt.Println(result)
}
4

Each pair of equal numbers cancels to 0, so only the single number is left. XOR uses O(1) memory, while a map would use O(n). Interviewers like this one as a quick follow-up.

Q5. How do you find the majority element in O(1) memory?

package main

import "fmt"

// majority uses Boyer-Moore voting: a different value cancels one vote for the candidate.
func majority(numbers []int) int {
    candidate := 0
    count := 0
    for _, number := range numbers {
        if count == 0 {
            candidate = number // no votes left, so pick a new candidate
        }
        if number == candidate {
            count++
        } else {
            count--
        }
    }
    return candidate
}

func main() {
    fmt.Println(majority([]int{2, 2, 1, 1, 1, 2, 2}))
}
2

Each number either adds a vote for the candidate or takes one away. The majority value appears more than half the time, so it survives all the cancelling.

Q6. How do you check if you can reach the last index of a jump array?

package main

import "fmt"

// canJump tracks the farthest index reachable so far.
func canJump(numbers []int) bool {
    farthest := 0
    for index, step := range numbers {
        if index > farthest {
            return false // this index can never be reached
        }
        farthest = max(farthest, index+step)
    }
    return true
}

func main() {
    fmt.Println(canJump([]int{2, 3, 1, 1, 4}), canJump([]int{3, 2, 1, 0, 4}))
}
true false

This greedy check is O(n). In the second case, every path gets stuck at the 0 at index 3.

Interview Strategy Questions

Q7. What should you do if you cannot find the optimal solution?

Write the brute force solution cleanly and state its Big O. A correct slow answer with clear reasoning often scores better than a broken fast one.

Q8. Should you use generics in an interview?

Only if the problem asks for a reusable type. For most problems, plain []int keeps the code short and easy to follow.

Q9. How do you test your code in a live interview?

Walk through one normal example line by line, then try an edge case, such as an empty slice or a single item. Say the variable values out loud as you go.

Q10. How many problems should you practise?

Quality beats quantity. Solve about 75 to 100 problems that cover the main patterns, then repeat the ones you got wrong a week later.

Practice Task

To practise Go coding interview programs, solve “minimum window substring”: find the smallest part of "ADOBECODEBANC" that contains all letters of "ABC", which is "BANC". Hint: use the sliding window from Program 2 with a map of needed letter counts.

Official Resources

Quick Recap

  • Go coding interview programs test correct code, clear talk and good Big O.
  • Sliding window and two pointers turn many O(n squared) searches into O(n).
  • An LRU cache combines a map with a doubly linked list for O(1) operations.
  • Dynamic programming saves answers to small cases to solve big ones.
  • Always state the brute force idea first, then improve it.

What’s Next?

You have finished all six levels of the Go Programs series. Coming soon: Build a Go Backend Service End to End, a hands-on project post. For more practice now, go through the Go coding scenario questions or browse every topic in the Go interview questions hub.