Skip to content

A technique to approach problems

Course: Intro Class 2- DSA - chapter 8

Whenever you have a problem which involves finding 2 indices (one or all pairs) from the array following some property, you can solve it by treating each element as the right element of the pair and trying to find an appropriate left element such that (left, right) satisfies the property. As we are moving from left to right in the loop, when we reach any element, the data structure only contains elements on the left hand side. So using the data structure, we should be able to quickly compute the left elements satisfying the property with the current element.

Let’s understand this with the example of 2 sum problem. We are asked to find count of all possible pairs of elements whose sum is equal to K. How to solve for it?

It satisfies the above conditions we have mentioned, i.e. we need to find **count of all pairs **satisfying a property which is A[i] + A[j] = K

So, we can iterate and fix the right element, and for each right element try finding count of all possible left elements s/t the pairs satisfy the property.

In brute force terms, it will be something like

for(right = 0; right < n; right++) {
// right is fixed. For this right, find count of all left's such that (left, right) satisfy the property
for(left = 0; left < right; left++) {
if (isPropertySatisfied(left, right)) {
ans += 1
}
}
}

Now we optimize this and completely get rid of the inner loop by using some data structure. Essentially, isPropertySatisfied is defined as A[left] + A[right] == K . Instead, we can maintain a frequency array, that stores the count of all the array elements we have seen till now in our loop. As we are moving from left to right, only the elements we have seen till now (i.e. the elements on the left hand side of the current element) are there in the frequency table.

The optimized code becomes something like the below:

freq = [] // All 0's initially
for(right = 0; right < n; right++) {
// right is fixed. For this right, find count of all left's such that (left, right) satisfy the property
need = K - A[right]
ans += freq[need]
freq[A[right]]++
}

💡 A subarray can also be treated as 2 indices, in case of subarrays we use the prefix computation concept as well. To compute for a subarray (i, j), we can use the prefix computation (0, j) and from that remove the computation for (0, i-1)