2dbi

Subarray with sum > 0 and length at least k

viaEngineBogie

Given an array arr containing only the values -1 and 1, and an integer k, determine whether there exists a subarray of length at least k whose elements sum to a value strictly greater than 0.

Input / Output

  • Input: integer array arr (each element is -1 or 1), integer k.
  • Output: boolean — true if such a subarray exists, otherwise false.

Constraints

  • 1 <= arr.length <= 10^5
  • 1 <= k <= arr.length
  • arr[i] is either -1 or 1.

Example

  • arr = [-1, 1, 1, -1], k = 2true (subarray [1, 1] has length 2 and sum 2 > 0).
  • arr = [-1, -1, -1, 1], k = 2false (no subarray of length >= 2 sums above 0).

Expected approach

  • Build a prefix-sum array pre, where pre[i] is the sum of the first i elements.
  • A subarray ending at j with length >= k has positive sum iff pre[j] > min(pre[0 .. j-k]).
  • Sweep j from k to n, keeping the running minimum of pre over indices 0 .. j-k; return true the moment pre[j] exceeds that minimum.
  • O(n) time, O(n) space.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account