Minimum Size Subarray in Infinite Array - Problem
You are given a 0-indexed array nums and an integer target.
Imagine creating an infinite array by repeatedly appending the elements of nums to itself: [nums[0], nums[1], ..., nums[n-1], nums[0], nums[1], ..., nums[n-1], ...]
Your task is to find the shortest contiguous subarray within this infinite array that has a sum exactly equal to target.
Return: The length of the shortest such subarray, or -1 if no such subarray exists.
Example: If nums = [1, 2, 3] and target = 5, the infinite array looks like [1, 2, 3, 1, 2, 3, 1, 2, 3, ...]. The shortest subarray with sum 5 is [2, 3] with length 2.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,2,3], target = 5
โบ
Output:
2
๐ก Note:
The infinite array is [1,2,3,1,2,3,1,2,3,...]. The shortest subarray with sum 5 is [2,3] with length 2.
example_2.py โ Multiple Cycles
$
Input:
nums = [1,1,1,2,3], target = 4
โบ
Output:
2
๐ก Note:
The infinite array is [1,1,1,2,3,1,1,1,2,3,...]. The shortest subarray with sum 4 is [1,3] with length 2.
example_3.py โ No Solution
$
Input:
nums = [2,4,6,8], target = 3
โบ
Output:
-1
๐ก Note:
Since all numbers in nums are even and 3 is odd, no subarray can sum to 3.
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 106
- 1 โค target โค 109
- All elements in nums are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Map the Circular Path
The array [1,2,3] becomes an infinite circular path: 1โ2โ3โ1โ2โ3...
2
Calculate Full Laps
If target is much larger than array sum, calculate how many complete laps needed
3
Find Shortest Segment
For remaining target, find shortest path segment using prefix sums
4
Combine Results
Total distance = (Full laps ร path length) + shortest segment
Key Takeaway
๐ฏ Key Insight: By recognizing that we only need to check at most 2 complete cycles and using prefix sums, we can solve this efficiently in O(n) time instead of brute force O(n ร target).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code