Given N ranges of the form [L, R], the task is to find the sum of all integers that lie in any of the given ranges.
Examples:
Input: arr[] = {{1, 5}, {3, 7}}, N = 2
Output: 28
Explanation: The set of integers that exist in one or more ranges is {1, 2, 3, 4, 5 , 6, 7}. Hence  their sum is 28.Input: ranges[] = {{-12, 15}, {3, 9}, {-5, -2}, {20, 25}, {16, 20}}
Output: 247
Approach: The given problem can be solved by an approach similar to the Merge Overlapping Intervals problem. Below are the steps to follow:
- Sort the intervals based on increasing order of L.
- Push the first interval onto a stack and for each interval do the following:
- If the current interval does not overlap with the stack top, push it.
- If the current interval overlaps with stack top and right end of the current interval is more than that of stack top, update stack top with the value of right end of current interval.
- After traversing through all intervals, the remaining stack contains the merged intervals. The sum of the merged intervals can be calculated using formula for the sum of an Arithmetic Progression as the range [L, R] forms an AP with a common difference as 1 and the number of elements as R – L + 1. The sum is ((L + R)*(R-L+1))/2.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> #define ll long long using namespace std; Â
// Function to find the sum of all // integers numbers in range [L, R] ll sumInRange( long L, long R) { Â Â Â Â ll Sum = ((R - L + 1) / 2) Â Â Â Â Â Â * (2 * L + (R - L)); Â Â Â Â return Sum; } Â
// Function to find sum of all integers // that lie in any of the given ranges ll calcSum(vector<pair< long , long > > data, Â Â Â Â Â Â Â Â Â Â Â int n) { Â
    // Sort intervals in increasing order     // according to their first element     sort(data.begin(), data.end()); Â
    // Merging the overlapping intervals     int i, idx = 0; Â
    // Loop to iterate through the array     for (i = 1; i < n; i++) { Â
        // If current interval overlaps         // with the previous intervals         if ((data[idx].second >=              data[i].first)             || (data[i].first ==                 data[idx].second + 1)) { Â
            // Merge the previous and the             // current interval             data[idx].second                 = max(data[idx].second,                       data[i].second);         }         else {             idx++;             data[idx].second = data[i].second;             data[idx].first = data[i].first;         }     } Â
    // Stores the required sum     ll Sum = 0; Â
    // Loop to calculate the sum of all     // the remaining merged intervals     for (i = 0; i <= idx; i++) { Â
        // Add sum of integers         // in current range         Sum += sumInRange(data[i].first,                           data[i].second);     } Â
    // Return the total Sum     return Sum; } Â
// Driver Code int main() {     vector<pair< long , long > > vec       = { { -12, 15 },          { 3, 9 },          { -5, -2 },          { 20, 25 },          { 16, 20 } }; Â
    cout << calcSum(vec, vec.size()); Â
    return 0; } |
Java
// Java program for the above approach import java.util.*; class GFG { Â
// Function to find the sum of all // integers numbers in range [L, R] static int sumInRange( int L, int R) { Â Â Â Â int Sum = ((R - L + 1 ) / 2 ) Â Â Â Â Â Â * ( 2 * L + (R - L)); Â Â Â Â return Sum; } Â
// Function to find sum of all integers // that lie in any of the given ranges static int calcSum( int [][]data, Â Â Â Â Â Â Â Â Â Â Â int n) { Â
    // Sort intervals in increasing order     // according to their first element     Arrays.sort(data,(a,b)->{         return a[ 0 ]-b[ 0 ];     }); Â
    // Merging the overlapping intervals     int i, idx = 0 ; Â
    // Loop to iterate through the array     for (i = 1 ; i < n; i++) { Â
        // If current interval overlaps         // with the previous intervals         if ((data[idx][ 1 ] >=              data[i][ 0 ])             || (data[i][ 0 ] ==                 data[idx][ 1 ] + 1 )) { Â
            // Merge the previous and the             // current interval             data[idx][ 1 ]                 = Math.max(data[idx][ 1 ],                       data[i][ 1 ]);         }         else {             idx++;             data[idx][ 1 ] = data[i][ 1 ];             data[idx][ 0 ] = data[i][ 0 ];         }     } Â
    // Stores the required sum     int Sum = 0 ; Â
    // Loop to calculate the sum of all     // the remaining merged intervals     for (i = 0 ; i <= idx; i++) { Â
        // Add sum of integers         // in current range         Sum += sumInRange(data[i][ 0 ],                           data[i][ 1 ]);     } Â
    // Return the total Sum     return Sum; } Â
// Driver Code public static void main(String[] args) {     int [][]vec       = { { - 12 , 15 },          { 3 , 9 },          { - 5 , - 2 },          { 20 , 25 },          { 16 , 20 } }; Â
    System.out.print(calcSum(vec, vec.length)); Â
} } Â
// This code is contributed by shikhasingrajput |
Python3
# Python 3 program for the above approach Â
# Function to find the sum of all # integers numbers in range [L, R] def sumInRange(L, R): Â
    Sum = ((R - L + 1 ) / / 2 ) * ( 2 * L + (R - L))     return Sum Â
# Function to find sum of all integers # that lie in any of the given ranges def calcSum(data, Â Â Â Â Â Â Â Â Â Â Â Â n): Â
    # Sort intervals in increasing order     # according to their first element     data.sort() Â
    # Merging the overlapping intervals     idx = 0 Â
    # Loop to iterate through the array     for i in range ( 1 , n): Â
        # If current interval overlaps         # with the previous intervals         if ((data[idx][ 1 ] > =              data[i][ 0 ])             or (data[i][ 0 ] = =                 data[idx][ 1 ] + 1 )): Â
            # Merge the previous and the             # current interval             data[idx][ 1 ] = max (data[idx][ 1 ],                                data[i][ 1 ]) Â
        else :             idx + = 1             data[idx][ 1 ] = data[i][ 1 ]             data[idx][ 0 ] = data[i][ 0 ]     # Stores the required sum     Sum = 0 Â
    # Loop to calculate the sum of all     # the remaining merged intervals     for i in range (idx + 1 ): Â
        # Add sum of integers         # in current range         Sum + = sumInRange(data[i][ 0 ],                           data[i][ 1 ]) Â
    # Return the total Sum     return Sum Â
# Driver Code if __name__ = = "__main__" : Â
    vec = [[ - 12 , 15 ],            [ 3 , 9 ],            [ - 5 , - 2 ],            [ 20 , 25 ],            [ 16 , 20 ]] Â
    print (calcSum(vec, len (vec))) Â
    # This code is contributed by ukasp. |
C#
// C# implementation of the approach using System; using System.Collections; using System.Collections.Generic; using System.Globalization; Â
class GFG { Â
  // Custom function for sort   public static void Sort<T>(T[][] data, int col)   {     Comparer<T> comparer = Comparer<T>.Default;     Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col]));   } Â
Â
Â
  // Function to find the sum of all   // integers numbers in range [L, R]   public static int sumInRange( int L, int R)   {     int Sum = ((R - L + 1) / 2) * (2 * L + (R - L));     return Sum;   } Â
  // Function to find sum of all integers   // that lie in any of the given ranges   public static int calcSum( int [][] data, int n)   { Â
    // Sort intervals in increasing order     // according to their first element      Sort< int >(data, 0); Â
    // Merging the overlapping intervals     int i = 0;     int idx = 0; Â
    // Loop to iterate through the array     for (i = 1; i < n; i++) { Â
      // If current interval overlaps       // with the previous intervals       if ((data[idx][1] >= data[i][0]) || (data[i][0] == data[idx][1] + 1)) { Â
        // Merge the previous and the         // current interval         data[idx][1] = Math.Max(data[idx][1], data[i][1]);       }       else {         idx++;         data[idx][1] = data[i][1];         data[idx][0] = data[i][0];       }     } Â
    // Stores the required sum     int Sum = 0; Â
    // Loop to calculate the sum of all     // the remaining merged intervals     for (i = 0; i <= idx; i++) { Â
      // Add sum of integers       // in current range       Sum += sumInRange(data[i][0], data[i][1]);     } Â
    // Return the total Sum     return Sum;   } Â
  static void Main() { Â
    int [][] vec = new int [][] {       new int [] {-12, 15},       new int [] {3, 9 },       new int [] {-5, -2 },       new int [] {20, 25},       new int [] {16, 20}     };     Console.WriteLine(calcSum(vec, vec.Length));   } } Â
// The code is contributed by Nidhi goel. |
Javascript
<script> Â Â Â Â Â Â Â // JavaScript code for the above approach Â
       // Function to find the sum of all        // integers numbers in range [L, R]        function sumInRange(L, R) {            let Sum = ((R - L + 1) / 2)                * (2 * L + (R - L));            return Sum;        } Â
       // Function to find sum of all integers        // that lie in any of the given ranges        function calcSum(data, n) { Â
           // Sort intervals in increasing order            // according to their first element            data.sort( function (a, b) { return a.first - b.first }) Â
           // Merging the overlapping intervals            let i, idx = 0; Â
           // Loop to iterate through the array            for (i = 1; i < n; i++) { Â
               // If current interval overlaps                // with the previous intervals                if ((data[idx].second >=                    data[i].first)                    || (data[i].first ==                        data[idx].second + 1)) { Â
                   // Merge the previous and the                    // current interval                    data[idx].second                        = Math.max(data[idx].second,                            data[i].second);                }                else {                    idx++;                    data[idx].second = data[i].second;                    data[idx].first = data[i].first;                }            } Â
           // Stores the required sum            let Sum = 0; Â
           // Loop to calculate the sum of all            // the remaining merged intervals            for (i = 0; i <= idx; i++) { Â
               // Add sum of integers                // in current range                Sum += sumInRange(data[i].first,                    data[i].second);            } Â
           // Return the total Sum            return Sum;        } Â
       // Driver Code Â
       let vec            = [{ first: -12, second: 15 },            { first: 3, second: 9 },            { first: -5, second: -2 },            { first: 20, second: 25 },            { first: 16, second: 20 }]; Â
       document.write(calcSum(vec, vec.length));          // This code is contributed by Potta Lokesh    </script> |
Â
Â
247
Â
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!