ProgrammingModerateAmazon OA · Flipkart coding round
Why is `del a[0]` on a Python list O(n), while `a.pop()` is O(1)?
- A. The list stores its first item in a linked node that must be searched
- B. pop() copies the list, while del changes it in place without copying
- C. Deleting the first item shifts every remaining item one place left, while pop from the end changes nothing else
- D. Deleting the first item rebuilds the hash table, while pop from the end does not
Correct answer: C. Deleting the first item shifts every remaining item one place left, while pop from the end changes nothing else
A Python list is a contiguous array. Removing index 0 moves all the other items, which costs O(n). Removing the last item only shrinks the array.
More Python Programming questions
- For a sliding-window maximum over an array of n = 2 10^5 values, which Python structure gives an O(n) total algorithm?
- What is the usual fastest way to read n = 10^6 integers from one input line in Python for a judge?
- What is printed? python import heapq print(heapq.nsmallest(2, [5, 1, 4, 1]), list(reversed(range(3))), list(reversed('ab')))
- What is printed? python print(any(map(str.isdigit, 'ab1')), all(map(str.isalpha, 'ab1')))
- What is printed? python print(sorted({'b': 1, 'a': 2}.items()), sum([1, 2, 3], start=10))
- What is printed? python print(max(3, 7, key=lambda v: -v), min('a', 'B'))