Leetcode-Top-150-Question-Day-5: Sliding Window
Topic : Sliding Window
Question: 1 -> 209. Minimum Size Subarray Sum
Problem Statement :
we have given an array of positive integers nums
and a positive integer target
, we have to return the minimal length of a subarray whose sum is greater than or equal to target
.
Intuition :
If we solve it by brute force
approach ,T.C will be high. We can also use Prefix-sum and binary-search approach
, T.C will be n(log n)
, that why i choose Sliding window,
so T.C will be O(n)
.
The sliding window technique allows us to efficiently search for the minimum length subarray that satisfies the given condition. By maintaining two pointers and adjusting the window based on the sum of elements, we can avoid unnecessary computations and achieve a time complexity of O(N), where N is the size of the input array nums
.
Sliding Window Approach :
- Initialize two pointers,
left
andright
, to track the start and end of the current subarray, respectively. Setleft
andright
to 0 initially. - Initialize a variable
sum
to keep track of the current sum of elements in the subarray. - Initialize a variable
miniLen
to store the minimum length found so far. Set it to the maximum possible integer value (INT_MAX
). - Start a while loop that continues until the
right
pointer reaches the end of the arraynums
. - Inside the loop, add the element at index
right
to thesum
variable. - Check if the
sum
is greater than or equal to the target value. - If the condition is true, enter another while loop. This loop will handle the case where the current subarray sum is equal to or greater than the target.
i ) . Decrement thesum
by subtracting the element at indexleft
.
ii ) . UpdateminiLen
with the minimum length found so far (right - left + 1
).
iii ) . Increment theleft
pointer to move the window to the right.
d. Repeat steps a-c until thesum
is no longer greater than or equal to the target value. - Increment the
right
pointer to move the window to the right. - Repeat steps 5–8 until the
right
pointer reaches the end of the array. - After the loop, check if the value of
miniLen
is stillINT_MAX
, indicating that no subarray was found. In this case, return 0. - Otherwise, return the value of
miniLen
, which represents the minimum length of a subarray whose sum is greater than or equal to the target.
Complexity
- The time complexity of this solution is
O(n)
, - The space complexity is
O(1)
because we are using a constant amount of extra space for the pointers and temporary variables.
CODE:
HOPE YOU LIKE MY APPROACHE!!!
THANKYOU!!!