What problem solving really means
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A coding problem is a puzzle that gives you starting data and asks you to produce an answer while following strict rules. Problem solving is the thinking you do on paper before your fingers ever touch the keyboard.
What a coding problem asks: input, output, and rules
Problem solving is the process of turning a problem statement into a correct, efficient program: understand the input and output, find a method that works, then write and test the code.
Long problem descriptions often wrap a simple question inside a story about warehouses, games, or bank accounts. Your first job is to strip away the story and find three facts.
Example 1 · Stripping a story down to input, output, and rules
public class StripTheStoryDemo { // Story: "A weather station logs hourly readings. Count how many hours // were strictly warmer than the safety limit. If no readings exist, return 0." // // Input : int[] readings, int limit // Output: int (count of readings > limit) // Rules : strictly greater (> not >=); empty array returns 0 public static int countAboveLimit(int[] readings, int limit) { if (readings == null || readings.length == 0) { return 0; } int count = 0; for (int temp : readings) { if (temp > limit) { count++; } } return count; }
public static void main(String[] args) { int[] morningTemps = {28, 35, 40, 35, 42}; System.out.println("Above 35: " + countAboveLimit(morningTemps, 35)); System.out.println("Empty : " + countAboveLimit(new int[]{}, 35)); }}Above 35: 2 Empty : 0
What this code does
- Writing the input, output, and rules as a short comment header keeps the exact requirements in front of you.
- Because the rule says 'strictly warmer',
35is not counted when the limit is35; only40and42qualify.
Input is the data your method receives, such as an int[] array of prices or a String of characters. Output is the exact answer your method must return or print. Rules (often called constraints) tell you what values are allowed, how large the input can grow, and how special cases must behave.
Ask these questions about every problem: Input: What types and parameters come into the method? Output: What type and value must come out? Rules: Can the array be empty? Are numbers negative? How many elements can there be? Time and space complexity: A measure of how run time and memory usage grow as the input gets larger.
Why typing code first usually fails
When beginners see a new question, they often start typing a for loop immediately. Halfway through the loop, they notice a case they forgot, so they bolt on an extra if statement. Two minutes later, a sample test fails, and they add another flag variable.
Example 2 · Why typing first fails: the max-temperature trap
public class TypingFirstTrapDemo { // Rush-and-type version: assumes 0 is a safe starting maximum public static int rushedMax(int[] temps) { int max = 0; // Bug: fails when all temperatures are negative! for (int t : temps) { if (t > max) { max = t; } } return max; }
// Planned version: starts from the first element after checking for empty input public static int plannedMax(int[] temps) { if (temps == null || temps.length == 0) { throw new IllegalArgumentException("temps must not be empty"); } int max = temps[0]; for (int i = 1; i < temps.length; i++) { if (temps[i] > max) { max = temps[i]; } } return max; }
public static void main(String[] args) { int[] winterTemps = {-12, -5, -8, -20}; System.out.println("Rushed max : " + rushedMax(winterTemps)); System.out.println("Planned max: " + plannedMax(winterTemps)); }}Rushed max : 0 Planned max: -5
What this code does
rushedMaxinitializesmax = 0without checking whether numbers can be negative, so it returns0—a number that isn't even in the array.plannedMaxchecks the empty-array rule first and initializesmaxtotemps[0], returning the true maximum-5.
This rush-and-patch habit usually produces tangled code that even the author cannot explain. Spending three calm minutes planning on paper usually saves twenty minutes of blind debugging.
Three reasons to plan first: Typing first locks you into your very first guess, even when a simpler idea exists. Fixing bugs by guessing i + 1 or i - 1 often breaks another test case. In interviews, typing silently without a plan makes it hard for the interviewer to help you.
The five-step routine used in this section
Instead of staring at a blank editor or guessing code, you will use a repeatable five-step routine on every problem in this course. Each step answers one clear question before you move to the next.
- Restate and make examples: Say the problem in one sentence and work out 2–3 small examples by hand.
- Start with brute force: State the simplest working idea first and explain why it might be slow on huge inputs.
- Dry run on paper: Trace your idea step by step on a small example before writing Java code.
- Check edge cases: Test empty inputs, single elements, duplicates, negatives, and extreme limits.
- Improve and code: Remove repeated work to reach a faster solution, then write clean Java code and test it.
Example 3 · The five-step routine in action: first duplicate badge ID
import java.util.HashSet;import java.util.Set;
public class FiveStepRoutineDemo { // Step 2 (Brute force): for each badge, scan earlier badges to see if it appeared before. // Time complexity: O(n^2) comparisons in the worst case. Extra space: O(1). public static int firstDuplicateBruteForce(int[] badges) { for (int i = 0; i < badges.length; i++) { for (int j = 0; j < i; j++) { if (badges[j] == badges[i]) { return badges[i]; } } } return -1; }
// Step 5 (Improved): remember seen badges in a HashSet so each check is O(1) on average. // Time complexity: O(n) on average. Extra space: O(n) for the set. public static int firstDuplicateOptimal(int[] badges) { Set<Integer> seen = new HashSet<>(); for (int badge : badges) { if (!seen.add(badge)) { return badge; } } return -1; }
public static void main(String[] args) { int[] swipeLog = {104, 205, 309, 205, 104}; int[] allUnique = {11, 22, 33};
System.out.println("Brute force duplicate: " + firstDuplicateBruteForce(swipeLog)); System.out.println("Optimal duplicate : " + firstDuplicateOptimal(swipeLog)); System.out.println("No duplicate case : " + firstDuplicateOptimal(allUnique)); }}Brute force duplicate: 205 Optimal duplicate : 205 No duplicate case : -1
What this code does
- Note why
{104, 205, 309, 205, 104}returns205and not104: as we scan left to right, the second205at index 3 is completed before the second104at index 4. seen.add(badge)returnsfalseas soon asbadgeis already in the set, giving a single-pass solution.
A brute-force solution is a straightforward approach that checks every possible option directly. A dry run is a hand trace on paper where you follow variables line by line on a small input. An edge case is an unusual or extreme input—such as an empty array, a single item, or negative numbers—that still obeys the rules.
Order of execution
Put the routine in order
Tap the five steps in the order you use them on a new problem.
Where the same routine shows up at work: bug fixes and new features
This five-step routine is not just for coding tests. Software engineers use the exact same thinking every day when fixing production bugs and building new features.
Example 4 · At work: using the routine to fix a checkout coupon bug
public class CheckoutBugFixDemo { // Bug report: "Applying a $50 coupon to a $30 cart charged the customer -$20!" // // Step 1 (Restate): Final payable amount is subtotal minus discount, but never below 0. // Step 4 (Edge cases): discount == 0, discount == subtotal, discount > subtotal. public static int calculatePayableCents(int subtotalCents, int discountCents) { if (subtotalCents < 0 || discountCents < 0) { throw new IllegalArgumentException("Amounts cannot be negative"); } int rawTotal = subtotalCents - discountCents; return Math.max(0, rawTotal); }
public static void main(String[] args) { System.out.println("Normal order : " + calculatePayableCents(5000, 1500)); System.out.println("Exact coupon : " + calculatePayableCents(3000, 3000)); System.out.println("Oversized coup: " + calculatePayableCents(3000, 5000)); }}Normal order : 3500 Exact coupon : 0 Oversized coup: 0
What this code does
- By listing the edge case
discountCents > subtotalCentsbefore coding, we clamp the payable amount at0usingMath.max(0, rawTotal). - Checking negative inputs upfront stops corrupted data from silently producing wrong totals.
When a bug report arrives, you restate what went wrong, build a tiny input that triggers the bug, dry run the code to see where the variable went wrong, check edge cases like null or 0, and write a clean fix. When building a new feature, you agree on the input and output first, build a simple working version, check whether it handles large customer lists, and test boundary cases before opening a pull request.
Examples from daily work: Bug fix Step 1: Turn a vague ticket ('checkout crashed') into a tiny input that reproduces the failure. Bug fix Step 3: Trace the exact values of variables rather than changing lines at random. New feature Step 4: Check what happens when a new user has zero orders or a power user has 50,000 orders.
Next step
Check your understanding
10 quick questions