Find the Number of Copy Arrays Problem
#3468
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3468.
You are given an array original of length n and a 2D array bounds of length n x 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])for1 <= i <= n - 1.u_i <= copy[i] <= v_ifor0 <= i <= n - 1.
Return the number of such arrays.
Example 1:
Input: original = [1,2,3,4], bounds = [[1,2],[2,3],[3,4],[4,5]]
Output: 2
Explanation:
The possible arrays are:
- [1, 2, 3, 4]
- [2, 3, 4, 5]
Example 2:
Input: original = [1,2,3,4], bounds = [[1,10],[2,9],[3,8],[4,7]]
Output: 4
Explanation:
The possible arrays are:
- [1, 2, 3, 4]
- [2, 3, 4, 5]
- [3, 4, 5, 6]
- [4, 5, 6, 7]
Example 3:
Input: original = [1,2,1,2], bounds = [[1,1],[2,3],[3,3],[2,3]]
Output: 0
Explanation:
No array is possible.
Constraints:
2 <= n == original.length <= 10^51 <= original[i] <= 10^9bounds.length == nbounds[i].length == 21 <= bounds[i][0] <= bounds[i][1] <= 10^9
Solution
Approach: Interval Intersection
Because a copy has the same adjacent differences as original, it is determined by its first value x: copy[i] = x + (original[i] - original[0]).
The condition bounds[i][0] <= copy[i] <= bounds[i][1] becomes bounds[i][0] - d <= x <= bounds[i][1] - d with d = original[i] - original[0]. Intersect these ranges over all i (the one for i = 0 is bounds[0] itself). If the intersection is [lo, hi], the answer is max(0, hi - lo + 1).
Complexity: O(n) time, O(1) extra space.
class Solution:
def countArrays(self, original: List[int], bounds: List[List[int]]) -> int:
lo, hi = bounds[0]
for i in range(1, len(original)):
d = original[i] - original[0]
lo = max(lo, bounds[i][0] - d)
hi = min(hi, bounds[i][1] - d)
return max(0, hi - lo + 1)