Create a Graph (for practice)

Pattern: Representations

easy

An adjacency matrix is an n × n table where m[u][v] = 1 when u and v are joined. For an undirected graph it is symmetric: set both m[u][v] and m[v][u].

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 undirected edges, return the adjacency matrix. Vertices are numbered from 0 and each edge is given as [u, v]. The catalogue has no practice link for this one.

Think first

  • How big is the table?
  • Which cells does one undirected edge set?
  • When is a matrix a poor choice?

Hints

    Brute force, and why it fails

    There is nothing simpler; the point is the representation.

    The key insight

    A matrix trades O(n²) memory for O(1) answers to 'is u joined to v?'.

    Dry run

    n = 4, edges [0, 1], [1, 2], [2, 3], [3, 0]. Start with a 4 × 4 table of zeros.

    Step 1 of 3

    The plan

    m = n × n zeros
    for (u, v): m[u][v] = m[v][u] = 1
    

    Complexity

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

    Creating the table dominates.

    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

    class Solution {
        public int[][] adjacencyMatrix(int n, int[][] edges) {
            int[][] m = new int[n][n];              // m[u][v] == 1 when u and v are joined
            for (int[] e : edges) m[e[0]][e[1]] = m[e[1]][e[0]] = 1;
            return m;
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> adjacencyMatrix(int n, vector<vector<int>>& edges) {
            vector<vector<int>> m(n, vector<int>(n, 0));   // m[u][v] == 1 when u and v are joined
            for (const vector<int>& e : edges) m[e[0]][e[1]] = m[e[1]][e[0]] = 1;
            return m;
        }
    };

    Python

    class Solution:
        def adjacencyMatrix(self, n: int, edges: list[list[int]]) -> list[list[int]]:
            m = [[0] * n for _ in range(n)]         # m[u][v] == 1 when u and v are joined
            for u, v in edges:
                m[u][v] = m[v][u] = 1
            return m

    Common mistakes

    • Setting only m[u][v].
    • Using a matrix for a million vertices.

    Similar problems