Adjacent Increasing Subarrays Detection I - Problem

Given an array nums of n integers and an integer k, determine whether there exist two adjacent subarrays of length k such that both subarrays are strictly increasing.

Specifically, check if there are two subarrays 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 true if it is possible to find two such subarrays, and false otherwise.

Input & Output

Example 1 — Basic Valid Case
$ Input: nums = [1,2,3,4,5], k = 2
Output: true
💡 Note: Subarrays [1,2] at index 0 and [2,3] at index 1 are adjacent. [1,2]: 2 > 1 ✓ (strictly increasing). [2,3]: 3 > 2 ✓ (strictly increasing). Both adjacent subarrays are strictly increasing.
Example 2 — Valid Adjacent Increasing Subarrays
$ Input: nums = [1,2,3,4,5], k = 2
Output: true
💡 Note: Subarrays [1,2] at index 0 and [2,3] at index 1 are adjacent. [1,2]: 2 > 1 ✓ (strictly increasing). [2,3]: 3 > 2 ✓ (strictly increasing). Both adjacent subarrays are strictly increasing.
Example 3 — No Valid Adjacent Pairs
$ Input: nums = [1,3,2,4], k = 2
Output: false
💡 Note: Position 0: [1,3] (increasing) + [3,2] (decreasing) = false. Position 1: [3,2] (decreasing) + [2,4] (increasing) = false. No adjacent pair of increasing subarrays exists.

Constraints

  • 2 ≤ nums.length ≤ 100
  • 1 ≤ k ≤ nums.length / 2
  • -100 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Adjacent Increasing Subarrays Detection INPUT Array nums: 2 i=0 5 i=1 3 i=2 4 i=3 1 i=4 k = 2 Goal: Find two adjacent strictly increasing subarrays of length k Adjacent: b = a + k Subarray 1 Subarray 2 ALGORITHM STEPS 1 Initialize counter cnt = 0 (increasing length) 2 Scan array If nums[i] > nums[i-1]: cnt++ Else: cnt = 0 3 Check condition If cnt >= 2*k - 1: return true 4 Trace Example k=2, need cnt >= 3 i nums[i] cnt check 1 5>2 1 1<3 2 3<5 0 0<3 3 4>3 1 1<3 -- [2,5][3,4] OK FOUND! FINAL RESULT Adjacent Increasing Subarrays Found: Subarray 1 [2, 5] i=0,1 Subarray 2 [3, 4] i=2,3 Verification: 2 < 5 (strictly increasing) 3 < 4 (strictly increasing) Adjacent: b=2 = a+k = 0+2 true Two adjacent increasing subarrays exist! Time: O(n) | Space: O(1) Key Insight: Instead of checking all possible subarray pairs, track the length of the current strictly increasing sequence. If this length reaches 2*k - 1, we have found two adjacent increasing subarrays of length k. For k=2: need 3 consecutive increasing elements (positions a, a+1, a+2) forming [a,a+1] and [a+1,a+2]. TutorialsPoint - Adjacent Increasing Subarrays Detection I | Single Pass with Length Tracking
Asked in
Google 12 Amazon 8 Microsoft 6
8.5K Views
Medium Frequency
~15 min Avg. Time
245 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