You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums.
6
+
You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.
7
+
Example 1:
8
+
Input: nums = [1,2,0]
9
+
Output: 3
10
+
Explanation: The numbers in the range [1,2] are all in the array.
11
+
Example 2:
12
+
Input: nums = [3,4,-1,1]
13
+
Output: 2
14
+
Explanation: 1 is in the array but 2 is missing.
15
+
Example 3:
16
+
Input: nums = [7,8,9,11,12]
17
+
Output: 1
18
+
Explanation: The smallest positive integer 1 is missing.
19
+
Constraints:
20
+
1 <= nums.length <= 10^5
21
+
-2^31 <= nums[i] <= 2^31 - 1
22
+
Explanation
23
+
Initialize n
24
+
const n = nums.length;
25
+
This line sets the variable n to the length of the input array nums. It represents the size of the array.
26
+
This is the cyclic sort algorithm. It iterates through the array and, in each step, it checks if the current element nums[i] is within the valid range (1 to n) and not in its correct position. If so, it swaps the element with the one at its correct position.
27
+
After the cyclic sort, this loop searches for the first element that is out of place. If nums[i] is not equal to i + 1, it means that i + 1 is the smallest missing positive integer, and it is returned.
28
+
Return Next Positive Integer if All Elements Are in Place,
29
+
If all elements are in their correct positions, the function returns the next positive integer after the maximum element in the array (n + 1).
0 commit comments