I'm presenting a problem my professor showed in class, with my O(n*log(n)) solution:

Given a list of n numbers we'd like to perform the following n-1 times:

  • Extract the two minimal elements x,y from the list and present them
  • Create a new number z , where z = x+y
  • Put z back into the list

Suggest a data structure and algorithm for O(n*log(n)) , and O(n)

Solution:

We'll use a minimal heap:

Creating the heap one time only would take O(n). After that, extracting the two minimal elements would take O(log(n)). Placing z into the heap would take O(log(n)).

Performing the above n-1 times would take O(n*log(n)), since:

O(n)+O(n∙(logn+logn ))=O(n)+O(n∙logn )=O(n∙logn )

But how can I do it in O(n)?

EDIT:

By saying: "extract the two minimal elements x,y from the list and present them ", I mean printf("%d,%d" , x,y), where x and y are the smallest elements in the current list.

Edit
Report