Unit 3 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
[1, 2, 3, 4, 6, 7, 8]
?
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through the list and check if each element matches its index + 1. If it doesn't, return the index + 1. If all elements match, return the next integer after the last element.
1) Initialize an index variable `i` to 0.
2) Iterate through the list:
- Check if the current element `nums[i]` equals `i + 1`.
- If it does, move to the next index by incrementing `i`.
- If it doesn't, return `i + 1` as the smallest missing positive integer.
3) If the loop completes, return `i + 1` as the smallest missing positive integer because all elements matched their expected values.
**⚠️ Common Mistakes**
- Not accounting for lists that are complete with no missing integers, in which case the next integer after the last element is the smallest missing positive integer.
- Assuming the list may contain duplicates or is unsorted, which is not the case here.
- Off-by-one errors when comparing the current element to `i + 1`.
## I-mplement
```python
def find_missing_positive(nums):
i = 0
while i < len(nums):
if nums[i] == i + 1:
i += 1
else:
return i + 1
return i + 1