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 graph
  • addEdge(v1, v2) - Add an edge between two vertices
  • removeVertex(vertex) - Remove a vertex and all its connections
  • removeEdge(v1, v2) - Remove the edge between two vertices
  • display() - 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
Adjacency List Graph ImplementationINPUT: OperationsaddVertex AaddVertex BaddEdge A BaddVertex CaddEdge B CALGORITHM: HashMap Build1Create empty HashMap2For each addVertex: map[v] = []3For addEdge: append to both lists4Handle removes efficientlyHashMap Structure:A --> [B]B --> [A, C]C --> [B]O(1) vertex lookup!RESULT: Adjacency ListFinal Graph:{"A": ["B"],"B": ["A", "C"],"C": ["B"]}Undirected: A-B meansB is in A's list ANDA is in B's listKey Insight:HashMap adjacency lists provide O(1) vertex access vs O(E) edge list scanning - perfect for dynamic graph operationsTutorialsPoint - Adjacency List Graph | Direct HashMap Access
Asked in
Google 35 Amazon 28 Facebook 22 Microsoft 18
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen