C++ Programming Practice With Solution
C++ Programming Practice With Solution
Problem 1:
Find the Time Complexities of the following C++ codes. Assume that there is no syntax error.
(a) Code 1:
int Sum = 0;
for (int i=1; i<N; i *= 2)
{
for (int j=N; j>0; j /= 3)
Sum++;
}
Θ(log2N)
(b) Code 2:
int Sum = 0;
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
If (j<0)
Sum++;
}
Θ(N2)
(c) Code 3:
int Sum = 0;
for (int i=0; i<N; i=i+2)
{
for (int j=0; j<i; j++)
Sum++;
}
Θ(N2)
(d) Code 4:
int Sum = 0;
for (int i=0; i<N; i++)
{
if ( i < (N/2) )
for (int j=0; j<N; j*=2)
Sum++;
}
(e) Code 5:
int Sum = 0;
for (int i=1; i<N; i++)
{
if ( (i%5) == 0 )
Sum = 10;
break;
}
Θ(1)
For Problems 2 & 3, design efficient algorithms (in pseudocode form). Find time complexity function and asymptotic
time complexity of the proposed algorithms. Also, write best case, average case, and worst case for the proposed
algorithms.
Problem 2:
There are N integers in a list A. All integers except one integer occur in pairs (the integers in the pair may not be
adjacent i.e. the two numbers in a pair can separately exist anywhere in the list). Write an algorithm (in pseudocode
form) to find out the number that occurs only once.
Problem 3:
Given N integers, write an algorithm (in pseudocode form) to count the total pairs of integers that have a difference
of K.
Inputs
Number of integers N, the difference K, and the list A of elements.
Output
One integer telling the number of pairs that have a difference of K.
Solution 1:
Solution 2:
Initialize count as 0
Sort all numbers in increasing order.
Remove duplicates from array.
Do following for each element arr[i]
a) Binary Search for arr[i] + k in subarray from i+1 to n-1.
b) If arr[i] + k found, increment count.
Return count.
Solution 3:
Initialize count as 0.
Insert all elements of arr[] in an AVL tree. While inserting, ignore an element if already
present in AVL tree.
Do following for each element arr[i].
Search for arr[i] + k in AVL tree, if found then increment count.
Search for arr[i] - k in AVL tree, if found then increment count.
Remove arr[i] from AVL tree.
Time complexity of above solution is also O(nLogn) as search and delete operations
take O(Logn) time for a self-balancing binary search tree.