What is a Graph?
A graph is a collection of nodes (vertices) connected by edges. Unlike trees, graphs can have cycles, multiple paths between nodes, and nodes with any number of connections.
Graphs model relationships: social networks (friends), maps (cities and roads), dependencies (course prerequisites), and many more real-world scenarios.
Two main representations:
Adjacency List - Store neighbors for each node. Space efficient for sparse graphs.
Adjacency Matrix - 2D array where matrix[i][j] = 1 if edge exists. Fast edge lookup but O(V^2) space.
For most interview problems, adjacency list is preferred because graphs are usually sparse.