ProgrammingHardAmazon OA · Flipkart coding round
A Python list q holds n items. A loop repeatedly does x = q.pop(0) until q is empty. What is the total time cost of the loop in big-O terms?
- A. O(n)
- B. O(n log n)
- C. O(n^3)
- D. O(n^2)
Correct answer: D. O(n^2)
Each pop(0) shifts all the remaining items one slot left, so the total work is about n^2/2 moves. Using collections.deque with popleft avoids this and costs O(n) in total.
More Python Programming questions
- What is printed? python def rob(a): p, c = 0, 0 for x in a: p, c = c, max(c, p + x) return c print(rob([2, 7, 9, 3, 1]), rob([5]), rob([]))
- What is printed? python def ed(a, b): prev = list(range(len(b) + 1)) for i in range(1, len(a) + 1): cur = [i] + [0] len(b) for j in…
- What is printed? python def minlen(a, t): best = float('inf') s = 0 l = 0 for r, x in enumerate(a): s += x while s >= t: best = min(best…
- What is printed? python import heapq def kthlargest(a, k): h = [] for x in a: heapq.heappush(h, x) if len(h) > k: heapq.heappop(h) return…
- What is printed? python from collections import deque def winmax(a, k): dq = deque() out = [] for i, x in enumerate(a): while dq and…
- What is printed? python from collections import deque g = {1: [2, 3], 2: [4], 3: [4, 5], 4: [6], 5: [], 6: []} dist = {1: 0} q =…