π One-stop destination for all your technical interview Preparation π
Coming Soon β¦
TODO: solve using morris traversal.
Previous Questions
[[C++] Simplest Solution | Optimization from Brute Force | One-Pass]](https://leetcode.com/problems/contiguous-array/discuss/1743341/C%2B%2B-Simplest-Solution-or-Optimization-from-Brute-Force-or-One-Pass) |
Complexity:
O(M * N)
, where M is number of rows, N is number of columns in the matrix.O(M * N)
, space for the queue.Complexity:
O(M * N)
, where M is number of rows, N is number of columns in the matrix.O(1)
lCnt=0
.if(prefix[j] - prefix[i]==k)
increment the count.Consider the below example:
array : 3 4 7 -2 2 1 4 2
presum : 3 7 14 12 14 15 19 21
index : 0 1 2 3 4 5 6 7
k = 7
Map should look like :
(0,1) , (3,1), (7,1), (14,2) , (12,1) , (15,1) , (19,1) , (21,1)
Consider 21(presum)
now what we do is sum-k
that is 21-7 = 14
. Now we will check our map if we go by just count++ logic we will just increment the count once and here is where we go wrong.
When we search for 14
in presum array we find it on 2
and 4
index. The logic here is that 14 + 7 = 21
so the array between indexes
-> 3
to 7
(-2 2 1 4 2)
-> 5
to 7
both have sum 7 ( 1 4 2)
The sum is still 7
in this case because there are negative numbers that balance up for. So if we consider count++
we will have one count less as we will consider only array 5
to 7
but now we know that 14
sum occured earlier too so even that needs to be added up so map.get(sum-k)
.
k
in the presum array we have found a new subarray so that is why we look for currentSum-k
.i/c
will give us the row number of output matrix. We will move to New row after every c elements and thus dividing by c will give the row number.i%c
will give us the column number of output matrix. We will be begin from start of new row after every c elements and this the remainder will give column of current row.soonβ¦
isOutOfBounds()
function returns true if the current position is out of bounds, found this trick in discussion tab.