07. Linked List#
Problems at a glance#
| LC | Problem | |
|---|---|---|
| 876 | Middle of the Linked List | ↗ |
| 141 | Linked List Cycle | ↗ |
| 142 | Linked List Cycle II | ↗ |
| 234 | Palindrome Linked List | ↗ |
| 206 | Reverse Linked List | ↗ |
| 92 | Reverse Linked List II | ↗ |
| 25 | Reverse Nodes in k-Group | ↗ |
| 143 | Reorder List | ↗ |
| 61 | Rotate List | ↗ |
| 19 | Remove N-th Node From End of List | ↗ |
| 237 | Delete Node in a Linked List | ↗ |
| 203 | Remove Linked List Elements | ↗ |
| 328 | Odd Even Linked List | ↗ |
| 21 | Merge Two Sorted Lists (Recursive) | ↗ |
| 138 | Copy List with Random Pointer | ↗ |
| 430 | Flatten a Multilevel Doubly Linked List | ↗ |
| 445 | Add Two Numbers II | ↗ |
| 23 | Merge k Sorted Lists | ↗ |
| 2 | Add Two Numbers | ↗ |
| 1669 | Merge in Between Linked Lists | ↗ |
| 2181 | Merge Nodes in Between Zeros | ↗ |
| 24 | Swap Nodes in Pairs | ↗ |
| 1721 | Swapping Nodes in a Linked List | ↗ |
| 86 | Partition List | ↗ |
1. Two‑Pointer (Fast & Slow Pointers)#
Problem 1: Middle of the Linked List (Leetcode:876)#
Problem Statement
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
Constraints:
- The number of nodes in the list is in the range
[1, 100].1 <= Node.val <= 100
Code and Explanation
- Initialize: Set
slowandfastboth tohead. - Move at different speeds: Advance
slowone step andfasttwo steps per iteration. - Stop at end: When
fastcan no longer move (Noneorfast.nextisNone),slowsits at the middle. - Even length: Because
faststops on the last node (not past it), the second middle is returned for even-length lists.
Time: O(n) | Space: O(1)
- Count nodes: Walk the list once to get
length. - Walk to middle: Advance
headbylength // 2steps. - Return: The node at that position is the middle (second middle when length is even).
Time: O(n) | Space: O(1) — two passes but still constant space.
Problem 2: Linked List Cycle (Leetcode:141)#
Problem Statement
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Constraints:
- The number of the nodes in the list is in the range
[0, 104].-105 <= Node.val <= 105posis-1or a valid index in the linked-list.
Follow up: Can you solve it using O(1) (i.e. constant) memory?
Code and Explanation
- Two pointers:
slowmoves 1 step,fastmoves 2 steps. - Cycle check: If they meet inside the loop, a cycle exists.
- No cycle: If
fastreachesNone, the list is acyclic.
Time: O(n) | Space: O(1)
- Track visited nodes: Add each node to a set while walking the list.
- Detect repeat: Revisiting a node means there is a cycle.
- End of list: Reaching
Nonemeans no cycle.
Time: O(n) | Space: O(n)
Problem 3: Linked List Cycle II(Leetcode:142)#
Problem Statement
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.
Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
Constraints:
- The number of the nodes in the list is in the range
[0, 104].-105 <= Node.val <= 105posis-1or a valid index in the linked-list.
Follow up: Can you solve it using O(1) (i.e. constant) memory?
Code and Explanation
- Phase 1 — detect cycle: Move
slow1 step andfast2 steps until they meet (orfastends). - No cycle: If the loop exits via
else(no meeting), returnNone. - Phase 2 — find entrance: Reset
slowtohead. Move both pointers 1 step at a time until they meet again — that node is the cycle start. - Math insight: Distance from head to cycle start equals distance from meeting point to cycle start (measured inside the loop).
Time: O(n) | Space: O(1)
- Walk and record: Store every visited node in a hash set.
- First repeat: The first node seen twice is where the cycle begins.
- No cycle: Return
Noneif the list ends.
Time: O(n) | Space: O(n)
Problem 4: Palindrome Linked List(Leetcode:234)#
Problem Statement
Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Constraints:
- The number of nodes in the list is in the range
[1, 105].0 <= Node.val <= 9
Follow up: Could you do it in O(n) time and O(1) space?
Code and Explanation
- Find middle: Use fast/slow pointers so
slowends at the second half's start. - Reverse second half: In-place reversal from
slow;prevbecomes the tail of the first half / head of reversed second half. - Compare halves: Walk
leftfromheadandrightfromprevsimultaneously. - Mismatch: Any unequal values → not a palindrome.
Time: O(n) | Space: O(1)
- Copy values: Store all node values in an array.
- Check palindrome: Compare the array with its reverse.
- Trade-off: Simple and readable, but uses O(n) extra space.
Time: O(n) | Space: O(n)
2. Reversal of Linked List#
Problem 1: Reverse Linked List (Leetcode:206)#
Problem Statement
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000].-5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
Code and Explanation
- Three pointers:
prev(reversed portion),head(current),nxt(saved next). - Flip link: Point
head.nexttoprev, then advance all three pointers. - Return:
previs the new head whenheadbecomesNone.
Time: O(n) | Space: O(1)
- Base case: Empty or single-node list is already reversed.
- Recurse: Reverse everything after
head;new_headis the tail of the original list. - Rewire: Make the next node point back to
head, then severhead.next.
Time: O(n) | Space: O(n) call stack
Problem 2: Reverse Linked List II (Leetcode:92)#
Problem Statement
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Example 2:
Input: head = [5], left = 1, right = 1
Output: [5]
Constraints:
- The number of nodes in the list is
n.1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= n
Follow up: Could you do it in one pass?
Code and Explanation
- Dummy head: Simplifies reversal when
left == 1. - Walk to
left - 1:prevanchors the node just before the sublist. - Repeated head-insert: For each node in the range, pull the next node to the front of the sublist (like reversing k-group of size 1 repeatedly).
- One pass:
right - leftiterations rewire the segment in place.
Time: O(n) | Space: O(1)
- Same anchor setup with dummy head and
prevbefore the segment. startstays fixed at the original left boundary;thenis the node being moved.- Each step: Detach
then, insert it right afterprev, advancethen. - Result: Nodes from
lefttorightend up reversed while the rest of the list stays connected.
Time: O(n) | Space: O(1)
Problem 3: Reverse Nodes in k-Group (Leetcode:25)#
Problem Statement
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Constraints:
- The number of nodes in the list is
n.1 <= k <= n <= 50000 <= Node.val <= 1000
Follow-up: Can you solve the problem in O(1) extra memory space?
Code and Explanation
- Dummy head:
group_prevtracks the node before each k-group. - Find kth node: Advance
ksteps; if fewer thanknodes remain, stop. - Reverse group: Standard in-place reversal between
group_prev.nextandkth. - Reconnect: Link reversed segment; move
group_prevto the tail of the just-reversed group (oldgroup_prev.next).
Time: O(n) | Space: O(1)
- Count k nodes: If the remaining list is shorter than
k, return as-is. - Reverse first k nodes iteratively within the recursive frame.
- Recurse on remainder: Attach the result to
head.next(old head becomes group tail). - Return
prev: New head of the reversed group.
Time: O(n) | Space: O(n/k) recursion depth
Problem 4: Reorder List (Leetcode:143)#
Problem Statement
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.
Example 1:
Input: head = [1,2,3,4]
Output: [1,4,2,3]
Example 2:
Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]
Constraints:
- The number of nodes in the list is in the range
[1, 5 * 104].1 <= Node.val <= 1000
Code and Explanation
- Find middle: Fast/slow stops
slowat the last node of the first half. - Split: Cut the list at
slow; reverse the second half. - Zip merge: Alternate nodes from
firstandsecondhalves. - In-place: No new nodes — only pointer rewiring.
Time: O(n) | Space: O(1)
- Same split at the middle using fast/slow.
- Push second half onto a stack (gives reverse order).
- Interleave: Pop from stack and splice between first-half nodes.
- Trade-off: O(n) extra space for the stack, but easier to follow.
Time: O(n) | Space: O(n)
Problem 5: Rotate List (Leetcode:61)#
Problem Statement
Given the head of a linked list, rotate the list to the right by k places.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Example 2:
Input: head = [0,1,2], k = 4
Output: [2,0,1]
Constraints:
- The number of nodes in the list is in the range
[0, 500].-100 <= Node.val <= 1000 <= k <= 2 * 109
Code and Explanation
- Get length and tail in one walk.
- Normalize k:
k % lengthhandlesk > length. - Make circular: Connect
tail.nexttohead. - Break at new tail: Walk
length - ksteps from head; the next node is the new head.
Time: O(n) | Space: O(1)
- Count length and reduce
kmodulo length. - Advance
fastbylength - ksteps — it lands on the new tail. - Split:
fast.nextis the new head; setfast.next = None. - Attach old head: Walk to the new tail and link back to the old head.
Time: O(n) | Space: O(1)
3. Dummy Node Technique#
Problem 1: Remove N-th Node From End of List (Leetcode:19)#
Problem Statement
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Constraints:
- The number of nodes in the list is
sz.1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz
Follow up: Could you do this in one pass?
Code and Explanation
- Dummy head: Handles deleting the actual head node cleanly.
- Create gap: Advance
fastnsteps ahead ofslow. - Move together: When
fastreaches the last node,slowis just before the target. - Delete: Skip the nth-from-end node via
slow.next = slow.next.next.
Time: O(n) | Space: O(1)
- First pass: Count total nodes.
- Second pass: Walk
length - nsteps from dummy to the predecessor. - Delete and return: Same skip logic; dummy head covers the head-deletion edge case.
Time: O(n) | Space: O(1)
Problem 2: Delete Node in a Linked List (Leetcode:237)#
Problem Statement
There is a singly-linked list head and we want to delete a node node in it.
You are given the node to be deleted node. You will not be given access to the first node of head.
All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list.
Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:
- The value of the given node should not exist in the linked list.
- The number of nodes in the linked list should decrease by one.
- All the values before
nodeshould be in the same order. - All the values after
nodeshould be in the same order.
Custom testing:
- For the input, you should provide the entire linked list
headand the node to be givennode.nodeshould not be the last node of the list and should be an actual node in the list. - We will build the linked list and pass the node to your function.
- The output will be the entire list after calling your function.
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
Constraints:
- The number of the nodes in the given list is in the range
[2, 1000].-1000 <= Node.val <= 1000- The value of each node in the list is unique.
- The
nodeto be deleted is in the list and is not a tail node.
Code and Explanation
- No
headaccess: We cannot reach the predecessor ofnode. - Overwrite: Copy the next node's value into
node. - Skip next: Point
node.nextpast the next node — effectively deletingnode's original value. - Constraint: Only works because
nodeis guaranteed not to be the tail.
Time: O(1) | Space: O(1)
- Standard deletion needs the previous node's pointer (
prev.next = node.next). - Without
head, only interior nodes can be removed via value-copying. - Head deletion requires the caller to update the head reference — not possible inside this API.
Time: O(1) | Space: O(1)
Problem 3: Remove Linked List Elements (Leetcode:203)#
Problem Statement
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
Output: []
Constraints:
- The number of nodes in the list is in the range
[0, 104].1 <= Node.val <= 500 <= val <= 50
Code and Explanation
- Dummy head: Handles cases where the head itself equals
val. - Check
prev.next: If it matchesval, skip it without advancingprev. - Otherwise advance: Move
prevforward only when the next node is kept. - Return
dummy.next: The new list head after all removals.
Time: O(n) | Space: O(1)
- Recurse on tail: Clean the rest of the list first.
- Filter current: If
head.val == val, returnhead.next; otherwise keephead. - Builds answer from the back of the list forward.
Time: O(n) | Space: O(n) recursion stack
Problem 4: Odd Even Linked List (Leetcode:328)#
Problem Statement
Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in O(1) extra space complexity and O(n) time complexity.
Example 1:
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
Example 2:
Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
Constraints:
- The number of nodes in the linked list is in the range
[0, 104].-106 <= Node.val <= 106
Code and Explanation
- Two chains:
oddbuilds the odd-index chain;evenbuilds the even-index chain. - Alternate links: Odd takes
even.next, then even takesodd.next. - Append evens: Connect
odd.nexttoeven_headat the end. - O(1) space: Only pointer rewiring, no extra structures.
Time: O(n) | Space: O(1)
- Separate by index into two node lists.
- Rewire each chain internally, then join odd tail to even head.
- Trade-off: Uses O(n) auxiliary arrays — violates the O(1) space constraint but illustrates the grouping logic.
Time: O(n) | Space: O(n)
4. Recursion on Linked List#
Problem 1: Reverse Linked List (Recursive) (Leetcode:206)#
Problem Statement
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000].-5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
Code and Explanation
- Base case: Single node or empty list needs no reversal.
- Recurse: Reverse the sublist starting at
head.next;new_headis the new list head. - Rewire:
head.next.next = headflips the link;head.next = Noneprevents cycles.
Time: O(n) | Space: O(n) call stack
- Iterative three-pointer swap — same problem, different paradigm.
- No recursion overhead — preferred when stack depth is a concern.
Time: O(n) | Space: O(1)
Problem 2: Merge Two Sorted Lists (Recursive) (Leetcode:21)#
Problem Statement
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
Constraints:
- The number of nodes in both lists is in the range
[0, 50].-100 <= Node.val <= 100- Both
list1andlist2are sorted in non-decreasing order.
Code and Explanation
- Base cases: If either list is empty, return the other.
- Pick smaller head: Attach the rest of the merge to that node's
next. - Return chosen node as the head of the merged sublist.
Time: O(n + m) | Space: O(n + m) recursion stack
- Dummy head avoids special-casing the first merged node.
- Compare and splice the smaller node each step.
- Attach remainder when one list is exhausted.
Time: O(n + m) | Space: O(1)
Problem 3: Copy List with Random Pointer (Leetcode:138)#
Problem Statement
A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.
Return the head of the copied linked list.
The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representingNode.valrandom_index: the index of the node (range from0ton-1) that therandompointer points to, ornullif it does not point to any node.
Your code will only be given the head of the original linked list.
Example 1:
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2:
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
Example 3:
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
Constraints:
0 <= n <= 1000-104 <= Node.val <= 104Node.randomisnullor is pointing to some node in the linked list.
Code and Explanation
- Pass 1: Create a copy of every node; map original → copy.
- Pass 2: Wire
nextandrandomon copies using the map. - No original pointers in the new list — all references go through the map.
Time: O(n) | Space: O(n)
- Interweave: Insert each copy immediately after its original (
A → A' → B → B' → …). - Set random:
copy.random = original.random.next(the paired copy). - Split: Restore original
nextlinks and link copies into their own list.
Time: O(n) | Space: O(1) excluding output list
Problem 4: Flatten a Multilevel Doubly Linked List (Leetcode:430)#
Problem Statement
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below.
Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.
Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.
Example 1:
Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Output: [1,2,3,7,8,11,12,9,10,4,5,6]
Explanation: The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
![]()
Example 2:
Input: head = [1,2,null,3]
Output: [1,3,2]
Explanation: The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
![]()
Example 3:
Input: head = []
Output: []
Explanation: There could be empty list in the input.
Constraints:
- The number of Nodes will not exceed
1000.1 <= Node.val <= 105
Code and Explanation
- DFS on child lists: Recursively flatten each
childsublist; return its tail. - Splice child in: Insert flattened child between
currandcurr.next. - Fix
prevpointers for doubly-linked consistency; null outchild. - Return tail of the flattened segment for parent-level splicing.
Time: O(n) | Space: O(n) recursion depth
- Stack stores
nextpointers deferred when a child is encountered. - Same splice logic as recursion, but explicit stack instead of call frames.
- When current level ends, pop and attach the saved
nextsublist.
Time: O(n) | Space: O(n) stack
Problem 5: Add Two Numbers II (Leetcode:445)#
Problem Statement
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Example 2:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Example 3:
Input: l1 = [0], l2 = [0]
Output: [0]
Constraints:
- The number of nodes in each linked list is in the range
[1, 100].0 <= Node.val <= 9- It is guaranteed that the list represents a number that does not have leading zeros.
Follow up: Could you solve it without reversing the input lists?
Code and Explanation
- Reverse both lists so digits are least-significant-first.
- Standard carry addition (same as LeetCode 2) with a dummy head.
- Reverse result to restore most-significant-first order.
Time: O(n + m) | Space: O(1) excluding output
- Push all digits onto two stacks (MSD at bottom).
- Pop and add from the ends with carry — processes MSD to LSD correctly.
- Prepend nodes to build the result list without reversing inputs.
Time: O(n + m) | Space: O(n + m) for stacks
5. Cycle Detection & Manipulation#
Problem 1: Remove Loop in Linked List (GFG)#
Problem Statement
Given the head of a singly linked list that may contain a cycle, detect the loop and remove it by setting the tail's next pointer to null. Return the head of the list after removal.
Example 1:
Input: 1 → 2 → 3 → 4 → 2 (cycle back to node 2)
Output: 1 → 2 → 3 → 4
Example 2:
Input: 1 → 2 → 3 → 4 → 5 (no cycle)
Output: 1 → 2 → 3 → 4 → 5
Constraints:
0 <= number of nodes <= 10^4- The cycle, if present, has at least one node.
Code and Explanation
- Detect cycle with fast/slow pointers.
- Find cycle start by resetting
slowtoheadand moving both 1 step. - Find tail of cycle: Advance
fastuntilfast.next == slow(last node in loop). - Break cycle: Set
fast.next = None.
Time: O(n) | Space: O(1)
- Track visited nodes in a hash set.
- On revisit: The previous node is the tail of the cycle — set
prev.next = None. - Simpler logic but uses O(n) extra memory.
Time: O(n) | Space: O(n)
Problem 2: Find Length of Loop (GFG)#
Problem Statement
Given the head of a linked list that may contain a cycle, return the number of nodes in the loop. Return 0 if there is no cycle.
Example 1:
Input: 1 → 2 → 3 → 4 → 2 (cycle)
Output: 3 (nodes 2, 3, 4 form the loop)
Example 2:
Input: 1 → 2 → 3 → 4 → 5 (no cycle)
Output: 0
Constraints:
0 <= number of nodes <= 10^4
Code and Explanation
- Detect meeting point with Floyd's algorithm.
- Count loop nodes: Start at
slow.next, count until returning toslow. - No meeting: Return 0.
Time: O(n) | Space: O(1)
- Store each node's position in a hash map.
- On repeat: Loop length = current position − first-seen position.
- End of list: No cycle → return 0.
Time: O(n) | Space: O(n)
Problem 3: Check if Linked List is Circular (GFG)#
Problem Statement
A circular linked list is one where the last node's next points back to the head (not merely any cycle). Given head, return true if the list is circular in this strict sense, else false.
Example 1:
Input: head → 1 → 2 → 3 → head (last points to head)
Output: true
Example 2:
Input: 1 → 2 → 3 → 4 → 2 (cycle but not to head)
Output: false
Constraints:
0 <= number of nodes <= 10^4
Code and Explanation
- Start from
head.next(empty single-node list is not circular by this definition). - Walk forward until
Noneor back tohead. - Circular iff we return to
head.
Time: O(n) | Space: O(1)
- Detect any cycle with Floyd's algorithm.
- Find cycle entrance with the standard reset trick.
- Strict circular check: Cycle start must equal
head.
Time: O(n) | Space: O(1)
6. Merge Techniques#
Problem 1: Merge Two Sorted Lists (Leetcode:21)#
Problem Statement
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
Constraints:
- The number of nodes in both lists is in the range
[0, 50].-100 <= Node.val <= 100- Both
list1andlist2are sorted in non-decreasing order.
Code and Explanation
- Dummy head simplifies building the merged list.
- Compare heads of both lists; splice the smaller node.
- Attach remainder when one list is exhausted.
Time: O(n + m) | Space: O(1)
- Base cases handle empty lists.
- Pick smaller head, recursively merge the rest.
- Elegant but uses O(n + m) stack space.
Time: O(n + m) | Space: O(n + m)
Problem 2: Merge k Sorted Lists (Leetcode:23)#
Problem Statement
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted linked list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
Constraints:
k == lists.length0 <= k <= 1040 <= lists[i].length <= 500-104 <= lists[i][j] <= 104lists[i]is sorted in ascending order.- The sum of
lists[i].lengthwill not exceed104.
Code and Explanation
- Seed heap with the head of each non-empty list (index
ibreaks value ties). - Pop smallest, append to result, push that node's
next. - Always pick globally smallest among k current heads.
Time: O(N log k) | Space: O(k) where N = total nodes
- Pairwise merge lists in rounds (like merge sort).
- Halve the number of lists each round using standard two-list merge with dummy head.
- O(1) extra space beyond recursion/iteration overhead.
Time: O(N log k) | Space: O(1) excluding output
Problem 3: Add Two Numbers (Leetcode:2)#
Problem Statement
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
- The number of nodes in each linked list is in the range
[1, 100].0 <= Node.val <= 9- It is guaranteed that the list represents a number that does not have leading zeros.
Code and Explanation
- Digits are LSD-first — add position by position.
- Track carry across all three conditions (
l1,l2,carry). - Dummy head builds the result list cleanly.
Time: O(max(n, m)) | Space: O(max(n, m)) for output
- Same digit-by-digit logic expressed recursively.
- Base case: All inputs and carry exhausted.
- Build list from front via return chain.
Time: O(max(n, m)) | Space: O(max(n, m)) stack
Problem 4: Merge in Between Linked Lists (Leetcode:1669)#
Problem Statement
You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
The blue edges and nodes in the following figure indicate the result:

Build the result list and return its head.
Example 1:
Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
Output: [10,1,13,1000000,1000001,1000002,5]
Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
Example 2:
Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]
Explanation: The blue edges and nodes in the above figure indicate the result.
Constraints:
3 <= list1.length <= 1041 <= a <= b < list1.length - 11 <= list2.length <= 104
Code and Explanation
- Find
prev_a: Node at indexa - 1(just before removal start). - Find
after_b: Node at indexb + 1(first node to keep after the gap). - Splice
list2: Connectprev_a → list2 → … → tail2 → after_b.
Time: O(n + m) | Space: O(1)
- Dummy head variant — walk
asteps from dummy to land on the node before indexa. - Same splice logic otherwise.
- Useful pattern when
acould be 0 in generalized variants.
Time: O(n + m) | Space: O(1)
Problem 5: Merge Nodes in Between Zeros (Leetcode:2181)#
Problem Statement
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0.
For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's.
Return the head of the modified linked list.
Example 1:
Input: head = [0,3,1,0,4,5,2,0]
Output: [4,11]
Explanation: The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 3 + 1 = 4.
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
Example 2:
Input: head = [0,1,0,3,0,2,2,0]
Output: [1,3,4]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 1 = 1.
- The sum of the nodes marked in red: 3 = 3.
- The sum of the nodes marked in yellow: 2 + 2 = 4.
Constraints:
- The number of nodes in the list is in the range
[3, 2 * 105].0 <= Node.val <= 1000- There are no two consecutive nodes with
Node.val == 0.- The beginning and end of the linked list have
Node.val == 0.
Code and Explanation
- Reuse existing nodes as the output list (no new allocations).
- Accumulate sum between zeros; on hitting
0, write sum towritenode. - Trim tail:
write.next = Noneremoves leftover zeros.
Time: O(n) | Space: O(1)
- Dummy head builds a fresh result list.
- Same sum-between-zeros logic but allocates new nodes.
- Clearer separation of input scan vs output construction.
Time: O(n) | Space: O(k) for k merged segments
7. Pointer Manipulation / Simulation#
Problem 1: Swap Nodes in Pairs (Leetcode:24)#
Problem Statement
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Explanation:
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Example 4:
Input: head = [1,2,3]
Output: [2,1,3]
Constraints:
- The number of nodes in the list is in the range
[0, 100].0 <= Node.val <= 100
Code and Explanation
- Dummy head handles swapping the first pair.
- Rewire three links:
first.next = second.next,second.next = first,prev.next = second. - Advance
prevby one (tofirst, the new second in the pair).
Time: O(n) | Space: O(1)
- Base case: 0 or 1 nodes — nothing to swap.
- Swap current pair, recurse on the rest.
- Return
secondas the new head of this sublist.
Time: O(n) | Space: O(n) recursion stack
Problem 2: Swapping Nodes in a Linked List (Leetcode:1721)#
Problem Statement
You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
Example 2:
Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]
Constraints:
- The number of nodes in the list is
n.1 <= k <= n <= 1050 <= Node.val <= 100
Code and Explanation
- Count length in one pass.
- Walk to kth from start (
k - 1steps) and kth from end (length - ksteps). - Swap values (problem allows value swap, not pointer swap).
Time: O(n) | Space: O(1)
- Advance
fastk steps ahead ofhead. - Move both together until
fastreaches end —kth_endis kth from end. kth_startstays at the kth from beginning; swap values.
Time: O(n) | Space: O(1)
Problem 3: Partition List (Leetcode:86)#
Problem Statement
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example 1:
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
Example 2:
Input: head = [2,1], x = 2
Output: [1,2]
Constraints:
- The number of nodes in the list is in the range
[0, 200].-100 <= Node.val <= 100-200 <= x <= 200
Code and Explanation
- Two dummy heads for "less than x" and "greater/equal" partitions.
- Append each node to the appropriate chain preserving order.
- Concatenate:
beforetail links toafterhead; terminateaftertail.
Time: O(n) | Space: O(1)
- Identical logic to Approach 1 — dual dummy-head partitioning.
- Key invariant: Nodes are moved, not copied; relative order preserved within each partition.
- Must set
ge.next = Noneto avoid cycles from the originalnextlinks.
Time: O(n) | Space: O(1)








Input: head = [1,2]

























