Skip to content
jgreenrise edited this page Oct 20, 2023 · 1 revision

I'll illustrate the sliding window approach used in the code with a diagram for the example where "target" is 7, and "nums" is [2,3,1,2,4,3]. The goal is to find the minimum length of a subarray with a sum greater than or equal to 7.

Initial state:

     [2, 3, 1, 2, 4, 3]
     ^                ^
 leftPtr           rightPtr
 currSum = 0
 currOutLength = MAX_VALUE
  1. The window starts at the beginning of the array. We increment "rightPtr" and add values to "currSum" until we reach a sum greater than or equal to the target:
     [2, 3, 1, 2, 4, 3]
        ^             ^
    leftPtr       rightPtr
    currSum = 5 (2 + 3)
    currOutLength = MAX_VALUE
  1. Continue moving the right pointer to the right:
     [2, 3, 1, 2, 4, 3]
           ^          ^
       leftPtr    rightPtr
       currSum = 6 (2 + 3 + 1)
       currOutLength = MAX_VALUE
  1. The sum is still less than the target, so we continue:
     [2, 3, 1, 2, 4, 3]
              ^       ^
          leftPtr rightPtr
          currSum = 8 (2 + 3 + 1 + 2)
          currOutLength = 3 (rightPtr - leftPtr + 1)
  1. Now, the sum is equal to the target. We update "currOutLength" to 3, which is the length of the current subarray.

  2. Move the left pointer to shrink the window:

     [2, 3, 1, 2, 4, 3]
                ^    ^
          leftPtr   rightPtr
          currSum = 7 (3 + 1 + 2 + 1)
          currOutLength = 2 (rightPtr - leftPtr + 1)
  1. Continue moving the left pointer:
     [2, 3, 1, 2, 4, 3]
                  ^  ^
          leftPtr  rightPtr
          currSum = 9 (3 + 1 + 2 + 1 + 2)
          currOutLength = 2
  1. Shrink the window again:
     [2, 3, 1, 2, 4, 3]
                    ^ ^
          leftPtr    rightPtr
          currSum = 7 (1 + 2 + 4)
          currOutLength = 3
  1. Continue moving the left pointer:
     [2, 3, 1, 2, 4, 3]
                      ^^
          leftPtr      rightPtr
          currSum = 7 (2 + 4 + 3)
          currOutLength = 3
  1. Shrink the window again:
     [2, 3, 1, 2, 4, 3]
                        ^^
          leftPtr        rightPtr
          currSum = 3 (4 + 3)
          currOutLength = 3
  1. Move the left pointer:
     [2, 3, 1, 2, 4, 3]
                           ^^
          leftPtr           rightPtr
          currSum = 0
          currOutLength = 2
  1. Finally, we reach the end of the array, and the minimum subarray length found is 2.

So, the code returns 2 as the minimum length of the subarray [4, 3] with a sum greater than or equal to the target (7).

Clone this wiki locally