Download Arrays & Linked Lists Guide – DSA Notes, Diagrams & Python Code and more Study notes Computer Science in PDF only on Docsity!
ARRAYS & LINKED LISTS
A Complete Study & Interview-Prep Guide
Theory • Diagrams • Time Complexity • Solved Coding Problems (Python)
Why This Guide Exists
Open the source code of any app on your phone right now — your banking app, your maps app, your
music player — and you will find the same two building blocks underneath almost everything: the array
and the linked list. Every playlist you scroll through, every "undo" button you press, every route your GPS
calculates, and every friend list you load is built on top of these two structures, or something derived from
them.
That is also exactly why they show up everywhere else that matters to you: college exams, semester lab
assignments, and the very first round of almost every software interview in the industry. Interviewers do
not start with arrays and linked lists because they are easy — they start there because how you reason
about memory, pointers, and complexity here predicts how you will reason about everything harder that
comes later (trees, graphs, dynamic programming). Get this foundation genuinely solid, and every data
structure after it becomes easier to learn, not harder.
What Makes This Guide Different
l Nothing is assumed.^ Every concept starts from "what is this and why do we need it" before any code
appears.
l Every operation has a diagram.^ Pointer movement is the #1 source of confusion in linked lists — so each
insertion and deletion is shown step-by-step, not just described in words.
l Every complexity claim is justified.^ You will not just see "O(1)" — you will see exactly why it is O(1).
l Theory and interview-readiness are merged, not separated.^ Each solved problem includes the plain
explanation you need for an assignment, and the optimal-approach reasoning an interviewer expects.
l Fully working Python code^ for every operation and every problem, with a hand-traced dry run so you can
verify your own understanding line by line.
One honest reminder before you dive in: reading notes and watching pointers move on a page is necessary but not
sufficient. The only way this material becomes permanent is if you close this PDF at least once and re-implement
singly-linked-list insertion, or reversal, from a blank file, from memory. Treat the code in this guide as the answer key,
not the first draft.
What You Will Master
# Topic What you'll walk away with
1 Introduction to Arrays Memory layout, types, trade-offs
2 Array Operations Traversal, insert, delete, search — with Big O
3 Introduction to Linked Lists Why arrays aren't always enough
4 Singly Linked List Structure, all operations, diagrams
5 Doubly Linked List Bidirectional traversal, operations
6 Circular Linked List Structure, operations, real-world uses
1.4 Advantages and Disadvantages
Advantages Disadvantages
Constant-time O(1) random access by index Fixed size in most languages — cannot grow dynamically
Simple and memory-efficient (no extra pointers) Insertion/deletion in the middle is expensive — O(n)
Good cache performance (elements are contiguous) Wastes memory if declared larger than needed
Easy to iterate and works well with CPU caching Resizing (in dynamic arrays) requires copying all elements
2
Array Operations
2.1 Traversal
Visiting every element of the array exactly once, typically to print, sum, or process values.
def traverse(arr): for i in range(len(arr)): print(arr[i])
traverse([10, 25, 7, 42, 3])
Output: 10 25 7 42 3
2.2 Insertion
Because array memory is contiguous, inserting a new element anywhere except the very end requires shifting
every element after the insertion point one position to the right, to open up a gap.
def insert_at(arr, pos, value): arr.append(None) # make room for one more element for i in range(len(arr) - 1, pos, -1): arr[i] = arr[i - 1] # shift elements right arr[pos] = value return arr
insert_at([10, 25, 7, 42], 1, 99) -> [10, 99, 25, 7, 42]
l At the beginning:^ every existing element shifts right — O(n).
l At the end:^ no shifting needed if space is available — O(1) (amortized O(1) for dynamic arrays).
l At a specific position:^ elements after that position shift right — O(n) worst case.
2.3 Deletion
Deleting an element leaves a gap, so every element after the deleted position must shift one step to the left to
close it.
def delete_at(arr, pos): for i in range(pos, len(arr) - 1):
arr[i] = arr[i + 1] # shift elements left arr.pop() # remove the now-duplicate last slot return arr
delete_at([10, 99, 25, 7, 42], 1) -> [10, 25, 7, 42]
2.4 Searching (Linear Search)
Linear search checks each element one by one from the start until the target is found or the array ends. It
makes no assumption about the array being sorted.
def linear_search(arr, target): for i in range(len(arr)): if arr[i] == target: return i # found — return index return -1 # not found
linear_search([10, 25, 7, 42, 3], 42) -> 3
2.5 Updating Elements
Since any index maps directly to a memory address, updating an element is a single, direct assignment — no
shifting is ever required.
arr[2] = 100 # directly overwrites the value at index 2 — O(1)
2.6 Time Complexity Summary
Operation Best Case Average Case Worst Case
Access (by index) O(1) O(1) O(1)
Traversal O(n) O(n) O(n)
Search (linear) O(1) O(n) O(n)
Insertion (at end) O(1) O(1) O(n)*
Insertion (at beginning/middle) O(n) O(n) O(n)
Deletion (at end) O(1) O(1) O(1)
Deletion (at beginning/middle) O(n) O(n) O(n)
Update O(1) O(1) O(1)
*Insertion at the end is O(n) only in the rare worst case where a dynamic array (like Python's list) runs out of
pre-allocated capacity and must resize by copying all existing elements to a larger block.
3
Introduction to Linked List
4
Singly Linked List
4.1 Structure and Node Representation
A Singly Linked List (SLL) is a chain of nodes where each node points only forward to the next node. Traversal
is possible in one direction only — from head to tail.
class Node: def init(self, data): self.data = data self.next = None
class SinglyLinkedList: def init(self): self.head = None
4.2 Insertion
(a) Insertion at the Head — O(1): the new node simply points to the old head.
def insert_at_head(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node
Before: HEAD → [25] → [7] → None
After: HEAD → [10] → [25] → [7] → None
(b) Insertion at the Tail — O(n) (without a tail pointer): traverse to the last node.
def insert_at_tail(self, data): new_node = Node(data) if self.head is None: self.head = new_node return current = self.head while current.next is not None: current = current.next current.next = new_node
(c) Insertion in the Middle — O(n) to find the position, O(1) to link.
def insert_at_position(self, data, position): if position == 0: return self.insert_at_head(data) new_node = Node(data) current = self.head for _ in range(position - 1): current = current.next new_node.next = current.next current.next = new_node
4.3 Deletion
def delete_at_head(self): if self.head: self.head = self.head.next # O(1)
def delete_at_tail(self): if self.head is None or self.head.next is None: self.head = None return current = self.head while current.next.next is not None: # stop one node before the last current = current.next current.next = None # O(n)
def delete_at_position(self, position): if position == 0: return self.delete_at_head() current = self.head for _ in range(position - 1): current = current.next current.next = current.next.next # O(n) to find, O(1) to unlink
4.4 Traversal and Searching
def traverse(self): current = self.head while current: print(current.data, end=" -> ") current = current.next print("None")
def search(self, target): current = self.head index = 0 while current: if current.data == target: return index current = current.next index += 1 return -
4.5 Time Complexity — Singly Linked List
Operation Time Complexity
Insertion at head O(1)
Insertion at tail (no tail pointer) O(n)
Insertion at position O(n)
Deletion at head O(1)
Deletion at tail O(n)
Deletion at position O(n)
current.next = new_node new_node.prev = current
Insertion in the Middle — O(n) to locate, O(1) to relink both directions:
def insert_after(self, prev_node, data): new_node = DNode(data) new_node.next = prev_node.next new_node.prev = prev_node if prev_node.next: prev_node.next.prev = new_node prev_node.next = new_node
Deletion (any node, given a reference to it) — O(1) once located:
def delete_node(self, node): if node.prev: node.prev.next = node.next else: self.head = node.next # deleting the head if node.next: node.next.prev = node.prev
Traversal — Forward and Backward :
def traverse_forward(self): current = self.head while current: print(current.data, end=" <-> ") current = current.next print("None")
def traverse_backward(self, tail): current = tail while current: print(current.data, end=" <-> ") current = current.prev print("None")
5.4 Singly vs Doubly Linked List
Aspect Singly Linked List Doubly Linked List
Pointers per node 1 (next) 2 (next and prev)
Memory per node Lower Higher (extra pointer)
Traversal direction Forward only Forward and backward
Deletion (given node ref) O(n) — needs previous node O(1) — prev is already known
Typical use case Simple stacks/queues Browser history, LRU cache, music playlists
6
Circular Linked List
6.1 Structure
In a Circular Linked List (CLL), the last node does not point to None — instead, it points back to the first
node, forming a closed loop. There is no true "end" of the list; traversal must stop deliberately (usually by
checking whether you've returned to the starting node) instead of checking for None.
[10] → [25] → [7] → (back to 10)
Diagram: the last node ([7]) links back to the first node ([10]) instead of None, closing the loop.
6.2 Types
l Circular Singly Linked List:^ each node has one^ next^ pointer; the last node's next points back to the head.
l Circular Doubly Linked List:^ each node has both^ next^ and^ prev^ pointers; the last node's next points to the
head, and the head's prev points to the last node — the loop closes in both directions.
6.3 Operations
Insertion at Head (circular singly linked list):
def insert_at_head(self, data): new_node = Node(data) if self.head is None: new_node.next = new_node # points to itself self.head = new_node return current = self.head while current.next != self.head: # find the last node current = current.next new_node.next = self.head current.next = new_node self.head = new_node
Deletion (removing a node with a given value):
def delete_value(self, value): if self.head is None: return current = self.head prev = None while True: if current.data == value: if prev is None and current.next == self.head: self.head = None # only node in the list elif prev is None: tail = self.head while tail.next != self.head: tail = tail.next self.head = current.next tail.next = self.head
Choosing the Right Structure
l Need fast lookups by position/index, and size is fairly stable?^ Use an^ array.
l Need frequent insertions/deletions at the front, and don't need backward traversal?^ Use a^ singly linked
list.
l Need to move both forward and backward efficiently (e.g., undo/redo, LRU cache)?^ Use a^ doubly
linked list.
l Need continuous cycling with no natural "end" (turns, scheduling, looping playback)?^ Use a^ circular
linked list.
8
Solved Practice Problems (Python)
Every problem below follows the same format: problem statement, approach, working code, a hand-traced dry
run, complexity analysis, and edge cases — useful whether you are completing a class assignment or prepping
for a technical interview.
Problem 1 — Reverse a Singly Linked List
Statement: Given the head of a singly linked list, reverse it in place and return the new head.
Approach: Walk through the list once, keeping three pointers: prev (initially None), current (starts at head),
and next_node (a temporary save of current.next). At each node, flip its next pointer to point backward to
prev, then advance all three pointers forward.
def reverse_list(head): prev = None current = head while current is not None: next_node = current.next # save the next node before overwriting current.next = prev # reverse the pointer prev = current # move prev forward current = next_node # move current forward return prev # prev is the new head
Dry Run for list 10 → 20 → 30 → None:
Step prev current next_node List state (next pointers)
Start None 10 - 10 → 20 → 30 →None
1 10 20 20 10 →None, 20→ 30 →None
2 20 30 30 20 → 10 →None, 30→None
3 30 None None 30 → 20 → 10 →None
Loop ends when current becomes None; prev (30) is returned as the new head: 30 → 20 → 10 → None.
Time Complexity Space Complexity
O(n) O(1)
Edge cases: empty list (head is None → returns None); single-node list (returns that same node unchanged, since the
loop runs once and its next becomes None).
Problem 2 — Detect a Loop in a Linked List (Floyd's Cycle Detection)
Statement: Given the head of a linked list, determine whether it contains a cycle (a node whose next pointer
eventually leads back to a previously visited node).
Approach: Use two pointers, slow (moves 1 step at a time) and fast (moves 2 steps at a time) — the classic
"tortoise and hare" technique. If a cycle exists, the faster pointer will eventually lap the slower one and they will
meet inside the loop. If the list has an end, fast will reach None first.
def has_cycle(head): slow = head fast = head while fast is not None and fast.next is not None: slow = slow.next # move 1 step fast = fast.next.next # move 2 steps if slow == fast: # they met -> cycle found return True return False # fast reached the end -> no cycle
Dry Run for a cyclic list 1 → 2 → 3 → 4 → (back to 2): slow starts at 1, fast at 1. Step 1: slow → 2, fast → 3.
Step 2: slow → 3, fast → 2 (via 4). Step 3: slow → 4, fast → 4 — slow equals fast, so the function correctly
returns True.
Time Complexity Space Complexity
O(n) O(1)
Edge cases: empty list (loop never runs → returns False); single self-looping node (fast and slow meet on the very first
iteration).
Problem 3 — Find the Middle Element
Statement: Given the head of a singly linked list, return the middle node in a single pass (if there are two
middle nodes, return the second one).
Approach: Reuse the slow/fast pointer idea. Both start at head; slow advances 1 step, fast advances 2 steps.
By the time fast reaches the end of the list, slow has covered exactly half the distance, landing on the middle
node.
def find_middle(head): slow = head fast = head while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next return slow # slow is now at the middle node
Dry Run for 10 → 20 → 30 → 40 → 50 → None: Start slow=10, fast=10. Step 1: slow=20, fast=30. Step 2:
slow=30, fast=50. fast.next is None, loop stops. Middle = 30 (correct — the 3rd of 5 nodes).
while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: break else: return None # no cycle found
pointer = head while pointer != slow: pointer = pointer.next slow = slow.next return pointer # this is the start of the cycle
Time Complexity Space Complexity
O(n) O(1)
Why an interviewer likes this question: it tests whether you can extend a known technique (Floyd's algorithm) instead
of just memorizing it, and whether you understand the pointer-distance reasoning behind it rather than the code alone.
Recommended next step: close this PDF, open a blank editor, and re-implement all five problems above from
scratch, without looking. That single act of retrieval is worth more than another full re-read.
9
Diagrams and Visual Representation
This section brings together clean, graphical (draw.io-style) pointer diagrams for every structure covered in this
guide — useful as a quick visual reference or for revision, separate from the inline diagrams already shown
within each section.
9.1 Array — Contiguous Memory Layout
Each element sits in a fixed-size slot right next to the previous one, so any index maps directly to a memory address
using Base + (index × element size).
9.2 Singly Linked List — Pointer Connections
Before/after view of insert_at_head(99): the new node's next pointer is set to the old head, then HEAD is moved to point
at the new node — no shifting of existing nodes.
9.3 Doubly Linked List — next & prev Pointers