Level: BeginnerGo Programs

Go Searching Programs: Linear Search, Binary Search, Two Sum

Updated 18 min read
Go Searching Programs featured image: linear and binary search output

Go searching programs find a value in a collection, such as an order ID in a list or a word in a dictionary. In this post, you will write fourteen search programs with their exact output, from simple linear search to binary search, first and last position, rotated arrays and the famous two-sum problem. Then you will practice the search questions that interviewers use to test your thinking about speed.

This post follows our Go sorting programs, because binary search only works on sorted data. You will also use the slice tools from our Go slice programs. All programs were tested on Go 1.27.

What are Go Searching Programs?

Go searching programs look through data to find where a value is, or to prove that it is not there. The two main methods are linear search, which checks items one by one, and binary search, which halves the search space each step.

Think of finding a word in a dictionary. You could read every page from the start, which is linear search. Or you open the middle, see whether your word comes before or after, and keep halving. That is binary search, and it finds any word in a few steps.

Why Go Searching Programs Matter

Search is one of the most common jobs a program does, so Go searching programs are worth learning well. For example, a login checks if a user exists, a shop finds a product by ID and a game looks up a high score. Interviewers also love binary search, because a tiny mistake in the loop causes wrong answers or endless loops.

  • Speed: binary search on 1 million items needs only about 20 checks.
  • Interviews: first and last position, rotated array and two-sum are very common.
  • Real code: slices.Index, slices.BinarySearch and maps cover most daily needs.

How Go Searching Programs Work

Binary search keeps two indexes, low and high, around the part that might hold the answer. Each step checks the middle item and throws away the half that cannot hold the value.

Go searching programs diagram showing binary search halving a sorted slice
Binary search checks the middle item and keeps only the half that can still hold the target.

The table below compares the search methods in this post.

MethodNeeds sorted dataTimeBest for
Linear searchNoO(n)Small or unsorted lists
Binary searchYesO(log n)Large sorted lists
Map lookupNo, but needs a mapO(1) averageMany lookups by key
Staircase searchSorted rows and columnsO(rows + cols)Sorted 2D grids

Linear Go Searching Programs

Linear Go searching programs work on any data, sorted or not.

Program 1: Check If a Name Is in the List

This is the easiest search of all. You look at each item and answer yes or no.

package main

import "fmt"

func main() {
    // := creates a variable and gives it a value in one go.
    guests := []string{"Asha", "Ravi", "Meera"}
    name := "Ravi"

    found := false // we have not found the name yet
    // range gives the index and the value on each turn. _ skips the index.
    for _, guest := range guests {
        if guest == name {
            found = true
            break // stop looking, we have the answer
        }
    }
    fmt.Println("Is", name, "invited?", found)
}
Is Ravi invited? true

The loop compares each guest with name. When it finds a match, it sets found to true and stops with break. If no guest matched, found would stay false.

package main

import "fmt"

// linearSearch returns the index of target in items, or -1 if it is missing.
func linearSearch(items []int, target int) int {
    for index, value := range items {
        if value == target {
            return index // first match found, so stop here
        }
    }
    return -1 // -1 means "not found", because no real index is negative
}

func main() {
    ids := []int{104, 87, 230, 15, 99}
    fmt.Println(linearSearch(ids, 230))
    fmt.Println(linearSearch(ids, 500))
}
2
-1

The function checks the items from left to right. It returns the index of the first match, or -1 when the value is missing. This is the same rule that slices.Index follows.

Program 3: Find All Positions of a Value

package main

import "fmt"

func main() {
    marks := []int{70, 85, 70, 90, 70}
    target := 70

    var positions []int // an empty slice to collect the answers
    for index, mark := range marks {
        if mark == target {
            // append adds the index at the end of positions.
            positions = append(positions, index)
        }
    }
    fmt.Println(positions, len(positions))
}
[0 2 4] 3

This time the loop does not stop at the first match. Each time a mark equals 70, you add its index to positions. So the result holds every place where 70 appears.

Program 4: Search with slices.Index and IndexFunc

package main

import (
    "fmt"
    "slices"
    "strings"
)

// startsWithM reports whether a city name begins with the letter M.
func startsWithM(city string) bool {
    return strings.HasPrefix(city, "M")
}

func main() {
    cities := []string{"Pune", "Delhi", "Goa", "Mumbai"}
    fmt.Println(slices.Index(cities, "Goa"))        // position of "Goa"
    fmt.Println(slices.Contains(cities, "Chennai")) // true or false

    // IndexFunc returns the first position where startsWithM returns true.
    index := slices.IndexFunc(cities, startsWithM)
    fmt.Println(index, cities[index])
}
2
false
3 Mumbai

slices.Index and slices.Contains search for an exact value. IndexFunc returns the first item where your function returns true. It is handy when you search by a rule instead of an exact value.

Binary Go Searching Programs

Binary Go searching programs need sorted data, but they are much faster on large lists.

package main

import "fmt"

// binarySearch finds target in a sorted slice and returns its index, or -1.
func binarySearch(numbers []int, target int) int {
    low := 0
    high := len(numbers) - 1

    // Keep going while there is still a part left to check.
    for low <= high {
        // mid is the middle index of the part we are checking.
        mid := low + (high-low)/2
        if numbers[mid] == target {
            return mid
        } else if numbers[mid] < target {
            low = mid + 1 // target is bigger, so drop the left half
        } else {
            high = mid - 1 // target is smaller, so drop the right half
        }
    }
    return -1
}

func main() {
    sorted := []int{3, 8, 15, 23, 42, 57, 61, 78}
    fmt.Println(binarySearch(sorted, 42))
    fmt.Println(binarySearch(sorted, 3))
    fmt.Println(binarySearch(sorted, 50))
}
4
0
-1

Each turn checks the middle item. If it is too small, you move low past it, and if it is too big, you move high below it. You write low + (high-low)/2, because it never overflows on huge slices.

package main

import "fmt"

// search looks for target between index low and index high.
// It calls itself on the smaller half (recursion) until it finds the target.
func search(numbers []int, target, low, high int) int {
    // Nothing left to check, so the target is missing.
    if low > high {
        return -1
    }
    mid := low + (high-low)/2
    if numbers[mid] == target {
        return mid
    }
    if numbers[mid] < target {
        return search(numbers, target, mid+1, high) // search the right half
    }
    return search(numbers, target, low, mid-1) // search the left half
}

func main() {
    numbers := []int{2, 4, 6, 8, 10, 12}
    fmt.Println(search(numbers, 10, 0, len(numbers)-1))
}
4

Each call checks the middle item, then calls itself on one half. The first middle is 6, so the next call searches the right half. This recursive version is easy to read, but the loop version uses less memory.

Program 7: slices.BinarySearch with Insert Position

package main

import (
    "fmt"
    "slices"
)

func main() {
    prices := []int{100, 250, 400, 650}

    // BinarySearch returns two values: the position, and found (true if the value is there).
    position, found := slices.BinarySearch(prices, 400)
    fmt.Println(position, found)

    // 300 is missing, but position tells you where it would go.
    position, found = slices.BinarySearch(prices, 300)
    fmt.Println(position, found)
    prices = slices.Insert(prices, position, 300)
    fmt.Println(prices)
}
2 true
2 false
[100 250 300 400 650]

The first search finds 400 at index 2. When the value is missing, BinarySearch still returns the index where it should go. So you can insert 300 there and keep the slice sorted.

Program 8: First and Last Position of a Value

With duplicates, a normal binary search may land on any copy. Here you find the first and last copies.

package main

import (
    "fmt"
    "sort"
)

func main() {
    numbers := []int{1, 3, 3, 3, 5, 7}
    target := 3

    // Step 1: first index where the number is 3 or more.
    first := sort.SearchInts(numbers, target)

    // Step 2: first index where the number is more than 3.
    // sort.Search asks our small function "is the rule true at index i?".
    afterLast := sort.Search(len(numbers), func(i int) bool {
        return numbers[i] > target
    })
    last := afterLast - 1 // one step back is the last 3

    // Step 3: make sure the target really is in the slice.
    if first < len(numbers) && numbers[first] == target {
        fmt.Println("First:", first, "Last:", last)
    }
}
First: 1 Last: 3

sort.Search finds the first index where your rule becomes true. So “first item greater than 3” is index 4, and one step back is the last 3. The check at the end makes sure 3 really exists.

Program 9: Search in a Rotated Sorted Array

A rotated array looks like [40 50 60 10 20 30]. One half is always sorted, so you check which half and search there.

package main

import "fmt"

// searchRotated finds target in a sorted slice that was rotated, or returns -1.
func searchRotated(numbers []int, target int) int {
    low := 0
    high := len(numbers) - 1
    for low <= high {
        mid := low + (high-low)/2
        if numbers[mid] == target {
            return mid
        }
        if numbers[low] <= numbers[mid] {
            // The left half is sorted. Is the target inside it?
            if target >= numbers[low] && target < numbers[mid] {
                high = mid - 1
            } else {
                low = mid + 1
            }
        } else {
            // The right half is sorted. Is the target inside it?
            if target > numbers[mid] && target <= numbers[high] {
                low = mid + 1
            } else {
                high = mid - 1
            }
        }
    }
    return -1
}

func main() {
    numbers := []int{40, 50, 60, 10, 20, 30}
    fmt.Println(searchRotated(numbers, 20), searchRotated(numbers, 50), searchRotated(numbers, 35))
}
4 1 -1

On each turn, you find which half is sorted by comparing its two ends. Then you check if the target falls inside that sorted half. If it does, you search there, otherwise you search the other half.

Clever Go Searching Programs

These Go searching programs use maths or a map instead of a plain search.

Program 10: Look Up a Phone Number by Name

A map finds a value by its key in one step, with no loop at all.

package main

import "fmt"

func main() {
    // A map links each name (key) to a phone number (value).
    phoneBook := map[string]string{
        "Asha": "98200 11111",
        "Ravi": "98200 22222",
    }

    // A map lookup gives two values: the value, and ok (true if the key exists).
    number, ok := phoneBook["Ravi"]
    fmt.Println(number, ok)

    number, ok = phoneBook["Kiran"]
    if !ok {
        fmt.Println("Kiran is not in the phone book")
    } else {
        fmt.Println(number)
    }
}
98200 22222 true
Kiran is not in the phone book

The first lookup finds Ravi, so ok is true. The second name is missing, so ok is false and the program prints a message. Always check ok, because a missing key gives an empty value.

Program 11: Two Sum with a Map

Find two numbers that add up to a target. A map gives an O(n) answer instead of checking every pair.

package main

import "fmt"

// twoSum returns the positions of two numbers that add up to target.
// The last value is true when such a pair exists.
func twoSum(numbers []int, target int) (int, int, bool) {
    seen := map[int]int{} // number -> its index

    for index, number := range numbers {
        partner := target - number // the number we need to reach target

        // ok is true if we have already seen the partner.
        partnerIndex, ok := seen[partner]
        if ok {
            return partnerIndex, index, true
        }
        seen[number] = index // remember this number for later
    }
    return 0, 0, false
}

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 true
1 2 true
0 0 false

For each number, you ask “have I already seen the partner I need?”. If yes, you return both positions. If not, you store the number in the map and move on, so the whole search is a single pass.

Program 12: Find the Missing Number

A slice holds the numbers 1 to n with one missing. The sum formula finds it without any search.

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 4, 6, 3, 7, 8}

    // Step 1: the full list would have one more number.
    count := len(numbers) + 1

    // Step 2: the sum of 1 to count is count * (count + 1) / 2.
    expected := count * (count + 1) / 2

    // Step 3: add the numbers we really have.
    actual := 0
    for _, number := range numbers {
        actual += number // same as actual = actual + number
    }

    // Step 4: the gap between the two sums is the missing number.
    fmt.Println("Missing:", expected-actual)
}
Missing: 5

A full list of 1 to 8 adds up to 36. The numbers you have add up to 31. So the missing number is 36 – 31, which is 5.

Program 13: Search a Sorted 2D Grid

Each row and column is sorted. You start at the top right and step left or down.

package main

import "fmt"

// searchGrid returns the row and column of target, and true if it was found.
func searchGrid(grid [][]int, target int) (int, int, bool) {
    // Start at the top right corner.
    row := 0
    col := len(grid[0]) - 1

    for row < len(grid) && col >= 0 {
        current := grid[row][col]
        if current == target {
            return row, col, true
        } else if current > target {
            col-- // too big, so move left to smaller numbers
        } else {
            row++ // too small, so move down to bigger numbers
        }
    }
    return -1, -1, false
}

func main() {
    grid := [][]int{
        {1, 4, 7, 11},
        {2, 5, 8, 12},
        {3, 6, 9, 16},
    }
    fmt.Println(searchGrid(grid, 9))
    fmt.Println(searchGrid(grid, 10))
}
2 2 true
-1 -1 false

If the current number is too big, everything below it is bigger too, so you move left. If it is too small, you move down. Every step removes a whole row or column, so this runs in O(rows + cols) time.

Program 14: Binary Search on Structs

slices.BinarySearchFunc searches by a field when the slice is sorted by that field.

package main

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

// Book is one book in a library, sorted by ID.
type Book struct {
    ID    int
    Title string
}

// compareID tells BinarySearchFunc if a book's ID is smaller, equal or bigger than id.
func compareID(book Book, id int) int {
    return cmp.Compare(book.ID, id)
}

func main() {
    books := []Book{{101, "Go Basics"}, {205, "Web APIs"}, {310, "Concurrency"}, {420, "Testing"}}
    position, found := slices.BinarySearchFunc(books, 310, compareID)
    fmt.Println(position, found, books[position].Title)
}
2 true Concurrency

The books are sorted by ID, so binary search works on that field. compareID tells the search whether to go left or right. It finds ID 310 at index 2, which is “Concurrency”.

Linear vs Binary Go Searching Programs

Choosing between Go searching programs depends on your data. The diagram and table below compare the two main methods.

Go searching programs comparison of linear search and binary search
Linear search works on any data, while binary search needs sorted data but is far faster on large lists.
FeatureLinear searchBinary search
Sorted data neededNoYes
Checks for 1,000,000 itemsUp to 1,000,000About 20
Code riskVery lowOff-by-one bugs
Works on linked dataYesNo, needs index access
Go helperslices.Indexslices.BinarySearch

In short, use linear search for small or unsorted lists. Sort once and use binary search when you search a big list many times.

Common Mistakes in Go Searching Programs

  • Binary search on unsorted data: it returns wrong answers without any error, so sort first.
  • Wrong loop condition: use low <= high, or you can miss the last item.
  • Not moving past mid: low = mid instead of mid + 1 can loop forever.
  • Ignoring the found flag: slices.BinarySearch returns an index even when the value is missing.
  • Searching a map in a loop: a map lookup m[key] is already O(1), so you do not need to loop.

Best Practices for Go Searching Programs

  • Prefer the standard library: slices.Index, slices.BinarySearch and sort.Search.
  • Keep data sorted if you search it often, and use binary search.
  • Use a map when you look up by key many times.
  • Test the edges: empty slice, one item, first item, last item and missing value.
  • Say the complexity of your search in interviews, before you write code.

Go Searching Programs Interview Questions and Answers

Interviewers ask these Go searching programs often in coding rounds. Each program is complete, with real output from Go 1.27.

Binary Search Questions on Go Searching Programs

Q1. Why is binary search O(log n)?

Each step cuts the search space in half. For 1,024 items you need at most 10 steps, because 2 to the power 10 is 1,024.

Q2. What does this program print?

package main

import "fmt"

func main() {
    numbers := []int{1, 3, 5, 7, 9, 11, 13}
    target := 11
    low := 0
    high := len(numbers) - 1
    steps := 0

    for low <= high {
        steps++ // count each check
        mid := low + (high-low)/2
        if numbers[mid] == target {
            break
        } else if numbers[mid] < target {
            low = mid + 1
        } else {
            high = mid - 1
        }
    }
    fmt.Println("Steps:", steps)
}
Steps: 2

The first middle is 7, so you move right. The next middle is 11, so the loop stops after 2 steps.

Q3. What does sort.Search return when nothing matches?

package main

import (
    "fmt"
    "sort"
)

func main() {
    numbers := []int{2, 4, 6}

    // First index where the number is 5 or more.
    fmt.Println(sort.Search(len(numbers), func(i int) bool { return numbers[i] >= 5 }))

    // First index where the number is 10 or more. There is none.
    fmt.Println(sort.Search(len(numbers), func(i int) bool { return numbers[i] >= 10 }))
}
2
3

It returns the first index where the rule is true. If the rule is never true, it returns len(numbers), so always check the result before you use it.

Q4. What does this program print?

package main

import (
    "fmt"
    "slices"
)

func main() {
    numbers := []int{10, 20, 30}
    fmt.Println(slices.BinarySearch(numbers, 5))  // where would 5 go?
    fmt.Println(slices.BinarySearch(numbers, 35)) // where would 35 go?
}
0 false
3 false

5 would go at the start, and 35 would go at the end. The false tells you neither value is in the slice.

Other Search Questions

Q5. What is the time complexity of two-sum with a map?

It is O(n) time and O(n) memory. The brute force version that checks every pair is O(n squared) time but uses no extra memory.

Q6. What does this program print?

package main

import "fmt"

func main() {
    stock := map[string]int{"pen": 40, "bag": 0}

    // ok is true if the key exists in the map.
    quantity, ok := stock["bag"]
    fmt.Println(quantity, ok)

    quantity, ok = stock["cap"]
    fmt.Println(quantity, ok)
}
0 true
0 false

Both lookups return 0, so you cannot tell them apart by value alone. The ok flag shows that “bag” exists but “cap” does not.

Q7. How do you find the missing number with XOR?

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 4, 5}

    // ^ is XOR. Two equal numbers XOR to 0, and x XOR 0 is x.
    result := 0

    // Step 1: XOR every number from 1 to 5 (the full list).
    for i := 1; i <= len(numbers)+1; i++ {
        result ^= i // same as result = result ^ i
    }

    // Step 2: XOR every number we have. Pairs cancel out.
    for _, number := range numbers {
        result ^= number
    }
    fmt.Println(result)
}
3

XOR of a number with itself is 0. So every number that appears twice cancels out, and only the missing 3 is left. This also avoids overflow for big sums.

Q8. What does this program print?

package main

import (
    "fmt"
    "slices"
)

func main() {
    words := []string{"go", "rust", "go", "java"}
    fmt.Println(slices.Index(words, "go"))

    // words[1:] skips the first word, so indexes start again at 0.
    position := slices.Index(words[1:], "go")
    fmt.Println(position, position+1)
}
0
1 2

Searching a sub-slice gives an index inside that sub-slice. Add the offset back to get the position in the full slice.

Q9. Can you use binary search on a linked list?

Not efficiently. Binary search needs to jump to the middle in one step, and a linked list must walk there item by item. So the total time becomes O(n).

Q10. How do you find the peak element in a slice?

package main

import "fmt"

// peak returns the index of a number that is bigger than its neighbours.
func peak(numbers []int) int {
    low := 0
    high := len(numbers) - 1
    for low < high {
        mid := low + (high-low)/2
        if numbers[mid] < numbers[mid+1] {
            low = mid + 1 // the numbers still go up, so the peak is to the right
        } else {
            high = mid // mid could be the peak, so keep it
        }
    }
    return low
}

func main() {
    numbers := []int{1, 3, 8, 12, 4, 2}
    index := peak(numbers)
    fmt.Println(index, numbers[index])
}
3 12

A peak is bigger than its neighbours. If the next item is bigger, a peak must be to the right, so binary search still works on unsorted data here.

When you look up by exact key many times and do not need order. A map gives O(1) average lookups, while binary search gives O(log n) but also supports range queries like “first price above 500”.

Q12. What does this program print?

package main

import (
    "fmt"
    "slices"
)

func main() {
    var empty []int // a nil slice with no items
    fmt.Println(slices.Index(empty, 1), slices.Contains(empty, 1))

    position, found := slices.BinarySearch(empty, 1)
    fmt.Println(position, found)
}
-1 false
0 false

All search helpers work safely on an empty or nil slice. They simply report that nothing was found.

Practice Task

This task turns maths into one of the Go searching programs. Write a program that finds the square root of a number rounded down, such as 17 giving 4, using binary search instead of math.Sqrt. Hint: search between 0 and n for the largest mid where mid*mid <= n.

Official Resources

Quick Recap

  • Go searching programs use linear search for any data and binary search for sorted data.
  • Binary search halves the work each step, so it runs in O(log n).
  • slices.BinarySearch returns the insert position even when the value is missing.
  • A map lookup with the ok flag is the fastest way to search by key.
  • Test empty slices, the first and last item and missing values every time.

What’s Next?

Next, we look closely at Go’s key-value collection. Read Go map programs with output, with word counts, sorting maps and grouping. For the theory first, see Go maps explained with examples.