Linked List 101
Fundamental · 4 chapters · 8 min read · Rewire nodes confidently with dummy heads, fast-slow pointers and in-place reversal.
Practise this in the app All guides
What a linked list is and why interviewers love it
Nodes and pointers
A singly linked list is a chain of nodes, each holding a value and a reference to the next node. The last node points to None. There is no indexing: to reach the 5th node you must walk from the head. In return, inserting or removing a node is O(1) once you hold a reference to the node before it, because only pointers change and nothing shifts.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
Why it shows up so often
Linked list problems rarely need a clever algorithm. They test whether you can change pointers in the right order without losing part of the list. A single wrong assignment (node.next = ... before saving the old node.next) silently drops the rest of the chain. That is why this topic is a favourite for checking care and clarity in both campus and lateral interviews.
Signals in a problem statement
- The input is explicitly a
ListNodehead. - "Reverse" the whole list, a section, or groups of
k. - "Merge" sorted lists, or "add two numbers stored as digits".
- "Remove the n-th node from the end", "find the middle".
- "Detect a cycle" or "find where two lists intersect".
- "Reorder", "partition", "rotate" a list.
Mental model
Draw boxes and arrows. For every pointer change, write the before and after picture. Most solutions only need three ideas: a dummy node in front of the head, a reversal loop with prev, cur and nxt, and fast and slow pointers. The next chapter gives a template for each.
Core patterns with templates
1. Dummy head
A dummy node removes the special case of changing the head.
def merge_two(a, b):
dummy = tail = ListNode()
while a and b:
if a.val <= b.val:
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a or b
return dummy.next
2. Reverse in place
def reverse(head):
prev, cur = None, head
while cur:
nxt = cur.next
cur.next = prev
prev, cur = cur, nxt
return prev
Save nxt first, flip the arrow, then advance both pointers. Example: 1 -> 2 -> 3 becomes 3 -> 2 -> 1.
3. Fast and slow pointers
def middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return False
4. Gap of n for "n-th from the end"
def remove_nth_from_end(head, n):
dummy = ListNode(0, head)
fast = slow = dummy
for _ in range(n + 1):
fast = fast.next
while fast:
fast, slow = fast.next, slow.next
slow.next = slow.next.next
return dummy.next
Starting both at the dummy and moving fast ahead n + 1 steps leaves slow just before the node to delete.
5. Digit addition with carry
Walk both lists together, sum the digits plus carry, append total % 10 to a dummy-headed result, and keep carry = total // 10. Continue while either list or the carry remains.
Complexity, mistakes and edge cases
Complexity
| Task | Time | Space |
|---|---|---|
| Traverse, reverse, find middle | O(n) | O(1) |
| Merge two sorted lists | O(n + m) | O(1) |
| Remove n-th from end | O(n) one pass | O(1) |
| Recursive reversal | O(n) | O(n) call stack |
Recursion on a linked list uses stack space proportional to its length; for lists of 10⁵ nodes Python's default recursion limit will be exceeded. Prefer iterative solutions and mention why.
Common mistakes
- Losing the rest of the list by overwriting
cur.nextbefore saving it. - Not handling the head changing. Removing or reversing the first node is the classic bug; a dummy node fixes it.
- Null access.
fast.next.nextfails iffast.nextisNone; checkfast and fast.next. - Returning the wrong node. After reversal the new head is
prev, notcur(which isNone). - Comparing values instead of nodes. For cycle and intersection questions use
is, because two different nodes can hold equal values. - Forgetting the final carry in digit addition (
5 + 5must give0 -> 1). - Creating a cycle by accident when relinking, for example forgetting to set the last node's
nexttoNoneafter a partition.
Edge cases
Empty list (head is None), one node, two nodes, n equal to the length (remove the head), lists of different lengths, k larger than the length, and k = 1 (no change).
Testing without a judge
Write two helpers in the interview if time allows: one that builds a list from a Python list, and one that converts a list back to a Python list. Then dry-run each edge case in seconds.
Variations and practise
How interviewers twist it
- Reverse a sublist between positions
leftandright: walk to the node beforeleft, then repeatedly move the next node to the front of the sublist. - Reverse in groups of k. Check that
knodes remain, reverse exactly those, connect the previous group's tail to the new group head, and move on. Leave a final short group unchanged. A dummy node and agroup_prevpointer keep this clean. - Find where a cycle starts. After fast and slow meet, move one pointer back to the head and advance both one step at a time; they meet at the cycle start.
- Palindrome list in O(1) space. Find the middle, reverse the second half, compare, and (politely) restore it.
- Merge k sorted lists. Use a heap of the current heads; this links to the Heap card.
- Copy a list with random pointers. Use a map from old node to new node, or interleave copies.
- Doubly linked list plus hash map. This is the classic LRU cache design question.
How to explain it
Before coding, draw three nodes and narrate each pointer change. Interviewers forgive slow typing far more readily than a muddled explanation.
Practise
The problems below start with reversal and merging, then the one-pass removal with a gap, digit addition with carry, and finally reversing in groups of k. For each one, decide up front whether a dummy node will simplify the head case; it almost always will.
Practise
Easy
- 1337. Reverse Linked List
- 1338. Merge Two Sorted Lists
- 1343. Count the Train Carriages
- 1348. Find the Center Carriage
- 1349. Spread of a Chain
- 1350. Strip a Value From the Chain
- 1351. Squash Sorted Repeats
- 1352. Bit Chain to Integer
- 1353. Does the Chain Read the Same Backwards
- 1354. Insert at a Position
- 1355. Remove at a Position
- 1356. Most Common Value in a Chain
- 1357. Twin Chains
- 1358. Keep Every k-th Carriage
- 1359. Strictly Climbing Chain
- 1360. Longest Climbing Stretch
- 1361. Runner-Up Value
- 1362. Signs Take Turns
- 1363. Echo Every Node
- 1364. Loop in a Pointer Table
- 1365. First Value Seen Twice
- 1366. Count the Summits
- 1367. Neighbor Sum Chain
- 1368. Slip in the Averages
- 1369. Find a Segment Inside a Chain
- 1370. Drop Every Second Carriage
- 1371. Slot Into a Sorted Chain
- 1372. Sign of the Chain Product
- 1373. Squares of a Sorted Chain
- 1374. First-Come Dedup
- 1375. Common Values of Two Sorted Chains
- 1376. Keep m, Drop n
- 1377. Never Step Down
- 1378. Run-Length Chain
- 1379. Which Chain Number Is Bigger
- 1380. Sorted After a Turn
- 1381. Record Setters
- 1433. Point Every Arrow Backwards
- 1437. Trim Overlong Runs
Medium
- 1339. Remove Nth Node From End of List
- 1340. Add Two Numbers
- 1344. Regroup by Position Parity
- 1345. Split Around a Pivot
- 1346. Fold the Chain
- 1382. Purge Repeated Values
- 1383. Swap Neighbors in Pairs
- 1384. Flip a Stretch of Positions
- 1385. Sort a Chain by Merging
- 1386. Three-Color Chain
- 1387. Where the Loop Begins
- 1388. Subtract Chain Numbers
- 1389. Multiply a Chain Number by a Digit
- 1390. Collapse Zero-Fenced Blocks
- 1391. Only the Unbeaten Survive
- 1392. Cut Out Zero-Sum Stretches
- 1393. Deal Into k Piles
- 1394. Count Marked Clusters
- 1395. Turning Point Distances
- 1396. Best Mirror Pair
- 1397. Trade k-th From Both Ends
- 1398. Flip the Even-Sized Groups
- 1399. Graft One Chain Into Another
- 1400. Evict Every Repeated Value
- 1401. Gather Equal Values
- 1402. Sort by True Value
- 1403. Longest Mirror Stretch
- 1404. Build Your Own Chain
- 1405. Recently Used Shelf
- 1406. Ring Buffer Deque
- 1407. Page Trail Navigator
- 1408. Front Middle Back Line
- 1409. First Loner Tracker
- 1410. Last One Standing in the Circle
- 1411. Add Two Sparse Polynomials
- 1412. Reverse Each Zero-Fenced Run
- 1413. Sorted Chain to Balanced Tree
- 1414. Tree to Preorder Chain
- 1415. Chain Along a Downward Path
- 1416. Reverse the Odd Values Only
- 1417. Same Chain After Turning
- 1418. Fuse Equal Neighbors
- 1419. Fewest Swaps to Settle Zeros
- 1420. k Values Nearest a Target
- 1421. Divide a Chain Number
- 1422. Longest Shared Ending
- 1423. Zigzag the Chain
- 1424. Smallest Stretch to Sort
- 1425. Sort With Prefix Flips
- 1426. Coil a Chain Into a Grid
- 1427. Smallest Number After k Deletions
- 1428. Send Even Positions to the Back, Reversed
- 1429. Steps to the Next Twin
- 1430. Order by Popularity
- 1431. Rebuild the Train From Couplings
- 1432. Is It One Clean Chain
- 1434. Cut the Richest Stretch
- 1435. One Flip to Sorted
- 1436. Fewest Moves to the Front
- 1438. Burst Runs of Three
- 1439. Best Stretch on a Loop
- 1440. Largest Merge of Two Chains
- 1441. Where Two Walkers Meet
- 1442. Raise to All Distinct
- 1443. Filter by a Blocklist Chain
- 1444. Values in Exactly One Sorted Chain
- 1445. Fewest Calm Segments
- 1446. Trim to a Multiple
- 1447. Unfold the Folded Chain
- 1448. Longest Even-Stepped Run
- 1449. Above the Tail Average
- 1450. Sort a Rise-and-Fall Chain
Hard
- 1341. Reverse Nodes in k-Group
- 1342. LFU Cache
- 1347. Merge Many Sorted Chains
- 1451. Count Out-of-Order Pairs
- 1452. Longest Loop in a Pointer Table
- 1453. Stack That Knows Its Max
- 1454. Constant-Time Tally Board
- 1455. Cursor Text Pad
- 1456. Express Lane List
- 1457. Circle Elimination With Changing Steps
- 1458. k-th Smallest Pair Total
- 1459. Fuse the Chain at Minimum Cost
- 1460. Count Calm Stretches
- 1461. Rolling Middle Values
- 1462. Cut and Paste Segments
- 1463. Shortest Stretch Reaching a Total
- 1464. Fewest Removals for a Ridge
- 1465. Fewest Cuts Into Mirrors
- 1466. Keep Both Chains Climbing
- 1467. Count Distinct Stretches
- 1468. Longest Repeated Stretch
- 1469. Smallest Turn of a Chain
- 1470. Pop the Beads
- 1471. Sum of Stretch Minimums
- 1472. Peak-Bookended Stretches
- 1473. Fold Neighbors Until Sorted
- 1474. Rounds of the Weak
- 1475. Clear the Chain in Blocks
- 1476. Smallest Order After k Adjacent Swaps
- 1477. Hop Along the Chain
- 1478. Tightest Band Across Chains
- 1479. Spread Out the Repeats
- 1480. Best k Separate Stretches
- 1481. Cheapest Way to Sort by Lifting
- 1482. Switch Between Two Tracks
- 1483. Stretches Centered on k
- 1484. Riffles Until Home
- 1485. Teleport Down the Chain