Design and Analysis of Algorithms

106502
Back to Design and Analysis of Algorithms

Module 3: Graph and Tree Algorithms

  1. Q1a. An adjacency matrix representation of a graph cannot contain information of (i) nodes (ii) edges (iii) direction of edges (iv) parallel edges20222m

    Module 3: Graph and Tree Algorithms

    An adjacency matrix representation of a graph cannot contain information of
    (i) nodes
    (ii) edges
    (iii) direction of edges
    (iv) parallel edges

    View this question on its own page →
    Worked Solution

    Answer: (iv) parallel edges

    Adjacency matrix A[i][j]=1 if edge exists. It shows node count (dimension), edges, direction (asymmetry for digraph). Simple 0/1 matrix cannot represent multiple edges between same pair (multigraph) without counts.

  2. Q1c. The minimum number of colors needed to color a graph having n > 3 vertices and 2 edges is (i) 2 (ii) 3 (iii) 4 (iv) 120222m

    Module 3: Graph and Tree Algorithms

    The minimum number of colors needed to color a graph having n>3n > 3 vertices and 2 edges is
    (i) 2
    (ii) 3
    (iii) 4
    (iv) 1

    View this question on its own page →
    Worked Solution

    Answer: (i) 2

    Graph with >3 vertices but only 2 edges is disconnected forest; at most needs 2 colors (bipartite, no odd cycle). Unless edge is loop, 2 colors suffice.

  3. Q1c. Which of the following algorithms is used to find the minimum spanning tree in a weighted undirected graph? (i) Dijkstra's algorithm (ii) Kruskal's algorithm (iii) Bellman-Ford algorithm (iv) Floyd-Warshall algorithm20232m

    Module 3: Graph and Tree Algorithms

    Which of the following algorithms is used to find the minimum spanning tree in a weighted undirected graph?
    (i) Dijkstra's algorithm
    (ii) Kruskal's algorithm
    (iii) Bellman-Ford algorithm
    (iv) Floyd-Warshall algorithm

    View this question on its own page →
    Worked Solution

    Answer: (ii) Kruskal's algorithm (also Prim's)

    Kruskal (edge greedy) and Prim (vertex greedy) both find MST. Dijkstra is shortest path, Bellman-Ford handles negatives, Floyd all-pairs.

  4. Q1d. BFS on a graph G = (V, E) has running time (i) O(|V| + |E|) (ii) O(|V|) (iii) O(|E|) (iv) None of these20222m

    Module 3: Graph and Tree Algorithms

    BFS on a graph G=(V,E)G = (V, E) has running time
    (i) O(∣V∣+∣E∣)O(|V| + |E|)
    (ii) O(∣V∣)O(|V|)
    (iii) O(∣E∣)O(|E|)
    (iv) None of these

    View this question on its own page →
    Worked Solution

    Answer: (i) O(|V|+|E|)

    BFS visits each vertex and edge once using adjacency list.

  5. Q1e. In an unweighted graph, which algorithm is guaranteed to find the shortest path between two nodes? (i) Depth First Search (ii) Kruskal's Algorithm (iii) Breadth First Search (iv) Prim's Algorithm20252m

    Module 3: Graph and Tree Algorithms

    In an unweighted graph, which algorithm is guaranteed to find the shortest path between two nodes?

    (i) Depth First Search
    (ii) Kruskal's Algorithm
    (iii) Breadth First Search
    (iv) Prim's Algorithm

    View this question on its own page →
    Worked Solution

    Answer: (iii) Breadth First Search

    BFS gives shortest path in unweighted graph (by levels). DFS not guaranteed, MST algorithms not for shortest path.

  6. Q1e. In DFS traversal of a graph, which data structure is used to keep track of visited nodes? (i) Queue (ii) Stack (iii) Priority Queue (iv) Heap20242m

    Module 3: Graph and Tree Algorithms

    In DFS traversal of a graph, which data structure is used to keep track of visited nodes?
    (i) Queue
    (ii) Stack
    (iii) Priority Queue
    (iv) Heap

    View this question on its own page →
    Worked Solution

    Answer: (ii) Stack

    DFS uses stack (explicit or recursion). BFS uses queue.

  7. Q1f. Which of the following algorithms is commonly used to find the Minimum Spanning Tree of a graph? (i) Dijkstra's Algorithm (ii) Kruskal's Algorithm (iii) Bellman-Ford Algorithm (iv) Floyd-Warshall Algorithm20252m

    Module 3: Graph and Tree Algorithms

    Which of the following algorithms is commonly used to find the Minimum Spanning Tree of a graph?

    (i) Dijkstra's Algorithm
    (ii) Kruskal's Algorithm
    (iii) Bellman-Ford Algorithm
    (iv) Floyd-Warshall Algorithm

    View this question on its own page →
    Worked Solution

    Answer: (ii) Kruskal's Algorithm

    Explanation:

    • Minimum Spanning Tree (MST) of a connected, undirected, weighted graph is found by greedy MST algorithms:
      • Prim's: grows tree from a vertex, repeatedly adds minimum-weight edge crossing cut. O(Elog⁡V)O(E \log V).
      • Kruskal's: sorts all edges, adds edges in increasing order skipping those forming a cycle (using Union-Find). O(Elog⁡E)O(E \log E).
    • Dijkstra's, Bellman-Ford, Floyd-Warshall solve shortest paths, not MST.
    • Both Prim's and Kruskal's are valid; here the option listed is Kruskal's.

    Correct choice: (ii) Kruskal's Algorithm (Prim's would also be correct if listed).

  8. Q1f. Which algorithm is used to find a Minimum Spanning Tree? (i) Dijkstra's algorithm (ii) Prim's algorithm (iii) Bellman-Ford algorithm (iv) Floyd-Warshall algorithm20242m

    Module 3: Graph and Tree Algorithms

    Which algorithm is used to find a Minimum Spanning Tree?
    (i) Dijkstra's algorithm
    (ii) Prim's algorithm
    (iii) Bellman-Ford algorithm
    (iv) Floyd-Warshall algorithm

    View this question on its own page →
    Worked Solution

    Answer: (ii) Prim's algorithm

    Explanation:

    • MST algorithms: Prim's (O(Elog⁡V)O(E \log V) with heap, O(E+Vlog⁡V)O(E+V\log V) with Fibonacci heap) and Kruskal's (O(Elog⁡E)O(E \log E)) both find Minimum Spanning Tree.
    • Dijkstra's, Bellman-Ford, Floyd-Warshall are shortest-path algorithms, not MST.
    • Among given options, (ii) Prim's is the only MST algorithm.

    Note: Q81 lists Kruskal's as option (ii) — both Prim's and Kruskal's are correct MST algorithms; the exam chooses whichever appears in options.

    Correct choice: (ii)

  9. Q1g. If all edge weights in a graph are positive, what is the minimum number of edges in a spanning tree for a graph with vertices? (i) V (ii) V-1 (iii) V+1 (iv) 2V20252m

    Module 3: Graph and Tree Algorithms

    If all edge weights in a graph are positive, what is the minimum number of edges in a spanning tree for a graph with vertices?

    (i) V
    (ii) V-1
    (iii) V+1
    (iv) 2V

    View this question on its own page →
    Worked Solution

    Answer: (ii) V−1V-1

    Explanation:

    • A spanning tree of a connected graph with VV vertices is a tree that includes all VV vertices.
    • Any tree with VV vertices has exactly V−1V-1 edges (proof by induction; also ∣E∣=∣V∣−1|E|=|V|-1 characterizes trees among connected graphs).
    • Edge weights (positive or otherwise) do not affect the count — any spanning tree, regardless of weight, has V−1V-1 edges. Minimum spanning tree also has V−1V-1 edges; weight affects which edges, not how many.
    • Additional edges would create a cycle → not a tree.

    Correct choice: (ii) V−1V-1 (if graph disconnected, spanning forest has V−cV-c edges for cc components).

  10. Q1g. Which of the following algorithm solves the All Pair Shortest Path problem (i) Dijkstra's (ii) Floyd's Warshall's (iii) Prim's (iv) Kruskal's20222m

    Module 3: Graph and Tree Algorithms

    Which of the following algorithm solves the All Pair Shortest Path problem
    (i) Dijkstra's
    (ii) Floyd's Warshall's
    (iii) Prim's
    (iv) Kruskal's

    View this question on its own page →
    Worked Solution

    Answer: (ii) Floyd-Warshall's Algorithm

    Explanation:

    • All-Pairs Shortest Path (APSP) = shortest distances between every pair (i,j)(i,j).
    • Floyd-Warshall: DP, Θ(V3)\Theta(V^3), handles negative edges (no negative cycles), simple triple loop: dist[k][i][j]=min(dist[k-1][i][j], dist[k-1][i][k]+dist[k-1][k][j]).
    • Dijkstra's = Single-Source Shortest Path for non-negative weights; to get APSP you must run it VV times → O(VElog⁡V)O(V E \log V), but not the canonical APSP algorithm.
    • Prim's / Kruskal's = MST algorithms, unrelated to shortest paths.

    Correct choice: (ii) Floyd's Warshall's (also Johnson's algorithm is another APSP method).

  11. Budget App•POCKETLY

    Pocketly on Android

    Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.

    Install Pocketly
  12. Q1g. Topological sorting is only possible in: (i) Undirected Graphs (ii) Trees (iii) Directed Acyclic Graphs (iv) Weighted Graphs20242m

    Module 3: Graph and Tree Algorithms

    Topological sorting is only possible in:
    (i) Undirected Graphs
    (ii) Trees
    (iii) Directed Acyclic Graphs
    (iv) Weighted Graphs

    View this question on its own page →
    Worked Solution

    Answer: (iii) Directed Acyclic Graphs (DAGs)

    Explanation:

    • Topological sorting is a linear ordering of vertices such that for every directed edge u→vu \to v, uu appears before vv.
    • Such ordering exists iff the graph has no directed cycle. If a cycle exists, no linear extension can satisfy all precedence constraints.
    • Undirected graphs have no direction → concept not defined (except trivial cases). Trees (when oriented as DAG) can be topologically sorted, but not all trees as undirected structures.
    • Weighted vs. unweighted is irrelevant; only acyclicity matters.

    Algorithm: DFS post-order reversed or Kahn's BFS with indegree queue, both O(V+E)O(V+E).

    Correct choice: (iii)

  13. Q1h. Which algorithm is typically used in maximum flow problems? (i) Kruskal's Algorithm (ii) Floyd-Warshall (iii) Ford-Fulkerson (iv) Prim's Algorithm20242m

    Module 3: Graph and Tree Algorithms

    Which algorithm is typically used in maximum flow problems?
    (i) Kruskal's Algorithm
    (ii) Floyd-Warshall
    (iii) Ford-Fulkerson
    (iv) Prim's Algorithm

    View this question on its own page →
    Worked Solution

    Answer: (iii) Ford-Fulkerson

    Explanation:

    • Maximum Flow problem: given network with capacities c(u,v)c(u,v), find flow ff maximizing value from ss to tt respecting capacity and conservation.
    • Ford-Fulkerson method (and Edmonds-Karp O(VE2)O(VE^2) implementation, Dinic, Push-relabel) repeatedly finds augmenting paths in residual graph and augments until none remain; correctness via max-flow min-cut theorem.
    • Kruskal/Prim = MST, Floyd-Warshall = APSP, not flow.

    Correct choice: (iii) Ford-Fulkerson (also Edmonds-Karp, Dinic are refinements).

  14. Q1i. What is the time complexity of topological sorting of a directed acyclic graph (DAG) with V vertices and E edges using Depth-First Search (DFS)? (i) O(V^2) (ii) O(E^2) (iii) O(V+E) (iv) O(V.E)20232m

    Module 3: Graph and Tree Algorithms

    What is the time complexity of topological sorting of a directed acyclic graph (DAG) with VV vertices and EE edges using Depth-First Search (DFS)?
    (i) O(V2)O(V^2)
    (ii) O(E2)O(E^2)
    (iii) O(V+E)O(V+E)
    (iv) O(V.E)O(V.E)

    View this question on its own page →
    Worked Solution

    Answer: (iii) O(V+E)O(V+E)

    Explanation:

    • Topological sort via DFS: run DFS on DAG, push vertex onto stack when finished (post-order), then reverse. Each vertex visited once, each edge examined once.
    • Time = O(V)O(V) for initialization + O(V+E)O(V+E) for DFS = O(V+E)O(V+E).
    • Kahn's algorithm (BFS with indegree) is also O(V+E)O(V+E).
    • O(V2)O(V^2) / O(E2)O(E^2) would be for adjacency matrix without adjacency lists; with adjacency list it's linear.

    Correct choice: (iii) O(V+E)O(V+E)

  15. Q3a. Give step by step procedure to find minimal spanning tree for the given graph. ![image](https://9lrt4yspyx.ufs.sh/f/z1z03jdN1p04sU7KeS0RokTQjiuapSXvByEJLFr8weIGhWCq)20227m

    Module 3: Graph and Tree Algorithms

    Give step by step procedure to find minimal spanning tree for the given graph.

    image

    View this question on its own page →
  16. Q3b. What is a Minimum Cost Spanning tree? Explain Kruskal's Minimum cost spanning tree algorithm with a suitable example.20257m

    Module 3: Graph and Tree Algorithms

    What is a Minimum Cost Spanning tree? Explain Kruskal's Minimum cost spanning tree algorithm with a suitable example.

    View this question on its own page →
    Worked Solution

    Minimum Cost Spanning Tree & Kruskal's Algorithm

    Definition

    For connected undirected weighted graph G(V,E,w)G(V,E,w), a spanning tree is acyclic connected subgraph spanning all VV with ∣V∣−1|V|-1 edges. Minimum Cost Spanning Tree (MST) / Minimum Spanning Tree is spanning tree minimizing ∑e∈Tw(e)\sum_{e\in T} w(e). If distinct weights, MST unique; otherwise multiple. Cut property and cycle property characterize MST.

    Kruskal's Algorithm (Greedy)

    Kruskal(G):
      T=∅
      sort E by weight ascending
      make Union-Find structure for V
      for (u,v) in sorted E:
        if Find(u) != Find(v):
          T.add((u,v))
          Union(u,v)
          if |T|==|V|-1: break
      return T
    

    Correctness via cut property: smallest edge crossing any cut belongs to some MST; cycle property prevents adding cycle edge.

    Complexities: Sorting O(Elog⁡E)O(E\log E), Union-Find O(Eα(V))O(E \alpha(V)) → total O(Elog⁡E)O(E\log E) (α\alpha inverse Ackermann). Space O(V)O(V).

    Example

    Graph: V={A,B,C,D}V=\{A,B,C,D\}, edges: AB1, AC3, BC3, BD4, CD2

    • Sorted: AB1, CD2, AC3, BC3, BD4
    • Add AB1 (A|B), add CD2 (C|D), add AC3 (merges {A,B} with {C,D} → {A,B,C,D}), skip BC3 (would cycle A-B-C), skip BD4. MST weight 1+2+3=6 edges AB,CD,AC.

    Kruskal vs Prim

    • Kruskal edge-based, good for sparse graphs; Prim vertex-based, good for dense (O(Elog⁡V)O(E\log V) with heap, O(V2)O(V^2) naive).
    • Both optimal, choice depends on density and structure.
  17. Q4a. Solve the single source shortest path problem for the following graph considering '1' as the source vertex using Dijkstra's algorithm. ![image](https://9lrt4yspyx.ufs.sh/f/z1z03jdN1p04cA0M12VDrIj0ikyQ82dzRXKGqChPbOmcuBt6)20227m

    Module 3: Graph and Tree Algorithms

    Solve the single source shortest path problem for the following graph considering '1' as the source vertex using Dijkstra's algorithm.

    image

    View this question on its own page →
  18. Q5a. Answer the following: (i) Compare and contrast the BFS and DFS traversal techniques in terms of their algorithmic approach, time complexity, data structures used, and typical applications. (ii) Give examples where one is preferred over the other.20247m

    Module 3: Graph and Tree Algorithms

    Answer the following:
    (i) Compare and contrast the BFS and DFS traversal techniques in terms of their algorithmic approach, time complexity, data structures used, and typical applications.
    (ii) Give examples where one is preferred over the other.

    View this question on its own page →
    Worked Solution

    BFS vs DFS — Algorithmic Comparison

    Aspect BFS (Breadth-First) DFS (Depth-First)
    Strategy Level-order using queue; explores all neighbors of current level before going deeper. Depth-first using stack (recursion); goes as deep as possible, backtracks.
    Algorithm queue Q={s}; visited[s]; while Q not empty: v=dequeue; for each w adj to v if not visited: visit, enqueue DFS(v): visited[v]=true; for each w adj to v if not visited: DFS(w) (or iterative stack)
    Time O(V+E)O(V+E) with adjacency list, O(V2)O(V^2) with matrix. O(V+E)O(V+E) / O(V2)O(V^2) same.
    Space O(V)O(V) queue + visited; worst O(V)O(V) (broad level) — more memory for wide graphs. O(V)O(V) stack/recursion, worst O(V)O(V) depth; often less memory for deep narrow graphs, but recursion may overflow.
    Tree vs Stack Finds shortest path (fewest edges) in unweighted graph; level = distance from source. Finds any path, not shortest; useful for connectivity, cycles, topological sort, strongly connected components.
    Traversal Order Visiting order by distance layers: s, all distance1, then distance2... (example linear). Visiting order by depth: s→first neighbor→its neighbor... deeper first, pre-order.
    Applications Shortest path unweighted, peer-to-peer, web crawling breadth, social network 1st-degree, bipartite check, Ford-Fulkerson (Edmonds-Karp uses BFS). Topological sort, cycle detection, articulation points, Kosaraju SCC, maze solving, backtracking, solving puzzles.
    Completeness Complete on infinite graphs with finite branching (if solution at finite depth). Not complete on infinite depth without visited set.

    Example on graph A→B,C etc: BFS from A order: A, B,C, D,E (level1,2) vs DFS order: A,B,D,E,C etc depending on adjacency order.

    Hybrid: Iterative deepening DFS combines BFS completeness with DFS memory.

  19. Q5a. Explain BFS algorithm in detail. Also explain its time complexity.20257m

    Module 3: Graph and Tree Algorithms

    Explain BFS algorithm in detail. Also explain its time complexity.

    View this question on its own page →
    Worked Solution

    BFS Algorithm — Detail & Time Complexity

    Algorithm (Queue)

    BFS(G, s):
      for each v in V: color[v]=WHITE, dist[v]=∞, parent[v]=NIL
      color[s]=GRAY; dist[s]=0; Q=queue(); ENQUEUE(Q,s)
      while Q ≠ ∅:
        u=DEQUEUE(Q)
        for each v in Adj[u]:
          if color[v]==WHITE:
            color[v]=GRAY; dist[v]=dist[u]+1; parent[v]=u; ENQUEUE(Q,v)
        color[u]=BLACK
    

    Variants output traversal order by recording dequeue order.

    Example

    Graph A→B,C etc, start A: queue [A] → visit A enqueue B,C → queue [B,C] → dequeue B enqueue D → [C,D] → dequeue C enqueue E → [D,E] → etc. Order A,B,C,D,E.

    Time Complexity

    • With adjacency list: Each vertex enqueued/dequeued once O(V)O(V), each adjacency list scanned once O(E)O(E) → O(V+E)O(V+E).
    • With adjacency matrix: scan row of VV entries per vertex → O(V2)O(V^2).

    Space O(V)O(V) for queue + color/dist arrays.

    Properties

    • Computes single-source shortest path (in edges) for unweighted graphs: dist[v] = minimum number of edges s→v.
    • Produces BFS tree (parent pointers).
    • Used as subroutine in Edmonds-Karp max flow, bipartite testing (2-coloring by levels), connected components.
    • BFS levels correspond to distance layers; can also detect cycles / test bipartiteness by parity.
  20. Q5b. Design a system that finds the shortest paths between various locations in a city. The locations and roads are represented using a graph. What algorithm would you use if: (i) All roads have equal length (ii) Roads have varying lengths, but no negative lengths (iii) Some roads have negative lengths Justify your choices with suitable algorithms and reasoning.20247m

    Module 3: Graph and Tree Algorithms

    Design a system that finds the shortest paths between various locations in a city. The locations and roads are represented using a graph. What algorithm would you use if:
    (i) All roads have equal length
    (ii) Roads have varying lengths, but no negative lengths
    (iii) Some roads have negative lengths
    Justify your choices with suitable algorithms and reasoning.

    View this question on its own page →
    Worked Solution

    Shortest-Path System Design — Choice by Edge Weight

    City = graph vertices = locations, edges = roads, weight = length/time.

    (i) All roads equal length (unweighted)

    Algorithm: Breadth-First Search (BFS)

    • Reason: BFS explores in increasing distance (number of edges) layers → first time target dequeued, its distance is minimum edges. O(V+E)O(V+E) with adjacency list, no need for priority queue.
    • Alternative: Dijkstra with uniform weight 1 reduces to BFS (overhead wasteful).
    • Use queue: dist[s]=0, push neighbors.

    (ii) Varying lengths, no negative weights (positive weighted)

    Algorithm: Dijkstra's Algorithm (with binary heap O((V+E)log⁡V)O((V+E)\log V), Fibonacci O(E+Vlog⁡V)O(E+V\log V))

    • Reason: Greedy choice of smallest tentative distance; proof relies on non-negative weights (once vertex extracted, distance final). Handles varying positive weights optimal.
    • Steps: dist[s]=0, priority queue keyed by dist; repeatedly extract min uu, relax edges u→vu→v: if dist[u]+w(u,v)<dist[v]dist[u]+w(u,v)<dist[v] update.
    • Why not Bellman-Ford? Correct but O(VE)O(VE) slower, unnecessary without negatives.
    • Why not BFS? BFS assumes uniform weight → would give wrong result.

    (iii) Some roads have negative lengths (negative weights, but no negative cycles reachable)

    Algorithm: Bellman-Ford Algorithm (O(VE)O(VE)) — or SPFA / Johnson's if many sources.

    • Reason: Dijkstra fails with negative edges (greedy finality broken; example s→as→a weight5, s→bs→b weight6, b→ab→a weight -4 → shortest to aa is via bb (2) not direct 5, Dijkstra would finalize aa too early).
    • Bellman-Ford relaxes all edges V−1V-1 times, then one more pass detects negative cycles.
    • If negative cycle exists, shortest path undefined (−∞-\infty); Bellman-Ford reports it.
    • If graph large and only few negatives, could use Johnson's (O(VElog⁡V)O(VE\log V)) reweighting.

    Summary Table

    Case Weights Algorithm Time Handles negatives?
    (i) uniform BFS O(V+E)O(V+E) No need
    (ii) ≥0≥0 varying Dijkstra (heap) O(Elog⁡V)O(E\log V) No
    (iii) arbitrary (no neg cycle) Bellman-Ford O(VE)O(VE) Yes + detects cycle

    Justification: Choose simplest correct algorithm for constraint; progressing BFS → Dijkstra → Bellman-Ford as generality increases, trading speed for correctness.

  21. Q5b. Explain how Bellman Ford algorithm can be used to detect the presence of negative weight cycles.20257m

    Module 3: Graph and Tree Algorithms

    Explain how Bellman Ford algorithm can be used to detect the presence of negative weight cycles.

    View this question on its own page →
    Worked Solution

    Bellman-Ford & Negative Weight Cycle Detection

    Bellman-Ford Recap

    Input: directed weighted graph G(V,E,w)G(V,E,w), source ss.

    Init: dist[s]=0, dist[v]=∞ for v≠s
    repeat V-1 times:
      for each edge (u,v) in E:
        if dist[u]+w(u,v) < dist[v]: dist[v]=dist[u]+w(u,v); parent[v]=u
    

    After V−1V-1 iterations, dist[v]dist[v] = shortest path weight from ss using ≤ V−1V-1 edges (any simple path has ≤ V−1V-1 edges). Complexity O(VE)O(VE).

    Detecting Negative Cycle

    Extra VV-th iteration:

    for each edge (u,v) in E:
      if dist[u]+w(u,v) < dist[v]: // still relaxable
        then v is reachable from a negative cycle (and from s)
        report "Negative cycle exists reachable from s"
    

    Why? In graph without negative cycles, after V−1V-1 rounds no edge can be relaxed (shortest paths have converged). If an edge can still be relaxed, the shortest path would require ≥ VV edges → must repeat a vertex → contains a cycle. Since total weight decreased by going around cycle, that cycle is negative. Moreover, repeated relaxation can propagate −∞-\infty along all vertices reachable from the cycle.

    Finding cycle: To retrieve cycle, follow parent pointers from vv VV times to get into cycle, then walk until repeat.

    Example

    Triangle s→as→a (1), a→ba→b (-2), b→ab→a (-2): sum b→a→bb→a→b = -4 negative. After V−1=2V-1=2 iterations dist keeps decreasing; Vth iteration detects relaxation.

    Scope

    • Detects only cycles reachable from ss. To detect any negative cycle in graph, add super-source s′s' with 0-edge to all vertices and run Bellman-Ford.
    • Dijkstra cannot detect/develop must not be used with negatives.
  22. Budget App•POCKETLY

    Pocketly on Android

    Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.

    Install Pocketly
  23. Q6a. In the below given weighted graph W (Given in form of matrix), apply Bellman Ford's algorithm to find the shortest distances from source node 3. Write the time complexity of Bellman Ford's algorithm. | | 1 | 2 | 3 | 4 | 5 | |---|---|---|---|---|---| | 1 | 0 | 1 | 8 | 1 | 4 | | 2 | 1 | 0 | 12 | 4 | 9 | | 3 | 8 | 12 | 0 | 7 | 3 | | 4 | 1 | 4 | 7 | 0 | 2 | | 5 | 4 | 9 | 3 | 2 | 0 |20237m

    Module 3: Graph and Tree Algorithms

    In the below given weighted graph W (Given in form of matrix), apply Bellman Ford's algorithm to find the shortest distances from source node 3. Write the time complexity of Bellman Ford's algorithm.

    1 2 3 4 5
    1 0 1 8 1 4
    2 1 0 12 4 9
    3 8 12 0 7 3
    4 1 4 7 0 2
    5 4 9 3 2 0
    View this question on its own page →
    Worked Solution

    Bellman-Ford from Source 3 on Graph with 5 Nodes (Undirected weighted)

    Adjacency matrix (symmetric): edges weights:
    1-2:1, 1-4:1, 1-5:4, 1-3:8, 2-4:4, 2-3:12, 2-5:9, 3-4:7, 3-5:3, 4-5:2

    Treat undirected as two directed edges.

    Initialization

    dist[3]=0, others ∞.
    dist = [∞,∞,0,∞,∞] indexed 1..5.

    Relax edges V−1=4V-1=4 times (order 1→5 edges):

    We can simulate quickly (using undirected edges both directions).

    Iter1:

    • From 3: to1 via8 → dist1=8, to2 via12→12, to4 via7→7, to5 via3→3
    • From1 (now8): 1-2 (1): 8+1=9<12 → dist2=9; 1-4(1):8+1=9>7 no; 1-5(4):8+4=12>3 no
    • From2(9): 2-4(4):9+4=13>7; 2-5(9):18>3
    • From4(7): 4-5(2):7+2=9>3
    • From5(3): 5-1(4):7<8 → dist1=7; 5-4(2):5<7 → dist4=5; 5-2(9):12>9? 3+9=12>9 no ; 5-3 done
      After iter1: dist=[7,9,0,5,3]

    Iter2:

    • Check all edges: 1-2:7+1=8<9 → dist2=8; 1-4:7+1=8>5; 1-3:7+8=15>0; 2-4:8+4=12>5; 3-4:0+7=7>5; 4-5:5+2=7>3; 1-5:7+4=11>3; etc. Improvement dist2 to8.
    • After iter2: [7,8,0,5,3]

    Iter3:

    • 2-1:8+1=9>7; 4-1:5+1=6<7 → dist1=6! ; Then 1-2 again 6+1=7<8 → dist2=7 ; Then 1-3 14>0 ; Now stable.
      After iter3: dist=[6,7,0,5,3] ?? Check 4-5:5+2=7>3, 5-1:3+4=7>6, 5-4:3+2=5 equal, 2-3:7+12=19>0, 4-3:5+7=12>0. So dist=[6,7,0,5,3]

    Iter4: No change → converged.

    Final distances from 3:

    • dist[1]=6 via 3-5(3)+5-4(2)+4-1(1)=3+2+1=6 (path 3-5-4-1)
    • dist[2]=7 via 3-5-4-1-2 =3+2+1+1=7 or 3-5-4-2? 3+2+4=9 longer, so 7 is min
    • dist[3]=0
    • dist[4]=5 via 3-5-4 (3+2)
    • dist[5]=3 direct

    Check alternative 3-1 direct 8 >6, so indirect via 5-4 shorter (graph has small edges).

    No negative edges → Vth iteration detects no negative cycle (no relaxation).

    Time Complexity of Bellman-Ford

    O(VE)O(VE); with adjacency matrix E=Θ(V2)E=\Theta(V^2) → O(V3)O(V^3); with list EE → O(VE)O(VE). Space O(V)O(V). Here V=5V=5, E=10E=10 undirected (20 directed) → ~80 relaxations.

  24. Q6a. A graph with five nodes is represented using the adjacency list as follows: | | | | | | |---|---|---|---|---| | A | -> | B (10) | C (3) | | | B | -> | C (1) | D (5) | | | C | -> | B (4) | D (8) | E (2) | | D | -> | E (7) | | | | E | -> | D (9) | | | Answer the following: (i) Draw the graph for the above adjacency list. (ii) Write the algorithm for the Breadth-First Traversal (BFS). (iii) Show the BFS traversal of the graph with the starting node as A.20247m

    Module 3: Graph and Tree Algorithms

    A graph with five nodes is represented using the adjacency list as follows:

    A -> B (10) C (3)
    B -> C (1) D (5)
    C -> B (4) D (8) E (2)
    D -> E (7)
    E -> D (9)

    Answer the following:
    (i) Draw the graph for the above adjacency list.
    (ii) Write the algorithm for the Breadth-First Traversal (BFS).
    (iii) Show the BFS traversal of the graph with the starting node as A.

    View this question on its own page →
    Worked Solution

    Graph from Adjacency List + BFS

    Adjacency List (directed weighted, weight in brackets)

    • A → B(10), C(3)
    • B → C(1), D(5)
    • C → B(4), D(8), E(2)
    • D → E(7)
    • E → D(9)

    (i) Graph Drawing (description)

    Vertices A-E.
    Edges: A→B (10), A→C (3), B→C (1), B→D (5), C→B (4), C→D (8), C→E (2), D→E (7), E→D (9). It's directed; no edge into A. Strongly connected component {B,C,D,E} partially.

    If sketched: A at top, arrows to B (right) and C (middle); B to C (down-left, 1) and D; C to B (up), to D (right), to E (down); D⟷E bidirectional with weights 7/9.

    (ii) BFS Algorithm (as in Q92)

    BFS(G, s):
      for v in V: visited[v]=false, dist[v]=∞
      Q=queue(); visited[s]=true; dist[s]=0; enqueue(s)
      order=[]
      while Q not empty:
        u=dequeue()
        order.append(u)
        for v in Adj[u] (in list order):
          if not visited[v]:
            visited[v]=true; dist[v]=dist[u]+1; parent[v]=u; enqueue(v)
    

    Time O(V+E)O(V+E), space O(V)O(V). BFS ignores weights (treats as unweighted for traversal order); for weighted shortest paths use Dijkstra.

    (iii) BFS Traversal Starting A (assuming adjacency order as listed)

    • Init Q=[A], visited {A}, order []
    • Dequeue A → order [A]; neighbors B,C not visited → enqueue B,C → Q=[B,C]
    • Dequeue B → order [A,B]; neighbors C (already visited), D not visited → enqueue D → Q=[C,D]
    • Dequeue C → order [A,B,C]; neighbors B already, D already, E not visited → enqueue E → Q=[D,E]
    • Dequeue D → order [A,B,C,D]; neighbor E already visited (via C) → Q=[E]
    • Dequeue E → order [A,B,C,D,E]; neighbor D already visited → Q=[] done.

    BFS order: A → B → C → D → E
    Distances (edges): dist[A]=0, dist[B]=1, dist[C]=1, dist[D]=2 (via B), dist[E]=2 (via C).

    Parent tree: parent[B]=A, parent[C]=A, parent[D]=B, parent[E]=C.

    If adjacency order C before B, order would be A,C,B,E,D etc but standard given order yields A,B,C,D,E. BFS levels: L0 {A}, L1 {B,C}, L2 {D,E}.

  25. Q6a. Explain the Prim's algorithm. What is the time complexity of Prim's algorithm?20257m

    Module 3: Graph and Tree Algorithms

    Explain the Prim's algorithm. What is the time complexity of Prim's algorithm?

    View this question on its own page →
    Worked Solution

    Prim's Algorithm & Time Complexity

    Algorithm (Greedy MST)

    Prim(G, s):
      for v in V: key[v]=∞, parent[v]=NIL, inMST[v]=false
      key[s]=0
      Q = min-priority queue of V keyed by key
      while Q not empty:
        u = Extract-Min(Q); inMST[u]=true
        for each v in Adj[u]:
          if !inMST[v] and w(u,v) < key[v]:
            parent[v]=u; key[v]=w(u,v); Decrease-Key(Q,v,key[v])
    

    Growth from source ss, repeatedly adds minimum-weight edge crossing cut (MST,V−MST)(MST, V-MST) (cut property guarantees safety). Result = MST with V−1V-1 edges, parent pointers form tree.

    Example (as in Q89): start A, edges AB1 etc → picks AB1, then CD2 etc until MST weight minimal.

    Correctness Sketch

    Cut property: lightest edge crossing any cut belongs to some MST. Prim's cut is (inMST, rest); picking min crossing edge maintains invariant that inMST vertices are connected by MST edges.

    Time Complexity

    Depends on priority queue:

    • Adjacency list + binary heap: O((V+E)log⁡V)O((V+E)\log V) = O(Elog⁡V)O(E\log V) (extract-min VV times, decrease-key up to EE times).
    • Adjacency list + Fibonacci heap: O(E+Vlog⁡V)O(E + V\log V) (amortized decrease-key O(1)O(1)).
    • Adjacency matrix + array (no heap, scan min): O(V2)O(V^2) — best for dense graphs (E≈V2E≈V^2).
    • Adjacency matrix + binary heap: still O(Elog⁡V)O(E\log V).

    Space: O(V+E)O(V+E) or O(V2)O(V^2) for matrix.

    Comparison

    Prim good for dense graphs (array O(V2)O(V^2)), Kruskal O(Elog⁡E)O(E\log E) better for sparse. Both optimal greedy MST algorithms.

  26. Q6b. What is minimum spanning tree (MST)? Explain the steps of Prim's algorithm to find the MST using an example.20237m

    Module 3: Graph and Tree Algorithms

    What is minimum spanning tree (MST)? Explain the steps of Prim's algorithm to find the MST using an example.

    View this question on its own page →
    Worked Solution

    MST & Prim's Algorithm (Detailed)

    MST Definition

    Connected, undirected, weighted G(V,E,w)G(V,E,w). Spanning tree TT with V−1V-1 edges spanning all vertices. MST minimizes ∑e∈Tw(e)\sum_{e\in T} w(e).

    Prim's Algorithm (as in Q94)

    Prim(G, r):
      key[v]=∞, parent[v]=NIL, inQueue[v]=true for all v
      key[r]=0; Q = min-heap on key
      while Q≠∅:
        u=Extract-Min(Q); inQueue[u]=false
        for v in Adj[u]:
          if inQueue[v] and w(u,v)<key[v]:
            parent[v]=u; key[v]=w(u,v); Decrease-Key(Q,v,key[v])
    

    Cut property ensures each added edge is safe.

    Example Run (Graph: V=4 edges AB1 AC4 BC2 BD5 CD3)

    Start A: key[A]=0

    • Extract A → relax B1, C4 → key[B]=1 parent A, key[C]=4
    • Extract B (min1) → relax C via2 <4 → key[C]=2 parent B; D via5 → key[D]=5
    • Extract C (2) → relax D via3 <5 → key[D]=3 parent C
    • Extract D (3) → done. MST edges: AB1, BC2, CD3 weight 6.

    Complexity: O(Elog⁡V)O(E\log V) binary heap, O(V2)O(V^2) array, O(E+Vlog⁡V)O(E+V\log V) Fibonacci.

    When to Use Prim vs Kruskal

    • Prim vertex-growth → dense graphs (O(V2)O(V^2) without heap good).
    • Kruskal edge-sort → sparse graphs (O(Elog⁡E)O(E\log E)). Both O(Elog⁡V)O(E\log V) order-wise.
  27. Q6b. Apply the Prim's algorithm and find the optimal solution for the following graph: ![Prim's Algorithm Graph](https://res.cloudinary.com/dvrkysimk/image/upload/v1780226131/image_anpxgf.png)20257m

    Module 3: Graph and Tree Algorithms

    Apply the Prim's algorithm and find the optimal solution for the following graph:

    Prim's Algorithm Graph

    View this question on its own page →
  28. Q6b. Write the Pseudo-code for the Dijkstra's Algorithm. Further, find the single source (A) shortest path on the following graph: ![image](https://9lrt4yspyx.ufs.sh/f/z1z03jdN1p04c1Or1kxVDrIj0ikyQ82dzRXKGqChPbOmcuBt)20247m

    Module 3: Graph and Tree Algorithms

    Write the Pseudo-code for the Dijkstra's Algorithm. Further, find the single source (A) shortest path on the following graph:

    image

    View this question on its own page →
  29. Q7a. Discuss the differences between BFS and DFS in terms of traversal order, memory usage, and their applications in real-world problems.20237m

    Module 3: Graph and Tree Algorithms

    Discuss the differences between BFS and DFS in terms of traversal order, memory usage, and their applications in real-world problems.

    View this question on its own page →
    Worked Solution

    BFS vs DFS Differences (Traversal, Memory, Applications)

    Detailed as in Q66/Q92 summary:

    Traversal Order

    • BFS: Level-order (queue) → visits neighbors layer by layer, yields vertices sorted by distance (edges) from source. Order: source, distance1, distance2...
    • DFS: Depth-first (stack/recursion) → dives to deepest unvisited neighbor before backtracking, yields pre-order depth path.

    Memory Usage

    • BFS: Needs queue storing entire frontier; worst O(V)O(V) but frontier can be wide → up to O(bd)O(b^d) for branching factor bb, depth dd; often more memory than DFS for wide graphs.
    • DFS: Stack stores current path; O(h)O(h) where hh = height/depth (O(V)O(V) worst). Recursion stack O(V)O(V) but typically smaller for deep narrow graphs. Risk of recursion overflow; iterative DFS also O(V)O(V).
    • Both O(V)O(V) visited array + O(V+E)O(V+E) or O(V2)O(V^2) graph storage.

    Applications & Real-World

    BFS:

    • Unweighted shortest path (GPS with equal roads, social network degrees, web crawler breadth, peer-to-peer search).
    • Bipartite testing, connected components, Edmonds-Karp max flow (BFS finds shortest augmenting path), broadcasting level synchrony.

    DFS:

    • Topological sort (DAG), cycle detection (back edge), strongly connected components (Kosaraju), articulation points/bridges, solving mazes/puzzles via backtracking, file system traversal.
    • Memory-constrained search (when BFS frontier too large).

    Tradeoff: Need shortest path on unweighted? BFS. Need any path / explore deep / detect cycles / topological? DFS. Need both? Use BFS for shortest, DFS for connectivity; iterative deepening combines benefits.

  30. Q7a. What is negative weight-cycle? Write Bellman-Ford algorithm to find single source shortest distance of a directed graph.20227m

    Module 3: Graph and Tree Algorithms

    What is negative weight-cycle? Write Bellman-Ford algorithm to find single source shortest distance of a directed graph.

    View this question on its own page →
    Worked Solution

    Negative Weight Cycle & Bellman-Ford Algorithm

    Negative Weight Cycle

    Directed cycle CC with sum ∑e∈Cw(e)<0\sum_{e\in C} w(e) <0. In such graph, shortest path from source to vertices reachable from CC is undefined (−∞-\infty) because traversing cycle repeatedly reduces path weight arbitrarily. Example: a→ba→b -2, b→ab→a -1 → cycle -3.

    Without negative cycles, shortest simple paths well-defined (≤ V−1V-1 edges).

    Bellman-Ford — Single Source Shortest Paths (SSSP) with Negatives

    BellmanFord(G, s):
      dist[s]=0; dist[v]=∞ for v≠s; parent[v]=NIL
      repeat V-1 times:
        for each edge (u,v)∈E:
          if dist[u]+w(u,v) < dist[v]:
            dist[v]=dist[u]+w(u,v); parent[v]=u
      // detect negative cycle
      for each edge (u,v):
        if dist[u]+w(u,v) < dist[v]:
          return "Negative cycle reachable from s" (and retrieve cycle via parent)
      return dist, parent
    

    Correctness: After ii iterations, dist[v]dist[v] = shortest path using ≤ ii edges. After V−1V-1, all simple paths considered. If still relaxable → ≥ VV edges → must contain cycle → negative.

    Complexities: Time O(VE)O(VE) (list) / O(V3)O(V^3) (matrix), Space O(V)O(V). Superior to Dijkstra which fails with negatives; slower but handles them.

    Finding All Negative Cycles: Add super source s′s' with 0 edges to all vertices, run once to detect any cycle in graph.

  31. Q7a. Answer the following: (i) Explain the concept of a Minimum Spanning Tree (MST) in a connected, weighted, undirected graph. (ii) Compare and contrast Prim's and Kruskal's algorithms for finding the MST. (iii) Analyze the time complexity of both algorithms and discuss their advantages and scenarios where one is preferred over the other.20247m

    Module 3: Graph and Tree Algorithms

    Answer the following:
    (i) Explain the concept of a Minimum Spanning Tree (MST) in a connected, weighted, undirected graph.
    (ii) Compare and contrast Prim's and Kruskal's algorithms for finding the MST.
    (iii) Analyze the time complexity of both algorithms and discuss their advantages and scenarios where one is preferred over the other.

    View this question on its own page →
    Worked Solution

    MST Concepts, Prim vs Kruskal

    (i) MST Concept

    Connected, undirected, weighted G(V,E,w)G(V,E,w). Spanning tree TT has V−1V-1 edges, connects all vertices, acyclic. MST minimizes ∑e∈Tw(e)\sum_{e\in T} w(e); unique if weights distinct. Characterized by Cut Property (lightest edge crossing any cut in some MST) and Cycle Property (heaviest edge on any cycle not in MST). Applications: network design (least cable), clustering.

    (ii) Compare Prim vs Kruskal

    Feature Prim Kruskal
    Growth Vertex-based: grows tree from start vertex, adds min edge crossing cut (inMST,rest)(inMST, rest). Edge-based: sorts all edges, adds min edge that doesn't form cycle (Union-Find).
    Data structure Priority queue (heap) + key[]. Union-Find (Disjoint Set) + sorting.
    Steps V−1V-1 iterations extract min vertex EE iterations over sorted edges
    Complexity O(Elog⁡V)O(E\log V) heap, O(V2)O(V^2) array (dense), O(E+Vlog⁡V)O(E+V\log V) Fibonacci O(Elog⁡E)O(E\log E) sort dominates (≈O(Elog⁡V)\approx O(E\log V) as log⁡E≈log⁡V\log E ≈ \log V)
    Graph type Good for dense (V2V^2 edges) Good for sparse (E≈VE≈V)
    Requires Connected to get single tree; else spanning forest Works on forest naturally

    Both greedy and optimal via cut property.

    (iii) Time & Advantages / Preference

    • Prim: O(V2)O(V^2) without heap best for dense; O(Elog⁡V)O(E\log V) with heap. Advantage: single tree growing → early stop or distributed. Preferred when EE large, graph dense, or adjacency matrix.
    • Kruskal: O(Elog⁡E)O(E\log E) sort. Advantage: simple, sorts edges, handles disconnected, easy parallel sort. Preferred when EE small (sparse) or edges already sorted.

    Overall both O(Elog⁡V)O(E\log V); choice depends on density: Prim for dense (E≫VE≫V), Kruskal for sparse (E≈VE≈V).

  32. Q7b. Given the flow network below with capacities: | EDGE | CAPACITY | |---|---| | S -> A | 10 | | S -> C | 10 | | A -> B | 4 | | A -> C | 2 | | C -> D | 9 | | B -> T | 10 | | D -> B | 6 | | D -> T | 10 | Answer the following: (i) Use the Ford-Fulkerson algorithm to find the maximum flow from source (S) to sink (T). (ii) Show the augmenting paths selected, the bottleneck capacities on each path, and the updated residual capacities after each augmentation. (iii) Calculate the final maximum flow value.20247m

    Module 3: Graph and Tree Algorithms

    Given the flow network below with capacities:

    EDGE CAPACITY
    S -> A 10
    S -> C 10
    A -> B 4
    A -> C 2
    C -> D 9
    B -> T 10
    D -> B 6
    D -> T 10

    Answer the following:
    (i) Use the Ford-Fulkerson algorithm to find the maximum flow from source (S) to sink (T).
    (ii) Show the augmenting paths selected, the bottleneck capacities on each path, and the updated residual capacities after each augmentation.
    (iii) Calculate the final maximum flow value.

    View this question on its own page →
    Worked Solution

    Ford-Fulkerson Max Flow — S→A10,S→C10,A→B4,A→C2,C→D9,B→T10,D→B6,D→T10S→A10,S→C10,A→B4,A→C2,C→D9,B→T10,D→B6,D→T10

    Network Structure

    Source SS, sink TT, intermediate A,B,C,D.

    Execution (Edmonds-Karp BFS for shortest augmenting path, but any path works; show one valid sequence)

    Init flow 0, residual = capacities.

    Augment 1: S−A−B−TS-A-B-T bottlenecks min(10,4,10)=4

    • Push 4: residual S−AS-A6, A−BA-B0, B−TB-T6. Flow=4

    Augment 2: S−A−C−D−TS-A-C-D-T (via A→CA→C)

    • Path capacities: S-A6, A-C2, C-D9, D-T10 → bottleneck 2
    • Push 2: S−AS-A4, A−CA-C0, C−DC-D7, D−TD-T8. Flow=6
    • Note alternative S−C−D−TS-C-D-T also available but we use through A to show.

    Augment 3: S−C−D−TS-C-D-T bottleneck min(S-C10, C-D7, D-T8)=7

    • Push 7: S−CS-C3, C−DC-D0, D−TD-T1. Flow=13

    Augment 4: S−C−D−B−TS-C-D-B-T ??? Need residual check: After 1, A→BA→B saturated, but reverse B→AB→A 4 exists. However D→BD→B6 is forward.
    Path S−CS-C3 → C−DC-D is 0 residual (saturated) so no. Let's instead use remaining S−AS-A4 → but A−CA-C0 and A−BA-B0 blocked, so S−AS-A cannot reach T via A. So remaining flow must go S−C−D−B−TS-C-D-B-T if C−DC-D0 no. Actually after step3 C−DC-D0, so D only reachable not via C. So need alternative.

    Let's choose better order: Instead of exhausting C-D early, more systematic:

    Re-run with better path selection (standard max flow =13? Let's compute min cut).

    Min Cut analysis: Cut (S,A)(S,A)? Edges crossing: S−AS-A10 + S−CS-C10 =20. Cut (S,A,C)(S,A,C) → edges A−BA-B4, C−DC-D9 → 13. Cut (S,A,C,D)(S,A,C,D) → A−BA-B4, D−BD-B6? Actually D−BD-B internal, B−TB-T10, D−TD-T10 → cut includes B−TB-T10 + D−TD-T10 =20? Wait compute: Partition {S,A,C}\{S,A,C\} vs {B,D,T}\{B,D,T\} edges A−BA-B4, C−DC-D9 →13. Add D→TD→T and B→TB→T are from right to T but crossing? Actually T in right, B,D in right, so not crossing? Need correct: Let's compute max flow via brute: The bottleneck is C−DC-D9 + A−BA-B4 =13, and S−CS-C10 + A−BA-B4 =14, so min is 13. So max flow =13 (limited by A−BA-B4 + C−DC-D9). Another cut {S,A,C,D}\{S,A,C,D\} vs {B,T}\{B,T\} edges A−BA-B4 + D−BD-B6 + D−TD-T10 =20? Not min. So max is 13.

    Our earlier flow 13 already achievable (4+2+7=13). After step3 flow=13, indeed max reached.
    Check residual: S−AS-A4, S−CS-C3 remain but no path to T because A−BA-B0, A−CA-C0, C−DC-D0 blocks; alternative S−CS-C → ??? D−BD-B still has 6 but DD unreachable (since C−DC-D0). So no augmenting path → algorithm terminates.

    Updated Residual After Each Augmentation (summary)

    Path Bottleneck Flow Residual key edges
    S-A-B-T 4 4 S-A6, A-B0(+4 reverse), B-T6
    S-A-C-D-T 2 6 S-A4, A-C0(+2), C-D7, D-T8
    S-C-D-T 7 13 S-C3, C-D0(+7), D-T1

    Max Flow value =13 (4 via A-B-T, 9 via C-D-T split as 2+7). Achieved.

    Any valid augmenting order yielding 13 is acceptable; another order S-C-D-B-T (6) etc also yields 13.