Sum of all elements between k1’th and k2’th smallest elements

06 Jul, 2022
Given an array of integers and two numbers k1 and k2. Find the sum of all elements between given two k1’th and k2’th smallest elements of the array. It may be assumed that (1 <= k1 < k2 <= n) and all elements of array are distinct.
Examples : 
Input : arr[] = {20, 8, 22, 4, 12, 10, 14},  k1 = 3,  k2 = 6  
Output : 26          
         3rd smallest element is 10. 6th smallest element 
         is 20. Sum of all element between k1 & k2 is
         12 + 14 = 26

Input : arr[] = {10, 2, 50, 12, 48, 13}, k1 = 2, k2 = 6 
Output : 73 
Method 1 (Sorting): First sort the given array using a O(n log n) sorting algorithm like Merge Sort, Heap Sort, etc and return the sum of all element between index k1 and k2 in the sorted array.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of all element between// to K1'th and k2'th smallest elements in array#include <bits/stdc++.h> using namespace std; // Returns sum between two kth smallest elements of the arrayint sumBetweenTwoKth(int arr[], int n, int k1, int k2){    // Sort the given array    sort(arr, arr + n);     /* Below code is equivalent to     int result = 0;     for (int i=k1; i<k2-1; i++)      result += arr[i]; */    return accumulate(arr + k1, arr + k2 - 1, 0);} // Driver programint main(){    int arr[] = { 20, 8, 22, 4, 12, 10, 14 };    int k1 = 3, k2 = 6;    int n = sizeof(arr) / sizeof(arr[0]);    cout << sumBetweenTwoKth(arr, n, k1, k2);    return 0;}
// Java program to find sum of all element// between to K1'th and k2'th smallest// elements in arrayimport java.util.Arrays; class GFG {     // Returns sum between two kth smallest    // element of array    static int sumBetweenTwoKth(int arr[],                                int k1, int k2)    {        // Sort the given array        Arrays.sort(arr);         // Below code is equivalent to        int result = 0;         for (int i = k1; i < k2 - 1; i++)            result += arr[i];         return result;    }     // Driver code    public static void main(String[] args)    {         int arr[] = { 20, 8, 22, 4, 12, 10, 14 };        int k1 = 3, k2 = 6;        int n = arr.length;         System.out.print(sumBetweenTwoKth(arr,                                          k1, k2));    }} // This code is contributed by Anant Agarwal.
# Python program to find sum of# all element between to K1'th and# k2'th smallest elements in array # Returns sum between two kth# smallest element of arraydef sumBetweenTwoKth(arr, n, k1, k2):     # Sort the given array    arr.sort()     result = 0    for i in range(k1, k2-1):        result += arr[i]    return result # Driver codearr = [ 20, 8, 22, 4, 12, 10, 14 ]k1 = 3; k2 = 6n = len(arr)print(sumBetweenTwoKth(arr, n, k1, k2))  # This code is contributed by Anant Agarwal.
// C# program to find sum of all element// between to K1'th and k2'th smallest// elements in arrayusing System; class GFG {     // Returns sum between two kth smallest    // element of array    static int sumBetweenTwoKth(int[] arr, int n,                                int k1, int k2)    {        // Sort the given array        Array.Sort(arr);         // Below code is equivalent to        int result = 0;         for (int i = k1; i < k2 - 1; i++)            result += arr[i];         return result;    }     // Driver code    public static void Main()    {        int[] arr = { 20, 8, 22, 4, 12, 10, 14 };        int k1 = 3, k2 = 6;        int n = arr.Length;         Console.Write(sumBetweenTwoKth(arr, n, k1, k2));    }} // This code is contributed by nitin mittal.
<?php// PHP program to find sum of all element between// to K1'th and k2'th smallest elements in array // Returns sum between two kth smallest elements of the arrayfunction sumBetweenTwoKth($arr, $n, $k1, $k2){    // Sort the given array    sort($arr);     // Below code is equivalent to        $result = 0;          for ($i = $k1; $i < $k2 - 1; $i++)            $result += $arr[$i];          return $result;} // Driver program     $arr = array( 20, 8, 22, 4, 12, 10, 14 );    $k1 = 3;    $k2 = 6;    $n = count($arr);;    echo sumBetweenTwoKth($arr, $n, $k1, $k2);     // This code is contributed by mits?>
<script> // Javascript program to find sum of all element// between to K1'th and k2'th smallest// elements in array // Returns sum between two kth smallest// element of arrayfunction sumBetweenTwoKth(arr, k1 , k2){         // Sort the given array    arr.sort(function(a, b){return a - b});     // Below code is equivalent to    var result = 0;     for(var i = k1; i < k2 - 1; i++)        result += arr[i];     return result;} // Driver codevar arr = [ 20, 8, 22, 4, 12, 10, 14 ];var k1 = 3, k2 = 6;var n = arr.length; document.write(sumBetweenTwoKth(arr,                                k1, k2)); // This code is contributed by shikhasingrajput </script>
26
Time Complexity: O(n log n) 
Method 2 (Using Min Heap):
We can optimize the above solution be using a min heap. 
Create a min heap of all array elements. (This step takes O(n) time) Do extract minimum k1 times (This step takes O(K1 Log n) time) Do extract minimum k2 – k1 – 1 time and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time)
Create a min heap of all array elements. (This step takes O(n) time) 
Do extract minimum k1 times (This step takes O(K1 Log n) time) 
Do extract minimum k2 – k1 – 1 time and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time)
Time Complexity Analysis: 
By doing a simple analysis, we can observe that time complexity of step3 [ Determining step for overall time complexity ] can reach to O(nlogn) also. 
Take a look at the following description:Time Complexity of step3 is:  O((k2-k1)*log(n)) . In worst case, (k2-k1) would be almost O(n) [ Assume situation when k1=0  and k2=len(arr)-1 ]When O(k2-k1) =O(n) then overall complexity will be O(n* Log n ) .but in most of the cases...it will be lesser than O(n Log n) that is equal to sorting approach described above.
Time Complexity of step3 is:  O((k2-k1)*log(n)) . 
In worst case, (k2-k1) would be almost O(n) [ Assume situation when k1=0  and k2=len(arr)-1 ]
When O(k2-k1) =O(n) then overall complexity will be O(n* Log n ) .
but in most of the cases...it will be lesser than O(n Log n) that is equal to sorting approach described above.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; int n = 7; void minheapify(int a[], int index){     int small = index;    int l = 2 * index + 1;    int r = 2 * index + 2;     if (l < n && a[l] < a[small])        small = l;     if (r < n && a[r] < a[small])        small = r;     if (small != index) {        swap(a[small], a[index]);        minheapify(a, small);    }} int main(){    int i = 0;    int k1 = 3;    int k2 = 6;     int a[] = { 20, 8, 22, 4, 12, 10, 14 };     int ans = 0;     for (i = (n / 2) - 1; i >= 0; i--) {        minheapify(a, i);    }     // decreasing value by 1 because we want min heapifying k times and it starts    // from 0 so we have to decrease it 1 time    k1--;    k2--;     // Step 1: Do extract minimum k1 times (This step takes O(K1 Log n) time)    for (i = 0; i <= k1; i++) {        // cout<<a[0]<<endl;        a[0] = a[n - 1];        n--;        minheapify(a, 0);    }     /*Step 2: Do extract minimum k2 – k1 – 1 times and sum all   extracted elements. (This step takes O ((K2 – k1) * Log n) time)*/    for (i = k1 + 1; i < k2; i++) {        // cout<<a[0]<<endl;        ans += a[0];        a[0] = a[n - 1];        n--;        minheapify(a, 0);    }     cout << ans;     return 0;}
// Java implementation of above approachclass GFG{     static int n = 7; static void minheapify(int []a, int index){     int small = index;    int l = 2 * index + 1;    int r = 2 * index + 2;     if (l < n && a[l] < a[small])        small = l;     if (r < n && a[r] < a[small])        small = r;     if (small != index)    {        int t = a[small];        a[small] = a[index];        a[index] = t;        minheapify(a, small);    }} // Driver codepublic static void main (String[] args){    int i = 0;    int k1 = 3;    int k2 = 6;     int []a = { 20, 8, 22, 4, 12, 10, 14 };     int ans = 0;     for (i = (n / 2) - 1; i >= 0; i--)    {        minheapify(a, i);    }     // decreasing value by 1 because we want    // min heapifying k times and it starts    // from 0 so we have to decrease it 1 time    k1--;    k2--;     // Step 1: Do extract minimum k1 times    // (This step takes O(K1 Log n) time)    for (i = 0; i <= k1; i++)    {        a[0] = a[n - 1];        n--;        minheapify(a, 0);    }     for (i = k1 + 1; i < k2; i++)    {        // cout<<a[0]<<endl;        ans += a[0];        a[0] = a[n - 1];        n--;        minheapify(a, 0);    }     System.out.println(ans);}} // This code is contributed by mits
# Python 3 implementation of above approachn = 7 def minheapify(a, index):    small = index    l = 2 * index + 1    r = 2 * index + 2     if (l < n and a[l] < a[small]):        small = l     if (r < n and a[r] < a[small]):        small = r     if (small != index):        (a[small], a[index]) = (a[index], a[small])        minheapify(a, small)     # Driver Codei = 0k1 = 3k2 = 6 a = [ 20, 8, 22, 4, 12, 10, 14 ]ans = 0 for i in range((n //2) - 1, -1, -1):    minheapify(a, i) # decreasing value by 1 because we want# min heapifying k times and it starts# from 0 so we have to decrease it 1 timek1 -= 1k2 -= 1 # Step 1: Do extract minimum k1 times# (This step takes O(K1 Log n) time)for i in range(0, k1 + 1):    a[0] = a[n - 1]    n -= 1    minheapify(a, 0) # Step 2: Do extract minimum k2 – k1 – 1 times and# sum all extracted elements.# (This step takes O ((K2 – k1) * Log n) time)*/for i in range(k1 + 1, k2) :    ans += a[0]    a[0] = a[n - 1]    n -= 1    minheapify(a, 0) print (ans) # This code is contributed# by Atul_kumar_Shrivastava
// C# implementation of above approachusing System; class GFG{     static int n = 7; static void minheapify(int []a, int index){     int small = index;    int l = 2 * index + 1;    int r = 2 * index + 2;     if (l < n && a[l] < a[small])        small = l;     if (r < n && a[r] < a[small])        small = r;     if (small != index)    {        int t = a[small];        a[small] = a[index];        a[index] = t;        minheapify(a, small);    }} // Driver codestatic void Main(){    int i = 0;    int k1 = 3;    int k2 = 6;     int []a = { 20, 8, 22, 4, 12, 10, 14 };     int ans = 0;     for (i = (n / 2) - 1; i >= 0; i--)    {        minheapify(a, i);    }     // decreasing value by 1 because we want    // min heapifying k times and it starts    // from 0 so we have to decrease it 1 time    k1--;    k2--;     // Step 1: Do extract minimum k1 times    // (This step takes O(K1 Log n) time)    for (i = 0; i <= k1; i++)    {        // cout<<a[0]<<endl;        a[0] = a[n - 1];        n--;        minheapify(a, 0);    }     /*Step 2: Do extract minimum k2 – k1 – 1 times    and sum all extracted elements. (This step    takes O ((K2 – k1) * Log n) time)*/    for (i = k1 + 1; i < k2; i++)    {        // cout<<a[0]<<endl;        ans += a[0];        a[0] = a[n - 1];        n--;        minheapify(a, 0);    }     Console.Write(ans);}} // This code is contributed by mits
<script> // Javascript implementation of above approachlet n = 7; function minheapify(a, index){    let small = index;    let l = 2 * index + 1;    let r = 2 * index + 2;     if (l < n && a[l] < a[small])        small = l;     if (r < n && a[r] < a[small])        small = r;     if (small != index)    {        let t = a[small];        a[small] = a[index];        a[index] = t;        minheapify(a, small);    }} // Driver codelet i = 0;let k1 = 3;let k2 = 6; let a = [ 20, 8, 22, 4, 12, 10, 14 ]; let ans = 0; for(i = parseInt(n / 2, 10) - 1; i >= 0; i--){    minheapify(a, i);} // decreasing value by 1 because we want// min heapifying k times and it starts// from 0 so we have to decrease it 1 timek1--;k2--; // Step 1: Do extract minimum k1 times// (This step takes O(K1 Log n) time)for(i = 0; i <= k1; i++){    a[0] = a[n - 1];    n--;    minheapify(a, 0);} for(i = k1 + 1; i < k2; i++){         // cout<<a[0]<<endl;    ans += a[0];    a[0] = a[n - 1];    n--;    minheapify(a, 0);} document.write(ans); // This code is contributed by vaibhavrabadiya117 </script>
26
Overall time complexity of this method is O(n + k2 Log n) which is better than sorting based method.
References : https://www.geeksforgeeks.org/heap-sort 
This article is contributed by Nishant_Singh (Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
nitin mittal
AbhishekVats3
md1844
Mithun Kumar
Atul_kumar_Shrivastava
shikhasingrajput
vaibhavrabadiya117
rajatkumargla19
khushboogoyal499
hardikkoriintern
STL
Arrays
Heap
Sorting
Arrays
Sorting
Heap
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
HeapSort
K'th Smallest/Largest Element in Unsorted Array | Set 1
Binary Heap
Introduction to Data Structures
Huffman Coding | Greedy Algo-3