Create a Graph, print it (implemented code)

Pattern: Representations

easy

An adjacency list stores, for each vertex, the list of its neighbours. For an undirected edge u-v, add v to u's list and u to v's list, in the order the edges are given.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given n vertices and a list of undirected edges, return the adjacency list: for each vertex, its neighbours in the order the edges list them. Vertices are numbered from 0 and each edge is given as [u, v]. The catalogue's link here was a shared file rather than a practice page, so it was removed.

Think first

  • What does each vertex need to know?
  • How many lists does one undirected edge change?
  • In what order do neighbours appear?

Hints

    Brute force, and why it fails

    Store only the edge list and scan it for every question: O(E) per neighbour lookup.

    The key insight

    One pass over the edges builds lists that give every vertex's neighbours directly.

    Dry run

    n = 5, edges [0, 1], [0, 4], [1, 2], [1, 3], [1, 4], [2, 3], [3, 4]. Start with five empty lists.

    Step 1 of 3

    The plan

    adj = n empty lists
    for (u, v) in edges: adj[u].append(v); adj[v].append(u)
    

    Complexity

    Time
    O(V + E)
    Space
    O(V + E)

    Each edge is stored twice.

    Edge cases

    • A single vertex with no edges.
    • A graph in several pieces.
    • Many edges at one vertex.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<Integer>> printGraph(int n, int[][] edges) {
            List<List<Integer>> adj = new ArrayList<>();
            for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
            for (int[] e : edges) {                 // an undirected edge is stored at both ends
                adj.get(e[0]).add(e[1]);
                adj.get(e[1]).add(e[0]);
            }
            return adj;
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> printGraph(int n, vector<vector<int>>& edges) {
            vector<vector<int>> adj(n);
            for (const vector<int>& e : edges) {    // an undirected edge is stored at both ends
                adj[e[0]].push_back(e[1]);
                adj[e[1]].push_back(e[0]);
            }
            return adj;
        }
    };

    Python

    class Solution:
        def printGraph(self, n: int, edges: list[list[int]]) -> list[list[int]]:
            adj = [[] for _ in range(n)]
            for u, v in edges:                      # an undirected edge is stored at both ends
                adj[u].append(v)
                adj[v].append(u)
            return adj

    Common mistakes

    • Adding only one direction.
    • Sorting the lists when the order of input is wanted.

    Similar problems