Find the Count of Monotonic Pairs I - Problem

You are given an array of positive integers nums of length n.

We call a pair of non-negative integer arrays (arr1, arr2) monotonic if:

  • The lengths of both arrays are n
  • arr1 is monotonically non-decreasing, in other words, arr1[0] <= arr1[1] <= ... <= arr1[n - 1]
  • arr2 is monotonically non-increasing, in other words, arr2[0] >= arr2[1] >= ... >= arr2[n - 1]
  • arr1[i] + arr2[i] == nums[i] for all 0 <= i <= n - 1

Return the count of monotonic pairs. Since the answer may be very large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,2]
Output: 4
💡 Note: Valid monotonic pairs: ([0,1,1],[2,2,1]), ([0,1,2],[2,2,0]), ([0,2,2],[2,1,0]), ([1,2,2],[1,1,0]). Each satisfies arr1 non-decreasing and arr2 non-increasing constraints.
Example 2 — Minimum Size
$ Input: nums = [5,5]
Output: 6
💡 Note: For each position, arr1 can be 0-5. Valid pairs: (0,5),(1,4),(2,3),(3,2),(4,1),(5,0) where arr1 is non-decreasing and arr2 is non-increasing.
Example 3 — Single Element
$ Input: nums = [3]
Output: 4
💡 Note: Single position allows arr1 values 0,1,2,3 with corresponding arr2 values 3,2,1,0. All are valid since no monotonic constraints between positions.

Constraints

  • 1 ≤ nums.length ≤ 2000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Monotonic Pairs: Split nums into Two Complementary Arrays232nums = [2,3,2]arr1[0]arr1[1]arr1[2]↗ non-decreasingarr2[0]arr2[1]arr2[2]↘ non-increasingValid Example Pairsarr1=[0,1,1], arr2=[2,2,1] ✓arr1=[0,1,2], arr2=[2,2,0] ✓arr1=[0,2,2], arr2=[2,1,0] ✓arr1=[1,2,2], arr2=[1,1,0] ✓Total Count: 4Constraint: arr1[i] + arr2[i] = nums[i] for all iChallenge: Count ALL valid monotonic pairs efficiently
Understanding the Visualization
1
Input
Array nums = [2,3,2] to split into arr1 + arr2
2
Constraints
arr1 non-decreasing, arr2 non-increasing, arr1[i] + arr2[i] = nums[i]
3
Count
Find all valid (arr1, arr2) pairs
Key Takeaway
🎯 Key Insight: Use DP to track valid arr1 values at each position, ensuring monotonic constraints are maintained
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
12.5K Views
Medium Frequency
~35 min Avg. Time
285 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