Problem Solving

How to Solve Coding Problems: a 5-Step Method With 4 Worked Problems

Read, work examples by hand, brute force, test, improve. Four problems solved step by step in Python and Java, with the traps that catch beginners.

Modern Age Coders Team
Modern Age Coders Team November 15, 2026
16 min read
How to solve coding problems: read, examples by hand, brute force, test and improve, shown as five steps beside a code window

To solve a coding problem, do five things in order: read it until you can say the input, the output and the rules in your own words; work two or three examples by hand; write the simplest brute-force solution that is obviously correct; test it on normal and awkward inputs; and only then improve it. Most beginners jump straight to typing, which is why they get stuck.

Below, the method is worked on four real problems, each solved in Python and in Java, with the first attempt, the trap it fell into and the improved version. Every program was run, and the output under it is what it printed. The last sections cover how to get faster and the mistakes that cost the most marks in tests and interviews.

If you are new to the idea of a method for problems in general, start with our guide to improving problem solving skills. This page is the coding version, in detail.

The 5-step method for coding problems

  1. Read. Rewrite the problem in your own words: what comes in, what must come out, what rules apply. Circle every word that limits the answer: "later", "exactly", "ignore case", "return None if".
  2. Examples by hand. Take the given example and one you make up, and solve them with a pen. If you cannot solve it by hand, you cannot tell a computer how to. Add one awkward example: empty input, one item, all the same, all negative.
  3. Brute force. Write the most obvious solution, even if it is slow. Try every pair, check every position. Its job is to be clearly right, so you have something to compare against.
  4. Test. Run it on your hand-worked examples and the awkward ones. Write down what you expect before you run it. A surprise is information.
  5. Improve. Ask what work the brute force repeats. Can you remember something instead of recomputing it? Then check the faster version gives the same answers as the slow one on every test.
The five steps for solving coding problems: read, examples by hand, brute force, test and improve, with what to write down at each step
Each step produces something you write down. If a step produced nothing, you skipped it.
💡

Write the expected output first

Before you press run, write what you expect to see. If you cannot predict it, you do not understand your own code yet, and that is the thing to fix, not the code.

Problem 1: two songs that fill a gap exactly

The problem (ours): a school assembly has a 7-minute gap, 420 seconds. Given a list of song lengths in seconds, find two different songs that add up to exactly 420. Return their positions, or nothing if no pair works.

Read: input is a list of whole numbers and a target. Output is two positions or nothing. The word that matters is different: one 210-second song cannot be used twice.

By hand with [185, 240, 200, 215, 180]: 185 needs 235 (not there), 240 needs 180 (there, at position 4). Answer: positions 1 and 4. Awkward cases: [210, 100] has no answer; [210, 210] does, using two different songs; an empty list has none.

Brute force, then improve. The brute force tries every pair. The improvement notices that for each song we only need to know whether its partner (420 minus its length) has already appeared, and a dictionary answers that in one step.

# Problem 1: a 7-minute gap (420 seconds) in a school assembly.
# Which two songs fill it exactly? Return their positions, or None.
def pair_brute(lengths, target):
    for i in range(len(lengths)):
        for j in range(i + 1, len(lengths)):
            if lengths[i] + lengths[j] == target:
                return (i, j)
    return None

def pair_fast(lengths, target):
    seen = {}                           # length -> position
    for j, length in enumerate(lengths):
        need = target - length
        if need in seen:
            return (seen[need], j)
        seen[length] = j
    return None

songs = [185, 240, 200, 215, 180]
for f in (pair_brute, pair_fast):
    print(f.__name__, f(songs, 420), f([210, 100], 420), f([210, 210], 420), f([], 420))

Output:

pair_brute (1, 4) None (0, 1) None
pair_fast (1, 4) None (0, 1) None

Both versions agree on every test, which is the point of keeping the brute force. Note the order inside pair_fast: it checks for the partner before storing the current song. Swap those two lines and [210, 100] would pair the 210 with itself. That is the "different" word from the reading step, turned into code. The same idea in Java:

import java.util.*;

public class SongPair {
    // Problem 1 in Java: positions of two songs that add up to the gap.
    static int[] pairFast(int[] lengths, int target) {
        Map<Integer, Integer> seen = new HashMap<>();   // length -> position
        for (int j = 0; j < lengths.length; j++) {
            int need = target - lengths[j];
            if (seen.containsKey(need)) {
                return new int[] { seen.get(need), j };
            }
            seen.put(lengths[j], j);
        }
        return null;
    }

    public static void main(String[] args) {
        int[] songs = { 185, 240, 200, 215, 180 };
        System.out.println(Arrays.toString(pairFast(songs, 420)));
        System.out.println(Arrays.toString(pairFast(new int[] { 210, 100 }, 420)));
        System.out.println(Arrays.toString(pairFast(new int[] { 210, 210 }, 420)));
    }
}

Output:

[1, 4]
null
[0, 1]

Problem 2: a palindrome that ignores spaces and capitals

The problem: decide whether a phrase reads the same forwards and backwards if you ignore spaces, punctuation and capital letters.

Read: the rules are the whole problem here. "Ignore spaces, punctuation and capitals" is three rules, and each one needs a test. By hand: "Never odd or even" becomes neveroddoreven, which reverses to itself. Awkward case: the empty string, which counts as a palindrome (there is nothing that fails to match).

The first try below is the one most beginners write. It passes "racecar" and so looks right, until a test with capitals or spaces arrives.

# Problem 2: is a phrase a palindrome if we ignore spaces, punctuation
# and capital letters?
def is_pal_first_try(s):
    return s == s[::-1]

def is_pal(s):
    letters = [c.lower() for c in s if c.isalnum()]
    i, j = 0, len(letters) - 1
    while i < j:
        if letters[i] != letters[j]:
            return False
        i += 1
        j -= 1
    return True

for s in ["racecar", "Never odd or even", "Was it a car or a cat I saw?", "coding", ""]:
    print(f"{s!r:32} first try: {is_pal_first_try(s)!s:5}  fixed: {is_pal(s)}")

Output:

'racecar'                        first try: True   fixed: True
'Never odd or even'              first try: False  fixed: True
'Was it a car or a cat I saw?'   first try: False  fixed: True
'coding'                         first try: False  fixed: False
''                               first try: True   fixed: True

The fixed version keeps only letters and digits, lowers them, and walks two pointers in from both ends. In Java you can skip the extra list entirely by moving the pointers past anything that is not a letter or digit:

public class Palindrome {
    // Problem 2 in Java: two pointers that skip anything not a letter or digit.
    static boolean isPal(String s) {
        int i = 0, j = s.length() - 1;
        while (i < j) {
            char a = s.charAt(i), b = s.charAt(j);
            if (!Character.isLetterOrDigit(a)) { i++; continue; }
            if (!Character.isLetterOrDigit(b)) { j--; continue; }
            if (Character.toLowerCase(a) != Character.toLowerCase(b)) return false;
            i++;
            j--;
        }
        return true;
    }

    public static void main(String[] args) {
        String[] tests = { "racecar", "Never odd or even", "Was it a car or a cat I saw?", "coding", "" };
        for (String t : tests) {
            System.out.println("\"" + t + "\" -> " + isPal(t));
        }
    }
}

Output:

"racecar" -> true
"Never odd or even" -> true
"Was it a car or a cat I saw?" -> true
"coding" -> false
"" -> true

Problem 3: the first letter that appears only once

The problem: given a word, return the first character that appears exactly once, or nothing if there is none.

By hand with "swiss": s appears three times, w once. So w. With "aabb" every letter repeats, so nothing. The word first matters: we need the original order, not alphabetical order.

The brute force calls count() for each letter, which walks the whole word every time. The improvement counts every letter once, then walks the word a second time in order.

# Problem 3: the first letter in a word that appears only once.
def first_unique_brute(s):
    for c in s:
        if s.count(c) == 1:            # count() walks the whole string each time
            return c
    return None

def first_unique(s):
    counts = {}
    for c in s:                         # pass 1: count everything
        counts[c] = counts.get(c, 0) + 1
    for c in s:                         # pass 2: keep the original order
        if counts[c] == 1:
            return c
    return None

for w in ["swiss", "programming", "aabb", "x"]:
    print(w, first_unique_brute(w), first_unique(w))

Output:

swiss w w
programming p p
aabb None None
x x x
import java.util.*;

public class FirstUnique {
    // Problem 3 in Java: count first, then walk the word again in order.
    static Character firstUnique(String s) {
        Map<Character, Integer> counts = new HashMap<>();
        for (char c : s.toCharArray()) {
            counts.put(c, counts.getOrDefault(c, 0) + 1);
        }
        for (char c : s.toCharArray()) {
            if (counts.get(c) == 1) return c;
        }
        return null;
    }

    public static void main(String[] args) {
        for (String w : new String[] { "swiss", "programming", "aabb", "x" }) {
            System.out.println(w + " -> " + firstUnique(w));
        }
    }
}

Output:

swiss -> w
programming -> p
aabb -> null
x -> x

A pattern worth noticing: problems 1 and 3 were both made faster by a dictionary (a HashMap in Java). "Have I seen this before?" and "how many times?" are questions a dictionary answers instantly. Recognising that shape is most of what people mean by getting faster.

Problem 4: the biggest rise in temperature

The problem: given a week of daily temperatures, find the biggest rise from an earlier day to a later day. If temperatures only ever fall, the answer is 0.

By hand with [21, 18, 24, 19, 27, 22, 20]: the coldest day so far before the 27 is 18, so the rise is 9. With [30, 28, 25, 22] there is no rise at all, so 0.

This problem has a famous trap: "biggest minus smallest". It looks right on the first test and is wrong on the second, because the smallest value can come after the biggest.

# Problem 4: daily temperatures for a week. What is the biggest rise from
# an earlier day to a LATER day? If it only ever falls, the answer is 0.
def biggest_rise_brute(temps):
    best = 0
    for i in range(len(temps)):
        for j in range(i + 1, len(temps)):
            best = max(best, temps[j] - temps[i])
    return best

def biggest_rise(temps):
    best = 0
    lowest = float("inf")               # coldest day seen SO FAR
    for t in temps:
        best = max(best, t - lowest)
        lowest = min(lowest, t)
    return best

def wrong_rise(temps):                  # the classic trap: max minus min
    return max(temps) - min(temps)

tests = [[21, 18, 24, 19, 27, 22, 20], [30, 28, 25, 22], [19, 19, 19], [12]]
for t in tests:
    print(t, biggest_rise_brute(t), biggest_rise(t), "trap says", wrong_rise(t))

Output:

[21, 18, 24, 19, 27, 22, 20] 9 9 trap says 9
[30, 28, 25, 22] 0 0 trap says 8
[19, 19, 19] 0 0 trap says 0
[12] 0 0 trap says 0

The trap gives 9 on the first test, matching the right answer by luck, and 8 on the falling week, where the correct answer is 0. This is why you test more than one example. The improved version walks once, remembering the coldest day seen so far. In Java:

import java.util.*;

public class BiggestRise {
    // Problem 4 in Java: one pass, remembering the coldest day so far.
    static int biggestRise(int[] temps) {
        int best = 0;
        int lowest = Integer.MAX_VALUE;
        for (int t : temps) {
            if (lowest != Integer.MAX_VALUE) best = Math.max(best, t - lowest);
            lowest = Math.min(lowest, t);
        }
        return best;
    }

    public static void main(String[] args) {
        int[][] tests = { { 21, 18, 24, 19, 27, 22, 20 }, { 30, 28, 25, 22 }, { 19, 19, 19 }, { 12 } };
        for (int[] t : tests) {
            System.out.println(Arrays.toString(t) + " -> " + biggestRise(t));
        }
    }
}

Output:

[21, 18, 24, 19, 27, 22, 20] -> 9
[30, 28, 25, 22] -> 0
[19, 19, 19] -> 0
[12] -> 0
The temperature problem: a falling week where biggest minus smallest gives 8 but the correct answer is 0, because the coldest day comes after the warmest
One extra test case caught the trap. The answer has to respect the word "later".

How to solve coding problems faster

Getting faster is not about typing. It comes from two things: recognising a problem's shape quickly, and choosing an approach that does less work. The second one you can measure. Here is how many checks the brute force and the improved version of problem 1 make as the list grows:

# Why "improve" matters: count the checks each version makes on a
# list where no pair works (the worst case for both).
def brute_checks(n):
    checks = 0
    for i in range(n):
        for j in range(i + 1, n):
            checks += 1
    return checks

def fast_checks(n):
    return n                       # one dictionary look-up per item

for n in (10, 100, 1000, 10000):
    print(f"n = {n:>5}: brute force {brute_checks(n):>10,} checks, improved {fast_checks(n):>6,}")

Output:

n =    10: brute force         45 checks, improved     10
n =   100: brute force      4,950 checks, improved    100
n =  1000: brute force    499,500 checks, improved  1,000
n = 10000: brute force 49,995,000 checks, improved 10,000

At 10 songs nobody would notice. At 10,000 the brute force makes nearly five thousand times as many checks. This is what Big O notation describes, and it is why the improve step exists. But notice the order: you only improve something that already works and has tests.

  • Keep a pattern list. After each problem, write one line: "seen-before question, use a dictionary", "later than, track the best so far". Re-read it weekly.
  • Solve the same problem twice. A week later, solve it again from a blank file. If you cannot, you understood the solution but did not learn to solve it.
  • Time-box being stuck. Twenty minutes stuck, then look at one hint only, not the whole answer.
  • Practise small and daily. One problem a day beats ten on a Sunday.

How to solve coding problems in Python and in Java

The method is the same in both languages; the habits differ a little.

Python Java
Fast first draft Very fast: lists, dictionaries and loops in few lines Slower: types and class wrapper, but the compiler catches mistakes early
Dictionary dict, with get(key, 0) HashMap, with getOrDefault(key, 0)
Watch out for Changing a list while looping over it; mutable default arguments == on Strings; integer division; array index past the end
Good for Beginners, maths and data problems, quick experiments School exams (ICSE, ISC, AP CSA), larger structured programs

If you are studying Java for school, our Java array programs for beginners are good practice for the brute-force step, and Python for beginners covers the basics these examples use.

Common traps when solving coding problems

These cost the most marks in tests and interviews. Three of them in one Java program, with the real output:

public class Traps {
    public static void main(String[] args) {
        // Trap 1: integer division throws away the fraction.
        int total = 7, count = 2;
        System.out.println("7 / 2 = " + (total / count));
        System.out.println("7 / 2.0 = " + (total / (double) count));

        // Trap 2: == compares whether two Strings are the same object, not their text.
        String typed = new String("yes");
        System.out.println("typed == \"yes\": " + (typed == "yes"));
        System.out.println("typed.equals(\"yes\"): " + typed.equals("yes"));

        // Trap 3: off by one. Valid positions in an array of 5 are 0 to 4.
        int[] marks = { 40, 55, 70, 85, 90 };
        try {
            for (int i = 0; i <= marks.length; i++) {
                System.out.print(marks[i] + " ");
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("\ncrashed: " + e.getMessage());
        }
    }
}

Output:

7 / 2 = 3
7 / 2.0 = 3.5
typed == "yes": false
typed.equals("yes"): true
40 55 70 85 90 
crashed: Index 5 out of bounds for length 5
  • Integer division: 7 / 2 is 3 in Java (and 7 // 2 is 3 in Python). Convert one side to a decimal when you need the fraction.
  • Comparing Strings with ==: in Java it asks whether they are the same object, not the same text. Use equals.
  • Off by one: an array of 5 has positions 0 to 4. A loop with <= runs once too many.
  • Ignoring a word in the statement: "later", "different", "ignore case". Every limiting word needs a test.
  • Testing only the given example: it is the one example the problem setter knew would work. Add empty, single, equal and falling cases.
  • Optimising first: a fast wrong answer is still wrong. Brute force first, then improve with the brute force as your check.

When something does go wrong, our page on how to debug code shows how to find the cause by searching instead of guessing.

Should beginners use AI to solve coding problems?

Use AI after you have tried, not before, and use it to explain rather than to answer. A good pattern: write your own brute force, then ask an assistant why your improved version fails one test, and make the fix yourself. If an AI tool hands you the full solution, you have practised reading, not solving. That gap is why some learners can follow every solution but cannot start their own.

⚠️

AI tools have age rules

Check the vendor's age rule before a young learner uses any AI tool. Most chat assistants require users to be at least 13. ChatGPT's terms ask for a parent's or guardian's permission for anyone under 18, and Claude is for adults (18 and over) only. Under-13s should build these skills with puzzles, Scratch and Python, without a chatbot account. Our guide to teaching kids AI at home covers safe options by age.

How we teach it

The principles on our how we teach page are this method in a classroom: students explain their thinking before they type, we trace a loop line by line until they can predict every step, learners derive a rule themselves before they see it, we solve the same problem three ways (just as each problem here has a brute force and an improvement), and mistakes are data. You can see it in the problem solving and algorithms course for teens, Python for teens and Java for teens. The first class is free.

Frequently asked questions

Pick easy problems and use the same five steps every time: read and restate the problem, work two examples by hand, write a simple brute-force solution, test it on normal and awkward inputs, then improve. Do one a day rather than many at once.

Work a small example by hand first. The steps your hand takes are the algorithm. If you still cannot see it, try an even smaller example, or ask which problem you have solved before looks most like this one.

Learn to recognise common shapes (seen-before questions use a dictionary, best-so-far questions use one pass), keep a written list of patterns, and re-solve old problems from a blank file. Speed comes from recognition, not typing.

Either works because the method is the same. Python is quicker for a first draft; Java is common in school exams and catches type mistakes early. Use the language your course or exam uses.

Go back to an example by hand and write each step down. If you are still stuck after about twenty minutes, look at one hint, not the whole solution, and then close it and try again.

No. It is the right first solution, because it is easy to check. You keep it as a reference and use it to test the faster version.

One or two done properly, with your own tests and a one-line note of the pattern, is better than many copied answers.

Yes, after a real attempt. Then close it and solve the problem again from a blank file a day later. If you can, you have learned it.

Modern Age Coders Team

About Modern Age Coders Team

Expert educators making coding and maths clear for ages 6 to 67.

Keep exploring Modern Age Coders

More from the blog

Learn more

Free resources

From the blog

Start here

Ask Misti AI
Chat with us
Enroll Watch Class Priority Demo Enrol Book a Demo Watch Class WhatsApp Book demo today