educative.io

Educative

Sum-of-elements-medium__pattern-top-k-elements__grokking-the-coding-interview-patterns-for-coding-questions

Hi Team,
if we go with a min-heap solution, it’s consuming additional space and also additional O(n*log n) for fetch operations, i can understand to match with the pattern you are considering this solution. In case if getting the same question interview, can I proceed with the below solution? and please guide which is optimal.

  1. sort array O(n*log n)
  2. find elements in given k1 and k2 range (O(k)
    Total: Time Complexity : O(k+n*log n)
    & no additional space required.
def find_sum_of_elements(array,start,end):
    array.sort()
    result=0
    for i in range(start,end-1):
        result+=array[i]
    return result

Hi @Eswar_Budha

Your solution is acceptable. You can go with it.

Happy learning,