Restate the problem and make examples
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Many wrong solutions happen not because the coder forgot Java syntax, but because they solved a slightly different problem than the one asked. Restating the problem in one sentence and writing three small examples by hand makes sure you solve the right question on the first try.
Restating a problem in your own words
A test example is a small input with its expected output, worked out by hand before coding. Good examples include normal, smallest and tricky cases.
Problem statements often hide a two-line rule inside three paragraphs of story. Before you think about loops or collections, rewrite the prompt in a single sentence using your own words.
A reliable template is: "Given [input], return [output] where [rule], or [fallback] if no answer exists." If you have to copy phrases directly from the prompt without knowing what they mean, pause and re-read the sample test case.
- Wordy prompt: 'A delivery van visits stops with package weights. Find the heaviest weight that appears at least twice, or -1.'
- One-sentence restatement: 'Given an int[] of weights, return the largest number that appears 2 or more times, or -1 if all numbers are unique.'
- Notice how 'delivery van' and 'stops' disappear, leaving only the exact data and rule.
Writing small examples by hand
Sample inputs in coding questions are often too simple to show tricky rules, or too long to trace quickly. You should always write three small examples of your own—each with 3 to 5 elements so you can work out the answer by hand in seconds.
- Example 1 (Normal / happy path):
[4, 7, 2, 7, 5]->7repeats, so return7. - Example 2 (Tricky / gray area):
[3, 8, 3, 8, 8]-> both3and8repeat; largest is8. - Example 3 (No match / boundary):
[10, 20, 30]-> nothing repeats, so return-1.
Example 1 · Restating a prompt and testing three hand-made examples
import java.util.HashMap;import java.util.Map;
public class RestateAndExamplesDemo { // Restatement: Given an int[] weights, return the largest value that appears // at least twice, or -1 if every value appears at most once. public static int largestRepeating(int[] weights) { Map<Integer, Integer> counts = new HashMap<>(); for (int w : weights) { counts.put(w, counts.getOrDefault(w, 0) + 1); } int best = -1; for (Map.Entry<Integer, Integer> entry : counts.entrySet()) { if (entry.getValue() >= 2 && entry.getKey() > best) { best = entry.getKey(); } } return best; }
public static void main(String[] args) { // 1. Normal example System.out.println("Normal : " + largestRepeating(new int[]{4, 7, 2, 7, 5})); // 2. Tricky example (two values repeat: 3 and 8) System.out.println("Tricky : " + largestRepeating(new int[]{3, 8, 3, 8, 8})); // 3. No-match example System.out.println("No match: " + largestRepeating(new int[]{10, 20, 30})); }}Normal : 7 Tricky : 8 No match: -1
What this code does
- Writing the three examples in
mainturns our hand traces into instant checks for the method. - The tricky example
{3, 8, 3, 8, 8}verifies that we return the largest repeating value (8), not merely the first repeating value (3).
A happy-path example is a normal input where the answer is obvious. A tricky example is an input designed to test a gray area, such as a tie between two numbers or reusing the same element twice. A no-answer example tests what your method should return when nothing matches.
Finding hidden questions: sorted? duplicates? value range?
While working out your three examples by hand, you will naturally bump into details the problem story did not mention clearly. Catching these hidden questions early saves you from rewriting your whole method later.
Example 2 · Why the 'same index twice' question changes the code
public class SameIndexQuestionDemo { // Buggy version: forgets to check i != j, so it pairs an element with itself! public static boolean hasPairSumSelfAllowed(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = 0; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return true; } } } return false; }
// Clarified version: two DISTINCT indices i and j (j starts at i + 1) public static boolean hasPairSumDistinctIndices(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return true; } } } return false; }
public static void main(String[] args) { int[] tricky = {5, 2, 9}; System.out.println("Self allowed (wrong) : " + hasPairSumSelfAllowed(tricky, 10)); System.out.println("Distinct indices (ok): " + hasPairSumDistinctIndices(tricky, 10)); }}Self allowed (wrong) : true Distinct indices (ok): false
What this code does
- On
{5, 2, 9}with target10, there is only one5. Pairing index0with index0falsely gives5 + 5 = 10. - Starting the inner loop at
j = i + 1ensures we only pair two distinct positions.
Example 3 · How tie-breaking rules change the answer
import java.util.HashMap;import java.util.Map;
public class TieBreakingRuleDemo { // Rule A: Return the most frequent number; on a tie, return the SMALLER number. public static int mostFrequentSmallerTie(int[] nums) { Map<Integer, Integer> counts = new HashMap<>(); for (int n : nums) { counts.put(n, counts.getOrDefault(n, 0) + 1); } int bestNum = nums[0]; int bestCount = 0; for (Map.Entry<Integer, Integer> e : counts.entrySet()) { int num = e.getKey(); int count = e.getValue(); if (count > bestCount || (count == bestCount && num < bestNum)) { bestCount = count; bestNum = num; } } return bestNum; }
// Rule B: Return the most frequent number; on a tie, return the FIRST one in the array. public static int mostFrequentFirstSeenTie(int[] nums) { Map<Integer, Integer> counts = new HashMap<>(); for (int n : nums) { counts.put(n, counts.getOrDefault(n, 0) + 1); } int bestNum = nums[0]; int bestCount = 0; for (int n : nums) { int count = counts.get(n); if (count > bestCount) { bestCount = count; bestNum = n; } } return bestNum; }
public static void main(String[] args) { int[] tied = {9, 4, 9, 4}; System.out.println("Tie -> smaller value: " + mostFrequentSmallerTie(tied)); System.out.println("Tie -> first in array: " + mostFrequentFirstSeenTie(tied)); }}Tie -> smaller value: 4 Tie -> first in array: 9
What this code does
- In
{9, 4, 9, 4}, both9and4appear twice. Without a clear tie-breaking rule, two coders will return different answers. - Notice that iterating over
HashMap.entrySet()does not preserve array order, so Rule B loops over the originalnumsarray in index order.
Example 4 · Checking the value-range rule: when int overflows
public class ValueRangeOverflowDemo { // If constraints say each price can be up to 1,500,000,000, // adding two prices in a 32-bit int overflows (> 2,147,483,647). public static int wrongSumInt(int a, int b) { return a + b; }
public static long safeSumLong(int a, int b) { return (long) a + b; }
public static void main(String[] args) { int itemA = 1_500_000_000; int itemB = 1_500_000_000; System.out.println("int sum (overflow): " + wrongSumInt(itemA, itemB)); System.out.println("long sum (correct): " + safeSumLong(itemA, itemB)); }}int sum (overflow): -1294967296 long sum (correct): 3000000000
What this code does
- In Java 17,
intholds at most2,147,483,647(Integer.MAX_VALUE, roughly 2 × 10⁹). - Checking the value range during Step 1 tells you right away when totals or products must use
long.
Check four things on every array or string problem: sort order (is the input already sorted?), duplicates (can values repeat, and can we use the same index twice?), value range (can numbers be negative, zero, or large enough to overflow a 32-bit int?), and tie-breaking (if two answers tie, do we return the first index, the last index, or the smaller value?).
Typical hidden questions: Sorted? If an array is already sorted, a problem is often much easier than on an unsorted array. Same index twice? For target sum 10 on [5, 2], does 5 + 5 count, or must the two indices differ? Value range? Adding two int values near 2,000,000,000 overflows int and requires long. Tie-breaker? In 'most frequent number', what if 4 and 9 both appear 3 times?
Predict the output
Which pairs count?
Read each program and pick what it prints.
Round 1 of 3
Count pairs of different positions whose prices add up to 10.
Asking clarifying questions the way interviews expect
In live coding interviews, interviewers often leave one or two rules unspoken on purpose. They want to see whether you rush ahead on assumptions or pause to clarify requirements like a careful engineer.
Ask short, specific questions that can be answered in one sentence. Instead of asking 'Can you explain the problem again?', offer two concrete options or a small example and ask which result is expected.
- Weak question: 'What are the edge cases here?' (Asks the interviewer to do your job.)
- Strong question: 'If two numbers tie for the highest frequency, should I return the smaller number or the one that appeared first?'
- Strong question: 'Can the input array contain negative numbers or be empty, and if it is empty, should I return -1?'
- In an online test where you cannot ask a person, check the 'Constraints' box at the bottom of the prompt—it answers these exact questions.
Next step
Check your understanding
10 quick questions