Adjacency List Graph - Problem
Implement a graph using an adjacency list representation. Your implementation should support the following operations:
addVertex(vertex)- Add a new vertex to the graphaddEdge(v1, v2)- Add an edge between two verticesremoveVertex(vertex)- Remove a vertex and all its connectionsremoveEdge(v1, v2)- Remove the edge between two verticesdisplay()- Return the adjacency list representation as a dictionary/map
The graph should be undirected, meaning if there's an edge from A to B, there's also an edge from B to A.
Given a list of operations, execute them and return the final adjacency list.
Input & Output
Example 1 — Basic Graph Operations
$
Input:
operations = [["addVertex", "A"], ["addVertex", "B"], ["addEdge", "A", "B"], ["display"]]
›
Output:
{"A": ["B"], "B": ["A"]}
💡 Note:
Add vertices A and B, create edge A-B. Since graph is undirected, both A has neighbor B and B has neighbor A.
Example 2 — Remove Operations
$
Input:
operations = [["addVertex", "A"], ["addVertex", "B"], ["addVertex", "C"], ["addEdge", "A", "B"], ["addEdge", "B", "C"], ["removeEdge", "A", "B"]]
›
Output:
{"A": [], "B": ["C"], "C": ["B"]}
💡 Note:
Create A-B-C path, then remove A-B edge. Result: A has no neighbors, B-C edge remains intact.
Example 3 — Remove Vertex
$
Input:
operations = [["addVertex", "A"], ["addVertex", "B"], ["addVertex", "C"], ["addEdge", "A", "B"], ["addEdge", "B", "C"], ["removeVertex", "B"]]
›
Output:
{"A": [], "C": []}
💡 Note:
Remove vertex B removes all its edges. A and C remain but lose their connections to B.
Constraints
- 1 ≤ operations.length ≤ 1000
- Each operation is one of: addVertex, addEdge, removeVertex, removeEdge
- Vertex names can be strings or numbers
- Graph is undirected
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code