Examveda

What will be the worst case time complexity for the following code?
#include <stdio.h> 
bool func(int arr[], int n, int sum) 
{ 
    if (sum == 0) 
	return true; 
    if (n == 0 && sum != 0) 
	return false; 
    if (arr[n-1] > sum) 
	return func(arr, n-1, sum); 
    return func(arr, n-1, sum) || func(arr, n-1, sum-arr[n-1]); 
} 
int main() 
{ 
    int arr[] = {4,6, 12, 2}; 
    int sum = 12; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    if (func(arr, n, sum) == true) 
	printf("true"); 
    else
	printf("false"); 
    return 0; 
}

A. O(n log n)

B. O(n2)

C. O(2n)

D. O(n2 log n)

Answer: Option C


This Question Belongs to Data Structure >> Miscellaneous On Data Structures

Join The Discussion

Related Questions on Miscellaneous on Data Structures