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
GraphAdding 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
- Identify the two nodes to connect (and the edge's weight, if applicable).
- Add the second node to the first node's neighbor list.
- If the graph is undirected, also add the first node to the second node's neighbor list.
- 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
- Add C to A's neighbor list: A -> [B, C]
- Add A to C's neighbor list: C -> [A]
Output: A and C are now directly connected both ways
Press ▶ Run to watch it step by step.
def add_edge(graph, a, b, directed=False):
graph.setdefault(a, []).append(b)
if not directed:
graph.setdefault(b, []).append(a)
# example: add edgeBehind 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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.