Problem

You are given a 0-indexed array of integers nums.

A prefix nums[0..i] is sequential if, for all 1 <= j <= i, nums[j] = nums[j - 1] + 1. In particular, the prefix consisting only of nums[0] is sequential.

Return thesmallest integer x missing from nums such that x is greater than or equal to the sum of thelongest sequential prefix.

Examples

Example 1

1
2
3
Input: nums = [1,2,3,2,5]
Output: 6
Explanation: The longest sequential prefix of nums is [1,2,3] with a sum of 6. 6 is not in the array, therefore 6 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.

Example 2

1
2
3
Input: nums = [3,4,5,1,12,14,13]
Output: 15
Explanation: The longest sequential prefix of nums is [3,4,5] with a sum of 12. 12, 13, and 14 belong to the array while 15 does not. Therefore 15 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.

Constraints

  • 1 <= nums.length <= 50
  • 1 <= nums[i] <= 50

Solution

Method 1 – Hash Set and Prefix Scan

Intuition

First, find the longest sequential prefix and compute its sum. Then, find the smallest integer greater than or equal to this sum that is missing from the array. A set allows for fast lookup of missing numbers.

Approach

  1. Scan the array to find the longest sequential prefix (nums[0..i] where nums[j] = nums[j-1] + 1).
  2. Compute the sum of this prefix.
  3. Put all numbers in a set for O(1) lookup.
  4. Starting from the prefix sum, increment until you find a number not in the set.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
    int missingInteger(vector<int>& nums) {
        int n = nums.size(), i = 1, s = nums[0];
        while (i < n && nums[i] == nums[i-1] + 1) s += nums[i++];
        unordered_set<int> st(nums.begin(), nums.end());
        int x = s;
        while (st.count(x)) ++x;
        return x;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import java.util.*;
class Solution {
    public int missingInteger(int[] nums) {
        int n = nums.length, i = 1, s = nums[0];
        while (i < n && nums[i] == nums[i-1] + 1) s += nums[i++];
        Set<Integer> st = new HashSet<>();
        for (int x : nums) st.add(x);
        int x = s;
        while (st.contains(x)) x++;
        return x;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def missingInteger(self, nums):
        i, s = 1, nums[0]
        while i < len(nums) and nums[i] == nums[i-1] + 1:
            s += nums[i]
            i += 1
        st = set(nums)
        x = s
        while x in st:
            x += 1
        return x

Complexity

  • ⏰ Time complexity: O(n + m), where n = len(nums), m is the answer minus prefix sum (at most 50).
  • 🧺 Space complexity: O(n) for the set.