Adjacent Increasing Subarrays Detection II - Problem

Given an array nums of n integers, your task is to find the maximum value of k for which there exist two adjacent subarrays of length k each, such that both subarrays are strictly increasing.

Specifically, check if there are two subarrays of length k starting at indices a and b (a < b), where:

  • Both subarrays nums[a..a + k - 1] and nums[b..b + k - 1] are strictly increasing.
  • The subarrays must be adjacent, meaning b = a + k.

Return the maximum possible value of k. A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,5,7,8,9,2,3,4,3,1]
Output: 1
💡 Note: We can find adjacent increasing subarrays of length 1, for example [2] at index 0 and [5] at index 1, both strictly increasing.
Example 2 — No Adjacent Pairs
$ Input: nums = [1,2,3,2,1]
Output: 1
💡 Note: We can find adjacent increasing subarrays of length 1, for example [1] at index 0 and [2] at index 1, both strictly increasing.
Example 3 — Small Array
$ Input: nums = [1,2]
Output: 0
💡 Note: Array is too small to have two adjacent subarrays of any positive length.

Constraints

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

Visualization

Tap to expand
Adjacent Increasing Subarrays Detection II INPUT nums array (n=10) 2 i=0 5 i=1 7 i=2 8 i=3 9 i=4 2 i=5 3 i=6 4 i=7 3 i=8 1 i=9 Goal: Find max k where two adjacent subarrays of length k are both strictly increasing b = a + k (adjacent) Both subarrays increasing ALGORITHM STEPS 1 Compute inc[] array Length of increasing run ending at each index 2 Build inc[] values inc[i] = inc[i-1]+1 if nums[i] > nums[i-1] inc[] = [1,2,3,4,5,1,2,3,1,1] Index: 0 1 2 3 4 5 6 7 8 9 3 Check adjacent pairs For each position i: k = min(inc[i], inc[i+k]) 4 Find maximum k Binary search or iterate to find largest valid k Time: O(n) | Space: O(n) FINAL RESULT Found adjacent subarrays at k=3: Subarray 1 (i=2 to 4): [7, 8, 9] Subarray 2 (i=5 to 7): [2, 3, 4] Verification: 7 < 8 < 9 -- OK (increasing) 2 < 3 < 4 -- OK (increasing) b=5 = a+k = 2+3 -- OK (adjacent) OUTPUT k = 3 Key Insight: Precompute inc[i] = length of strictly increasing subarray ending at index i. Then for each position, check if inc[i] >= k AND inc[i+k] >= k for some k. The max valid k at position i is min(inc[i], inc[i+k]). TutorialsPoint - Adjacent Increasing Subarrays Detection II | Precompute Increasing Lengths Approach
Asked in
Google 15 Microsoft 12 Amazon 8
8.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