Problem of the day
In old times when there was no direct communication channel present, for the security of kingdoms and to convey the danger to the kingdom the soldier used to fire light torches on the hills, and the soldier on other hills could watch those light torches and used to get the message.
A soldier can watch the torch of another hill if there is no hill between them that is higher than any of the two hills.
You are given an array of size ‘N’ representing the heights of the hill in order by the name ‘HILLS’ and you have to tell the number of pairs of soldiers who can see the torch of each other.
For a pair, (a, b) is same as (b, a).
Example:Input: ‘N’ = 4, ‘HILLS’ = [3, 2, 1, 3]
Output: 5
If we consider the indices from 0 to 3 then the pairs are (0, 1), (0,3), (1, 2), (1,3), and (2, 3).
The soldier at hill 0 can not see hill 2 as hill[1]>hill[2].
Note : Test cases are made in such a way that the answer will fit in 32-bit integer.
The first line will contain the integer 'T', denoting the number of test cases.
The next line contains a single integer ‘N’ representing the number of hills.
The next line contains ‘N’ integers denoting the height of hills.
Output format :
For each test case print the number of pairs of soldiers who can see the torch of each other’s hills.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^5
1 <= HILLS[i] <= 10^9
Time Limit: 1 sec
2
4
3 2 1 3
5
1 2 3 4 5
5
4
For the first test case:-
If we consider the indices from 0 to 3 then the pairs are (0, 1), (0,3), (1, 2), (1,3), and (2, 3).
The soldier at hill 0 can not see hill 2 as hill[1]>hill[2].
For the second test case:-
Only consecutive hill soldiers can see each other for others there is a higher hill in between them.
2
5
3 2 1 3 5
6
2 2 1 3 4 6
7
7
Hills between two hills should not be taller than those two hills.
A trivial solution that comes to mind is for each hill we can check all the hills ‘j’ that come earlier in the ‘HILLS’ array. Let’s consider the current hill as ‘HILLS[i]’ and for some ‘HILLS[j]’ where( j < i ) there should not be any hill in-between ‘i’ and ‘j’ such that it is taller than any of the hills. We are counting only for previous hills because if we count for hills ahead as well then we will be counting each pair twice.
The steps are as follows:
countPairs( n, hills ):
O( N^2 ), Where ‘N’ is the number of Hills.
We are traversing the ‘HILLS’ array and then for each hill, we are checking all the previous hills.
Hence the time complexity will be O( N^2 ).
O( 1 ).
We are not using any extra space.
Hence the space complexity will be O( 1 ).