ProgrammingHardProduct-company MCQ pattern
A program makes 10^5 membership checks of the form x in visited, where visited holds 10^5 items. Which statement is correct?
- A. A list costs O(n) per check, so the worst case is about 10^10 comparisons, while a set costs O(1) on average per check
- B. A list is faster because its contiguous memory makes the whole loop O(n) in total
- C. A set costs O(n) per check because it must rehash on every lookup
- D. Both are O(n log n) in total because Python sorts the container before searching
Correct answer: A. A list costs O(n) per check, so the worst case is about 10^10 comparisons, while a set costs O(1) on average per check
A list membership test scans items one by one, so the cost per check is O(n). A set uses hashing, giving O(1) average per check, which turns the whole loop into roughly O(n + m) instead of O(n * m).
More Python Programming questions
- What is printed? python def cnt(a, k): p, l, res = 1, 0, 0 for r, x in enumerate(a): p = x while l <= r and p >= k: p //= a[l] l += 1 res…
- What is printed? python g = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] n, m = 3, 3 P = [[0] (m + 1) for in range(n + 1)] for i in range(n): for j…
- What is printed? python def splits(a): total = sum(a) s = 0 c = 0 for x in a[:-1]: s += x if 2 s == total: c += 1 return c…
- What is printed? python from collections import deque def zeroone(n, edges, src): adj = [[] for in range(n)] for u, v, w in edges…
- What is printed? python from collections import deque def ladder(begin, end, words): S = set(words) q = deque([(begin, 1)]) seen = {begin}…
- What is printed? python def can(a): s = sum(a) if s % 2: return False t = s // 2 dp = [False] (t + 1) dp[0] = True for x in a: for v in…