![]() |
VOOZH | about |
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
The simplest approach is to sort the array, sum the elements lying between the k1-th and k2-th smallest elements, and return the result..
26
In this approach, we will use a min-heap to efficiently extract the smallest elements and sum the elements strictly between the k1-th and k2-th smallest.
Steps:
k1 times. These elements are smaller than or equal to the k1-th smallest, so we skip them.k2 - k1 - 1 elements. These are the elements strictly between the k1-th and k2-th smallest.26
Time Complexity: O(n + k2 × log n) Building the min-heap takes O(n), and extracting the first k2 elements (including skipped k1 elements and summed elements) requires O(k2 × log n) because each extraction involves re-heapifying. In the worst case, when k2 is close to n, this becomes O(n log n).
Auxiliary Space: O(1)
The Below Idea uses the Max Heap Strategy to find the solution.
Algorithm:
- The idea is to find the Kth Smallest element for the K2 .
- Then just keep an popping the elements until the size of heap is K1, and make sure to add the elements to a variable before popping the elements.
Now the idea revolves around Kth Smallest Finding:
- The CRUX over here is that, we are storing the K smallest elements in the MAX Heap
- So while every push, if the size goes over K, then we pop the Maximum value.
- This way after whole traversal. we are left out with K elements.
- Then the N-K th Largest Element is Popped and given, which is as same as K'th Smallest element.
So by this manner we can write a functional code with using the C++ STL Priority_Queue, we get the most time and space optimized solution.
26
Time Complexity: ( N * log K2 ) + ( (K2-K1) * log (K2-K1) ) + O(N) = O(NLogK2) (Dominant Term)
Reasons:
Extra Space Complexity: O(K2), As we use Heap / Priority Queue and we only store at max K elements, not more than that.