5

The first line contains the value of the number 'N' followed by multiple lines. I could solve it in order of n^2 algorithm. Can someone suggest a better one?

1 Answer 1

7
  1. You can use a minimum-heap and do it in O(n*(log(N))):

       heap = new Min-Heap(N)
       foreach line in text:
            if length(line) > heap.min():
            heap.pop()
            heap.insert(line)
       foreach line in heap:
            print to stdout: line.
    
  2. it could also be done in O(n) using Select(N) (which selects the Nth number) followed by partition around the Nth number (which arranges all the with size larger or equal to the Nth number to one side of it).

       i = Select(lines, N)
       partition(lines, i)
       for i to size(lines):
             print to stdout: lines[i]
    
3
  • It's not a trivial algorithm, say like partition... more information can be found here: en.wikipedia.org/wiki/Select_algorithm
    – Gal
    May 11, 2011 at 7:16
  • the heap is ordered by the length of the line. so how are you inserting the line into the heap. what i mean is how do you have the mapping between the line and it's length? u use a struct or something?
    – rkt
    May 11, 2011 at 18:48
  • Well, this question isn't language specific... but generally speaking, elements that are expected to be inserted in to a heap can compared to one another. Seeing as are you asking about structs, I'm assuming you are using C, so when inserting new elements, you would order them by strlen(). (I guess you could use a struct with a field for line length, and save the call to strlen() if you wish for some optimization).
    – Gal
    May 12, 2011 at 7:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.