Skip to Content
Hands-On Data Structures and Algorithms with Python - Third Edition
book

Hands-On Data Structures and Algorithms with Python - Third Edition

by Dr. Basant Agarwal
July 2022
Intermediate to advanced
496 pages
11h 18m
English
Packt Publishing
Content preview from Hands-On Data Structures and Algorithms with Python - Third Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Hands-On Data Structures and Algorithms with Python - Second Edition

Hands-On Data Structures and Algorithms with Python - Second Edition

Dr. Basant Agarwal, Benjamin Baka, David Julian
Data Structures and Algorithms in Python

Data Structures and Algorithms in Python

Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Data Structures & Algorithms in Python

Data Structures & Algorithms in Python

John Canning, Alan Broder, Robert Lafore

Publisher Resources

ISBN: 9781801073448Supplemental Content