IBM Interview Question
Tech LeadsCountry: India
Interview Type: Phone Interview
I'm not sure if that is possible in O(n) time. I would suggest the following algorithm:
Loop through the linked list:
Add to min or max binary heap
While the heap is not empty:
Pop off the heap and print
The complexity is O(n log(n)) on average it would be O(n) time since inserting on a heap approximates constant time (according to wikipedia article on it).
If a node of linked list contain only positive integers, then you can sort it in O(n), using Counting sort. And then print it in Ascending and Descending order. Solution complexity is O(n).
Is the question about printing an unsorted list in sorted order (ascending and descending), or is it about printing a list left-to-right and right-to-left?
- 010010.bin June 09, 2015If it's the former, it's pretty much impossible unless you are given some specific information about the data that the list holds, since sorting in general is not achievable in O(n).