- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 54 lines of Java from the credited upstream file 2074.java.
- The implementation keeps its working state in language-native values and containers.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public ListNode reverseEvenLengthGroups(ListNode head) {3 4 ListNode dummy = new ListNode(0, head);5 ListNode prev = dummy;6 ListNode tail = head;7 ListNode next = head.next;8 int groupLength = 1;9 10 while (true) {11 if (groupLength % 2 == 1) {12 prev.next = head;13 prev = tail;14 } else {15 tail.next = null;16 prev.next = reverse(head);17 18 head.next = next;19 prev = head;20 }21 if (next == null)22 break;23 head = next;24 Pair<ListNode, Integer> res = getTailAndLength(head, groupLength + 1);25 tail = res.getKey();26 next = tail.next;27 groupLength = res.getValue();28 }29 30 return dummy.next;31 }32 33 private Pair<ListNode, Integer> getTailAndLength(ListNode head, int groupLength) {34 int length = 1;35 ListNode tail = head;36 while (length < groupLength && tail.next != null) {37 tail = tail.next;38 ++length;39 }40 return new Pair<>(tail, length);41 }42 43 ListNode reverse(ListNode head) {44 ListNode prev = null;45 while (head != null) {46 ListNode next = head.next;47 head.next = prev;48 prev = head;49 head = next;50 }51 return prev;52 }53}54