Data Structures · Visualization

Graph: Add Edge

Graph

Adding an edge creates a connection between two existing nodes. Time: O(1) with an adjacency list. Space: O(1) per edge.

Big-O: BFS/DFS visit each vertex and edge once: O(V + E).

Graph: Add Edge

Graph

Adding an edge creates a connection between two existing nodes. In an undirected graph, this means adding each node to the other's neighbor list; in a directed graph, only the source node gets the destination added to its list, representing a one-way connection.

How Add Edge Works

  1. Identify the two nodes to connect (and the edge's weight, if applicable).
  2. Add the second node to the first node's neighbor list.
  3. If the graph is undirected, also add the first node to the second node's neighbor list.
  4. If directed, skip the reverse step — the connection only goes one way.

Add Edge Worked Example

Input: Add an undirected edge between A and C

  1. Add C to A's neighbor list: A -> [B, C]
  2. Add A to C's neighbor list: C -> [A]

Output: A and C are now directly connected both ways

Graph: Introduction
A set of nodes connected by edges — edges can be one-way or two-way, and optionally carry a weight (cost/distance).
A
B
C
D
E
Unvisited Visited / discovered Current Start
Graph: Introduction
Press ▶ Run to watch it step by step.
Python · Graphs in Code
def add_edge(graph, a, b, directed=False):
    graph.setdefault(a, []).append(b)
    if not directed:
        graph.setdefault(b, []).append(a)
# example: add edge
Input: Add an undirected edge between A and C

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Add Edge Time & Space Complexity

TimeO(1) with an adjacency list
SpaceO(1) per edge

When to Use Add Edge

  • Creating a friendship connection between two users
  • Adding a new road between two cities on a map
  • Declaring that one task depends on another in a build/task graph

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.