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
Minimum Size Subarray in Infinite ArrayInput:123Target: 5Infinite Array:123123...Found: [2,3] with sum = 5Process: Check all possible subarrays for target sumOutput: 2 (minimum length)
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
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
28.5K Views
Medium-High Frequency
~25 min Avg. Time
892 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