Tutorialspoint
Problem
Solution
Submissions

Range Sum

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to count the number of range sums that lie in a given range [lower, upper] inclusive. Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums from indices i to j inclusive, where i <= j.

Example 1
  • Input: nums = [-2,5,-1], lower = -2, upper = 2
  • Output: 3
  • Explanation:
     Step 1: Calculate all possible range sums
     Step 2: S(0,0) = -2, S(0,1) = 3, S(0,2) = 2, S(1,1) = 5, S(1,2) = 4, S(2,2) = -1
     Step 3: Range sums in [-2, 2]: S(0,0) = -2, S(0,2) = 2, S(2,2) = -1
     Step 4: Therefore, count = 3
Example 2
  • Input: nums = [0], lower = 0, upper = 0
  • Output: 1
  • Explanation:
     Step 1: Only one element in array
     Step 2: S(0,0) = 0
     Step 3: 0 lies within range [0, 0]
     Step 4: Therefore, count = 1
Constraints
  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • -10^5 <= lower <= upper <= 10^5
  • Time Complexity: O(n^2) for brute force approach
  • Space Complexity: O(1)
ArraysControl StructuresAccentureZomato
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use nested loops to generate all possible range sums
  • For each starting index i, calculate cumulative sum to all ending indices j >= i
  • Check if each range sum falls within [lower, upper]
  • Keep a counter for valid range sums
  • Use long long to avoid integer overflow during sum calculations

Steps to solve by this approach:

 Step 1: Initialize a counter variable to keep track of valid range sums
 Step 2: Use outer loop to iterate through each starting index i from 0 to numsSize-1
 Step 3: For each starting index i, initialize sum to 0 and use inner loop for ending index j from i to numsSize-1
 Step 4: Add nums[j] to current sum to get range sum from index i to j
 Step 5: Check if current range sum falls within [lower, upper] bounds
 Step 6: If range sum is valid, increment the counter
 Step 7: Return the final count of valid range sums

Submitted Code :