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: [5,3,4,6,7]5346701234Examples of incremovable subarrays:Remove [3] → [5,4,6,7] ✗Remove [3,4] → [5,6,7] ✓Remove [4,6] → [5,3,7] ✗Remove [6,7] → [5,3,4] ✗Remove [7] → [5,3,4,6] ✗Remove [3,4,6,7] → [5] ✓Answer: 9 incremovable subarrays total
Understanding the Visualization
1
Input Array
[5,3,4,6,7] with mixed increasing/decreasing sections
2
Try Removals
Test removing various subarrays and check if remainder is sorted
3
Count Valid
Total of 9 different subarrays can be removed
Key Takeaway
🎯 Key Insight: Use prefix/suffix analysis with two pointers to efficiently count valid removals without testing each one
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