Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Longest Contiguous Subarray Sum Equals K

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Longest Contiguous Subarray Sum Equals K. Start with the requirements on the right.

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.

Problem

Facebook News Feed analytics may represent each interaction as an integer score, including positive, negative, and zero values. Given an integer array nums and an integer k, return the length of the longest contiguous subarray whose elements sum exactly to k.

You must consider every contiguous subarray and may return 0 if no qualifying subarray exists.

Formal Specification

  • Input: nums, a list of integers, and k, an integer.
  • Output: An integer representing the maximum length of a contiguous subarray with sum exactly k.
  • A subarray must contain consecutive elements, and an empty subarray is not counted.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • -10^9 <= k <= 10^9

Function Signature

def longest_subarray_sum_k(nums, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output