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


Given an array of integers and two numbers k1 and k2. Find sum of all elements between given two k1’th and k2’th smallest elements of array. It may be assumed that (1 <= k1 < k2 <= n) and all elements of array are distinct.


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.

Below C++ code uses an interesting method accumulate()

// C++ program to find sum of all element between
// to K1'th and k2'th smallest elements in array
using namespace std;

// Returns sum between two kth smallest element of array
int 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 program
int 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;



Time Complexity: O(n log n)

Method 2 (Using Min Heap)
We can optimize above solution be using a min heap.
1) Create a min heap of all array elements. (This step takes O(n) time)
2) Do extract minimum k1 times (This step takes O(K1 Log n) time)
3) Do extract minimum k2 – k1 – 1 times and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time)

Overall time complexity of this method is O(n + k2 Log n) which is better than sorting based method.

This article is contributed by Nishant_Singh (Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at to report any issue with the above content.

Recommended Posts:

1.8 Average Difficulty : 1.8/5.0
Based on 22 vote(s)

Writing code in comment? Please use, generate link and share the link here.