how can we reverse a subarray ( say from i-th index to j-th index ) of an array ( or any other data structure , like linked-list ( not doubly )), in less than O(n) time ? the O(n) time consumption is trivial.( I want to do this reversion many times on the array , like starting from the beginning and reversing it for n times (each time , going forward for one index and then reversing it again), so there should be a way ,which its amortized analysis would give us a time consumption less than O(n) , any idea ?
thanks In advance 🙂
how can we reverse a subarray ( say from i-th index to j-th index
Share
I think you want to solve this with a wrong approach. I guess you want to improve the algorithm as a whole, and not the O(n) reversing stuff. Because that’s not possible. You always have O(n) if you have to consider each of the n elements.
As I said, what you can do is improve the O(n^2) algorithm. You can solve that in O(n):
Let’s say we have this list:
You then modify this list using your algorithm:
and so on.. in the end you have this:
You can get this list if you have two pointers coming from both ends of the array and alternate between the pointers (increment/decrement/get value). Which gives you O(n) for the whole procedure.
More detailed explanation of this algorithm:
Using the previous list, we want the elements in the follow order:
So you create two pointers. One pointing at the beginning of the list, the other one at the end:
Then the algorithms works as follows: