Sobes.tech
Senior

Code task: find the smallest natural number missing in an array.

sobes.tech AI

Answer from AI

Task: find the smallest natural number (greater than 0) missing from the array.

Example solution in Go with linear complexity and using additional memory:

package main

import "fmt"

func findMissingPositive(nums []int) int {
    n := len(nums)
    present := make([]bool, n+1) // indices from 0 to n

    for _, num := range nums {
        if num > 0 && num <= n {
            present[num] = true

        }
    }

    for i := 1; i <= n; i++ {
        if !present[i] {
            return i
        }
    }

    return n + 1
}

func main() {
    arr := []int{3, 4, -1, 1}
    fmt.Println(findMissingPositive(arr)) // Outputs 2
}

Idea: mark which numbers from 1 to n are present, then find the first missing one. If all are present, the answer is n+1.

Code task: find the smallest natural number missing… - sobes.tech