Intermediate   Chapter 192 · 30 min read · Module 15: Career and Interview Preparation

Problem-Solving Techniques

Learning objectives
  • After this chapter you can restate a problem in your own words and list its inputs, outputs and edge cases.
  • You can break a large problem into small steps and write them as plain-language pseudocode.
  • You can use proven techniques such as working by hand, simplifying, using a dictionary or set, and two pointers.
  • You can test your solution with normal, edge and tricky inputs, and improve it afterwards.

Writing Python code is only half of programming. The other half is deciding what the code should do. Many beginners know loops, lists and functions, but freeze when they see a new problem. This is normal. Problem solving is a separate skill, and like any skill it can be learned with a method and a lot of practice.

In this chapter you will learn a simple method that works for small exercises and for large projects. You will first understand the problem, then plan it in plain words, then solve a tiny example by hand, and only then write code. After the code works, you test it with tricky inputs and make it cleaner.

We will also look at a few techniques that appear again and again: breaking a problem into parts, using a dictionary to count or look up things, using a set to remove duplicates, and moving two pointers through a list. Every code example here was run, so you can trust the outputs.

Why a method helps

When you start typing code before you understand the task, you often write something that almost works. Then you spend a long time patching it. A method saves this time. It gives you a fixed list of questions to ask, so you are never staring at a blank screen wondering what to do first.

Algorithm: a clear, step-by-step list of instructions that solves a problem and always finishes

The six steps

  1. Understand: read the problem twice. Say it in your own words. Write down the input, the output and one or two examples.
  2. Plan: write the steps in plain language (pseudocode). Do not worry about Python syntax yet.
  3. Break down: split a big step into smaller steps until each one is easy.
  4. Solve by hand: take a small example and work it out on paper. Notice exactly what you do.
  5. Code: turn your notes into Python, one small part at a time.
  6. Test and improve: run normal inputs, edge cases and wrong inputs. Then make the code shorter or faster if needed.

Step 4 is the one most beginners skip, and it is the most useful. If you cannot solve a small example by hand, you cannot tell the computer how to do it. If you can, then your hand steps are almost your program.

Example: find the largest number

Problem: given a list of numbers, return the largest one without using max(). By hand, you look at the first number and call it the best so far. Then you look at each next number. If it is bigger than the best, it becomes the new best. At the end, the best is the answer. Those words are the plan, and the code follows them one by one.

Example 1: largest number by hand-written plan
def largest(numbers):
    best = numbers[0]
    for n in numbers[1:]:
        if n > best:
            best = n
    return best

print(largest([4, 9, 2, 7]))
print(largest([-5, -2, -9]))
print(largest([3]))
9 -2 3

Notice the tests. The second call uses only negative numbers, which shows why we start with numbers[0] and not with 0. The third call has a single item, which is an edge case. An empty list would crash with IndexError, so a real program must decide what to do in that case: raise a clear error, or return None.

Break a big problem into small functions

Suppose you must print the average of the even numbers in a list. That sounds like one task, but it is really two: pick the even numbers, then compute an average. Give each part its own function. Small functions are easy to name, easy to test and easy to reuse.

Example 2: split the task into two functions
def only_even(values):
    return [v for v in values if v % 2 == 0]

def average(values):
    if not values:
        return 0
    return sum(values) / len(values)

data = [1, 2, 3, 4, 5, 6]
evens = only_even(data)
print(evens)
print(average(evens))
print(average([]))
[2, 4, 6] 4.0 0

Use the right data structure

Many problems become easy when you pick a good container. A dictionary is perfect for counting and for fast lookups. A set is perfect for removing duplicates and checking membership. A list is best when order matters. Before you write nested loops, ask yourself whether a dictionary or set could do the job in one pass.

Example 3: count letters with a dictionary
text = 'banana'
counts = {}
for ch in text:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)

first_unique = None
for ch in text:
    if counts[ch] == 1:
        first_unique = ch
        break
print(first_unique)
{'b': 1, 'a': 3, 'n': 2} b
Python dictionaries keep insertion order (guaranteed since Python 3.7), so the output above is always the same. Sets do not promise an order, so sort them before printing.

Two pointers technique

Some problems on sorted lists or strings can be solved by keeping two positions, one at the start and one at the end, and moving them toward each other. For example, to check if a word is a palindrome you compare the left and right letters, then step inward. You never need a reversed copy, and the loop stops as soon as a pair does not match.

Example 4: palindrome check with two pointers
def is_palindrome(word):
    left, right = 0, len(word) - 1
    while left < right:
        if word[left] != word[right]:
            return False
        left += 1
        right -= 1
    return True

print(is_palindrome('level'))
print(is_palindrome('python'))
print(is_palindrome(''))
True False True

When you are stuck

  • Solve a simpler version first, for example with a smaller list or without the special rule.
  • Draw the data: write the list on paper and move a finger along it.
  • Print intermediate values to see what your code really does.
  • Explain the problem aloud to a friend or a rubber duck. Saying it often reveals the gap.
  • Take a short break. Your brain keeps working on the problem in the background.

Test like a detective

After the code runs on the example from the problem, try to break it. Test the smallest input (empty list, single item), the largest sensible input, repeated values, negative numbers and wrong types. A solution is finished only when you know what it does in all of these cases, even if the answer is a clear error message.

Test typeExample for a function on lists
Normal[4, 9, 2, 7]
Edge[] or [3]
Duplicates[5, 5, 5]
Negative[-5, -2, -9]
Largelist(range(100000))

Python syntax

Syntax
# plan in comments first
# 1. read input
# 2. process
# 3. return result
def solve(data):
    result = None
    return result
Syntax
counts = {}
for item in items:
    counts[item] = counts.get(item, 0) + 1
Syntax
left, right = 0, len(seq) - 1
while left < right:
    left += 1
    right -= 1

Real-world applications

  • Coding interviews, where explaining your plan matters as much as the final code.
  • Debugging real bugs by shrinking them to the smallest failing example.
  • Planning features in team projects by splitting them into small tasks.
  • Competitive programming and online practice sites.

Common mistakes

Mistake: Starting to code before understanding the problem
Fix: Restate the task, write one example input and output first.
Mistake: Forgetting edge cases such as an empty list or a single item
Fix: Make a short checklist of edge cases and test each one.
Mistake: Starting a maximum search with 0 instead of the first item
Fix: Use the first element as the starting best value so negative numbers work.
Mistake: Writing one giant function that does everything
Fix: Split the work into small named functions that each do one job.
Mistake: Changing code randomly until the output looks right
Fix: Print intermediate values and find the exact step that goes wrong.

Important tips

  • Write the plan as comments, then put code under each comment.
  • Use meaningful names like best and counts, not a and b.
  • Always keep one tiny test example at hand.
  • Make it work first, then make it fast.
  • Read your code aloud; unclear parts often show up.

Key points summary

  • Problem solving is a skill with steps: understand, plan, break down, solve by hand, code, test.
  • Hand-solving a small example turns into your algorithm.
  • Dictionaries count and look up; sets remove duplicates; two pointers scan from both ends.
  • Edge cases decide whether a solution is really correct.
  • Small functions make big problems manageable.

Exam and interview points

  • An algorithm must be finite, clear and produce the correct output.
  • Edge cases: empty input, one item, duplicates, negatives.
  • Dictionary lookup is on average O(1); searching a list is O(n).
  • Two pointers on a sorted sequence often turns O(n squared) into O(n).
  • Decomposition means splitting a problem into smaller sub-problems.

Quick revision

  • Understand, plan, break down, hand-solve, code, test.
  • Start best-so-far values from the first item.
  • Count with dict.get(key, 0) + 1.
  • Test empty, single, duplicate and negative inputs.
  • Small functions, clear names.

Frequently asked questions

What should I do if I have no idea how to start?

Write down the input and output of one small example, then solve it by hand. Describe each action you take. Those actions are the beginning of your algorithm.

Is it cheating to search for hints?

Looking up a concept such as how a dictionary works is fine. Try hard on your own first, and after reading a solution, close it and rewrite it from memory so you really learn it.

How do I know if my solution is good enough?

It must be correct for normal and edge cases, easy to read, and fast enough for the input size you expect. Only optimise further when you have a real speed problem.

Why write pseudocode?

Pseudocode lets you think about logic without worrying about syntax. It is easier to fix a plan than to fix a tangled program.

Practise this chapter

16 practice questions Take the chapter quiz

Related chapters