41. First Missing Positive
Asked at 30Amazon61Microsoft49Google48Meta41Bloomberg40tcs73Netskope100ServiceNow79Geico66MakeMyTrip65Myntra64Zomato62EPAM Systems60Nutanix60Swiggy59Cognizant57Walmart Labs53PhonePe53Zoho52General Motors52Tesla52Netflix49Oracle45Adobe44PayPal42Nvidia39Visa39Salesforce35Goldman Sachs33Infosys30
Problem
Given an unsorted integer array nums, return the smallest positive integer that does not appear in it.
Example: [3,4,-1,1] → 2; [1,2,0] → 3
Constraints: n ≤ 10⁵; must run in O(n) time with O(1) extra space.
The answer is in [1, n+1]. Use the array as a hash table: cyclic-swap each value v ∈ [1, n] to index v-1. Then the first index i with nums[i] != i+1 gives i+1.
[3, 4, -1, 1]
swap 3 -> idx2: [-1, 4, 3, 1]
swap 4 -> idx3: [-1, 1, 3, 4]
swap 1 -> idx0: [ 1,-1, 3, 4]
scan: idx1 holds -1 -> answer 2
Complexity: O(n) time (each swap fixes one slot), O(1) space.
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
n = len(nums)
for i in range(n):
while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
j = nums[i] - 1
nums[i], nums[j] = nums[j], nums[i]
for i in range(n):
if nums[i] != i + 1:
return i + 1
return n + 1
assert Solution().firstMissingPositive([1, 2, 0]) == 3
assert Solution().firstMissingPositive([3, 4, -1, 1]) == 2
assert Solution().firstMissingPositive([7, 8, 9, 11, 12]) == 1
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
int j = nums[i] - 1, t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
for (int i = 0; i < n; i++) if (nums[i] != i + 1) return i + 1;
return n + 1;
}
}
func firstMissingPositive(nums []int) int {
n := len(nums)
for i := range nums {
for nums[i] >= 1 && nums[i] <= n && nums[nums[i]-1] != nums[i] {
j := nums[i] - 1 // put value v at index v-1
nums[i], nums[j] = nums[j], nums[i]
}
}
for i, v := range nums {
if v != i+1 {
return i + 1
}
}
return n + 1
}