Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Time Complexity of this Function in Scheme?

I am trying to find the time complexity of this function in Theta notation. Now, n is a positive integer, and lst is a list with 2 numbers.

(define (func n lst)
  (if (= n 0) lst
      (accumulate append null
                  (map (lambda (x)
                         (func (- n 1) (list x x)))
                       lst))))

As you know, the time complexity of append is Θ(n) where n is the overall size of the lists. I tried to see what happens if I treat append and accumulate as Θ(1) functions, then I get:

T(n) = 2T(n-1) + Θ(1) which is --> Θ(2^n)

Does this mean that the actual time complexity of this thing in Theta notation is way bigger than Θ(2^n)?

I'm not even sure that I'm right with this assumption alone, and anyways, I'm clueless on what to do if I need to take into consideration both accumulate and append...

I've wasted hours on this one, and I really don't understand why I can't figure it out on my own... Any help would be gladly appreciated.

btw, here is the code of accumulate:

(define (accumulate op init lst)
   (if (null? lst)
       init
          (op (car lst)
             (accumulate op init (cdr lst)))))
like image 299
Robert Shalom Avatar asked Dec 23 '11 13:12

Robert Shalom


People also ask

What is time complexity of function in function?

Time complexity is defined as the amount of time taken by an algorithm to run, as a function of the length of the input. It measures the time taken to execute each statement of code in an algorithm.

What is ACC in scheme?

Note: “ACC” stands for “Accident Compensation Corporation”, which is the government organisation that manages the accident compensation scheme and makes decisions about claims.

What do you mean by time complexity?

So, the time complexity is the number of operations an algorithm performs to complete its task (considering that each operation takes the same amount of time). The algorithm that performs the task in the smallest number of operations is considered the most efficient one in terms of the time complexity.

What is the time complexity of O N 2?

O(n2) O(n2) represents a function whose complexity is directly proportional to the square of the input size. Adding more nested iterations through the input will increase the complexity which could then represent O(n3) with 3 total iterations and O(n4) with 4 total iterations.


1 Answers

It sounds plausible, if you take a look at the output.

(func 3 (list 1 2 3))
=> (1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3)

For every element of lst 2^n elements are created which is l*2^n. The algorithm could only be worse.

And obviously it is bad. The function accumulate is not tail recursive and func therefore either not. A 2^n non tail recursive function is quite useless.

like image 93
ceving Avatar answered Oct 09 '22 02:10

ceving