Count the Number of Incremovable Subarrays I - Problem

You're given a 0-indexed array of positive integers nums. Your task is to count how many subarrays can be removed to make the remaining array strictly increasing.

A subarray is called incremovable if removing it results in a strictly increasing sequence. For example, in the array [5, 3, 4, 6, 7], removing the subarray [3, 4] gives us [5, 6, 7], which is strictly increasing.

Key points:

  • A subarray is a contiguous sequence of elements
  • An empty array is considered strictly increasing
  • You need to count all possible incremovable subarrays

Return the total number of incremovable subarrays in the given array.

Input & Output

example_1.py โ€” Basic case
$ Input: [1, 2, 3, 4]
โ€บ Output: 10
๐Ÿ’ก Note: Array is already strictly increasing. We can remove any subarray: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], [1,2,3,4]. Total = 10 subarrays.
example_2.py โ€” Mixed case
$ Input: [6, 3, 7, 11]
โ€บ Output: 9
๐Ÿ’ก Note: We can remove: [6], [3], [7], [11], [6,3], [3,7], [7,11], [6,3,7], [3,7,11] to get valid increasing sequences. Total = 9 subarrays.
example_3.py โ€” Single element
$ Input: [5]
โ€บ Output: 1
๐Ÿ’ก Note: Only one subarray [5] can be removed, leaving an empty array which is considered strictly increasing.

Constraints

  • 1 โ‰ค nums.length โ‰ค 50
  • 1 โ‰ค nums[i] โ‰ค 50
  • All elements are positive integers
  • Subarray must be contiguous and non-empty

Visualization

Tap to expand
Incremovable Subarray StrategyStep 1: Find Increasing Prefix and Suffix1324156PREFIXREMOVABLESUFFIXStep 2: Valid Removal Example13563 < 5 โœ“Result: [1,3,5,6] - Valid!Count all valid combinations where prefix + suffix forms increasing sequence
Understanding the Visualization
1
Identify prefix
Find the longest increasing sequence from the start
2
Identify suffix
Find the longest increasing sequence from the end
3
Count removals
Count all valid ways to remove middle elements
4
Verify connections
Ensure prefix and suffix can connect properly
Key Takeaway
๐ŸŽฏ Key Insight: The optimal approach leverages the fact that after removing any subarray, we're left with a prefix and suffix that must connect to form a strictly increasing sequence. By pre-computing the longest increasing prefix and suffix, we can efficiently count all valid removal combinations.
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
28.9K Views
Medium Frequency
~15 min Avg. Time
847 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