← TCS bank

TCS · Question 1 · Graphs

Implement Graph Using Adjacency List

GraphsC++code⏱ O(1)💾 O(V + E)
Service-based

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

  1. 1One neighbour list per vertex.
  2. 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.
↻ repeat↻ repeatSTARTinclude <iostream>include <vector>using namespace stdCLASS GraphDEFINE Vvector<vector<int>> adjDEFINEGraph(int vertices) :V(vertices), adj(vertices){}DEFINE addEdge(int u, intv)adj[u].push_back(v)adj[v].push_back(u)DEFINE print()for (int i = 0; i < V;++i)cout << i << ": ["for (size_t j = 0; j <adj[i].size(); ++j)if (j) cout << ", "cout << adj[i][j]cout << "]" << endlDEFINE main()Graph g(5)g.addEdge(0, 1)g.addEdge(0, 4)g.addEdge(1, 2)g.addEdge(1, 3)g.addEdge(3, 4)g.print()RETURN 0END
  • 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