KatInterview

327. Count of Range Sum

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the number of subarrays (or ranges) whose sum falls within a given inclusive range [lower, upper]. A naive approach would be to iterate through all possible subarrays, calculate their sums, and check if they are within the range. This would take O(n²) time, which is too slow given the constraint n <= 10^5.

Solution

Count of Range Sum in Python

class Solution:
    def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
        n = len(nums)
        # Python's integers handle arbitrary size, so no overflow worries.
        sums = [0] * (n + 1)
        for i in range(n):
            sums[i+1] = sums[i] + nums[i]

        # The core logic is in the recursive helper function.
        return self.countWhileMerging(sums, 0, n, lower, upper)

    def countWhileMerging(self, sums: List[int], start: int, end: int, lower: int, upper: int) -> int:
        # Base case: if the subarray has 0 or 1 element, no range sum can be formed.
        if start >= end:
            return 0

        # Divide the problem into two halves.
        mid = start + (end - start) // 2
        count = self.countWhileMerging(sums, start, mid, lower, upper) + \
                self.countWhileMerging(sums, mid + 1, end, lower, upper)

        # Count pairs (i, j) where i is in the left half and j is in the right half.
        # For each sums[j] in the right half, we need to find the number of sums[i] in the left half such that:
        # lower <= sums[j] - sums[i] <= upper
        # which is equivalent to:
        # sums[j] - upper <= sums[i] <= sums[j] - lower
        l, r = start, start
        for j in range(mid + 1, end + 1):
            # Find the first index l in the left half such that sums[l] >= sums[j] - upper.
            while l <= mid and sums[l] < sums[j] - upper:
                l += 1
            # Find the first index r in the left half such that sums[r] > sums[j] - lower.
            while r <= mid and sums[r] <= sums[j] - lower:
                r += 1
            count += (r - l)

        # Merge the two sorted halves.
        sums[start:end+1] = sorted(sums[start:end+1])
        # An explicit merge is also possible and might be slightly more efficient than Python's sorted().
        # temp = []
        # i, j = start, mid + 1
        # while i <= mid and j <= end:
        #     if sums[i] < sums[j]:
        #         temp.append(sums[i])
        #         i += 1
        #     else:
        #         temp.append(sums[j])
        #         j += 1
        # temp.extend(sums[i:mid+1])
        # temp.extend(sums[j:end+1])
        # for k in range(len(temp)):
        #     sums[start + k] = temp[k]

        return count

Count of Range Sum in Java

class Solution {
    public int countRangeSum(int[] nums, int lower, int upper) {
        int n = nums.length;
        // Use long for prefix sums to avoid integer overflow.
        long[] sums = new long[n + 1];
        for (int i = 0; i < n; i++) {
            sums[i + 1] = sums[i] + nums[i];
        }
        // The core logic is in the recursive helper function.
        // A temporary array is passed to avoid repeated allocation in recursion.
        return countWhileMerging(sums, 0, n, lower, upper, new long[n + 1]);
    }

    private int countWhileMerging(long[] sums, int start, int end, int lower, int upper, long[] temp) {
        // Base case: if the subarray has 0 or 1 element, no range sum can be formed.
        if (start >= end) {
            return 0;
        }

        // Divide the problem into two halves.
        int mid = start + (end - start) / 2;
        int count = countWhileMerging(sums, start, mid, lower, upper, temp) +
                    countWhileMerging(sums, mid + 1, end, lower, upper, temp);

        // Count pairs (i, j) where i is in the left half and j is in the right half.
        // For each sums[j] in the right half, we need to find the number of sums[i] in the left half such that:
        // lower <= sums[j] - sums[i] <= upper
        // which is equivalent to:
        // sums[j] - upper <= sums[i] <= sums[j] - lower
        int l = start, r = start;
        for (int j = mid + 1; j <= end; j++) {
            // Find the first index l in the left half such that sums[l] >= sums[j] - upper.
            while (l <= mid && sums[l] < sums[j] - upper) {
                l++;
            }
            // Find the first index r in the left half such that sums[r] > sums[j] - lower.
            while (r <= mid && sums[r] <= sums[j] - lower) {
                r++;
            }
            count += (r - l);
        }

        // Merge the two sorted halves into the temp array.
        int i = start, j = mid + 1, k = start;
        while (i <= mid && j <= end) {
            if (sums[i] < sums[j]) {
                temp[k++] = sums[i++];
            } else {
                temp[k++] = sums[j++];
            }
        }
        while (i <= mid) {
            temp[k++] = sums[i++];
        }
        while (j <= end) {
            temp[k++] = sums[j++];
        }

        // Copy the sorted elements back to the original sums array for the parent call.
        System.arraycopy(temp, start, sums, start, end - start + 1);

        return count;
    }
}

Count of Range Sum in C++

class Solution {
public:
    int countRangeSum(vector<int>& nums, int lower, int upper) {
        int n = nums.size();
        // Use long long for prefix sums to avoid overflow.
        vector<long long> sums(n + 1, 0);
        for (int i = 0; i < n; ++i) {
            sums[i + 1] = sums[i] + nums[i];
        }
        // The core logic is in the recursive helper function.
        return countWhileMerging(sums, 0, n, lower, upper);
    }

private:
    int countWhileMerging(vector<long long>& sums, int start, int end, int lower, int upper) {
        // Base case: if the subarray has 0 or 1 element, no range sum can be formed.
        if (start >= end) {
            return 0;
        }

        // Divide the problem into two halves.
        int mid = start + (end - start) / 2;
        int count = countWhileMerging(sums, start, mid, lower, upper) +
                    countWhileMerging(sums, mid + 1, end, lower, upper);

        // Count pairs (i, j) where i is in the left half and j is in the right half.
        // For each sums[j] in the right half, we need to find the number of sums[i] in the left half such that:
        // lower <= sums[j] - sums[i] <= upper
        // which is equivalent to:
        // sums[j] - upper <= sums[i] <= sums[j] - lower
        int l = start, r = start;
        for (int j = mid + 1; j <= end; ++j) {
            // Find the first index l in the left half such that sums[l] >= sums[j] - upper.
            while (l <= mid && sums[l] < sums[j] - upper) {
                l++;
            }
            // Find the first index r in the left half such that sums[r] > sums[j] - lower.
            while (r <= mid && sums[r] <= sums[j] - lower) {
                r++;
            }
            count += (r - l);
        }

        // Merge the two sorted halves.
        // std::inplace_merge can be used, but a temporary vector is often clearer and can be faster.
        vector<long long> temp;
        temp.reserve(end - start + 1);
        int i = start, j = mid + 1;
        while(i <= mid && j <= end) {
            if(sums[i] < sums[j]) {
                temp.push_back(sums[i++]);
            } else {
                temp.push_back(sums[j++]);
            }
        }
        while(i <= mid) {
            temp.push_back(sums[i++]);
        }
        while(j <= end) {
            temp.push_back(sums[j++]);
        }
        
        // Copy the sorted elements back to the original array.
        for(int k = 0; k < temp.size(); ++k) {
            sums[start + k] = temp[k];
        }

        return count;
    }
};

Count of Range Sum in TypeScript

function countRangeSum(nums: number[], lower: number, upper: number): number {
    const n = nums.length;
    // JavaScript numbers are 64-bit floats, which can safely handle integers up to 2^53.
    // The max possible sum is ~10^5 * 2^31, which is within this safe range.
    const sums: number[] = new Array(n + 1).fill(0);
    for (let i = 0; i < n; i++) {
        sums[i + 1] = sums[i] + nums[i];
    }

    function countWhileMerging(start: number, end: number): number {
        // Base case: if the subarray has 0 or 1 element, no range sum can be formed.
        if (start >= end) {
            return 0;
        }

        // Divide the problem into two halves.
        const mid = Math.floor(start + (end - start) / 2);
        let count = countWhileMerging(start, mid) + countWhileMerging(mid + 1, end);

        // Count pairs (i, j) where i is in the left half and j is in the right half.
        // For each sums[j] in the right half, we need to find the number of sums[i] in the left half such that:
        // lower <= sums[j] - sums[i] <= upper
        // which is equivalent to:
        // sums[j] - upper <= sums[i] <= sums[j] - lower
        let l = start, r = start;
        for (let j = mid + 1; j <= end; j++) {
            // Find the first index l in the left half such that sums[l] >= sums[j] - upper.
            while (l <= mid && sums[l] < sums[j] - upper) {
                l++;
            }
            // Find the first index r in the left half such that sums[r] > sums[j] - lower.
            while (r <= mid && sums[r] <= sums[j] - lower) {
                r++;
            }
            count += (r - l);
        }

        // Merge the two sorted halves.
        const temp: number[] = [];
        let i = start, j = mid + 1;
        while (i <= mid && j <= end) {
            if (sums[i] < sums[j]) {
                temp.push(sums[i++]);
            } else {
                temp.push(sums[j++]);
            }
        }
        while (i <= mid) {
            temp.push(sums[i++]);
        }
        while (j <= end) {
            temp.push(sums[j++]);
        }

        // Copy the sorted elements back to the original sums array.
        for (let k = 0; k < temp.length; k++) {
            sums[start + k] = temp[k];
        }

        return count;
    }

    return countWhileMerging(0, n);
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.