Total number subarray in an array which has a total sum equal to target value k

Yash Jain
CodingWithYash
Published in
1 min readAug 18, 2020

For example you have an array = [1, 3, 1, 2, 1]
And target value, k = 4

Now possible subarray are

  1. [1, 3] i.e. from index = 0 to index = 1
  2. [3, 1] i.e. from index = 1 to index 2
  3. [1, 2, 1] i.e. from index = 2 to index = 4

Approaches:

First, with O(n2) ie. n square complexity

Now let’s just traverse the whole program to understand the above code.

Finally, after all the iteration we will get the answer = 3 which is the total number subarray possible.

Second, with O(n) ie. n complexity

To know how to solve this problem with O(n) complexity, go to Algo Mart

--

--