I was trying out leetcode's first missing positive.
As per the challenge's description:
Given an unsorted integer array nums, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.
My solution passes all tests, except last five i.e. where the nums
array's size is \$10^5\$. When the array is of that size I get "Time Limit Exceeded".
Here is my solution: (PS: class and methods naming are kept as given by leetcode)
class Solution {
public int firstMissingPositive(int[] nums) {
int minIndex = 0;
int integerCounter = 0;
for (int i = minIndex; i < nums.length; i++) {
if (i == 0) {
integerCounter += 1;
}
if (nums[i] == integerCounter) {
// swap
int temp = nums[minIndex];
nums[minIndex] = nums[i];
nums[i] = temp;
minIndex += 1;
i = minIndex - 1;
integerCounter++;
}
}
return integerCounter > 0 ? integerCounter : -1;
}
}
My Question
How can I improve this algorithm to tackle super large (e.g. \$10^5\$) nums
array without getting the "Time Limit Exceeded" and without having to completely modify the function?
unordered_set<int> s(nums.begin(), nums.end()); int i = 1; for (; s.contains(i); i++); return i;
\$\endgroup\$