#2875

Minimum Size Subarray in Infinite Array

Medium
ArrayHash TableSliding WindowPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages prefix sums and a hash map to efficiently find the shortest subarray that sums to the target. By calculating prefix sums, we can quickly determine the sum of any subarray.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the prefix sums of the nums array and store them in a list.
  2. 2Step 2: Use a hash map to track the first occurrence of each prefix sum modulo the total sum of nums.
  3. 3Step 3: Iterate through the prefix sums, checking if the difference between the current prefix sum and target can be found in the hash map, and update the minimum length accordingly.
solution.py22 lines
1# Full working Python code
2
3def min_size_subarray(nums, target):
4    n = len(nums)
5    total_sum = sum(nums)
6    prefix_sum = [0] * (2 * n + 1)
7    for i in range(1, 2 * n + 1):
8        prefix_sum[i] = prefix_sum[i - 1] + nums[(i - 1) % n]
9
10    min_length = float('inf')
11    prefix_map = {0: -1}
12
13    for i in range(2 * n):
14        current_sum = prefix_sum[i + 1]
15        needed_sum = current_sum - target
16
17        if needed_sum in prefix_map:
18            min_length = min(min_length, i - prefix_map[needed_sum])
19
20        prefix_map[current_sum % total_sum] = i
21
22    return min_length if min_length != float('inf') else -1

Complexity note: This complexity arises because we compute prefix sums in linear time and use a hash map to store them, which also takes linear space.

  • 1Understanding how to leverage prefix sums can greatly reduce the complexity of array problems.
  • 2Recognizing that the infinite nature of the array can be handled with modular arithmetic is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.