New: 6 free SQL practice datasets with 300+ questions — try the SQL Compiler →
DSA

How to Learn DSA in Python: A Roadmap

How to learn DSA in Python: a seven-stage roadmap from Big O and hash maps to trees, graphs and dynamic programming, with a checkpoint each.

Upskly AI Team September 26, 2026 12 min read
How to Learn DSA in Python: A Roadmap

The best way to learn DSA in Python (data structures and algorithms) is to learn it in layers. First, learn how to measure the cost of code. Then learn the everyday tools, then the structures that need a little more thought, and finally the problem-solving methods that combine them. This guide is that order: a seven-stage roadmap with a short working example and a checkpoint at each stage, so you know when to move on.

Everything here is in Python, and every example runs in our free Python compiler, right in your browser. Each stage links to a detailed guide with real, tested output.

In this guide

The short version

  • Learn in order: Python basics, Big O, hash maps and array techniques, stacks and queues, recursion and trees, graphs, then backtracking and dynamic programming.
  • Always ask “what does this cost?”. Count steps, not seconds.
  • Learn the patterns, not answers to memorise. A new problem is usually an old pattern in a new costume.
  • Type the code yourself, and solve each problem again a week later without looking.

The 7 stages at a glance

A DSA learning roadmap in Python
StageWhat you learnDetailed guidesCheckpoint
1. Python firstLists, dicts, functions, loopsPython roadmap, List vs Tuple vs Set, Dictionaries, FunctionsCount words in a sentence
2. Measuring costBig O, cost of built-in operationsBig O Notation, Time Complexity of Python Data StructuresSay the cost of your own loop
3. Arrays and hash mapsHash tables, two pointers, sliding window, binary search, sortingHash Tables, Two Pointers, Sliding Window, Binary Search, SortingSolve two-sum in one pass
4. Linear structuresStack, queue, deque, linked listStack, Queue and Deque, Linked ListCheck balanced brackets
5. Recursion and treesRecursion, binary trees, BSTs, heaps, triesRecursion, Binary Tree, BST, Heap, TrieFind the height of a tree
6. GraphsAdjacency lists, BFS, DFSGraphs in PythonShortest path in a maze
7. ParadigmsBacktracking, dynamic programming, interview patternsBacktracking, Dynamic Programming, Interview PatternsFewest coins for an amount

Plan on roughly one to two weeks per stage if you practise most days. The pace that works is the one you keep up, and some stages, especially 5 to 7, will take longer than others.

Stage 1: Python you need first

DSA needs only a small part of Python, but you need it to be comfortable: lists and slicing, dictionaries and sets, loops, functions, and a first taste of classes. If writing a loop or a function still makes you stop and think, spend a few more days on the basics first. That time pays back in every later stage. A good sign you are ready: you can count how often each word appears in a sentence without looking anything up.

text = "to be or not to be"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)

Output

{'to': 2, 'be': 2, 'or': 1, 'not': 1}

Checkpoint: you can write that word counter from memory, and you can explain why a dictionary suits it better than a list.

Read next: How to Learn Python: A Step-by-Step Roadmap, Python List vs Tuple vs Set: Key Differences and Python Dictionaries Explained With Examples.

Stage 2: Measuring cost

The first real DSA skill is not a data structure but a way of thinking: how does the work grow as the input grows? That is what Big O notation describes. You do not need heavy maths, only the habit of asking “how many steps for 10 items, and for 10 million?”. We count steps and not seconds, because seconds change from computer to computer and steps do not:

for n in [1_000, 1_000_000]:
    print(f"{n} items: up to {n} steps to scan, about {n.bit_length()} steps with binary search")

Output

1000 items: up to 1000 steps to scan, about 10 steps with binary search
1000000 items: up to 1000000 steps to scan, about 20 steps with binary search

Then learn the cost of what Python already gives you. Knowing that x in a_list is a scan but x in a_set is a lookup will improve your programs for the rest of your career.

Checkpoint: you can look at a piece of code and say whether it is O(1), O(n), O(n²) or O(log n), and why.

Read next: Big O Notation Explained With Python Examples and Time Complexity of Python Data Structures.

Stage 3: Arrays, strings and hash maps

Most everyday problems live here. Start with the hash table (Python’s dict and set), the most useful structure of all: it turns “have I seen this before?” into a single step. Then learn the techniques that avoid a nested loop: two pointers for sorted data, a sliding window for contiguous stretches, and binary search for sorted data, which halves the search each step. Sorting comes here too, because so many of these need sorted input.

def two_sum(nums, target):
    seen = {}
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i
    return []

print(two_sum([2, 7, 11, 15], 9))

Output

[0, 1]

One pass and no nested loop: the number that would complete the pair is looked up in the dictionary.

Checkpoint: you can solve two-sum in one pass, and you can explain why binary search needs sorted data.

Read next: Hash Tables in Python: Dict and Set for DSA, Two Pointers Technique in Python, Sliding Window Technique in Python, Binary Search in Python: 3 Common Variations and Sorting Algorithms in Python: Bubble to Merge.

Stage 4: Stacks, queues and linked lists

These are the structures defined by how you take things out. A stack gives back the newest item first, and a queue gives back the oldest. In Python a list works as a stack, and collections.deque is the right tool for a queue. A linked list is a chain of nodes, and it teaches you how references work, which is why interviewers like it:

from collections import deque

stack = []
stack.append("a")
stack.append("b")
print(stack.pop())            # last in, first out

queue = deque(["a", "b"])
print(queue.popleft())        # first in, first out

Output

b
a

Checkpoint: you can check whether a string of brackets is balanced with a stack, and you can reverse a linked list.

Read next: Stack in Python: Implementation and Uses, Queue and Deque in Python Explained and Linked List in Python: Singly and Doubly.

Stage 5: Recursion, trees and heaps

Recursion, a function that calls itself on a smaller problem, is the key that unlocks trees: a tree is a node with smaller trees inside it. Learn recursion first, then binary trees and their four traversals, then the binary search tree, which keeps its values in order. Then meet two structures built on the same ideas: the heap (always gives you the smallest item fast) and the trie (stores words by prefix):

class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def height(node):
    if node is None:
        return 0
    return 1 + max(height(node.left), height(node.right))

tree = Node(1, Node(2, Node(4)), Node(3))
print(height(tree))

Output

3

A tree of three levels has height 3. The whole function is a base case, and one line that trusts the function to work on the smaller subtrees.

Checkpoint: you can write a recursive function with a proper base case, traverse a tree in all four orders, and say when to reach for a heap.

Read next: Recursion in Python Explained Simply, Binary Tree in Python: Traversals Explained, Binary Search Tree in Python From Scratch, Heap and heapq in Python: Priority Queues and Trie in Python: Prefix Search Explained.

Stage 6: Graphs

Maps, social networks, dependencies, mazes and grids are all graphs. Learn how to store one (a dictionary of lists), and the two basic searches: BFS with a queue, which finds the fewest steps, and DFS with a stack or recursion, which explores everything. A lot of interview questions turn out to be a graph problem in disguise:

from collections import deque

def min_steps(graph, start, goal):
    queue = deque([(start, 0)])
    seen = {start}
    while queue:
        node, steps = queue.popleft()
        if node == goal:
            return steps
        for nb in graph[node]:
            if nb not in seen:
                seen.add(nb)
                queue.append((nb, steps + 1))
    return -1

graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": ["E"], "E": []}
print(min_steps(graph, "A", "E"))

Output

3

Checkpoint: you can build a graph from a list of edges, find the shortest path in an unweighted graph, and count connected groups.

Read next: Graphs in Python: Adjacency List, BFS and DFS.

Stage 7: Backtracking and dynamic programming

These are the paradigms that combine everything before. Backtracking builds every possible answer step by step and undoes the steps that fail: subsets, permutations, puzzles. Dynamic programming solves a big problem by saving the answers to its smaller problems, so that no work is repeated. It takes practice, so do not be discouraged if it feels hard at first. Start with the memoised recursion:

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(50))

Output

12586269025

Without the cache, computing fib(50) would take billions of calls. With it, each value is computed once. Finish with the summary of patterns, which shows which technique to try for which kind of question.

Checkpoint: you can solve the fewest-coins problem with a table, and given a new problem, name two or three patterns that might apply.

Read next: Backtracking in Python: Subsets and Permutations, Dynamic Programming in Python for Beginners and 10 Coding Interview Patterns in Python.

How to practise

  • Type it, do not paste it. Typing forces you to notice every detail.
  • Try the problem for 20 to 30 minutes before you look at a solution. Struggling first is what makes the solution stick.
  • Say the cost out loud. After every solution, state its time and space cost, and whether a better one exists.
  • Write down the pattern. Keep a short note: “two-sum: hash map”, “shortest steps: BFS”. These notes become your cheat sheet.
  • Solve it again a week later, without looking. If you can, you have learned it. If not, that is useful to know.
  • Test edge cases. Empty input, one item, duplicates, the biggest case.

You can run all your practice code in our free Python compiler. If you get stuck on an error, AI Assist works inside the Python notebook, so you can ask about it without leaving the page.

Common mistakes

  • Memorising solutions. You will forget them. Understand why each one works instead.
  • Skipping Big O. Without it you cannot tell a good solution from a merely working one.
  • Jumping to dynamic programming early. It builds on recursion, hash maps and arrays. Give those time first.
  • Only reading. DSA is a skill like typing or driving. You learn it by doing it.
  • Ignoring the built-ins. dict, set, deque, heapq, bisect and sorted already solve many problems. Know them before you write your own.
  • Never testing. A solution that passes the example and fails on an empty list is not finished.

After the roadmap

When the seven stages feel comfortable, mix them. Take problems you have not seen and decide the pattern yourself, then check it with the cheat sheet of patterns. Time-box yourself, as in a real interview. Keep going back to the Python details that trip people up, which are collected in 7 Python Gotchas That Trip Up Interviews.

If you want to use data as well as algorithms, SQL is the natural companion. Our roadmap for learning SQL follows the same step-by-step format as this one.

Frequently asked questions

How long does it take to learn DSA in Python?

It depends on your starting point and how often you practise. With regular practice, many people cover the fundamentals in a few months, and get more confident as they solve more problems. There is no fixed timeline.

What should I learn first in DSA?

Start with Big O notation and the built-in structures (lists, dictionaries, sets), then hash maps, two pointers and sliding window, then stacks and queues, and only then trees, graphs and dynamic programming.

Is Python good for learning DSA?

Yes. Python is short to write, so you can focus on the idea instead of the syntax, and it has strong built-ins such as dict, set, deque, heapq and bisect. Most interviews accept it.

Do I need to know DSA for every job?

No. It is most useful for software engineering interviews and for writing efficient programs. Many data and analyst roles use much less of it, though Big O thinking and hash maps still help everywhere.

How many problems do I need to solve?

The number matters less than how you practise. A modest set of problems per pattern, understood well and revisited after a week, teaches more than hundreds solved once and forgotten.

Should I memorise algorithms?

No. Understand the idea well enough to rebuild the algorithm on a blank page. Memorised code fades, but understanding a pattern stays with you.

Run this code in your browser

The free Upskly compiler runs Python with nothing to install. Paste the example, change it and see what happens.

Open Python Compiler

Stuck on a traceback?

AI Assist works inside the Python notebook, so you can ask about an error or a concept without leaving the cell.

Try AI Assist

Test yourself

Timed questions with an explanation for every answer.

Take the Quiz
Upskly AI Team
Learning made simple
Scroll to Top