Count the Number of Incremovable Subarrays II — LeetCode 2972 Python Solution

HardArrayTwo PointersBinary Search
Problem
#2972
Reading time
3 min

The problem

You are given a 0-indexed array of positive integers nums. A subarray of nums is called incremovable if nums becomes strictly increasing on removing the subarray.

Example

Input
nums = [1,2,3,4]
Output
10
Explanation
The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray.

Python solution

Python
class Solution:
    def incremovableSubarrayCount(self, nums: List[int]) -> int:
        i, n = 0, len(nums)
        while i + 1 < n and nums[i] < nums[i + 1]:
            i += 1
        if i == n - 1:
            return n * (n + 1) // 2
        ans = i + 2
        j = n - 1
        while j:
            while i >= 0 and nums[i] >= nums[j]:
                i -= 1
            ans += i + 2
            if nums[j - 1] >= nums[j]:
                break
            j -= 1
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2972. Count the Number of Incremovable Subarrays II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2972. Count the Number of Incremovable Subarrays II?
LeetCode 2972. Count the Number of Incremovable Subarrays II is rated Hard on LeetCode.
What is the time complexity of LeetCode 2972. Count the Number of Incremovable Subarrays II?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 2972. Count the Number of Incremovable Subarrays II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2972. Count the Number of Incremovable Subarrays II cover?
LeetCode 2972. Count the Number of Incremovable Subarrays II is tagged Array, Two Pointers and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview