Find the Number of Copy Arrays - Problem
Array Transformation with Constraints

You're given an original array of length n and a 2D array bounds where each bounds[i] = [ui, vi] defines the valid range for position i.

Your task is to find how many different copy arrays can be created such that:

๐Ÿ“ Preserve Differences: The difference between consecutive elements in copy must match the differences in original: (copy[i] - copy[i-1]) == (original[i] - original[i-1]) for all valid i

๐ŸŽฏ Stay Within Bounds: Each copy[i] must satisfy ui โ‰ค copy[i] โ‰ค vi

Example: If original = [1, 3, 2] and we start copy[0] = 5, then copy[1] = 7 and copy[2] = 6 to preserve the differences +2 and -1.

Input & Output

example_1.py โ€” Basic Case
$ Input: original = [1, 3, 2], bounds = [[1,5], [2,4], [1,3]]
โ€บ Output: 2
๐Ÿ’ก Note: Two valid copy arrays exist: [1,3,2] and [2,4,3]. Both preserve the differences +2,-1 and stay within bounds.
example_2.py โ€” No Valid Arrays
$ Input: original = [1, 5], bounds = [[1,2], [1,3]]
โ€บ Output: 0
๐Ÿ’ก Note: The difference +4 is required, but starting from bounds [1,2] would need copy[1] to be 5-7, exceeding bound [1,3].
example_3.py โ€” Single Element
$ Input: original = [5], bounds = [[2,8]]
โ€บ Output: 7
๐Ÿ’ก Note: With only one element, any value in bounds [2,8] works: 2,3,4,5,6,7,8 = 7 possibilities.

Visualization

Tap to expand
Array Copy ConstructionOriginal:132Differences:+2-1Bounds:[1,5][2,4][1,3]Valid Copies:132243Result: 2 arraysStarting positions:1 and 2 work3,4,5 would violate bounds
Understanding the Visualization
1
Identify Differences
Calculate differences between consecutive elements in original array
2
Apply Constraints
For each position, determine what values are valid given the bounds
3
Propagate Backwards
Work backwards to find valid starting positions
4
Count Solutions
Count how many starting positions lead to valid arrays
Key Takeaway
๐ŸŽฏ Key Insight: Once we choose the first element, the entire array is determined by the difference pattern. We only need to find which starting values keep all elements within bounds.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(R ร— n)

R is the range of the first bound (vi - ui), n is array length

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Space to store the copy array being constructed

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค n โ‰ค 1000
  • bounds.length == n
  • bounds[i].length == 2
  • -104 โ‰ค original[i] โ‰ค 104
  • -104 โ‰ค bounds[i][0] โ‰ค bounds[i][1] โ‰ค 104
  • The bounds are inclusive ranges
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
23.5K Views
Medium Frequency
~25 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