Skip to content

2996. Smallest Missing Integer Greater Than Sequential Prefix Sum 👎

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int missingInteger(vector<int>& nums) {
    const unordered_set<int> numsSet{nums.begin(), nums.end()};
    int ans = nums[0];

    for (int i = 1; i < nums.size(); ++i) {
      if (nums[i] != nums[i - 1] + 1)
        break;
      ans += nums[i];
    }

    while (numsSet.contains(ans))
      ++ans;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int missingInteger(int[] nums) {
    Set<Integer> numsSet = Arrays.stream(nums).boxed().collect(Collectors.toSet());
    int ans = nums[0];

    for (int i = 1; i < nums.length; ++i) {
      if (nums[i] != nums[i - 1] + 1)
        break;
      ans += nums[i];
    }

    while (numsSet.contains(ans))
      ++ans;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def missingInteger(self, nums: list[int]) -> int:
    numsSet = set(nums)
    ans = nums[0]

    for i in range(1, len(nums)):
      if nums[i] != nums[i - 1] + 1:
        break
      ans += nums[i]

    while ans in numsSet:
      ans += 1

    return ans