← Questions

Most consecutive elements from an index whose sum stays below a target

0
MicrosoftCodingLast asked Nov 2025

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).
  • nums is 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 index and target?

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 first k elements from index is P[index + k] - P[index]; binary search for the first k where it reaches target. 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 reaches target, 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 index as well as the right.

Where it's asked

What it tests

prefix sums · binary-search

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding