Skip to content

What is a Graph?

Data Structures·6 min·Python code

Graphs model relationships as vertices (nodes) joined by edges (links). Edges point one way or both ways and can carry weights, which covers road maps, social networks, web pages and task dependencies. Adjacency lists and adjacency matrices store them.

Graph Vertices and Edges Explained

Picture maps of dots and lines. Dots are vertices, like people, cities, web pages or tasks. Lines are edges, like friendships, roads, hyperlinks or rules that say one task must happen first.

That is the full model. Trees and linked lists are graphs with extra rules, while plain graphs promise nothing about shape. Vertices can connect to none, one or thousands of others, and cycles are allowed.

Once you spot items plus relationships, a library of algorithms opens up for shortest paths, reachability, cycle detection and ordering. Spotting the structure hiding inside a word problem is the hardest step, and watching traversals move across nodes makes it much easier.

Directed, Undirected and Weighted Edges

Edges carry meaning through two properties. Direction comes first. Undirected edges are mutual, like friendships, while directed edges go one way, like follows on social apps or course prerequisites.

Weight comes second. Unweighted edges only say two vertices connect, while weighted edges attach a number like distance, cost, time or capacity. Road maps are weighted undirected graphs, and build systems are directed graphs where an edge means depends on.

These choices decide which algorithm applies. Dijkstra needs non negative weights, topological sort needs a directed acyclic graph (DAG) and cycle detection differs between directed and undirected graphs. Name the edge type first and the right algorithm follows.

Adjacency List vs Adjacency Matrix

Two layouts store graphs. Adjacency lists keep a list of neighbours for every vertex, which stays compact when edges are few. Adjacency matrices use a V by V grid where cell [u][v] marks an edge, giving O(1) edge lookups but costing O(V²) space even for a nearly empty graph.

Start with an adjacency list. It stays compact and walks a vertex's neighbours in time proportional to their count, which is exactly what Breadth-First Search and Depth-First Search need.

Switch to a matrix when edges are dense or the data is tiny, or when you need constant time edge checks or matrix maths. Practise both on CodeStory's graph practice problems.

Graph Code Example in Python

pythonAdjacency list graph in Python with a breadth-first traversal for directed or undirected edges.

from collections import defaultdict, deque

class Graph:
    def __init__(self, directed=False):
        self.adj = defaultdict(list)
        self.directed = directed

    def add_edge(self, u, v):
        self.adj[u].append(v)
        if not self.directed:
            self.adj[v].append(u)

    def bfs(self, start):
        seen, order, q = {start}, [], deque([start])
        while q:
            node = q.popleft()
            order.append(node)
            for nxt in self.adj[node]:
                if nxt not in seen:
                    seen.add(nxt)
                    q.append(nxt)
        return order

Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App

Graph Time and Space Complexity

TimeO(V + E) to traverse with BFS or DFS. Edge lookup costs O(degree) with lists and O(1) with a matrix
SpaceO(V + E) for an adjacency list and O(V²) for an adjacency matrix

V means vertices and E means edges. Adjacency lists suit sparse graphs, where E sits far below V², which describes real data. Matrices suit dense graphs and constant time edge checks.

Watch Graph Traversals and Shortest Paths

Seeing a search spread across the nodes shows how paths form. Follow either of these on your own input, one step at a time.

When to Use a Graph

  • You model items that connect, like social networks, road and transit maps, computer networks and web page links.
  • You find shortest or cheapest paths, like GPS routing and network latency, with BFS, Dijkstra or A*.
  • You order tasks with dependencies, like build systems, course prerequisites and package installs, using topological sort on a DAG.
  • You answer reachability questions. Does a route exist between two nodes, how many connected components exist and does a cycle exist?

Mistakes to Avoid

  • Storing large sparse data in adjacency matrices, which burns O(V²) memory when an adjacency list needs far less.
  • Forgetting to track visited nodes during traversal. Cycles then cause infinite loops or exponential repeated work.
  • Mixing up directed and undirected edges, by adding an edge one way when the link is mutual or both ways when it is not.

Graph FAQs

Is graph theory hard to learn?

Dots joined by lines is a plain idea, and most learners grasp it quickly. Recognising secret graphs inside problems and choosing the matching traversal takes practice. Watching a traversal animate node by node helps more than tracing it on paper.

When should I use an adjacency list vs an adjacency matrix?

Start with an adjacency list, since it stays compact and suits sparse graphs. Choose a matrix when edges are dense or the data is very small, or when you need constant time checks for an edge between u and v.

What is the difference between a graph and a tree?

Trees are graphs that are connected, undirected and free of cycles, with exactly V − 1 edges. General graphs have no such rules, so they can hold cycles, split into pieces and give any node any number of connections. Every tree is a graph, but not every graph is a tree.

What is the time complexity of traversing a graph?

BFS or DFS visits every vertex and edge once, which costs O(V + E) using adjacency lists. With an adjacency matrix the cost becomes O(V²), because finding one vertex's neighbours means scanning a full row.

What is the difference between a directed and an undirected graph?

Directed graphs give edges a direction, so a link from node 1 to node 2 does not link node 2 to node 1. Undirected graphs treat every edge as two way. Choose the type that matches the relationship you model, then store it the same way in code.

What are weighted edges?

Weighted edges carry a number, like distance, cost or time. Dijkstra and A* use those numbers to find the cheapest path instead of the one with the fewest edges.

How do I practise graphs on CodeStory?

Watch BFS, DFS and Dijkstra in the visualisers, write the traversal yourself, then try CodeStory's graph practice problems.

Related Guides

Guides are step one. In a CodeStory batch you code the traversals yourself, then explain every edge in a scored mock round.

Talk to a Mentor

Stuck on Graphs? Get a Free Callback

Tell CodeStory which graph idea confuses you, and a mentor shapes your next steps.

  1. 1CodeStory finds your starting point, from your first edge to interview ready.
  2. 2CodeStory explains online and campus batches, with timings for your mornings or evenings.
  3. 3You decide. No pressure, no payment on the call.

Get a Free Callback

I am a
I want to learn

CodeStory dials your number only for this callback.