Appendix
Answers to the Questions
Chapter 2: Introduction to Algorithm Design
Question 1
Find the time complexity of the following Python snippets:
-
i=1 while(i<n): i*=2 print("data")
-
i =n while(i>0): print("complexity") i/ = 2
-
for i in range(1,n): j = i while(j<n): j*=2
-
i=1 while(i<n): print("python") i = i**2
Solution
- The complexity will be
O(log(n))
.As we are multiplying the integer
i
by2
in each step there will be exactlylog(n)
steps. (1
,2
,4
, …… tilln
).
- The complexity will be
O(log(n))
.As we are dividing the integer
i
by2
in each step there will be exactlylog(n)
steps. (n
,n
/2
,n
/4
, …… till1
).
- The outer loop will run
n
times for eachi
in the outer loop, while the innerwhile
loop will runlog(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.