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?
- A. Use seen_list.index(x) inside a try block instead of the membership test
- B. Keep seen_list but sort it before each check so that bisect is used
- C. Store the values in a set and test membership with `x not in seen_set`
- 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
- What is printed? python import heapq print(heapq.nsmallest(0, [5, 1]), max([], default=-1), min([3, 1, 2], key=lambda x: -x))
- What is printed? python print(pow(2, -1, 10 9 + 7))
- What is printed? python import math n = 10 30 - 1 print(math.isqrt(n), int(n 0.5))
- What is printed? python print(2 53 + 1 == float(2 53 + 1))
- What is printed? python import io s = io.StringIO("abcn") print(repr(s.readline()), repr(s.readline()))
- What is printed? python data = "2n10 20n30n" it = iter(data.split()) n = int(next(it)) arr = [int(next(it)) for in range(n)] print(arr…