Find the Number of Copy Arrays - Problem

You are given an array original of length n and a 2D array bounds of length n × 2, where bounds[i] = [u_i, v_i].

You need to find the number of possible arrays copy of length n such that:

  • (copy[i] - copy[i - 1]) == (original[i] - original[i - 1]) for 1 <= i <= n - 1
  • u_i <= copy[i] <= v_i for 0 <= i <= n - 1

Return the number of such arrays.

Input & Output

Example 1 — Basic Case
$ Input: original = [1,3,2], bounds = [[1,1],[1,3],[2,4]]
Output: 1
💡 Note: Only one valid copy array [1,3,2]. Starting with copy[0]=1, we get copy[1]=1+(3-1)=3, copy[2]=3+(2-3)=2. All elements satisfy their bounds.
Example 2 — No Valid Arrays
$ Input: original = [1,2,3], bounds = [[1,1],[2,2],[5,5]]
Output: 0
💡 Note: If copy[0]=1, then copy[1]=1+(2-1)=2, copy[2]=2+(3-2)=3. But copy[2]=3 doesn't satisfy bounds[2]=[5,5], so no valid arrays exist.
Example 3 — Multiple Valid Arrays
$ Input: original = [1,1,1], bounds = [[1,3],[1,3],[1,3]]
Output: 3
💡 Note: Since all differences are 0, copy array will be [x,x,x] for any starting value x. Valid starting values are 1,2,3, giving 3 possible arrays.

Constraints

  • 1 ≤ n ≤ 105
  • -109 ≤ original[i] ≤ 109
  • -109 ≤ ui ≤ vi ≤ 109

Visualization

Tap to expand
Find the Number of Copy Arrays INPUT original[] 1 3 2 i=0 i=1 i=2 bounds[][] [1,1] u=1,v=1 [1,3] u=1,v=3 [2,4] u=2,v=4 Differences: d[1] = 3-1 = +2 d[2] = 2-3 = -1 copy must maintain same differences within bounds ALGORITHM STEPS 1 Initialize Range Start: low=1, high=1 (from bounds[0]) 2 Process i=1 Add diff: low=1+2=3 high=1+2=3 Intersect [1,3]: [3,3] 3 Process i=2 Add diff: low=3-1=2 high=3-1=2 Intersect [2,4]: [2,2] 4 Count Valid Arrays Final range: [2,2] Count = high-low+1 Count = 2-2+1 = 1 Range shrinks: [1,1]-->[3,3]-->[2,2] FINAL RESULT Valid copy[] Array: 1 3 2 Verification: Differences match: OK 3-1=2 (same as original) 2-3=-1 (same as original) All within bounds: OK Output: 1 Only 1 valid copy array exists Key Insight: Range Intersection Approach The key is to track the valid range of copy[0] values. Since differences are fixed, once copy[0] is chosen, all other values are determined. We iteratively intersect the valid range with bounds constraints. Final count = (high - low + 1) if range is valid, otherwise 0. Time: O(n), Space: O(1). TutorialsPoint - Find the Number of Copy Arrays | Range Intersection Approach
Asked in
Google 15 Microsoft 12
8.5K Views
Medium Frequency
~25 min Avg. Time
350 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