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?
- A. Replace lst with a tuple
- B. Use a while loop instead of a for loop
- C. Replace lst with a set built once before the loop
- 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
- What is printed? python def tri(t): dp = t[-1][:] for row in range(len(t) - 2, -1, -1): for j in range(len(t[row])): dp[j] = t[row][j] +…
- What is printed? python def lps(s): n = len(s) dp = [[0] n for in range(n)] for i in range(n): dp[i][i] = 1 for L in range(2, n + 1): for…
- What is printed? python fs = [lambda: i for i in range(3)] gs = [lambda i=i: i for i in range(3)] print([f() for f in fs], [g() for g in…
- What is printed? python def isprime(n): if n < 2: return False i = 2 while i i <= n: if n % i == 0: break i += 1 else: return True return…
- For a Python list a, which operation takes time proportional to j - i?
- What is printed? python from functools import lrucache @lrucache(maxsize=None) def f(n, last): if n == 0: return 1 total = f(n - 1, 0) if…