Most consecutive elements from an index whose sum stays below a target
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Microsoft's HackerRank assessment, last asked Nov 2025. It tests prefix sums and binary-search.
You get an array nums sorted in non-decreasing order, a start position index and an integer target. Take elements going right from index: nums[index], nums[index + 1], and so on. Return the largest k such that the running sum stays strictly below target for each of the first k elements taken. If nums[index] >= target, the answer is 0.
Interface
Unless you agree on a different interface with the interviewer, assume:
max_run(nums: list[int], index: int, target: int) -> int
Example
nums = [1, 2, 3, 4, 5], index = 0, target = 7 -> 3 # sums 1, 3, 6; adding 4 gives 10
nums = [1, 2, 3, 4, 5], index = 2, target = 100 -> 3 # 3, 7, 12, then the array ends
nums = [1, 2, 3, 4, 5], index = 4, target = 5 -> 0 # 5 is not below 5
Constraints
-
1 <= len(nums) <= 10^5,0 <= index < len(nums). -
numsis sorted non-decreasing and may contain negative numbers and zeros. - The sum must be strictly less than
target; equal does not count.
Clarifying questions
- Strictly less than
target, or at most? - Can values be negative or zero?
- One query, or many queries on the same array with different
indexandtarget?
What a strong answer covers
- The direct scan from
index, O(k) time and O(1) space, which is optimal for a single query. - For many queries: prefix sums
P, so the sum of the firstkelements fromindexisP[index + k] - P[index]; binary search for the firstkwhere it reachestarget. O(n) preprocessing, O(log n) per query. - Why binary search is valid: once the elements reach zero or above the running sum only grows, and while they are negative the sum only falls, so the first crossing is unique.
- Edge cases:
nums[index] >= target, the array ending before the sum reachestarget, sums that overflow 32-bit integers.
Follow-ups
- The array is no longer sorted and may hold negatives. Does binary search still work?
- Return the longest run starting anywhere, not at a fixed index.
- Take elements to the left of
indexas well as the right.
Where it's asked
- Microsoft · HackerRank assessment · Last asked Nov 202590 min · Two problems in a locked full-screen browser
What it tests
prefix sums · binary-search
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
