Leetcode #2972: Count the Number of Incremovable Subarrays II
In this guide, we solve Leetcode #2972 Count the Number of Incremovable Subarrays II in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Two Pointers, Binary Search
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
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
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
The time complexity is , where is the length of the array . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.