Python · Module 7Module material
Time complexity and Big O interview questions
25 questions interviewers ask on time and space complexity, from first principles to the follow-ups. The first 3 model answers are free to read; Pro opens the rest.
Complexity
- What is time complexity, and why count operations rather than seconds?●
How the number of operations a function performs grows with the size of its input. Seconds change from machine to machine and from run to run; the count of a chosen operation, such as a comparison, does not.
largestmakes10,100and1000comparisons for 10, 100 and 1,000 values. - What does Big-O notation keep, and what does it drop?●
It keeps the term that grows fastest and drops constants and smaller terms:
4n + 4is O(n), and3n² + 2n + 4is O(n²), because at n = 1,000 the3n²is3000000against2004for the rest. - Order these from slowest-growing to fastest: O(n²), O(1), O(n log n), O(log n), O(n).●
O(1), O(log n), O(n), O(n log n), O(n²). At n = 1,000 they are about
1,10,1000,9966and1000000operations. - What are the best, worst and average cases of a linear search?●●
- A function takes 13 ms on 1,000 values and 55 ms on 2,000. What is its complexity likely to be?●●
- Why is this function O(n²), though it has one loop?●●
- What is space complexity?●
- What is a time–space trade-off? Give an example.●●
- What are the time complexities of
append,insert(0, x),x in a_listandsorted?●● - Does a lower Big-O always mean faster code?●●
Binary search
- How does binary search work, and what does it need?●
- Why is binary search O(log n)?●●
- What happens if you binary-search an unsorted list?●●
- When is sorting first, then binary search, worth it?●●
- What are the classic bugs in a hand-written binary search?●●
- What does
bisect_leftreturn for a value that is not in the list?●● - How would you count the occurrences of a value in a sorted list in O(log n)?●●
- Write binary search recursively. What is its space complexity?●●
Hash tables
- What is a hash table?●
- What is a collision, and how is it handled?●●
- What is the load factor, and why does it matter?●●
- Is a dictionary lookup always O(1)?●●
- Why must dictionary keys be hashable, and why is a list not?●●
- How do you find the elements two lists share, and at what cost?●●
- Why does a set of strings print in a different order each session?●●