Docsity

Data Structures and Algorithms Study Guide: Big-O, Trees, Graphs + 50 Questions, Study Guides, Projects, Research of Data Structures and Algorithms

Partial preview of the text

Download Data Structures and Algorithms Study Guide: Big-O, Trees, Graphs + 50 Questions and more Study Guides, Projects, Research Data Structures and Algorithms in PDF only on Docsity!

CORELEAF GUIDES

DATA STRUCTURES

& ALGORITHMS

A Practical Revision Guide

PRACTICE 50 questions SOLUTIONS Worked step by step EXAMPLES Clear Python code 2026 EDITION

Before you start

This gude s for the stage where you have seen the topcs n class but stll need them to clck. Work through the chapters n order, pause before each explanaton, and trace the examples on paper. Thie practce set s at the end; try t before openng the solutons. A SIMPLE ROUTINE Read the idea, trace one example, check the running time, then solve a question without looking back.

What is covered

  • Choosng a data structure for the job.
  • Workng out tme and extra-space costs.
  • Tracng search, sort, tree, heap, and graph algorthms.
  • Spotting common mplementaton mstakes.
  • Answerng typcal exam questons clearly.

About this guide

This s an ndependent revson gude. It s not ted to one unversty or course, and t does not use leaked exam materal. Thie examples and practce questons were wrttien for ths gude.

Inside the guide

Part Focus Outcome 1-3 Complexity and linear structures Reason about cost and storage 4-6 Hashing, trees, and heaps Select and trace non-linear structures 7-9 Sorting, graphs, and problem-solving patteerns Analyze core algorithms 10 Exam method and quick reference Answer efficciently under time pressure Practice 50 mixed questions + solutions Test and correct your understanding

1.4 Loop analysis

Worked trace: linear outer loop, logarithmic inner loop count = 0 for i in range(n): j = 1 while j < n: count += 1 j *= 2 Thie outer loop runs n tmes. Thie nner loop doubles j untl t reaches n, so t runs Θ(log n) tmes per outer teraton. Multplyng the nested costs gves Θ(n log n).

1.5 Amortized analysis

A dynamc array occasonally performs an expensve resze, but most appends are constant-tme. Across a long sequence of appends wth geometrc capacty growth, the total copyng cost s lnear, so append s Θ(1) amortzed. Amortzed s not the same as average-case: t guarantees the average cost across a sequence wthout requrng a probablty dstrbuton.

2. Arrays and Linked Lists

2.1 Arrays

An array stores elements n contguous logcal postons and supports drect ndexng. Gven a base address and finxed element sze, the address of ndex  can be calculated n constant tme. Dynamc arrays add automatc reszng whle preservng ndex access. Operation Dynamic array Singly linked list Access element i Θ(1) Θ(n) Search unsorted Θ(n) Θ(n) Insert at front Θ(n) Θ(1) Append at end Θ(1) amortized Θ(1) with tail pointer Delete known node Not directly applicable Θ(1) if predecessor is known

2.2 Linked lists

A sngly lnked node stores a value and a reference to the next node. A doubly lnked node also stores a reference to the prevous node. Lnked lsts avod shfting elements durng nserton, but reachng a poston requres followng lnks from a known node. Python illustration: constant-time insertion at the head

class Node: def init(self, value, next_node=None): self.value = value self.next = next_node def push_front(head, value): return Node(value, head)

2.3 Choosing between them

Choose an array when: you need frequent ndexng, compact storage, or cache-frendly traversal. Choose a linked list when: you perform frequent nsertons/removals near already-known nodes and random access s unmportant. COMMON TRAP “Linked-list insertion is O(1)” is incomplete. Finding the insertion position may cost O(n). State whether a pointer to the position or predecessor is already available.

3. Stacks, Queues, and Deques

3.1 Stack: last in, first out

A stack exposes push, pop, and peek at one end. It s used for functon calls, undo hstores, delmter matchng, depth-finrst search, and expresson evaluaton. Wth a dynamc array or lnked lst, core stack operatons are Θ(1) amortzed or Θ(1). Worked pattern: balanced delimiters def balanced(text): pairs = {')': '(', ']': '[', '}': '{'} stack = [] for ch in text: if ch in '([{': stack.append(ch) elif ch in pairs: if not stack or stack.pop() != pairs[ch]: return False return not stack

3.2 Queue: first in, first out

A queue exposes enqueue at the rear and dequeue at the front. It models watng lnes, task schedulng, buffeerng, and breadth-finrst search. An array-based queue should be crcular; repeatedly removng ndex 0 from a typcal dynamc array shftis elements and costs Θ(n).

5. Trees and Binary Search Trees

5.1 Tree vocabulary

A rooted tree contans nodes connected by edges wthout cycles. Each non-root node has one parent. A leaf has no chldren. Depth counts edges from the root to a node; heght counts the longest downward path from a node to a leaf.

5.2 Traversals

Traversal Order Useful property Preorder Node, left,, right Copy/serialize a tree structure Inorder Left,, node, right Produces sorted keys in a BST Postorder Left,, right, node Delete/evaluate children before parent Level order Breadth by depth Shortest levels / BFS behavior

5.3 Binary search tree invariant

For each node, every key n the lefti subtree s smaller and every key n the rght subtree s larger, under the chosen duplcate-key polcy. Search follows one root-to-leaf path. Its tme s Θ(h), where h s tree heght: Θ(log n) when balanced and Θ(n) n the worst case. Iterative BST search def search(root, target): node = root while node is not None: if target == node.key: return node node = node.left if target < node.key else node.right return None

5.4 Deletion cases

  • Leaf: detach t from ts parent.
  • One chld: connect the parent drectly to the chld.
  • Two chldren: replace the key wth ts norder successor or predecessor, then delete that replacement node.

5.5 Balanced search trees

AVL and red-black trees mantan structural constrants that keep heght Θ(log n). Thiey spend extra work on rotatons and recolorng/rebalancng so search, nserton, and deleton reman logarthmc n the worst case.

6. Heaps and Priority Queues

6.1 Heap invariant

A bnary mn-heap s a complete bnary tree n whch each parent key s no greater than ts chldren. Thie mnmum s at the root. Thie heap does not keep sblngs or entre subtrees globally sorted.

6.2 Array representation

For a zero-ndexed heap, parent() = flooor((−1)/2), lefti() = 2+1, and rght() = 2+2. Completeness allows storage wthout explct chld ponters. Operation Method Complexity Find minimum Read root Θ(1) Insert Append, then sift, up Θ(log n) Remove minimum Move last item to root, sift, down Θ(log n) Build heap Botteom-up heapify Θ(n) WATCH FOR THIS Building a heap bottoom-up is Θ(n), not Θ(n log n). Most lower-level nodes move only a small distance.

6.3 Priority queue use cases

Prorty queues support event smulaton, CPU schedulng, Djkstra’s algorthm, Prm’s algorthm, top-k selecton, and mergng sorted streams. Thie prorty determnes removal order; arrval tme only mattiers when the desgn explctly makes equal-prorty entres stable.

7. Searching and Sorting

7.1 Searching

Lnear search works on any sequence and takes Θ(n) n the worst case. Bnary search repeatedly halves a sorted search nterval and takes Θ(log n). Thie sorted-order precondton s essental. Binary search with an inclusive interval def binary_search(a, target): lo, hi = 0, len(a) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if a[mid] == target: return mid if a[mid] < target:

Representation Space Check edge (u,v) Iterate neighbors of u Adjacency list Θ(V+E) Typically Θ(deg(u)) Θ(deg(u))

8.2 Breadth-first search

BFS uses a queue and explores vertces n nondecreasng dstance from the source. In an unweghted graph, t finnds shortest paths measured by number of edges. Wth an adjacency lst, BFS runs n Θ(V+E).

8.3 Depth-first search

DFS uses recurson or an explct stack. It s useful for connected components, cycle detecton, topologcal sortng, and structural exploraton. Wth an adjacency lst, DFS also runs n Θ(V+E).

8.4 Weighted shortest paths

Algorithm Allowed weights Core structure BFS All edges equal / unweighted Queeue Dijkstra Nonnegative weights Min-priority queue Bellman-Ford Negative edges allowed Repeated edge relaxation IMPORTANT Dijkstra’s algorithm is not correct in general when reachable negative-weight edges exist.

8.5 Topological ordering

A topologcal orderng places every drected edge u→v wth u before v. Such an orderng exsts f and only f the drected graph s acyclc. It models prerequste and dependency schedulng.

9. Recursion, Greedy Choice, and Dynamic Programming

9.1 Recursion

A recursve soluton needs a base case that stops expanson and a recursve step that moves toward t. Analyze both the number of calls and the memory used by the call stack. Tal recurson does not automatcally become constant-space n languages wthout guaranteed tal-call optmzaton.

9.2 Divide and conquer

Dvde-and-conquer algorthms splt a problem nto smaller ndependent subproblems, solve them recursvely, and combne ther results. Merge sort follows T(n)=2T(n/2)+Θ(n), whch resolves to Θ(n log n).

9.3 Greedy algorithms

A greedy algorthm commts to a locally best choce. It s correct only when the problem has a property that makes those choces extend to an optmal soluton. Evdence from a few examples s not a proof; common proofs use exchange arguments or cut propertes.

9.4 Dynamic programming

Dynamc programmng apples when subproblems overlap and optmal solutons can be composed from optmal subproblem solutons. Memozaton s top-down recurson wth cachng; tabulaton s bottiom-up evaluaton of a dependency order. Dynamic programming pattern: minimum coin count def min_coins(amount, coins): dp = [0] + [flooat('inf')] * amount for value in range(1, amount + 1): for coin in coins: if coin <= value: dp[value] = min(dp[value], 1 + dp[value - coin]) return dp[amount] DP CHECKLIST Defiene the state, write the recurrence, set the base cases, choose an evaluation order, and state the time and space cost.

10. Exam Method and Quick Reference

10.1 Five-step algorithm question method

Step What to write 1 - Clarify State the input, output, constraints, and defirnition of n. 2 - Choose Name the data structure or algorithm and the invariant it relies on. 3 - Trace Work through a small example, including edge cases. 4 - Analyze Give time and auxiliary-space complexity with the relevant case. 5 - Justify Explain why the result is correct, not only what the code does.

Practice Set: 50 Original Questions INSTRUCTIONS Allow 75-90 minutes. Record a confiedence score from 1-3 beside each answer. Review low- confiedence answers even when they are correct. Q1. Which statement best describes Θ (n)? A. An upper bound only B. A lower bound only C. A tight asymptotic bound D. Thee exact running time Q2. A loop multiplies its index by 3 each iteration until it reaches n. What is its complexity? A. Θ(1) B. Θ(log n) C. Θ(n) D. Θ(n²) Q3. Which operation is Θ (1) for an array but Θ (n) for a singly linked list? A. Insert at a known head B. Access element at index i C. Insert afteer a known node D. Read the fierst element Q4. What is the amortized cost of appending to a geometrically growing dynamic array? A. Θ(1) B. Θ(log n) C. Θ(n) D. Θ(n²) Q5. Which structure directly supports LIFO behavior? A. Queeue B. Heap C. Stack D. Graph Q6. Which data structure is used by breadth-first search? A. Stack B. Queeue C. Min-heap only D. Hash set only

Q7. Under standard assumptions, expected hash-table lookup time is: A. Θ(1) B. Θ(log n) C. Θ(n log n) D. Always Θ(n) Q8. Why does open-addressing deletion often use a tombstone? A. To sort the keys B. To preserve probe chains C. To reduce the hash value D. To make the table stable Q9. Inorder traversal of a binary search tree produces: A. Keys in sorted order B. Keys by depth C. Leaves only D. Thee reverse insertion order Q10. The worst-case search time in an unbalanced BST is: A. Θ(1) B. Θ(log n) C. Θ(n) D. Θ(n log n) Q11. Which binary-heap operation is Θ (1)? A. Insert B. Remove minimum C. Find minimum D. Build heap Q12. Bottom-up construction of a binary heap takes: A. Θ(log n) B. Θ(n) C. Θ(n log n) D. Θ(n²) Q13. Which sorting algorithm has Θ (n log n) worst-case time and is stable in its standard array form? A. Insertion sort B. Merge sort C. Queicksort D. Heapsort

Q21. Define auxiliary space and distinguish it from total space. Q22. Analyze: for i from 1 to n, for j from 1 to i, perform constant work. Q23. Explain why inserting at the front of a dynamic array is not constant time. Q24. State one advantage and one disadvantage of a doubly linked list compared with a singly linked list. Q25. Explain why repeatedly removing index 0 from a typical dynamic array is inefficient for a queue. Q26. For a hash table with 80 entries and 100 slots, calculate the load factor. Q27. Describe the three BST deletion cases. Q28. For heap index i=5 in a zero-indexed array, give the parent and child indices. Q29. Explain why binary search runs in logarithmic time. Q30. Give a case where sort stability matters. Q31. Compare adjacency matrices and adjacency lists for a sparse graph. Q32. Explain one difference between BFS and DFS beyond the container they use. Q33. Why can Dijkstra’s algorithm fail with a negative edge? Q34. Distinguish memoization from tabulation. Q35. What must be shown to prove a greedy algorithm correct? Q36. Trace binary search for target 23 in [2, 5, 9, 14, 18, 23, 31]. List the mid values examined. Q37. Insert 7, 3, 10, 1, 5, 8 into an empty BST. Give preorder and inorder traversals. Q38. Starting with min-heap [2, 5, 4, 9, 7, 8], insert 1 and give the final array. Q39. Apply one pass of bubble sort to [5, 1, 4, 2]. Give the array after the pass. Q40. Merge the sorted lists [2, 6, 9] and [1, 5, 10]. Q41. A graph has edges A-B, A-C, B-D, C-E. Starting at A and visiting alphabetically, give BFS order. Q42. Using the same graph and alphabetical neighbors, give recursive DFS preorder. Q43. Evaluate postfix expression: 5 2 + 3 * 4 −. Q44. A queue begins [A, B, C] with A at the front. Enqueue D, dequeue twice, then enqueue E. Give final order. Q45. A stack begins empty. Push 4, push 7, pop, push 2, peek. State popped and peeked values. Q46. For recurrence T(n)=2T(n/2)+n, state the asymptotic complexity.

Q47. Compute the first six DP values for Fibonacci using F0=0, F1=1. Q48. Choose the best structure for repeatedly retrieving the smallest pending task, and justify. Q49. Choose the best graph representation for 100,000 vertices and 150,000 edges, and justify. Q50. Design an O(n) method to detect whether an array contains a duplicate. State expected time and space.

Q15 - B - Relative order of equal-key records Stablty lets an earler orderng survve when a later sort uses another key. Q16 - D - Θ (V+E) Adjacency lsts store a lst for each vertex plus one lst entry per drected edge, or two per undrected edge. Q17 - B - Unweighted or equal-cost edges BFS mnmzes number of edges. If weghts dffeer, fewer edges may not mean lower total cost. Q18 - B - Nonnegative edge weights Djkstra finnalzes the smallest tentatve dstance; a later negatve edge could nvaldate that decson. Q19 - C - Acyclic A drected cycle creates mutually dependent orderng constrants. Every DAG has at least one vald topologcal order. Q20 - B - Top-down recursion with caching Memozaton stores results when recursve subproblems are finrst solved, preventng repeated work. Q21 - Auxiliary space excludes the input itself Auxlary space measures extra workng memory, such as temporary arrays, maps, or recurson frames. Total space ncludes nput storage as well. Q22 - Θ (n²) Thie nner body runs 1+2+…+n = n(n+1)/2 tmes, whch s Θ(n²). Q23 - Existing elements must shift Openng poston 0 requres movng n current elements one slot to the rght, so nserton s Θ(n). Q24 - Advantage: easier two-way traversal; disadvantage: more memory and pointer updates A prevous ponter can make deleton or backward traversal convenent, but each node stores an extra reference and mutatons must mantan more lnks. Q25 - Each removal shifts remaining elements Removng the finrst array element s Θ(n); repeated dequeues can therefore become quadratc. A crcular buffeer avods shfting. Q26 - 0. Load factor α = entres / slots = 80 / 100 = 0.8. Q27 - Leaf, one child, two children Detach a leaf; bypass a one-chld node; for two chldren, replace wth an norder successor or predecessor and delete that replacement node. Q28 - Parent 2; children 11 and 12 For zero-based ndexng: parent=flooor((5−1)/2)=2, lefti=2·5+1=11, rght=12. Thie chldren may be outsde the current heap. Q29 - The interval halves each step Aftier k steps, at most n/2^k canddates reman. Setting ths to 1 gves k≈log₂n.

Q30 - Sorting records by multiple keys If records are finrst sorted by name and then stably sorted by grade, equal-grade records retan ther name order. Q31 - Adjacency list is usually better For a sparse graph E s far below V², so Θ(V+E) storage s dramatcally smaller than a Θ(V²) matrx whle neghbor teraton s efficcent. Q32 - BFS explores by distance; DFS explores one branch deeply This dffeerence affeects results: BFS gves unweghted shortest paths, whle DFS naturally supports backtrackng and finnshng-tme analyses. Q33 - A finalized distance can later improve A negatve edge from a not-yet-finnalzed regon can create a shorter route to a vertex Djkstra already treated as finnal. Q34 - Top-down cache vs bottom-up table Memozaton solves only reached states through recurson. Tabulaton finlls states teratvely n a dependency order and avods recurson overhead. Q35 - A proof that local choices preserve a global optimum A correctness argument typcally establshes the greedy-choce property, oftien wth an exchange argument, plus optmal substructure. Q36 - Mid values: 14, 23 Thie finrst mdpont ndex s 3 (value 14), so search contnues n ndces 4-6. Thie next mdpont s 5 (value 23), whch matches. Q37 - Preorder: 7, 3, 1, 5, 10, 8; inorder: 1, 3, 5, 7, 8, 10 Thie nserton sequence definnes the structure. Preorder vsts each node before ts subtrees; norder vsts the BST keys n sorted order. Q38 - [1, 5, 2, 9, 7, 8, 4] Append 1 at ndex 6. Swap wth parent 4 at ndex 2, then swap wth root 2. Thie heap nvarant s restored. Q39 - [1, 4, 2, 5] Compare adjacent pars lefti to rght: swap 5/1, swap 5/4, then swap 5/2. Thie largest value reaches the end. Q40 - [1, 2, 5, 6, 9, 10] Repeatedly compare the finrst unmerged values and append the smaller one, then append the remander. Q41 - A, B, C, D, E Thie queue starts wth A. Its undscovered neghbors B and C are enqueued, followed by D from B and E from C. Q42 - A, B, D, C, E DFS follows A→B→D as deeply as possble, backtracks to A, then vsts C→E. Q43 - 17 Push 5 and 2; + gves 7. Push 3; * gves 21. Push 4; subtracton gves 21−4=17.