#2996
Smallest Missing Integer Greater Than Sequential Prefix Sum
EasyArrayHash TableSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach efficiently finds the longest sequential prefix in a single pass and uses a set to track existing numbers, allowing for quick checks for the smallest missing integer.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a set to store the numbers in the array for quick lookup.
- 2Step 2: Iterate through the array to find the longest sequential prefix and calculate its sum.
- 3Step 3: After determining the sum, check for the smallest integer greater than or equal to this sum that is not in the set.
solution.py23 lines
1# Full working Python code
2
3def smallest_missing_integer(nums):
4 num_set = set(nums)
5 max_sum = 0
6 current_sum = 0
7
8 for i in range(len(nums)):
9 if i == 0 or nums[i] == nums[i - 1] + 1:
10 current_sum += nums[i]
11 else:
12 max_sum = max(max_sum, current_sum)
13 current_sum = nums[i]
14
15 max_sum = max(max_sum, current_sum)
16
17 missing = max_sum
18 while missing in num_set:
19 missing += 1
20 return missing
21
22# Example usage
23print(smallest_missing_integer([1, 2, 3, 2, 5])) # Output: 6ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the array to find the longest sequential prefix and another pass to find the missing integer. The space complexity is O(n) due to the set used for quick lookups.
- 1The longest sequential prefix can be found in a single pass through the array.
- 2Using a set allows for O(1) average time complexity for checking existence of numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.