TheAlgorithms/Go · warning

target not found in array

Error message

target not found in array

What it means

search.ErrNotFound (search/errors.go:6) is the sentinel error returned by search functions (Binary, BinaryIterative, LowerBound) and by math.FindKthMax/FindKthMin (via kthNumber) when the requested target or rank cannot be found in the slice. Callers get -1 as the value alongside this error. For the kth-number functions it fires when k is out of range: k < 0 or k >= len(nums) after index conversion.

Source

Thrown at search/errors.go:6

package search

import "errors"

// ErrNotFound is returned by search functions when target is not found
var ErrNotFound = errors.New("target not found in array")

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Validate k against 1 <= k <= len(nums) (and len(nums) > 0) before calling FindKthMax/FindKthMin
  2. Ensure the slice is sorted ascending before calling binary-search functions
  3. Always check err != nil and treat -1 as a sentinel value, not a valid result
  4. Check membership/emptiness of the slice before searching for a specific target

Example fix

// before
v, _ := math.FindKthMax(nums, k) // ErrNotFound swallowed, v == -1
// after
if k < 1 || k > len(nums) {
    return 0, fmt.Errorf("k=%d out of range for %d elements", k, len(nums))
}
v, err := math.FindKthMax(nums, k)
if err != nil {
    if errors.Is(err, search.ErrNotFound) { /* handle miss */ }
}
Defensive patterns

Strategy: try-catch

Validate before calling

if len(nums) == 0 || k < 1 || k > len(nums) {
    return 0, fmt.Errorf("k=%d invalid for slice of len %d", k, len(nums))
}
// for binary search: sort.Ints(nums) before calling

Type guard

func validRank(k, n int) bool { return n > 0 && k >= 1 && k <= n }

Try / catch

v, err := math.FindKthMax(nums, k)
if err != nil {
    if errors.Is(err, search.ErrNotFound) {
        // fallback: return default or report k out of range
    }
    return 0, err
}

Prevention

When it happens

Trigger: Calling search.Binary/BinaryIterative/LowerBound on a slice that does not contain the target (or is not sorted as required); calling math.FindKthMax(nums, k) with k < 1 or k > len(nums); calling FindKthMin with k < 1 or k > len(nums); passing an empty slice.

Common situations: Off-by-one in 1-based vs 0-based k (FindKthMax(nums, 0) or k = len(nums)); searching for a value absent from data; forgetting the slice must be sorted for binary search, so a present element is missed; empty slices from upstream queries.

Related errors


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/288ceb88fe6018a3. Report an issue: GitHub.