πŸ† Founder Dhruvika Solanki named 2026 Regeneron STS Scholar β€” Top 300 of 2,600+ nationwide View Official List β†’

Data Structures

Data structures form the backbone of computer programming. They define how data is arranged, stored, and accessed, which is essential for efficient processing and retrieval.

πŸ“Œ Overview of Data Structures

Linear Data Structures

Elements arranged sequentially, each connected to its previous and next neighbor.
Examples: Array, Stack, Queue, Linked List

Non-Linear Data Structures

Elements not arranged in a straight line, cannot traverse in one single pass.
Examples: Trees, Graphs

Static Data Structures

Fixed size, simplifies accessing elements.
Example: Array

Dynamic Data Structures

Can change size during runtime, memory efficient.
Examples: Dynamic Queue, Stack implementations

πŸ“¦ Array

An array is a linear structure that holds a sequence of elements of the same type in contiguous memory. This setup allows for quick access to any element using its index.

# Creating and using arrays in Python
my_list = [10, "hello", 3.14, True]
print(my_list)
[10, "hello", 3.14, True]

πŸ“š Dictionary (Hash Map)

A dictionary is a collection of key-value pairs, where each key acts as an identifier. It offers average O(1) time complexity for lookups.

# Creating a dictionary
student_scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
print("Student Scores:", student_scores)

# Accessing a value
print("Alice's Score:", student_scores['Alice'])

# Adding new entry
student_scores['David'] = 88
Student Scores: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
Alice's Score: 85

πŸ“š Stack (LIFO)

A stack follows the Last-In-First-Out (LIFO) principle. The last added element is the first to be removed. Think of a stack of plates!

# Using a list as a stack
stack = []

# Push operations
stack.append("apple")
stack.append("banana")
stack.append("cherry")
print("Stack after push:", stack)

# Pop operation
print("Popped:", stack.pop())
print("Stack after pop:", stack)
Stack after push: ['apple', 'banana', 'cherry']
Popped: cherry
Stack after pop: ['apple', 'banana']

🚢 Queue (FIFO)

A queue follows the First-In-First-Out (FIFO) rule. Like a line of people waitingβ€”the first person in line gets served first!

# Using a list as a queue
queue = []

# Enqueue
queue.append(10)
queue.append(20)
queue.append(30)
print("Queue:", queue)

# Dequeue (FIFO)
print("Dequeued:", queue.pop(0))
print("Queue after dequeue:", queue)
Queue: [10, 20, 30]
Dequeued: 10
Queue after dequeue: [20, 30]

πŸ”— Linked List

A linked list is a sequence of nodes where each node contains data and a reference to the next node. Unlike arrays, elements are not stored in contiguous memory.

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def print_list(self):
        current = self.head
        while current:
            print(current.data, end=" β†’ ")
            current = current.next
        print("None")

# Create linked list: 1 β†’ 2 β†’ 3
ll = LinkedList()
ll.head = Node(1)
ll.head.next = Node(2)
ll.head.next.next = Node(3)
ll.print_list()
1 β†’ 2 β†’ 3 β†’ None

🌳 Binary Tree

A binary tree is a hierarchical structure where each node has at most two children (left and right). The top node is called the root.

Tree Traversals

Inorder
Left β†’ Root β†’ Right
Preorder
Root β†’ Left β†’ Right
Postorder
Left β†’ Right β†’ Root
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def inorder(root):
    if root:
        inorder(root.left)
        print(root.data, end=' ')
        inorder(root.right)

# Create tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print("Inorder:")
inorder(root)
Inorder: 4 2 5 1 3

πŸ•ΈοΈ Graph

A graph is a collection of nodes (vertices) and edges that connect pairs of nodes. Graphs model relationships like social networks, road maps, and communication systems.

# Graph using adjacency list
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F'],
    'D': ['B'],
    'E': ['B', 'F'],
    'F': ['C', 'E']
}

for vertex, edges in graph.items():
    print(f"{vertex}: {edges}")
A: ['B', 'C']
B: ['A', 'D', 'E']
C: ['A', 'F']
D: ['B']
E: ['B', 'F']
F: ['C', 'E']

Graph Traversals

from collections import deque

# BFS - Breadth First Search
def bfs(graph, start):
    visited = set()
    queue = deque([start])
    while queue:
        node = queue.popleft()
        if node not in visited:
            print(node, end=' ')
            visited.add(node)
            queue.extend(graph[node])

# DFS - Depth First Search
def dfs(graph, node, visited=None):
    if visited is None:
        visited = set()
    if node not in visited:
        print(node, end=' ')
        visited.add(node)
        for neighbor in graph[node]:
            dfs(graph, neighbor, visited)

print("BFS:"); bfs(graph, 'A')
print("\nDFS:"); dfs(graph, 'A')
BFS: A B C D E F
DFS: A B D E F C

🐍 Python Collections Module

Python's collections module provides specialized container types with enhanced functionality.

Counter - Count element occurrences
OrderedDict - Preserves insertion order
DefaultDict - Default values for missing keys
Deque - Fast appends/pops from both ends
NamedTuple - Tuple with named fields
ChainMap - Group multiple dicts
from collections import Counter, deque

# Counter example
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
fruit_count = Counter(fruits)
print("Fruit Count:", fruit_count)

# Deque example
dq = deque([1, 2, 3])
dq.appendleft(0)  # O(1) operation
dq.append(4)
print("Deque:", dq)
Fruit Count: Counter({'apple': 3, 'banana': 2, 'orange': 1})
Deque: deque([0, 1, 2, 3, 4])

Want to Learn More?

Explore our curated resources for deeper learning on data structures and algorithms.

Competition Resources β†’ Coding Books β†’