Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions array/find_first_missing_positive.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package array

// FindFirstMissingPositive returns the smallest missing positive integer.
// The algorithm runs in O(n) time and O(1) space by placing each value at its correct index.
func FindFirstMissingPositive(nums []int) int {
n := len(nums)
for i := 0; i < n; i++ {
for nums[i] > 0 && nums[i] <= n && nums[nums[i]-1] != nums[i] {
// Swap nums[i] with nums[nums[i] - 1]
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
}
}

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

42 changes: 42 additions & 0 deletions array/find_first_missing_positive_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package array

import (
"testing"
)

/*
TestFindFirstMissingPositive tests solution(s) with the following signature:

FindFirstMissingPositive(nums []int) int

Given an unsorted integer slice, return the smallest missing positive integer.

Examples:
Input: []int{1, 2, 0} → Output: 3
Input: []int{3, 4, -1, 1} → Output: 2
Input: []int{7, 8, 9, 11, 12} → Output: 1
*/
func TestFindFirstMissingPositive(t *testing.T) {
tests := []struct {
nums []int
expected int
}{
{[]int{1, 2, 0}, 3},
{[]int{3, 4, -1, 1}, 2},
{[]int{7, 8, 9, 11, 12}, 1},
{[]int{}, 1},
{[]int{1, 2, 3}, 4},
{[]int{0, -1, -2}, 1},
{[]int{2, 1}, 3},
{[]int{1}, 2},
{[]int{2}, 1},
{[]int{3, 4, -1, 1, 2}, 5},
}

for i, test := range tests {
if got := FindFirstMissingPositive(append([]int(nil), test.nums...)); got != test.expected {
t.Fatalf("Failed test case #%d. Input: %v. Want %d, got %d", i, test.nums, test.expected, got)
}
}
}