I am looking for a method that reverses the same instance of a given list, with O(1) additional space and O(n) time.
this is not HW nor I am looking for some library method to do the job for me, as this is only an exercise for myself, and out of pure curiousity.
any ideas how to do it with O(1) additional space and O(n) time? (and if possible without reflection as well)?
signature is public <T> void reverse(List<T> list)
.
(*)assume get() to the head and tail of the list is O(1), but to the middle of it is O(n).
I came up with a recursive solution, but it is O(n) space, O(n) time
public <T> void reverseAux(List<T> list,int size) {
if (size == 0) return;
T elem = list.remove(size-1);
reverseAux(list,size-1);
list.add(0,elem);
}
public <T> void reverse(List<T> list) {
reverseAux(list, list.size());
}
EDIT: I am looking for a java solution, for List<T>
, only assumption on implementation is access time O(1) for head and tail, and using List<T>
interface.
A memory efficient doubly linked list with head and tail pointers can also be reversed in O(1) time by swapping head and tail pointers. But we would have to traverse the list in forward direction using prev pointer and reverse direction using next pointer which may not be considered valid.
You cannot reverse a string in O(1) time, however, you can do so with O(1) space complexity. Most likely it was reverse it in one-liner , as it's not even clear what an "operation" is really is. or you may as well use a simple loop to do it: for (size_t i=0; i<str.
The time complexity of reversing a linked list? It is linear in time i.e O(n) where n is the size of the linked list.
Just read one of the following. It is the thing you're talking about.
Please note that we're talking about singly 'linked' lists.
http://www.teamten.com/lawrence/writings/reverse_a_linked_list.html
http://www.mytechinterviews.com/reverse-a-linked-list
http://www.geekpedia.com/code48_Reverse-a-linked-list.html
http://www.codeproject.com/KB/recipes/ReverseLinkedList.aspx
Plus an extra question for you:
How would you find
N
th element from the tail of a linked list assuming it is singly linked and you have only head pointer with O(1) space and O(N) time?
using ListIterators:
ListIterator<T> head = list.listIterator();
ListIterator<T> tail = list.listIterator(size);//assuming this can be done in O(1) though O(n) doesn't hurt that much and total is still O(n)
while(head.nextIndex()<tail.previousIndex()){
T tmp = head.next();
head.set(tail.previous());
tail.set(tmp);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With