Count of Range Sum

HardArrays & Hashingmerge sort

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums and two integers lower and upper, count the contiguous subarrays nums[i..j] (with i <= j) whose sum lies in the inclusive range [lower, upper]. Return that count. Subarray sums may exceed the 32-bit range even though each element fits in 32 bits. Aim for O(n log n) time; the O(n^2) approach of checking every subarray is too slow at the largest sizes.

Examples

Input: nums = [-2,5,-1], lower = -2, upper = 2
Output: 3
The subarrays [-2], [-1], and [-2,5,-1] have sums -2, -1, and 2.
Input: nums = [0], lower = 0, upper = 0
Output: 1
The single subarray [0] sums to 0.

Constraints

  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • -10^5 <= lower <= upper <= 10^5

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More merge sort problems