Question presented to candidate: "Given an integer array, find the contiguous subarray with the largest sum and return that sum. Code it in Python. What if every number is negative? Can you also return where the subarray starts and ends?"
What a strong answer should cover:
- The state "best sum of a subarray ending here" and the update
cur = max(x, cur + x),best = max(best, cur)β Kadane, O(n) time, O(1) space. - Why a negative running sum should be dropped, and that the two forms (restart if
cur < 0/max(x, cur + x)) are the same rule. - Initialising from the first element so all-negative arrays return their largest element, not 0.
- The brute-force baselines (O(nΒ³), O(nΒ²)) and the prefix-sum view; tracking start and end indices.
- Python specifics: starting from
nums[0]rather than 0 orfloat("-inf"),IndexErroron an empty list, slicing being end-exclusive for returning the subarray, andintnever overflowing.
Clarifying questions expected:
- "Must the subarray be non-empty, and what should an empty input return?"
- "Do you want the sum only, or the indices too?"
Code / implementation expected: Yes β a one-pass Python function, with indices as a follow-up.