Data Structures & AlgorithmsHardProduct Company SDE · Kadane variants
Problem: Kadane's algorithm is started with best = 0 and a running sum initialised to 0, then applied to an array where every number is negative, such as [-5, -2, -9]. The problem requires a non-empty subarray. What should the answer be?
- A. 0, since the empty subarray sums to 0
- B. -2, the largest element
- C. -16, the sum of everything
- D. -9, the last element
Correct answer: B. -2, the largest element
Initialising best to 0 wrongly admits the empty subarray. The correct answer is the maximum element, here -2, so best must start at the first element or negative infinity.
More Coding Interview Problems questions
- Problem: You binary search the answer x for 'the minimum possible largest sum when an array is split into k contiguous parts'. Which…
- Problem: What is the time complexity of this loop in terms of n? python for i in range(1, n + 1): for j in range(i, n + 1, i): work()
- Problem: Count right/down paths from the top-left to the bottom-right of the 3x3 grid below, where '#' is blocked. The code returns the…
- Problem: What does the following print? python def add(x, bucket=[]): bucket.append(x) return bucket add(1) add(2) print(add(3))
- Problem: What does the following print for the array [7, 10, 4, 3, 20, 15] with k = 3? python import heapq def kth(a, k): h = [] for x in…
- Problem: What does the following print? python ops = [('b', 2), ('a', 2), ('c', 1), ('d', 3)] print([x for x, in sorted(ops, key=lambda t…