Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Longest Subarray Less Than Or Equal To K
00:00
5 left

Longest Subarray Less Than Or Equal To K

HardPython

Problem

In Canva's design editor, a sequence of integers represents the estimated render-cost change for consecutive elements. Given nums and a budget k, return the length of the longest non-empty contiguous subarray whose sum is less than or equal to k.

Values may be negative, so a standard sliding-window approach is not valid. Design an algorithm that handles arbitrary integers efficiently.

Formal Specification

Implement longest_subarray_at_most_k(nums, k).

  • Input: nums, a list of integers, and k, an integer.
  • Output: An integer representing the maximum length of a non-empty contiguous subarray with sum at most k.
  • If nums is empty, return 0.

Constraints

  • 0 <= nums.length <= 2 * 10^5
  • -10^9 <= nums[i] <= 10^9
  • -10^14 <= k <= 10^14
  • The subarray must be non-empty when nums is not empty

Function Signature

def longest_subarray_at_most_k(nums, k):
Interviewer

Your question is Longest Subarray Less Than Or Equal To K. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.