I am trying to solve LeetCode problem 143. Reorder List:
You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → … → Ln − 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln − 1 → L2 → Ln − 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
This is my attempt at it:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) {
return;
}
ListNode n1 = head;
ListNode temp = null;
while (n1.next.next != null) {
n1 = n1.next;
}
temp = n1.next;
n1.next = null;
temp.next = head.next;
head.next = temp;
reorderList(temp.next);
}
}
I'm unable to come up with concrete reasoning for the time complexity of my code. My brain says O(n^2) but I just can't justify the why. How can the time complexity be derived?
Yes, it is O(²). One execution of
reorderList-- excluding the recursive call -- will visit all the nodes in the list in thewhileloop. So if at that moment there are nodes in the list, this will be O(). The recursive call is made with a list that has −2 elements (sinceheadandtempare "behind" the reference that is passed to the recursive call). This means we have a number of visits that progresses as follows:+ −2 + −4 + ... + (1 or 2)
This is about the double of the /2 triangular number, which is O(/2(/2+1)) = O(²).
Improving the time complexity
It is possible to solve this problem with O() time complexity. Here are some spoiler hints to get an idea how to approach it:
Hint 1:
Hint 2:
Hint 3:
Spoiler O() solution: