C# - O(n) two pointer - sliding window


  • 0

    Your window is between the left and right inclusive. Anytime the sum of the window meets the criteria check for a min length. If the sum is greater than or equal to the target move the left edge and subtract from you running sum, else move the right edge and add to the running sum. The trickiest part was the edge cases, here I decided to add and remove right edge unless it advances to have fewer conditionals and make the code a little more concise.

        public int MinSubArrayLen(int s, int[] nums) 
        {
            int left = 0;
            int right = 0;
            int sum = 0;
            int minLen = int.MaxValue;
            
            while (right < nums.Length)
            {
                sum += nums[right];
                
                if (sum >= s)
                {
                    minLen = Math.Min(minLen, right - left + 1);
                    sum -= nums[left];
                    left++;
                    sum -= nums[right];
                }
                else
                {
                    right++;
                }
            }
            
            return minLen != int.MaxValue ? minLen : 0;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.