Complexity

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

90% Refund @Courses DSA Data Structure Analysis of Algorithms Sorting Searching Greedy Recur

Sample Practice Problems on Complexity Analysis of


Algorithms
Read Courses Practice Jobs

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.

We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Got It !
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 1/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

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
We use cookies to ensure you have the best browsing experience on our website. By using
= 22(2T(n-3)-1)
our site, you acknowledge that you have– read
2 –and
1 understood our Cookie Policy & Privacy
= 23T(n-3) – 22 – 2Policy 1 – 20

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 2/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

…..
…..
= 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:

CPP

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 */

We usestatic
cookies tovoid
ensurefunction(int
you have the best browsing
n)
experience on our website. By using
our site,
{
you acknowledge that you have read and understood our Cookie Policy & Privacy
if (n==1)
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 3/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

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.

Python3

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.
We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 4/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

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.

Learn Data Structures & Algorithms with GeeksforGeeks

Solution: Consider the comments in the following function.

CPP

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
We use cookies to ensure you have the best browsing experience on our website. By using
printPattern(n);
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
}
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 5/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

static void printPattern(int n) {


for (int i = 1; i <= n; i++) {
// Print a single '*' on each line
System.out.println("*");
}
}
}

Python3

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.
We use cookies to ensure you have
// the
If best
youbrowsing
want experience
the inner on our website.
loop to By using through the ent
iterate
our site, you acknowledge that//
you you
have read
canand understood
remove or our Cookie Policy
comment out &the
Privacy
break statement.
break; Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 6/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

}
#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

Learn Data Structures & Algorithms with GeeksforGeeks

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:

CPP

void function(int n)
{
int count = 0;
We use cookies
forto ensure
(int you have thei<=n;
i=n/2; best browsing
i++) experience on our website. By using
our site, you acknowledge
for (int j=1; j<=n; junderstood
that you have read and = 2 * j) our Cookie Policy & Privacy
for (int k=1; Policyk<=n; k = k * 2)

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 7/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

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.

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 (i = n / 2; i <= n; i++)
for (j = 1; j <= n; j = 2 * j)
for (k = 1; k <= n; k = k * 2)
count++;
}

// This code is contributed by umadevi9616

Learn Data Structures & Algorithms with GeeksforGeeks

We use cookies to ensure


Solution: you havethe
Consider the comments
best browsing experience on our website.
in the following By using
function.
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 8/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

CPP

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++;
}

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(n log2n).

Problem 5: Find the complexity of the below program:

CPP

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++;
}

We use//cookies
Thisto ensure
code you
is have the best browsing
contributed by experience
PushpeshonRaj.
our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 9/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

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;
}

Learn Data Structures & Algorithms with GeeksforGeeks

Solution: Consider the comments in the following function.

CPP

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++;
}

// The code is contributed by Nidhi goel.

We useJava
cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
static void function(int Policy
n)

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 10/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

{
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++;
}

// This code is contributed by Aman Kumar

Python3

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//2 + 1):

# inner loop executes logn times


for k in range(1, n+1, 2):
count++

# The code is contributed by Nidhi goel.

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++)
We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge
//that you have
inner read and
loop understood
executes our Cookie
logn times Policy & Privacy
for (int k=1; Policyk<=n; k = k * 2)

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 11/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

count++;
}

// The code is contributed by Nidhi goel.

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++;
}

// The code is contributed by Nidhi goel.

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(n2logn).

Problem 6: Find the complexity of the below program:

CPP

void function(int n)
{
int i = 1, s =1;
while (s <= n)
{
i++;
s += i;
printf("*");
}
}

Learn Data Structures & Algorithms with GeeksforGeeks

We use cookies to ensure you have the best browsing experience on our website. By using
Solution:
our site, We can
you acknowledge define
that you theand
have read terms ‘s’ according
understood to relation
our Cookie Policy & Privacy si = si-1 + i. The
value of ‘i’ increases by one Policy
for each iteration. The value contained in ‘s’ at
https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 12/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

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:

CPP

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("*");
}
}

Learn Data Structures & Algorithms with GeeksforGeeks

Solution: Consider the comments in the following function.

CPP

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("*");
We use cookies to ensure you have the best browsing experience on our website. By using
}
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
} Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 13/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

Learn Data Structures & Algorithms with GeeksforGeeks

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 review-
team@geeksforgeeks.org. 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.

Feeling lost in the world of random DSA topics, wasting time without
progress? It's time for a change! Join our DSA course, where we'll guide you
on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course,
trusted by over 100,000 geeks!

DSA in C++
DSA in Java
DSA in Python
DSA in JavaScript

Recommended Problems
Solve Problems
Frequently asked DSA Problems

Participate in Three 90 Challenge! Enroll in any GeeksforGeeks course and get 90%
refund by completing 90% course. Explore offer now.

Last Updated : 12 Feb, 2024 127

Previous Next

How to Analyse Loops for Complexity Why the Analysis of Algorithm is


Analysis of Algorithms important?
We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 14/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

Share your thoughts in the comments Add Your Comment

Similar Reads
Asymptotic Notation and Analysis Practice Questions on Time Complexity
(Based on input size) in Complexity Analysis
Analysis of Algorithms

Time and Space Complexity Analysis of Types of Asymptotic Notations in


Tree Traversal Algorithms Complexity Analysis of Algorithms

How to Analyse Loops for Complexity Time Complexity and Space


Analysis of Algorithms Complexity

Algorithms Sample Questions | Set 3 | Miscellaneous Problems of Time


Time Order Analysis Complexity

Analysis of Algorithms | Big-O analysis Practice Problems on Hashing

Complete Tutorials
Learn Algorithms with Javascript | DSA DSA Crash Course | Revision Checklist
using JavaScript Tutorial with Interview Guide

Learn Data Structures and Algorithms | Mathematical and Geometric


DSA Tutorial Algorithms - Data Structure and
Algorithm Tutorials

Learn Data Structures with Javascript |


DSA using JavaScript Tutorial

M Mr. Somesh Awasthi

WeArticle Tags
use cookies : Scala-Arrays
to ensure you have the ,best
SQL-PL/SQL , TCS-coding-questions
browsing experience on our website. By,using
Tek Systems ,
our site, you acknowledgeAnalysis
that youofhave
Algorithms
read and,understood
DSA our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 15/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

Additional Information

A-143, 9th Floor, Sovereign Corporate


Tower, Sector-136, Noida, Uttar Pradesh -
201305

Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Careers GfG Weekly Contest
In Media Offline Classes (Delhi/NCR)
Contact Us DSA in JAVA/C++
Advertise with us Master System Design
GFG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Apply for Mentor Geeks Community

Languages DSA
Python Data Structures
Java Algorithms
We use cookies to ensure you have the best browsing experience on our website. By using
C++ DSA for Beginners
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
PHP Policy Basic DSA Problems

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 16/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

GoLang DSA Roadmap


SQL Top 100 DSA Interview Problems
R Language DSA Roadmap by Sandeep Jain
Android Tutorial All Cheat Sheets
Tutorials Archive

Data Science & ML HTML & CSS


Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning Tutorial Web Templates
ML Maths CSS Frameworks
Data Visualisation Tutorial Bootstrap
Pandas Tutorial Tailwind CSS
NumPy Tutorial SASS
NLP Tutorial LESS
Deep Learning Tutorial Web Design

Python Computer Science


Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Python Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps Competitive Programming


Git Top DS or Algo for CP
AWS Top 50 Tree
Docker Top 50 Graph
Kubernetes Top 50 Array
Azure Top 50 String
GCP Top 50 DP
DevOps Roadmap Top 15 Websites for CP

System Design
We use cookies to ensure you have the best browsing experience on our website. By using
JavaScript
our site, you acknowledge
Highthat youDesign
Level have read and understood our Cookie Policy & Privacy
JavaScript Examples
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 17/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

Low Level Design TypeScript


UML Diagrams ReactJS
Interview Guide NextJS
Design Patterns AngularJS
OOAD NodeJS
System Design Bootcamp Lodash
Interview Questions Web Browser

NCERT Solutions School Subjects


Class 12 Mathematics
Class 11 Physics
Class 10 Chemistry
Class 9 Biology
Class 8 Social Science
Complete Study Material English Grammar

Commerce UPSC Study Material


Accountancy Polity Notes
Business Studies Geography Notes
Economics History Notes
Management Science and Technology Notes
HR Management Economy Notes
Finance Ethics Notes
Income Tax Previous Year Papers

SSC/ BANKING Colleges


SSC CGL Syllabus Indian Colleges Admission & Campus Experiences
SBI PO Syllabus List of Central Universities - In India
SBI Clerk Syllabus Colleges in Delhi University
IBPS PO Syllabus IIT Colleges
IBPS Clerk Syllabus NIT Colleges
SSC CGL Practice Papers IIIT Colleges

Companies Preparation Corner


META Owned Companies Company-Wise Recruitment Process
We use cookies Alphabhet Owned
to ensure you have Companies Resume Templates
the best browsing experience on our website. By using
our site, you acknowledge
TATA Groupthat you have
Owned read and understood our Cookie Policy & Privacy
Companies Aptitude Preparation
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 18/19
13/02/2024, 07:28 Sample Practice Problems on Complexity Analysis of Algorithms - GeeksforGeeks

Reliance Owned Companies Puzzles


Fintech Companies Company-Wise Preparation
EdTech Companies

Exams More Tutorials


JEE Mains Software Development
JEE Advanced Software Testing
GATE CS Product Management
NEET SAP
UGC NET SEO - Search Engine Optimization
Linux
Excel

Free Online Tools Write & Earn


Typing Test Write an Article
Image Editor Improve an Article
Code Formatters Pick Topics to Write
Code Converters Share your Experiences
Currency Converter Internships
Random Number Generator
Random Password Generator

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/analysis-algorithms-set-5-practice-problems/?ref=lbp 19/19

You might also like