class Solution {
//adding comments as requested to make it clearer
public int firstMissingPositive(int[] nums) {
// concept:
//start check from 1-->+ if in array
// example nb=1: loop array to find it
// a) not found --> 1 is the first missing number
// b) found --> swap 1 with element at index minIndex, and so next loop starts from minIndex and moves forward
//etc...
int minIndex = 0;
int integerCounter = 0;//start checking and comparing with regular positive integers ie:1,2,3,4..etc.. to see if found in array
for (int i = minIndex; i < nums.length; i++) {
if (i == 0) {
integerCounter += 1;
}
if (nums[i] == integerCounter) {
// swap found item with item at index = minIndex
// this way next loop will start from new minIndex and forward
int temp = nums[minIndex];
nums[minIndex] = nums[i];
nums[i] = temp;
minIndex += 1;
i = minIndex - 1;//-1 coz will increment for next loop ie i = minindex
integerCounter++;
}
}
//if reached here and integerCounter > 0 ie this is the minimum missing positive integer.
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?My QuestionHow 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?Graphical explanation of my solution using an example
Graphical explanation of my solution using an example