The solution given by the editor, is also O(N^2) only na…, how is it O(9N), or O(N)?
what I understood from the editor has given as the solution as:
for(int i=1;i<N;i++)
{
for(int j=i+1;j<min(i+9,N);j++)
{
…comparision condition…
}
}
Now, as i itself starts from 1, so min(i+9,N) will always be N…
So, even the editorial solution is O(N^2)…, how it is O(9N) or O(N)?
it is of O(9.N) in worst case as in second loop j is traversing upto min(i+9 , N) in which when you will take a big constraints it will give O(9.N) which is also equivalent to O(N).
You can also say that the second loop will only run for 9 times at worst.
@m0nk3yd1u55y I am still not getting that how will it be O(9N)…
The solution given by the editor, is also O(N^2) only na…, how is it O(9N), or O(N)?
what I understood from the editor has given as the solution as:
for(int i=1;i<N;i++)
{
for(int j=i+1;j<min(i+9,N);j++)
{
…comparision condition…
}
}
Lets analyze:
Now, as i itself starts from 1, so min(i+9,N) will be as follows…
min(1+9,N)=10–>loop j runs 10 times.
min(2+9,N)=11–>loop j runs 11 times.
min(3+9,N)=12–>loop j runs 12 times.
min(4+9,N)=13–>loop j runs 13 times.
…continuing…
min(N-9+9,N)=N–>loop j runs N times.
min(N-8+9,N)–>loop j runs N times.
min(N-7+9,N)–>loop j runs N times.
…till min(N+9,N)–>where loop j runs N times.
So how is it that, loop j will run at “most 9” times?
Please explain…
@anyone?
PS: I haven’t really done with the hash map, so I am not commenting on the solution given by other guys. As soon as I will complete it, I will revisit the solution of hash map as well.
it is like that it max to max run to 9 elements further because after that difference between i and j is always greater than 9 and we can never obtain the required solution therefore no need of running it N^2 times :)…
@prit_esh_07 Yeah, I got the thing that diff of j-i is max 9.
But in order to travel the whole string, i.e, upto the size of the string(or we can say the last element of the string…), it is basically N–>size of the string. I am talking abt inner loop , or loop j btw…
@ajit123q could you explain the solution which you have given…, sorry but I still fail to understand that how will the j loop, min(i+9,N) will not be O(N)…
yeah sure !
That is a simplification of nC2 , where n is the number of occurrences of a value X. we just need to find how many pairs can be made with X number of options.
so, nC2 translates to n!/((2!)*((n-2)!))
which on solving further gives : n(n-1)/2*
Hope it is was a clear explanation for answering your question.