SchoolWhool
Quizzes and saved progress, freeSign in freeSign in
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

  1. 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. largest makes 10, 100 and 1000 comparisons for 10, 100 and 1,000 values.

  2. 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 + 4 is O(n), and 3n² + 2n + 4 is O(n²), because at n = 1,000 the 3n² is 3000000 against 2004 for the rest.

  3. 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, 9966 and 1000000 operations.

  4. What are the best, worst and average cases of a linear search?●●
  5. A function takes 13 ms on 1,000 values and 55 ms on 2,000. What is its complexity likely to be?●●
  6. Why is this function O(n²), though it has one loop?●●
  7. What is space complexity?●
  8. What is a time–space trade-off? Give an example.●●
  9. What are the time complexities of append, insert(0, x), x in a_list and sorted?●●
  10. Does a lower Big-O always mean faster code?●●

Binary search

  1. How does binary search work, and what does it need?●
  2. Why is binary search O(log n)?●●
  3. What happens if you binary-search an unsorted list?●●
  4. When is sorting first, then binary search, worth it?●●
  5. What are the classic bugs in a hand-written binary search?●●
  6. What does bisect_left return for a value that is not in the list?●●
  7. How would you count the occurrences of a value in a sorted list in O(log n)?●●
  8. Write binary search recursively. What is its space complexity?●●

Hash tables

  1. What is a hash table?●
  2. What is a collision, and how is it handled?●●
  3. What is the load factor, and why does it matter?●●
  4. Is a dictionary lookup always O(1)?●●
  5. Why must dictionary keys be hashable, and why is a list not?●●
  6. How do you find the elements two lists share, and at what cost?●●
  7. Why does a set of strings print in a different order each session?●●