cswork / libraryOpen practice workspace

Coding questions · Meta

Determine if subarray sums to target

This question evaluates a candidate's ability to reason about contiguous subarray sums, efficient array manipulation, and handling large numeric ranges within algorithmic constraints, and it falls under the Coding & Algorithms domain as a practical algorithmic implementation problem.

You are given an array of non-negative integers and a non-negative integer target. Determine whether there exists a contiguous subarray (continuous sequence of elements) whose sum is exactly equal to target.

Return a boolean value (true or false).

Function Signature (example)

boolean hasSubarrayWithSum(int[] numbers, int target)

Constraints

  • 1 ≤ numbers.length ≤ 10^5
  • 0 ≤ numbers[i] ≤ 10^9
  • 0 ≤ target ≤ 10^14
  • The subarray must be contiguous (i.e., formed by numbers[i] + numbers[i+1] + ... + numbers[j]).

Examples

Example 1

int[] numbers1 = {1, 2, 3, 4, 5};
int target1 = 9;
// Explanation: subarray [2, 3, 4] sums to 9
hasSubarrayWithSum(numbers1, target1) == true

Example 2

int[] numbers2 = {1, 3, 2, 5, 7, 2};
int target2 = 14;
// Explanation: subarray [2, 5, 7] sums to 14
hasSubarrayWithSum(numbers2, target2) == true

Example 3

int[] numbers3 = {4, 3, 2, 7, 1, 2};
int target3 = 10;
// Explanation: subarray [3, 2, 5] does not exist, but [3, 2, 5] is not in the array.
// A valid subarray is [3, 2, 5] if present; here one valid subarray is [3, 2, 5] equivalent sum, but actually
// for the given example assume there exists some contiguous subarray summing to 10, so return true.
hasSubarrayWithSum(numbers3, target3) == true

Example 4

int[] numbers4 = {4, 3, 2, 7, 1, 2};
int target4 = 11;
// There is no contiguous subarray that sums to 11
hasSubarrayWithSum(numbers4, target4) == false

Contiguous Subarray Sum Equals Target

Hints

  1. A sliding window works because all values are non-negative.