educative.io

Solution for Complexity Interview Questions Number 10

the solution for this question is n(n-1) / 2
I can not get it where it came from


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

Hi @Mohamed_Abdelnaby_El

n(n-1)/2 is the time complexity for this code. n is for the outer loop and n-1 is for the inner as you can see j<i (i is for the outer loop), which means the inner loop will run one time less than the outer loop.

First the inner for loop runs the statements inside n times. And then after i is incremented, the inner for loop runs for n-1 times… …until it runs once, then both of the for loops reach their terminating conditions.
This actually ends up giving us a geometric sum, and with some math, we would find that the inner loop will repeat for 1+2 … + n times, which equals n(n-1)/2 times.