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 Array INPUT nums = [1, 2, 3] 1 idx 0 2 idx 1 3 idx 2 infinite_nums (conceptual): 1 2 3 1 2 3 ... target = 5 nums = [1, 2, 3] target = 5 Array sum = 6 Length = 3 ALGORITHM (Hash) 1 Prefix Sum Hash Store prefix sums in hashmap prefixSum: index 0:0, 1:1, 3:2, 6:3 7:4, 9:5, 12:6... 2 Check Full Copies target/sum = full array count 5/6 = 0 copies, rem = 5 3 Find Remainder Search in 2 copies for remaining sum = 5 Sliding window in [1,2,3,1,2,3]: [2,3] at idx 1-2, sum=5 OK 4 Return Min Length full_copies*n + remainder 0*3 + 2 = 2 FINAL RESULT Shortest subarray with sum = 5: 1 2 3 1 sum = 2+3 = 5 Output 2 OK - Verified! Subarray [2,3] Length = 2, Sum = 5 Key Insight: For infinite array, we only need to consider at most 2 copies of original array. Use prefix sum hashing to find subarray sums in O(1). Total copies = target/totalSum. Then find remaining sum in doubled array. Time: O(n), Space: O(n) for hashmap storing prefix sums. TutorialsPoint - Minimum Size Subarray in Infinite Array | Hash Approach
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