ProgrammingHardTCS CodeVita · Infosys HackWithInfy

A solution loops over 2 x 10^5 queries, and each query runs `if x in lst` on a list of 2 x 10^5 items. Which change keeps the same answers and fixes the running time?

  1. A. Replace lst with a tuple
  2. B. Use a while loop instead of a for loop
  3. C. Replace lst with a set built once before the loop
  4. D. Sort lst before each query

Correct answer: C. Replace lst with a set built once before the loop

A set answers membership in O(1) on average, so building it once gives O(n) total work instead of O(n^2) list scans. A tuple has the same linear membership test, and sorting before each query only adds cost.

More Python Programming questions

Exams that ask this topic