TCS · Question 1 · Graphs
Implement Graph Using Adjacency List
Problem
Represent a graph using an adjacency list.
Approach
A vector of vectors stores each vertex's neighbours.
Time O(1)Space O(V + E)
How it works
- 1One neighbour list per vertex.
- 2Undirected edges append both ways.
Sample input / output
Input: V = 5, edges = [[0,1],[0,4],[1,2],[1,3],[3,4]] Output: 0: [1, 4] 1: [0, 2, 3] 2: [1] 3: [1, 4] 4: [0, 3]
Constraints
0 <= V <= 10^4.
Solution — read it, then walk it
Time O(1)Space O(V + E)Loops 2Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/28
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits