Sample Practice Problems on Complexity Analysis of Algorithms
Last Updated :
29 Jan, 2025
Prerequisite: Asymptotic Analysis, Worst, Average and Best Cases, Asymptotic Notations, Analysis of loops.
Problem 1: Find the complexity of the below recurrence:
{ 3T(n-1), if n>0,
T(n) = { 1, otherwise
Solution:
Let us solve using substitution.
T(n) = 3T(n-1)
= 3(3T(n-2))
= 32T(n-2)
= 33T(n-3)
...
...
= 3nT(n-n)
= 3nT(0)
= 3n
This clearly shows that the complexity of this function is O(3n).
Problem 2: Find the complexity of the recurrence:
{ 2T(n-1) - 1, if n>0,
T(n) = { 1, otherwise
Solution:
Let us try solving this function with substitution.
T(n) = 2T(n-1) - 1
= 2(2T(n-2)-1)-1
= 22(T(n-2)) - 2 - 1
= 22(2T(n-3)-1) - 2 - 1
= 23T(n-3) - 22 - 21 - 20
.....
.....
= 2nT(n-n) - 2n-1 - 2n-2 - 2n-3
..... 22 - 21 - 20
= 2n - 2n-1 - 2n-2 - 2n-3
..... 22 - 21 - 20
= 2n - (2n-1)
[Note: 2n-1 + 2n-2 + ...... + 20 = 2n - 1]
T(n) = 1
Time Complexity is O(1). Note that while the recurrence relation looks exponential
he solution to the recurrence relation here gives a different result.
Problem 3: Find the complexity of the below program:
C++
void function(int n)
{
if (n==1)
return;
for (int i=1; i<=n; i++)
{
for (int j=1; j<=n; j++)
{
cout << "*";
break;
}
cout << endl;
}
}
Java
/*package whatever //do not write package name here */
static void function(int n)
{
if (n==1)
return;
for (int i=1; i<=n; i++)
{
for (int j=1; j<=n; j++)
{
System.out.print("*");
break;
}
System.out.println();
}
}
// The code is contributed by Nidhi goel.
Python
def funct(n):
if (n==1):
return
for i in range(1, n+1):
for j in range(1, n + 1):
print("*", end = "")
break
print()
# The code is contributed by Nidhi goel.
C#
/*package whatever //do not write package name here */
public static void function(int n)
{
if (n==1)
return;
for (int i=1; i<=n; i++)
{
for (int j=1; j<=n; j++)
{
Console.Write("*");
break;
}
Console.WriteLine();
}
}
// The code is contributed by Nidhi goel.
JavaScript
function funct(n)
{
if (n==1)
return;
for (let i=1; i<=n; i++)
{
for (let j=1; j<=n; j++)
{
console.log("*");
break;
}
console.log();
}
}
// The code is contributed by Nidhi goel.
Solution: Consider the comments in the following function.
C++
function(int n)
{
if (n==1)
return;
for (int i=1; i<=n; i++)
{
// Inner loop executes only one
// time due to break statement.
for (int j=1; j<=n; j++)
{
printf("*");
break;
}
}
}
Java
public class Main {
public static void main(String[] args) {
int n = 5; // You can change the value of n as needed
printPattern(n);
}
static void printPattern(int n) {
for (int i = 1; i <= n; i++) {
// Print a single '*' on each line
System.out.println("*");
}
}
}
Python
def my_function(n):
if n == 1:
return
for i in range(1, n+1):
# Inner loop executes only one
# time due to break statement.
for j in range(1, n+1):
print("*", end="")
break
my_function(5) # Example: calling the function with n=5
#this code is contributed by Monu Yadav.
C#
using System;
class Program
{
static void PrintPattern(int n)
{
if (n == 1)
return;
for (int i = 1; i <= n; i++)
{
// Inner loop executes only once
// due to the break statement.
#pragma warning disable CS0162
for (int j = 1; j <= n; j++)
{
Console.Write("*");
// The following break statement exits the inner loop
// after printing a single '*' character.
// If you want the inner loop to iterate through the entire range,
// you can remove or comment out the break statement.
break;
}
#pragma warning restore CS0162
}
}
static void Main()
{
int n = 5; // You can change the value of 'n' as needed
PrintPattern(n);
}
}
JavaScript
function printStars(n) {
if (n === 1) {
return; // If n is 1, exit the function
}
for (let i = 1; i <= n; i++) {
// Outer loop to iterate from 1 to n
// Inner loop executes only once due to the break statement
for (let j = 1; j <= n; j++) {
console.log("*"); // Print a star
break; // Break the inner loop after printing one star
}
}
}
// Example usage:
printStars(5); // Call the function with n = 5
Time Complexity: O(n), Even though the inner loop is bounded by n, but due to the break statement, it is executing only once.
Problem 4: Find the complexity of the below program:
C++
void function(int n)
{
int count = 0;
for (int i=n/2; i<=n; i++)
for (int j=1; j<=n; j = 2 * j)
for (int k=1; k<=n; k = k * 2)
count++;
}
Java
static void function(int n)
{
int count = 0;
for (int i = n / 2; i <= n; i++)
for (int j = 1; j <= n; j = 2 * j)
for (int k = 1; k <= n; k = k * 2)
count++;
}
// This code is contributed by rutvik_56.
Python
def function1(n):
count = 0
for i in range(n // 2, n + 1):
for j in range(1, n + 1, 2 * j):
for k in range(1, n + 1, k * 2):
count += 1
C#
static void function(int n)
{
int count = 0;
for (int i = n / 2; i <= n; i++)
for (int j = 1; j <= n; j = 2 * j)
for (int k = 1; k <= n; k = k * 2)
count++;
}
// This code is contributed by pratham76.
JavaScript
function function1(n)
{
var count = 0;
for (var i = n / 2; i <= n; i++)
for (var j = 1; j <= n; j = 2 * j)
for (var k = 1; k <= n; k = k * 2)
count++;
}
Solution: Consider the comments in the following function.
C++
#include <iostream>
using namespace std;
void function(int n) {
int count = 0;
for (int i = n / 2; i <= n; i++) {
// Executes O(Log n) times
for (int j = 1; j <= n; j = 2 * j) {
// Executes O(Log n) times
for (int k = 1; k <= n; k = k * 2) {
count++;
}
}
}
cout << "Count: " << count << endl;
}
int main() {
// Example usage
function(10); // Call function with an example value of n
return 0;
}
Java
public class Main {
public static void function(int n) {
int count = 0;
for (int i = n / 2; i <= n; i++) {
// Executes O(Log n) times
for (int j = 1; j <= n; j = 2 * j) {
// Executes O(Log n) times
for (int k = 1; k <= n; k = k * 2) {
count++;
}
}
}
System.out.println("Count: " + count);
}
public static void main(String[] args) {
// Example usage
function(10); // Call function with an example value of n
}
}
//This code is contributed by Adarsh
Python
def function(n):
count = 0
# Outer loop executes n/2 times
for i in range(n // 2, n + 1):
# Middle loop executes O(Log n) times
j = 1
while j <= n:
# Inner loop also executes O(Log n) times
k = 1
while k <= n:
count += 1
k *= 2
j *= 2
print("Count:", count)
# Example usage
function(10)
JavaScript
function functionMain(n) {
let count = 0;
for (let i = Math.floor(n / 2); i <= n; i++) {
// Executes O(Log n) times
for (let j = 1; j <= n; j *= 2) {
// Executes O(Log n) times
for (let k = 1; k <= n; k *= 2) {
count++;
}
}
}
console.log("Count: " + count);
}
functionMain(10); // Example usage
Time Complexity: O(n log2n).
Problem 5: Find the complexity of the below program:
C++
void function(int n)
{
int count = 0;
for (int i=n/2; i<=n; i++)
for (int j=1; j+n/2<=n; j = j++)
for (int k=1; k<=n; k = k * 2)
count++;
}
Java
static void function(int n)
{
int count = 0;
for (int i=n/2; i<=n; i++)
for (int j=1; j+n/2<=n; j = j++)
for (int k=1; k<=n; k = k * 2)
count++;
}
// This code is contributed by Pushpesh Raj.
Python
def function(n):
# Initialize count to 0
count = 0
# Outer loop starts from n/2 and goes up to n
for i in range(n//2, n+1):
# Middle loop starts from 1 and goes up to n/2
for j in range(1, n + 1 - n//2): # j + n//2 <= n
# Inner loop starts from 1 and doubles at each step
for k in range(1, n+1, k*2):
# Increment count at each iteration
count += 1
JavaScript
function myFunction(n) {
let count = 0;
// Outer loop runs from n/2 to n
for (let i = n / 2; i <= n; i++) {
// Middle loop runs from 1 to n - n/2
for (let j = 1; j + n / 2 <= n; j++) {
// Inner loop runs from 1 to n, doubling k in each iteration
for (let k = 1; k <= n; k = k * 2) {
count++;
}
}
}
return count;
}
Solution: Consider the comments in the following function.
C++
void function(int n)
{
int count = 0;
// outer loop executes n/2 times
for (int i=n/2; i<=n; i++)
// middle loop executes n/2 times
for (int j=1; j+n/2<=n; j = j++)
// inner loop executes logn times
for (int k=1; k<=n; k = k * 2)
count++;
}
Java
static void function(int n)
{
int count = 0;
// outer loop executes n/2 times
for (int i=n/2; i<=n; i++)
// middle loop executes n/2 times
for (int j=1; j+n/2<=n; j = j++)
// inner loop executes logn times
for (int k=1; k<=n; k = k * 2)
count++;
}
Python
def function(n):
count = 0
# outer loop executes n/2 times
for i in range(n//2, n+1):
# middle loop executes n/2 times
for j in range(1, n + 1 - n//2): # j + n//2 <= n
# inner loop executes logn times (k doubles each time)
for k in range(1, n+1, k*2):
count += 1
C#
using System;
public static void function(int n)
{
int count = 0;
// outer loop executes n/2 times
for (int i=n/2; i<=n; i++)
// middle loop executes n/2 times
for (int j=1; j+n/2<=n; j = j++)
// inner loop executes logn times
for (int k=1; k<=n; k = k * 2)
count++;
}
JavaScript
function function(n)
{
let count = 0;
// outer loop executes n/2 times
for (let i= Math.floor(n/2); i<=n; i++)
// middle loop executes n/2 times
for (let j=1; j+n/2<=n; j = j++)
// inner loop executes logn times
for (let k=1; k<=n; k = k * 2)
count++;
}
Time Complexity: O(n2logn).
Problem 6: Find the complexity of the below program:
C++
#include <iostream>
// Function to print '*' until the sum of consecutive integers exceeds n
void function(int n) {
int i = 1; // Initialize i to 1
int s = 1; // Initialize s to 1
// Loop until the sum of consecutive integers exceeds n
while (s <= n) {
i++; // Increment i
s += i; // Add i to the sum
std::cout << "*"; // Print '*'
}
}
int main() {
int n = 10; // Example value of n
function(n); // Call the function
return 0;
}
Java
public class Main {
// Function to print '*' until the sum of consecutive integers exceeds n
public static void function(int n) {
int i = 1; // Initialize i to 1
int s = 1; // Initialize s to 1
// Loop until the sum of consecutive integers exceeds n
while (s <= n) {
i++; // Increment i
s += i; // Add i to the sum
System.out.print("*"); // Print '*'
}
}
public static void main(String[] args) {
int n = 10; // Example value of n
function(n); // Call the function
}
}
Python
def function(n):
i = 1 # Initialize i to 1
s = 1 # Initialize s to 1
# Loop until the sum of consecutive integers exceeds n
while s <= n:
i += 1 # Increment i
s += i # Add i to the sum
print("*", end="") # Print '*' without a newline
# Example value of n
n = 10
function(n) # Call the function
JavaScript
function functionJS(n) {
let i = 1; // Initialize i to 1
let s = 1; // Initialize s to 1
// Loop until the sum of consecutive integers exceeds n
while (s <= n) {
i++; // Increment i
s += i; // Add i to the sum
process.stdout.write("*"); // Print '*' without a newline
}
}
// Example value of n
let n = 10;
functionJS(n); // Call the function
Solution: We can define the terms 's' according to relation si = si-1 + i. The value of 'i' increases by one for each iteration. The value contained in 's' at the ith iteration is the sum of the first 'i' positive integers. If k is total number of iterations taken by the program, then while loop terminates if: 1 + 2 + 3 ....+ k = [k(k+1)/2] > n So k = O(√n).
Time Complexity: O(√n).
Problem 7: Find a tight upper bound on the complexity of the below program:
C++
void function(int n)
{
int count = 0;
for (int i=0; i<n; i++)
for (int j=i; j< i*i; j++)
if (j%i == 0)
{
for (int k=0; k<j; k++)
printf("*");
}
}
Java
void function(int n)
{
int count = 0;
for (int i=0; i<n; i++)
for (int j=i; j< i*i; j++)
if (j%i == 0)
{
for (int k=0; k<j; k++)
printf("*");
}
}
Python
def myFunction(n):
for i in range(n):
for j in range(i, i * i):
if j % i == 0: # Check if j is divisible by i
for k in range(j):
print("*", end="") # Print '*' to the console without newline
print() # Move to the next line after printing '*' for each j
# Example usage
myFunction(5)
JavaScript
function myFunction(n) {
for (let i = 0; i < n; i++) {
for (let j = i; j < i * i; j++) {
if (j % i === 0) { // Check if j is divisible by i
for (let k = 0; k < j; k++) {
process.stdout.write("*"); // Print '*' to the console
}
}
}
}
}
Solution: Consider the comments in the following function.
C++
void function(int n)
{
int count = 0;
// executes n times
for (int i=0; i<n; i++)
// executes O(n*n) times.
for (int j=i; j< i*i; j++)
if (j%i == 0)
{
// executes j times = O(n*n) times
for (int k=0; k<j; k++)
printf("*");
}
}
Java
public class Main {
static void function(int n) {
int count = 0; // Initialize count variable
// executes n times
for (int i = 0; i < n; i++) {
// executes O(n*n) times.
for (int j = i; j < i * i; j++) {
if (j % i == 0) {
// executes j times = O(n*n) times
for (int k = 0; k < j; k++) {
System.out.print("*");
count++; // Increment count
}
}
}
}
System.out.println("\nCount: " + count); // Print count after loops
}
public static void main(String[] args) {
int n = 5; // example value for n
function(n);
}
}
Python
def function(n):
count = 0
# executes n times
for i in range(n):
# executes O(n*n) times.
for j in range(i, i*i):
if j % i == 0:
# executes j times = O(n*n) times
for k in range(j):
print("*", end="")
JavaScript
// JavaScript equivalent of the Python code
function someFunction(n) {
let count = 0;
// executes n times
for (let i = 0; i < n; i++) {
// executes O(n*n) times.
for (let j = i; j < i * i; j++) {
if (j % i === 0) {
// executes j times = O(n*n) times
for (let k = 0; k < j; k++) {
process.stdout.write("*");
}
}
}
}
}
// Example usage
someFunction(5); // You can replace 5 with any desired value for n
Time Complexity: O(n5)
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Similar Reads
Analysis of Algorithms Analysis of Algorithms is a fundamental aspect of computer science that involves evaluating performance of algorithms and programs. Efficiency is measured in terms of time and space.Basics on Analysis of Algorithms:Why is Analysis Important?Order of GrowthAsymptotic Analysis Worst, Average and Best
1 min read
Complete Guide On Complexity Analysis - Data Structure and Algorithms Tutorial Complexity analysis is defined as a technique to characterise the time taken by an algorithm with respect to input size (independent from the machine, language and compiler). It is used for evaluating the variations of execution time on different algorithms. What is the need for Complexity Analysis?
15+ min read
Why is Analysis of Algorithm important? Why is Performance of Algorithms Important ? There are many important things that should be taken care of, like user-friendliness, modularity, security, maintainability, etc. Why worry about performance? The answer to this is simple, we can have all the above things only if we have performance. So p
2 min read
Types of Asymptotic Notations in Complexity Analysis of Algorithms We have discussed Asymptotic Analysis, and Worst, Average, and Best Cases of Algorithms. The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don't depend on machine-specific constants and don't require algorithms to be implemented and time taken by programs
8 min read
Worst, Average and Best Case Analysis of Algorithms In the previous post, we discussed how Asymptotic analysis overcomes the problems of the naive way of analyzing algorithms. Now let us learn about What is Worst, Average, and Best cases of an algorithm:1. Worst Case Analysis (Mostly used) In the worst-case analysis, we calculate the upper bound on t
10 min read
Asymptotic Analysis Given two algorithms for a task, how do we find out which one is better? One naive way of doing this is - to implement both the algorithms and run the two programs on your computer for different inputs and see which one takes less time. There are many problems with this approach for the analysis of
3 min read
How to Analyse Loops for Complexity Analysis of Algorithms We have discussed Asymptotic Analysis, Worst, Average and Best Cases and Asymptotic Notations in previous posts. In this post, an analysis of iterative programs with simple examples is discussed. The analysis of loops for the complexity analysis of algorithms involves finding the number of operation
15+ min read
Sample Practice Problems on Complexity Analysis of Algorithms Prerequisite: Asymptotic Analysis, Worst, Average and Best Cases, Asymptotic Notations, Analysis of loops.Problem 1: Find the complexity of the below recurrence: { 3T(n-1), if n>0,T(n) = { 1, otherwiseSolution: Let us solve using substitution.T(n) = 3T(n-1) = 3(3T(n-2)) = 32T(n-2) = 33T(n-3) ...
14 min read
Basics on Analysis of Algorithms
Why is Analysis of Algorithm important?Why is Performance of Algorithms Important ? There are many important things that should be taken care of, like user-friendliness, modularity, security, maintainability, etc. Why worry about performance? The answer to this is simple, we can have all the above things only if we have performance. So p
2 min read
Asymptotic AnalysisGiven two algorithms for a task, how do we find out which one is better? One naive way of doing this is - to implement both the algorithms and run the two programs on your computer for different inputs and see which one takes less time. There are many problems with this approach for the analysis of
3 min read
Worst, Average and Best Case Analysis of AlgorithmsIn the previous post, we discussed how Asymptotic analysis overcomes the problems of the naive way of analyzing algorithms. Now let us learn about What is Worst, Average, and Best cases of an algorithm:1. Worst Case Analysis (Mostly used) In the worst-case analysis, we calculate the upper bound on t
10 min read
Types of Asymptotic Notations in Complexity Analysis of AlgorithmsWe have discussed Asymptotic Analysis, and Worst, Average, and Best Cases of Algorithms. The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don't depend on machine-specific constants and don't require algorithms to be implemented and time taken by programs
8 min read
How to Analyse Loops for Complexity Analysis of AlgorithmsWe have discussed Asymptotic Analysis, Worst, Average and Best Cases and Asymptotic Notations in previous posts. In this post, an analysis of iterative programs with simple examples is discussed. The analysis of loops for the complexity analysis of algorithms involves finding the number of operation
15+ min read
How to analyse Complexity of Recurrence RelationThe analysis of the complexity of a recurrence relation involves finding the asymptotic upper bound on the running time of a recursive algorithm. This is usually done by finding a closed-form expression for the number of operations performed by the algorithm as a function of the input size, and then
7 min read
Introduction to Amortized AnalysisAmortized Analysis is used for algorithms where an occasional operation is very slow, but most other operations are faster. In Amortized Analysis, we analyze a sequence of operations and guarantee a worst-case average time that is lower than the worst-case time of a particularly expensive operation.
10 min read
Asymptotic Notations
Big O Notation Tutorial - A Guide to Big O AnalysisBig O notation is a powerful tool used in computer science to describe the time complexity or space complexity of algorithms. Big-O is a way to express the upper bound of an algorithmâs time or space complexity. Describes the asymptotic behavior (order of growth of time or space in terms of input si
10 min read
Big O vs Theta Πvs Big Omega Ω Notations1. Big O notation (O): It defines an upper bound on order of growth of time taken by an algorithm or code with input size. Mathematically, if f(n) describes the running time of an algorithm; f(n) is O(g(n)) if there exist positive constant C and n0 such that,0 <= f(n) <= Cg(n) for all n >=
3 min read
Examples of Big-O analysisPrerequisite: Analysis of Algorithms | Big-O analysis In the previous article, the analysis of the algorithm using Big O asymptotic notation is discussed. In this article, some examples are discussed to illustrate the Big O time complexity notation and also learn how to compute the time complexity o
13 min read
Difference between Big O Notation and TildeIn asymptotic analysis of algorithms we often come across terms like Big O, Omega, Theta and Tilde, which describe the performance of an algorithm. Here, we will see difference between two notations: Big O and Tilde.Big O Notation (O) This notation is basically used to describe the asymptotic upper
4 min read
Analysis of Algorithms | Big-Omega ⦠NotationIn the analysis of algorithms, asymptotic notations are used to evaluate the performance of an algorithm, in its best cases and worst cases. This article will discuss Big-Omega Notation represented by a Greek letter (â¦). Table of Content What is Big-Omega ⦠Notation?Definition of Big-Omega ⦠Notatio
9 min read
Analysis of Algorithms | Î (Theta) NotationIn the analysis of algorithms, asymptotic notations are used to evaluate the performance of an algorithm by providing an exact order of growth. This article will discuss Big - Theta notations represented by a Greek letter (Î).Definition: Let g and f be the function from the set of natural numbers to
6 min read