Count the Number of Incremovable Subarrays II - 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.

For example, the subarray [3, 4] is an incremovable subarray of [5, 3, 4, 6, 7] because removing this subarray changes the array [5, 3, 4, 6, 7] to [5, 6, 7] which is strictly increasing.

Return the total number of incremovable subarrays of nums.

Note: An empty array is considered strictly increasing. A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Mixed Array
$ Input: nums = [5,3,4,6,7]
Output: 9
💡 Note: We can remove subarrays like [3], [4], [3,4], [3,4,6], [3,4,6,7], [4,6], [4,6,7], [6,7], [7] to make remaining array strictly increasing.
Example 2 — Already Sorted
$ Input: nums = [1,2,3,4,5]
Output: 15
💡 Note: Array is already strictly increasing, so any subarray can be removed. Total = 5×6/2 = 15 subarrays.
Example 3 — Small Array
$ Input: nums = [6,5,7,8]
Output: 7
💡 Note: Can remove [5], [6], [6,5], [5,7], [6,5,7], [5,7,8], [6,5,7,8] to get strictly increasing arrays.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Count Incremovable Subarrays II INPUT Array nums: 5 i=0 3 i=1 4 i=2 6 i=3 7 i=4 Strictly Increasing Parts: Prefix: [5] Suffix: [6,7] Find all subarrays [l,r] where removing them makes array strictly increasing nums = [5,3,4,6,7] n = 5 ALGORITHM STEPS 1 Find Prefix Length Longest increasing prefix prefix_end = 0 (5 only) 2 Find Suffix Start Longest increasing suffix suffix_start = 3 (6,7) 3 Two Pointer Merge For each prefix end i, find valid suffix start j 4 Count Valid Pairs Count subarrays where nums[i] < nums[j] Valid Incremovable Subarrays: [3] [4] [3,4] [3,4,6] [3,4,6,7] [4,6] [4,6,7] [6] [6,7] Total: 9 subarrays FINAL RESULT After removing each subarray: Remove [3]: [5,4,6,7] X Remove [4]: [5,3,6,7] X Remove [3,4]: [5,6,7] OK Remove [3,4,6]: [5,7] OK Remove [3,4,6,7]: [5] OK Remove [4,6]: [5,3,7] X ... and more Output: 9 9 incremovable subarrays Time: O(n), Space: O(1) Key Insight: Use two-pointer technique: find longest strictly increasing prefix and suffix. For each valid prefix endpoint i, binary search or move pointer j in suffix where nums[i] < nums[j]. Count all valid (l,r) pairs where removing subarray [l..r] keeps remaining elements strictly increasing. TutorialsPoint - Count the Number of Incremovable Subarrays II | Optimal Solution
Asked in
Google 15 Meta 12
12.0K Views
Medium Frequency
~35 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen