ProgrammingModerateAmazon OA · Flipkart coding round

A solution does `if x not in seen_list` for each of n = 2 * 10^5 values, where seen_list grows to n items. Which change gives the best speedup while keeping the same logic?

  1. A. Use seen_list.index(x) inside a try block instead of the membership test
  2. B. Keep seen_list but sort it before each check so that bisect is used
  3. C. Store the values in a set and test membership with `x not in seen_set`
  4. D. Replace the list with a tuple built fresh on each iteration

Correct answer: C. Store the values in a set and test membership with `x not in seen_set`

Membership in a list scans the whole list, O(n) per check and O(n^2) overall. A set uses a hash table, so the average membership test is O(1) and the total is O(n).

More Python Programming questions

Exams that ask this topic