I solve problems for the practice of interviewing, and I cannot figure out how to answer the complexity of time and space of the following problem:
Given two sorted linked lists, combine them into a third list in sorted order. Suppose we use a descending ordering.
One of the answers I came across that is clearly not the most efficient is the following recursive solution:
Node mergeLists(Node head1, Node head2) {
if (head1 == null) {
return head2;
} else if (head2 == null) {
return head1;
}
Node newHead = null;
if(head1.data < head2.data) {
newHead = head1;
newHead.next = mergeLists(head1.next, head2);
} else {
newHead = head2;
newHead.next = mergeLists(head1, head2.next);
}
return newHead;
}
, , . , O(M + N) O(M) + O(N). . , O(N) + O(M) O(max(N,M)), ( ).
:
, O(N+M) O(N) + O(M)? -? , , - .