From 2d14f0f0cdc9a2589ffcd6fa9a934f0b3711b611 Mon Sep 17 00:00:00 2001 From: lenardjombo Date: Sat, 12 Jul 2025 21:04:55 +0300 Subject: [PATCH] add: FindFirstMissingPositive rehearsal with in-place O(n) solution --- array/find_first_missing_positive.go | 21 ++++++++++++ array/find_first_missing_positive_test.go | 42 +++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 array/find_first_missing_positive.go create mode 100644 array/find_first_missing_positive_test.go diff --git a/array/find_first_missing_positive.go b/array/find_first_missing_positive.go new file mode 100644 index 0000000..013810f --- /dev/null +++ b/array/find_first_missing_positive.go @@ -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 +} + diff --git a/array/find_first_missing_positive_test.go b/array/find_first_missing_positive_test.go new file mode 100644 index 0000000..b846550 --- /dev/null +++ b/array/find_first_missing_positive_test.go @@ -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) + } + } +} +