Appendix

Answers to the Questions

Chapter 2: Introduction to Algorithm Design

Question 1

Find the time complexity of the following Python snippets:

  1. i=1 
    while(i<n): 
        i*=2 
        print("data")
    
  2. i =n
    while(i>0):
        print("complexity")
        i/ = 2
    
  3. for i in range(1,n):
        j = i 
        while(j<n):
            j*=2
    
  4. i=1
    while(i<n): 
        print("python")
        i = i**2
    

Solution

  1. The complexity will be O(log(n)).

    As we are multiplying the integer i by 2 in each step there will be exactly log(n) steps. (1, 2, 4, …… till n).

  1. The complexity will be O(log(n)).

    As we are dividing the integer i by 2 in each step there will be exactly log(n) steps. (n, n/2, n/4, …… till 1).

  1. The outer loop will run n times for each i in the outer loop, while the inner while loop will run log(i) times because ...

Get Hands-On Data Structures and Algorithms with Python - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.