Count the Number of Incremovable Subarrays I - Problem

You are given a 0-indexed array of positive integers nums. A subarray of nums is called incremovable if nums becomes strictly increasing after 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 that an empty array is considered strictly increasing. A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,3,4,6,7]
Output: 6
💡 Note: The 6 incremovable subarrays are: [3,4], [3,4,6], [3,4,6,7], [5,3], [5,3,4], [5,3,4,6]. After removing any of these, the remaining array is strictly increasing.
Example 2 — Already Sorted
$ Input: nums = [1,2,3,4]
Output: 10
💡 Note: Since the array is already strictly increasing, we can remove any subarray. Total subarrays = n(n+1)/2 = 4×5/2 = 10.
Example 3 — Minimum Size
$ Input: nums = [6,5]
Output: 3
💡 Note: We can remove [6], [5], or [6,5]. All result in strictly increasing (or empty) arrays.

Constraints

  • 1 ≤ nums.length ≤ 50
  • 1 ≤ nums[i] ≤ 50

Visualization

Tap to expand
Count Incremovable Subarrays INPUT Array nums: 5 i=0 3 i=1 4 i=2 6 i=3 7 i=4 Red = Example removable subarray Incremovable Subarray: A subarray whose removal makes the remaining array strictly increasing Remove [3,4] --> [5,6,7] 5 < 6 < 7 (OK - Increasing) nums = [5, 3, 4, 6, 7] n = 5 elements ALGORITHM STEPS 1 Find Left Prefix Find longest increasing prefix from start 2 Find Right Suffix Find longest increasing suffix from end 3 Count Subarrays For each valid (i,j) pair count removable subarrays 4 Two Pointer Merge Check nums[i] < nums[j] for valid combinations Valid Subarrays to Remove: [3] --> [5,4,6,7] [4] --> [5,3,6,7] [3,4] --> [5,6,7] [3,4,6] --> [5,7] [3,4,6,7] --> [5] + 1 more... FINAL RESULT Answer: 6 6 Incremovable Subarrays All Valid Removals: 1. Remove [3] i=1 to 1 2. Remove [4] i=2 to 2 3. Remove [3,4] i=1 to 2 4. Remove [3,4,6] i=1 to 3 5. Remove [3,4,6,7] i=1 to 4 6. Remove [4,6] i=2 to 3 (Each removal leaves strictly increasing array) Output: 6 (OK) Key Insight: Use two pointers: find longest increasing prefix (left) and suffix (right). A subarray is incremovable if removing it leaves elements where prefix_end < suffix_start. Count all valid (i, j) pairs in O(n) time by merging prefix and suffix pointers, ensuring the remaining array maintains strict increasing order. TutorialsPoint - Count the Number of Incremovable Subarrays I | Optimized Single Pass Approach
Asked in
Microsoft 8 Google 5
12.5K Views
Medium Frequency
~25 min Avg. Time
234 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