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?
int
, that would only be 390 KiB, and will fit in L2 cache on recent CPUs. "super large" or "huge" to me implies much larger than L3 cache sizes, like many megabytes, maybe a few gigabytes of data. (Or depending on context, like HPC number crunching, many gigabytes; high-end HPC systems can have terabytes of RAM.) This size is medium, or the lower end of large. \$\endgroup\$