Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Subarray Sum Equals Target

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

Your question is Subarray Sum Equals Target. 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

Coforge analytics pipelines may need to detect whether a contiguous sequence of transaction adjustments reaches a required target. Given an integer array and a target value, determine whether at least one non-empty contiguous subarray has a sum exactly equal to the target.

Your solution must support positive numbers, zero, and negative numbers. Design it to run in expected O(n) time, since the input may contain up to one million values.

Formal Specification

Implement has_subarray_sum(nums, target).

  • Input: nums, a list of integers, and target, an integer.
  • Output: Return True if a non-empty contiguous subarray sums to target; otherwise, return False.
  • A subarray must contain consecutive elements and cannot be empty.

Constraints

  • 0 <= nums.length <= 10^6
  • -10^9 <= nums[i] <= 10^9
  • -10^15 <= target <= 10^15
  • The subarray must be non-empty
  • Values may be positive, zero, or negative

Function Signature

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