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
1231Infinite Circular Array: [1,2,3,1,2,3,...]Target = 5: Shortest path 2โ†’3 (length 2)
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).
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
31.8K Views
Medium Frequency
~25 min Avg. Time
1.4K 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