Solution 3 for Scaler Topics Fortnightly Contest - 12

Learn via video course
FREE
View all courses
DSA Problem Solving for Interviews using Java
DSA Problem Solving for Interviews using Java
by Jitender Punia
1000
4.9
Start Learning
DSA Problem Solving for Interviews using Java
DSA Problem Solving for Interviews using Java
by Jitender Punia
1000
4.9
Start Learning
Topics Covered

This article is part of the Scaler Topics Fortnightly Contest - 12

Solution Approach

  • Note that the Brute force of O(N4)O(N^4) can be reduced to O(N3)O(N^3) by considering the fact that only tuple with property ji=lkj-i = l-k will be counted.
  • Can you optimize it further?
  • This question can be solved in O(n2)O(n^2) by mapping all elements into very big elements let's say in the range 1 to 101510^15 and the sum of subarrays can be used as hash values.
  • Now we can just store the sum in the map to find an answer in O(N2)O(N^2).
  • Note that a similar array must have the same sum, although the converse is not true: for example 1+3=2+21+3 = 2 +2 but 1, 2, and 3 are randomly mapped to a very big integer.
  • Thus the possibility of collision is very low.

C++ Implementation

Java Implementation

Python Implementation