Solution: Nested Loop with Multiplication (Basic)
Explore how to analyze the time complexity of a nested loop involving multiplication. Learn to break down the outer loop running logarithmically and the inner loop iterating linearly, culminating in identifying the overall Big O complexity as O(n log n). This lesson equips you with skills to evaluate algorithms’ efficiency in interview coding challenges.
We'll cover the following...
Given Code #
Time Complexity
The outer loop in this problem, i.e., everything under line 9 while (var < n) runs times since var will first be equal to , then , then , then , until it is such that . This means that the outer loop runs a total of times.
Now, let’s have a look at the inner loop for(int j = 1; j < n; j += 2). int j = 1; runs times, j<n executed times and j += 2 executed times. sum++; also runs a total of ...