25/06/2021

[Java] Minimum subarray of sum K

Given an array of positive integers and a target positive integer value, find the subarray of consecutive elements whose sum is equal to or more than target.

We use our trusty sliding window technique, and keep summing until we reach the threshold.

Then we check if we can reduce the current subarray size by reducing the window start range while remaining above the threshold and keep doing that as long as it's possible (either we reached current element in array or sum of subarray would fall below threshold).

At most we do 2N passes on the array as the end range pointer will walk all of it and the start range pointer might follow all the way to the end, so in O(N) time ans constant space we have our answer.

You can check my implementation of minSubarrayOfSumK on my Gist along with some tests in MinSubarrayOfSumKJTests.

No comments:

Post a Comment

With great power comes great responsibility