What’s the runtime for this nested for loop in big O notation?
for(i = 1 to k)
{
for(j = i+1 to k)
{}
}
It’s smaller than O(k^2) but I can’t figure it out.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your question is closely related to the series sum S(k) = 0 + 1 + 2 + … + (k-2) + (k-1). It can be shown that S(k) = (k*(k-1))/2 = (k*k)/2 – k/2. [How? Reorder the sum as S(k) = {0+(k-1)} + {1+(k-2)} + {2+(k-3)} + …. This shows how.]
Therefore, is the algorithmic order smaller than O(k*k)? Remember that constant coefficients like 1/2 do not influence the big O notation.
Question: So it’s equivalent to replacing
j = i+1 to kwithj = 1 to k?Answer: Right. This is tricky, so let’s think it through. For
i == 1, how many times does the inner loop’s action run? Answer: it runsk-1times. Again, fori == 2, how many times does the inner loop’s action run? Answer: it runsk-2times. Ultimately, fori == k, how many times does the inner loop’s action run? Answer: it runs zero times. Therefore, over all values ofi, how many times does the inner loop’s action run? Answer:(k-1) + (k-2) + ... + 0, which is just the aforementioned sum S(k).