Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sum Of Variable Length Subarrays

Compute the sum of each query subarray, where the subarray length may vary from query to query.

Acceptance 0%
Problem Statement

Given an array of integers, answer multiple queries of the form: sum the elements in a subarray whose length is specified by the query. For each query, use the starting position and requested length to determine the segment, then return the sum of that segment.

This problem is a good fit for prefix sums because it asks for repeated range-sum queries on a static array.

Input Format

  • An integer array nums.
  • A set of queries, where each query specifies a subarray starting index and a length.
  • For every query, compute the sum of the contiguous subarray covered by that range.

Output Format

  • Return the sum for each query in the same order they are given.

Constraints

  • The array is static; there are no updates.
  • Query ranges are valid and fully contained within the array.
  • Efficiently answering many range-sum queries is expected.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1, 2, 3, 4]
queries = [[0, 2], [1, 3], [2, 1]]

Output

[3, 9, 3]

Explanation

The queried subarrays are [1, 2], [2, 3, 4], and [3]. Their sums are 3, 9, and 3.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.