Skip to content

Volume ITechnology

4.0.0 — The Five Moves Behind Every Classic Problem ​

"Reverse a number." "Is this string a palindrome?" "Find the second largest element." "Sort this array without using sort()." These questions open the coding round at most start-ups and service companies. They look like thirty different puzzles. They are really five small moves, used again and again in different orders.

This page teaches the five moves once, slowly. Every page after it in 4.0 uses them by name, so when you see "this is the digit loop again", you already know the loop.

Move 1 — The digit loop: peel a number one digit at a time ​

Take the number 4721. Two Python operators split it apart.

  • n % 10 is the remainder after dividing by 10. That is always the last digit. 4721 % 10 is 1.
  • n // 10 is whole-number division. It throws away the last digit. 4721 // 10 is 472.

Why does this work? Our numbers are written in base 10. Each place is worth ten times the place to its right. So 4721 means 4 \times 1000 + 7 \times 100 + 2 \times 10 + 1. Every part except the final 1 is a multiple of 10. Dividing by 10 leaves exactly that 1 over as the remainder.

Repeat the two steps until the number becomes 0, and you visit every digit from right to left.

python
n = 4721
while n > 0:          # (1)
    digit = n % 10    # (2)
    print(digit)      # prints 1, then 2, then 7, then 4
    n = n // 10       # (3)

(1) Keep going while there are digits left. When n reaches 0, every digit has been removed.

(2) Read the last digit.

(3) Remove the last digit. The number gets one digit shorter each time round.

The loop runs once per digit. A number n has about \log_{10} n digits, so the loop costs O(\log n) steps. A billion has only 10 digits, so this is very fast.

Watch out: if n is 0 at the start, the loop never runs. A question like "count the digits of 0" must answer 1, so it needs a special case. Negative numbers also need care, because -4721 % 10 is 9 in Python, not 1. Strip the sign first with abs(n).

Move 2 — The counter: how many of each ​

Many questions ask "which character appears most", "which element repeats", or "do these two strings use the same letters". Every one of them needs a count of each value. A dictionary stores that. The value is the key, and its count is what the key points to.

python
word = "banana"
counts = {}
for ch in word:
    counts[ch] = counts.get(ch, 0) + 1   # (1)
print(counts)   # → {'b': 1, 'a': 3, 'n': 2}

(1) counts.get(ch, 0) reads the current count. If ch is not in the dictionary yet, it gives 0 instead of crashing. We add 1 and store it back.

Python also ships this exact tool as collections.Counter. Counter("banana") builds the same table in one line. Interviewers at service companies often ask you to write the loop by hand first. Then they let you use Counter. So know both.

A dictionary lookup takes about the same short time no matter how big the dictionary gets. Chapter 4.3 explains why. So counting n items costs O(n).

Move 3 — The swap: exchange two values ​

Sorting, reversing and rotating all move values around in place. The basic step is swapping two positions.

python
a, b = 5, 9
a, b = b, a
print(a, b)   # → 9 5

Python first builds the pair (b, a) on the right side, which is (9, 5). Only then does it unpack that pair into a and b. Because the right side is fully built before anything is assigned, neither value is lost. In most other languages you need a third variable to hold one value while you overwrite it. 4.0.1 shows that version and the famous trick that avoids the third variable.

Swapping two items inside a list works the same way: arr[i], arr[j] = arr[j], arr[i].

Move 4 — Two indexes walking towards each other ​

To reverse a list, check a palindrome, or split values into groups, put one index at the start and one at the end. Do something with the pair. Then move both inward.

python
arr = [1, 2, 3, 4, 5]
left, right = 0, len(arr) - 1
while left < right:                                   # (1)
    arr[left], arr[right] = arr[right], arr[left]     # (2)
    left += 1
    right -= 1
print(arr)   # → [5, 4, 3, 2, 1]

(1) Stop when the two indexes meet or cross. At that point every pair has been handled. If the length is odd, the middle element pairs with itself and stays where it is.

(2) Do the work for this pair. Here, swap.

Each step handles two elements, so the loop runs n/2 times. That is O(n) time, and no extra list is needed, so O(1) extra memory. This is the same "two pointers" idea that gets a whole chapter later, in 4.5.

Move 5 — Recursion: solve a smaller copy of the same problem ​

Some problems contain a smaller version of themselves. The factorial of 5 is 5 \times the factorial of 4. A function can call itself to solve the smaller copy.

python
def factorial(n: int) -> int:
    if n <= 1:                      # (1)
        return 1
    return n * factorial(n - 1)     # (2)

print(factorial(5))   # → 120

(1) The base case. This is the smallest version, answered directly, with no further call. Without it the function would call itself forever. Python would stop it after about 1,000 calls with a RecursionError.

(2) The recursive case. Trust that factorial(n - 1) returns the right answer. Use it to build the answer for n.

Every call waits for the one below it to finish. Python keeps all the waiting calls on the call stack, a pile of unfinished function calls. So recursion uses O(\text{depth}) memory even when the code has no list in it. That hidden cost is a favourite interview question.

How the pages after this one are laid out ​

The simplest problems get a short page. The problem, the code, a few lines on why it works, and the cost. As problems need more thought, the pages slow down. Every line is walked through, a small table traces the code by hand, and the cost is worked out step by step.

The order runs from numbers, to patterns, to strings, to arrays, to the seven sorting algorithms taught in every college course, and ends with the Tower of Hanoi. Each page ends with the questions an interviewer asks after you have solved it.

Next: 4.0.1 Swap Two Variables Without a Third. It is the most common warm-up question, and it shows how numbers can be combined and split apart again.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet