Miscellaneous Problems of Time Complexity
Last Updated :
23 Jul, 2025
Prerequisite : Asymptotic Notations
Time Complexity :
Time complexity is the time needed by an algorithm expressed as a function of the size of a problem. It can also be defined as the amount of computer time it needs to run a program to completion. When we solve a problem of time complexity then this definition help the most -
"It is the number of operations an algorithm performs to complete its task with respect to the input size."
There are following some miscellaneous problems of time complexity which are always frequently asking in different types of quizzes.
1. What is the time complexity of the following code -
C++
void function(int n)
{
int i = 1, s = 1;
while (s < n) {
s = s + i;
i++;
}
}
// This code is contributed by Shubham Singh
C
void function(int n)
{
int i = 1, s = 1;
while (s < n) {
s = s + i;
i++;
}
}
Java
public static void function(int n)
{
int i = 1, s = 1;
while (s < n) {
s = s + i;
i++;
}
}
// This code is contributed by Shubham Singh
Python3
def function(n):
i = 1
s = 1
while (s < n):
s = s + i
i+=1
# This code is contributed by Shubham Singh
C#
public static void function(int n)
{
int i = 1, s = 1;
while (s < n) {
s = s + i;
i++;
}
}
// This code is contributed by Shubham Singh
JavaScript
<script>
function function(int n)
{
var i = 1;
var s = 1;
while (s < n) {
s = s + i;
i++;
}
}
// This code is contributed by Shubham Singh
</script>
Solution -
Time complexity = O(√n).
Explanation -
We can define the ‘S’ terms according to the relation Si = Si-1 + i. Let k is the total number of iterations taken by the program
i | S |
1
|
1
|
2
|
2
|
3
|
2 + 2
|
4
|
2 + 2 + 3
|
…
|
…
|
k
| 2 + 2 + 3 + 4 + ……+ k
|
When S>=n , then loop will stop at kth iterations,
⇒ S>=n ⇒ S=n
⇒ 2 + 2 + 3 + 4 + ……+ k = n
⇒ 1 + (k * (k + 1))/2 = n
⇒ k2 = n
k = √n
Hence, the time complexity is O(√n).
2. What is the time complexity of the following code :
C++
void fun(int n)
{
if (n < 5)
cout << "GeeksforGeeks";
else {
for (int i = 0; i < n; i++) {
cout << i;
}
}
}
// This code is contributed by Shubham Singh
C
void fun(int n)
{
if (n < 5)
printf("GeeksforGeeks");
else {
for (int i = 0; i < n; i++) {
printf("%d", i);
}
}
}
Java
public static void fun(int n)
{
if (n < 5)
System.out.print("GeeksforGeeks");
else {
for (int i = 0; i < n; i++) {
System.out.print(i + " ");
}
}
}
// This code is contributed by Shubham Singh
Python3
def fun(n):
if (n < 5):
print("GeeksforGeeks", end ="")
else:
for i in range(n):
print(i, end= " ")
# This code is contributed by Shubham Singh
C#
public static void fun(int n)
{
if (n < 5)
Console.Write("GeeksforGeeks");
else {
for (int i = 0; i < n; i++) {
Console.Write(i + " ");
}
}
}
// This code is contributed by Shubham Singh
JavaScript
<script>
function fun(n)
{
if (n < 5)
document.write("GeeksforGeeks");
else {
for (var i = 0; i < n; i++) {
document.write(i + " ");
}
}
}
//This code is contributed by Shubham Singh
</script>
Solution -
Time complexity = O(1) in best case and O(n) in worst case.
Explanation -
This program contains if and else condition. Hence, there are 2 possibilities of time complexity. If the value of n is less than 5, then we get only GeeksforGeeks as output and its time complexity will be O(1).
But, if n>=5, then for loop will execute and time complexity becomes O(n), it is considered as worst case because it takes more time.
3. What is the time complexity of the following code :
C++
void fun(int a, int b)
{
// Consider a and b both are positive integers
while (a != b) {
if (a > b)
a = a - b;
else
b = b - a;
}
}
// This code is contributed by Shubham Singh
C
void fun(int a, int b)
{
while (a != b) {
if (a > b)
a = a - b;
else
b = b - a;
}
}
Java
public static void fun(int a, int b)
{
while (a != b) {
if (a > b)
a = a - b;
else
b = b - a;
}
}
// This code is contributed by Shubham Singh
Python3
def fun(a, b):
while (a != b):
if (a > b):
a = a - b
else:
b = b - a
# This code is contributed by Shubham Singh
C#
public static void fun(int a, int b)
{
while (a != b) {
if (a > b)
a = a - b;
else
b = b - a;
}
}
// This code is contributed by Shubham Singh
JavaScript
<script>
function fun(a, b)
{
while (a != b) {
if (a > b)
a = a - b;
else
b = b - a;
}
}
// This code is contributed by Shubham Singh
</script>
Solution -
Time complexity = O(1) in best case and O(max(a, b)) worst case.
Explanation -
If the value of a and b are the same, then while loop will not be executed. Hence, time complexity will be O(1).
But if a!=b, then the while loop will be executed. Let a=16 and b=5;
no. of iterations | a | b |
1
|
16
|
5
|
2
|
16-5=11
|
5
|
3
|
11-5=6
|
5
|
4
|
6-5=1
|
5
|
5
|
1
|
5-1=4
|
6
|
1
|
4-1=3
|
7
|
1
|
3-1=2
|
8
|
1
|
2-1=1
|
For this case, while loop executed 8 times (a/2⇒16/2⇒8).
If a=5 and b=16, then also the loop will be executed 8 times. So we can say that time complexity is O(max(a/2,b/2))⇒O(max(a, b)), it is considered as worst case because it takes more time.
4. What is the time complexity of the following code :
C++
void fun(int n)
{
for(int i=0;i*i<n;i++)
cout<<"GeeksforGeeks";
}
// This code is contributed by Shubham Singh
C
void fun(int n)
{
for(int i=0;i*i<n;i++)
printf("%s","GeeksforGeeks");
}
Java
public static void fun(int n)
{
for(int i=0;i*i<n;i++)
System.out.print("GeeksforGeeks");
}
// This code is contributed by Pushpesh Raj.
Python3
def fun(n):
i = 0
while i*i < n:
print("GeeksforGeeks")
i += 1
# This code is contributed by Shubham Singh and edited by Pawan
C#
public static void fun(int n)
{
for(int i=0;i*i<n;i++)
Console.Write("GeeksforGeeks");
}
// This code is contributed by Aman Kumar
JavaScript
function fun(n)
{
for(let i = 0; i*i < n; i++)
console.log("GeeksforGeeks");
}
// This code is contributed by Utkarsh.
Solution -
Time complexity = O(√n).
Explanation -
Let k be the no. of iteration of the loop.
i |
i*i |
1
|
1
|
2
|
2
2 |
3
|
3
2 |
4
|
4
2 |
…
|
…
|
k
| k
2 |
⇒ The loop will stop when i * i >=n i.e., i*i=n
⇒ i*i=n ⇒ k2 = n
⇒k =√n
Hence, the time complexity is O(√n).
5. What is the time complexity of the following code :
C++
void fun(int n, int x)
{
for (int i = 1; i < n; i = i * x) //or for(int i = n; i >=1; i = i / x)
cout << "GeeksforGeeks";
}
//This code is contributed by Shubham Singh
C
void fun(int n, int x)
{
for (int i = 1; i < n; i = i * x) //or for(int i = n; i >=1; i = i / x)
print("GeeksforGeeks");
}
Java
public static void fun(int n, int x)
{
for (int i = 1; i < n; i = i * x) //or for(int i = n; i >=1; i = i / x)
System.out.print("GeeksforGeeks");
}
// This code is contributed by Pushpesh Raj.
Python3
def fun(n, x):
for i in range(1, n, i * x):
print("GeeksforGeeks")
C#
public static void fun(int n, int x)
{
for (int i = 1; i < n; i = i * x) //or for(int i = n; i >=1; i = i / x)
Console.Write("GeeksforGeeks");
}
// This code is contributed by Aman Kumar
JavaScript
function fun(n, x)
{
for(let i = 1; i < n; i = i * x) //or for(let i = n; i >=1; i = i / x)
document.write("GeeksforGeeks");
}
// This code is contributed by Utkarsh
Solution -
Time complexity = O(logxn).
Explanation -
Let k be the no. of iteration of the loop.
no. of itr | i=i*x |
1
| 1*x=x
|
2
| x*x=x
2 |
3
| x
2 *x=x
3 |
…
|
…
|
k
| x
k-1 *x= x
k |
⇒ The loop will stop when i>=n ⇒ xk = n
⇒ xk=n (Take log both sides)
⇒ k=logxn
⇒Hence, time complexity is O(logxn).
6. What is the time complexity of the following code :
C++
#include <iostream>
using namespace std;
void fun(int n)
{
for (int i = 0; i < n / 2; i++)
for (int j = 1; j + n / 2 <= n; j++)
for (int k = 1; k <= n; k = k * 2)
cout << "GeeksforGeeks";
}
int main()
{
int n=8;
fun(3);
}
// The code is contributed by Nidhi goel.
C
void fun(int n)
{
for (int i = 0; i < n / 2; i++)
for (int j = 1; j + n / 2 <= n; j++)
for (int k = 1; k <= n; k = k * 2)
printf("GeeksforGeeks");
}
int main()
{
int n=8;
fun(3);
}
Java
public static void fun(int n)
{
for (int i = 0; i < n / 2; i++)
for (int j = 1; j + n / 2 <= n; j++)
for (int k = 1; k <= n; k = k * 2)
System.out.print("GeeksforGeeks");
}
// This code is contributed by Pushpesh Raj.
Python3
import math;
def fun(n):
for i in range(0,math.floor(n/2)):
for j in range(1,n-math.floor(n/2)+1):
k=1;
for k in range(1,n+1,2*k):
print("GeeksforGeeks");
C#
public static void fun(int n)
{
for (int i = 0; i < n / 2; i++)
for (int j = 1; j + n / 2 <= n; j++)
for (int k = 1; k <= n; k = k * 2)
Console.Write("GeeksforGeeks");
}
// This code is contributed by Aman Kumar
JavaScript
function fun(n)
{
for (let i = 0; i < Math.floor(n / 2); i++)
for (let j = 1; j + Math.floor(n / 2) <= n; j++)
for (let k = 1; k <= n; k = k * 2)
console.log("GeeksforGeeks");
}
// This code is contributed by Utkarsh
Solution -
Time complexity = O(n2log2n).
Explanation -
Time complexity of 1st for loop = O(n/2) ⇒ O(n).
Time complexity of 2nd for loop = O(n/2) ⇒ O(n).
Time complexity of 3rd for loop = O(log2n). (refer question number - 5)
Hence, the time complexity of function will become O(n2log2n).
7. What is the time complexity of the following code :
C++
void fun(int n)
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j = j + i)
cout << "GeeksforGeeks";
}
//This Code is contributed by Shubham Singh
C
void fun(int n)
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j = j + i)
print("GeeksforGeeks");
}
Java
public static void fun(int n)
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j = j + i)
System.out.print("GeeksforGeeks");
}
// This code is contributed by Pushpesh Raj.
Python3
def fun(n):
for i in range(1,n+1):
for j in range(1,n+1,i):
print("GeeksforGeeks");
C#
public static void fun(int n)
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j = j + i)
Console.Write("GeeksforGeeks");
}
// This code is contributed by Aman Kumar
JavaScript
function fun(n)
{
for (let i = 1; i <= n; i++)
for (let j = 1; j <= n; j = j + i)
console.log("GeeksforGeeks");
}
fun(7)
// This code is contributed by Utkarsh
Solution - Time complexity = O(nlogn).
Explanation -
Time complexity of 1st for loop = O(n). 2nd loop executes n/i times for each value of i.
Its time complexity is O(∑ni=1 n/i) ⇒ O(logn).
Hence, time complexity of function = O(nlogn).
8. What is the time complexity of the following code :
C++
void fun(int n)
{
for (int i = 0; i <= n / 3; i++)
for (int j = 1; j <= n; j = j + 4)
cout << "GeeksforGeeks";
}
// The code is contributed by Arushi Jindal.
C
void fun(int n)
{
for (int i = 0; i <= n / 3; i++)
for (int j = 1; j <= n; j = j + 4)
cout << "GeeksforGeeks";
}
Java
public static void fun(int n)
{
for (int i = 0; i <= n / 3; i++)
for (int j = 1; j <= n; j = j + 4)
System.out.print("GeeksforGeeks");
}
// This code is contributed by Pushpesh Raj.
Python3
def fun(n):
for i in range(n//3 + 1):
for j in range(1, n+1, 4):
print("GeeksforGeeks")
# the code is contributed by Arushi Jindal.
C#
public static void fun(int n)
{
for (int i = 0; i <= n / 3; i++)
for (int j = 1; j <= n; j = j + 4)
Console.Write("GeeksforGeeks");
}
// This code is contributed by Aman Kumar
JavaScript
function fun(n)
{
for (let i = 0; i <= Math.floor(n / 3); i++)
for (let j = 1; j <= n; j = j + 4)
document.write("GeeksforGeeks");
}
// This code is contributed by Utkarsh
Solution - Time complexity = O(n2).
Explanation -
Time complexity of 1st for loop = O(n/3) ⇒ O(n).
Time complexity of 2nd for loop = O(n/4) ⇒ O(n).
Hence, the time complexity of function will become O(n2).
9. What is the time complexity of the following code :
C++
void fun(int n)
{
int i = 1;
while (i < n) {
int j = n;
while (j > 0) {
j = j / 2;
}
i = i * 2;
}
}
//This code is contributed by Shubham Singh
C
void fun(int n)
{
int i = 1;
while (i < n) {
int j = n;
while (j > 0) {
j = j / 2;
}
i = i * 2;
}
}
Java
public static void fun(int n)
{
int i = 1;
while (i < n) {
int j = n;
while (j > 0) {
j = j / 2;
}
i = i * 2;
}
}
// This code is contributed by Pushpesh Raj.
Python3
def fun(n):
i = 1
while (i < n):
j = n
while (j > 0):
j = j // 2
i = i * 2
# This code is contributed by Arushi Jindal.
C#
public static void fun(int n)
{
int i = 1;
while (i < n) {
int j = n;
while (j > 0) {
j = j / 2;
}
i = i * 2;
}
}
// This code is contributed by Aman Kumar
JavaScript
function fun(n)
{
let i = 1;
while (i < n) {
let j = n;
while (j > 0) {
j = Math.floor(j / 2);
}
i = i * 2;
}
}
// This code is contributed by Utkarsh
Solution - Time complexity = O(log2n).
Explanation -
In each iteration , i become twice (T.C=O(logn)) and j become half (T.C=O(logn)). So, time complexity will become O(log2n).
We can convert this while loop into for loop.
for( int i = 1; i < n; i = i * 2)
for( int j=n ; j > 0; j = j / 2).
Time complexity of above for loop is also O(log2n).
10. Consider the following code, what is the number of comparisons made in the execution of the loop ?
C++
void fun(int n)
{
int j = 1;
while (j <= n) {
j = j * 2;
}
}
// The code is contributed by Arushi Jindal.
C
void fun(int n)
{
int j = 1;
while (j <= n) {
j = j * 2;
}
}
Java
public static void fun(int n)
{
int j = 1;
while (j <= n) {
j = j * 2;
}
}
// This code is contributed by Pushpesh Raj.
Python3
def fun(n):
j = 1
while (j <= n):
j = j * 2
# The code is contributed by Arushi Jindal.
C#
public static void fun(int n)
{
int j = 1;
while (j <= n) {
j = j * 2;
}
}
// This code is contributed by Aman Kumar
JavaScript
function fun(n)
{
let j = 1;
while (j <= n) {
j = j * 2;
}
}
// This code is contributed by Utkarsh
Solution -
ceil(log2n)+1.
Explanation -
Let k be the no. of iteration of the loop. After the kth step, the value of j is 2k. Hence, k=log2n. Here, we use ceil of log2n, because log2n may be in decimal. Since we are doing one more comparison for exiting from the loop.
So, the answer is ceil(log2n)+1.
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem