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

Common Python Programming Problems

Learning objectives
  • After this chapter you can solve FizzBuzz, palindrome, prime and Fibonacci problems from scratch.
  • You can count words and characters with dictionaries and Counter.
  • You can detect anagrams and duplicates using sorting and sets.
  • You can flatten nested lists and find the second largest value.
  • You can explain the idea behind each solution before writing code.

Many beginner and interview tasks are small, well-known problems. They look simple, but they test whether you can break a task into steps, pick a fitting data structure and handle edge cases such as empty input.

In this chapter you will meet the problems that appear most often. Each one has a plain-English plan, a short solution and a checked output. Read the plan first and try to write the code yourself before reading the answer.

All code uses Python 3.10 or newer and only the standard library. The goal is not to memorise answers but to learn the patterns, because the same few patterns solve hundreds of problems.

A method for any small problem

Before writing code, follow four steps. First, restate the problem in your own words. Second, write one or two tiny examples with the answer you expect. Third, decide on the steps in plain language. Fourth, write the code and test it on your examples, including an empty input or a single item. This habit prevents most mistakes and also impresses interviewers, because it shows how you think.

FizzBuzz and number checks

FizzBuzz prints numbers from 1 to a limit, but writes Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both. The trick is to test the combined case first, because a multiple of 15 is also a multiple of 3 and 5. The remainder operator % tells you if a number divides evenly.

Example 1: FizzBuzz up to 15
for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

A prime number is greater than 1 and has no divisors except 1 and itself. You only need to test divisors up to the square root of the number, because a larger divisor would pair with a smaller one you already checked. Factorial and Fibonacci are the other two favourites: factorial multiplies all whole numbers up to n, and each Fibonacci number is the sum of the previous two.

Example 2: prime, factorial and Fibonacci
def is_prime(n):
    if n < 2:
        return False
    d = 2
    while d * d <= n:
        if n % d == 0:
            return False
        d += 1
    return True

def factorial(n):
    result = 1
    for k in range(2, n + 1):
        result *= k
    return result

def fibonacci(count):
    a, b = 0, 1
    items = []
    for _ in range(count):
        items.append(a)
        a, b = b, a + b
    return items

print([n for n in range(1, 21) if is_prime(n)])
print(factorial(5))
print(fibonacci(10))
[2, 3, 5, 7, 11, 13, 17, 19] 120 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Notice that Fibonacci uses a loop with two variables instead of recursion. The simple recursive version repeats the same work many times and becomes very slow for large inputs, so the loop is the better answer in an interview unless you add caching.

Strings: palindromes, anagrams and counting

A palindrome reads the same forwards and backwards. To check one, make the text lowercase, keep only letters and digits, and compare it with its reverse. Slicing with [::-1] reverses a string. Two words are anagrams if they use the same letters in any order. Sorting the letters of both words and comparing the results is the shortest correct solution. For counting, a dictionary or collections.Counter stores how many times each item appears.

Example 3: palindrome, anagram and word count
from collections import Counter

def is_palindrome(text):
    cleaned = [c.lower() for c in text if c.isalnum()]
    return cleaned == cleaned[::-1]

def is_anagram(a, b):
    return sorted(a.lower()) == sorted(b.lower())

print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_anagram("Listen", "Silent"))

text = "the cat and the hat and the bat"
counts = Counter(text.split())
print(counts.most_common(2))
True True [('the', 3), ('and', 2)]

The word count result lists the most frequent words. When two words have the same count, most_common keeps the order in which they were first seen, so the output is stable. Counting characters works the same way: pass the string itself to Counter.

Lists: duplicates, second largest and flattening

To remove duplicates while keeping the original order, loop through the items and remember what you have seen in a set. Using set(items) alone loses the order. To find the second largest value, remove duplicates first, because the largest number may appear twice. To flatten a list of lists, a nested comprehension is clear and short; for lists nested to any depth, use a recursive function.

Example 4: unique, second largest and flatten
def unique(items):
    seen = set()
    result = []
    for x in items:
        if x not in seen:
            seen.add(x)
            result.append(x)
    return result

def second_largest(nums):
    distinct = sorted(set(nums))
    return distinct[-2] if len(distinct) >= 2 else None

def flatten(items):
    flat = []
    for x in items:
        if isinstance(x, list):
            flat.extend(flatten(x))
        else:
            flat.append(x)
    return flat

print(unique([3, 1, 3, 2, 1]))
print(second_largest([5, 9, 9, 7]))
print(flatten([1, [2, [3, 4]], 5]))
[3, 1, 2] 7 [1, 2, 3, 4, 5]

Reading input and simple searching

Many tasks read numbers from the user. Use input(), split the text, and convert each part with int(). Another classic is finding two numbers that add up to a target. Checking every pair works but is slow. A faster way is to keep a dictionary of the numbers you have already seen and look for the missing partner in one step.

Example 5: sum of numbers read from input
line = input()
numbers = [int(part) for part in line.split()]
print(sum(numbers), max(numbers))
43 16
Example 6: two numbers that add up to a target
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        need = target - n
        if need in seen:
            return (seen[need], i)
        seen[n] = i
    return None

print(two_sum([2, 7, 11, 15], 9))
print(two_sum([1, 2], 10))
(0, 1) None
Always test the edge cases: an empty list, one element, negative numbers and repeated values. Most hidden bugs live there.

Python syntax

Syntax
for n in range(1, limit + 1):
    ...
Syntax
text[::-1]
Syntax
sorted(a) == sorted(b)
Syntax
Counter(items).most_common(k)

Real-world applications

  • Coding interviews and online judges use these problems as warm-ups.
  • Text cleaning and word statistics rely on counting and palindromes-style checks.
  • Removing duplicates is needed when cleaning data lists.
  • Prime and factorial ideas appear in simple security and maths tools.

Common mistakes

Mistake: Checking n % 3 before n % 15 in FizzBuzz, so FizzBuzz is never printed.
Fix: Test the combined condition first.
Mistake: Using set() to remove duplicates and expecting the order to stay the same.
Fix: Use a seen set while building a new list, or dict.fromkeys(items).
Mistake: Comparing a palindrome without removing spaces, punctuation and capital letters.
Fix: Clean the text first, then compare with its reverse.
Mistake: Finding the second largest by sorting and taking [-2] when the largest value repeats.
Fix: Remove duplicates before sorting.
Mistake: Forgetting that 1 is not prime.
Fix: Return False for any number below 2.

Important tips

  • Write two examples before the code.
  • Prefer a loop over naive recursion for Fibonacci.
  • Use Counter for any counting task.
  • Test with empty and single-item input.

Key points summary

  • Check the most specific condition first in an if/elif chain.
  • Slicing [::-1] reverses a string or list.
  • Sorted letters identify anagrams.
  • A set remembers items already seen, in constant time.
  • A dictionary makes pair searches fast.

Exam and interview points

  • Order of conditions matters in if/elif chains.
  • range(1, n + 1) includes n.
  • sorted() returns a new list and does not change the original.
  • Counter.most_common(k) returns a list of (item, count) pairs.
  • Two-sum with a dictionary runs in linear time.

Quick revision

  • FizzBuzz: test % 15 first.
  • Palindrome: clean, then compare with reverse.
  • Anagram: compare sorted letters.
  • Unique in order: seen set plus result list.
  • Two-sum: dictionary of values seen.

Frequently asked questions

What is the fastest way to check if a number is prime?

For interview-size numbers, test divisors up to the square root. For very large numbers, special tests exist, but they are rarely needed.

Why is recursive Fibonacci slow?

It recalculates the same values again and again, so the time grows very quickly. A loop or caching with functools.cache fixes this.

How do I reverse a string in Python?

Use slicing: text[::-1]. Strings are immutable, so this builds a new string.

How can I count letters in a word?

Use collections.Counter(word), or build a dictionary with a loop and dict.get(letter, 0) + 1.

Should I memorise these solutions?

No. Learn the pattern behind each, such as a seen set or a counter, and you can rebuild the code when needed.

Practise this chapter

18 practice questions Take the chapter quiz

Related chapters