Minimum Size Subarray in Infinite Array - Problem
You are given a 0-indexed array nums and an integer target.
A 0-indexed array infinite_nums is generated by infinitely appending the elements of nums to itself.
Return the length of the shortest subarray of the array infinite_nums with a sum equal to target. If there is no such subarray return -1.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3], target = 5
›
Output:
2
💡 Note:
In the infinite array [1,2,3,1,2,3,1,2,3,...], the subarray [2,3] has sum 5 and length 2, which is the minimum possible.
Example 2 — Wraparound
$
Input:
nums = [1,4,4], target = 5
›
Output:
2
💡 Note:
The infinite array is [1,4,4,1,4,4,...]. The subarray [4,1] (wrapping around) has sum 5 and length 2.
Example 3 — No Solution
$
Input:
nums = [2,4,6,8], target = 3
›
Output:
-1
💡 Note:
All elements are even, so no combination can sum to the odd target 3.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
- 1 ≤ target ≤ 108
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,2,3] repeated infinitely, target = 5
2
Process
Find shortest contiguous subarray summing to target
3
Output
Return length 2 (subarray [2,3])
Key Takeaway
🎯 Key Insight: The minimum subarray length in an infinite array is bounded by 2×n, making the problem tractable with finite array extensions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code