Clarifying Questions and Edge Cases
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)The interviewer states the problem in one vague line, and the right answer depends on details you have not heard yet. They are checking whether you ask before you code, or confidently solve a slightly different problem.
The first two minutes: restate and confirm input and output
Restating is saying the problem back in your own words as a method signature with types, so a misunderstanding shows up before you write any code.
The first two minutes decide whether you solve the right problem. Example 1 turns a vague sentence into a signature, a written contract and agreed examples.
Example 1 · From a vague statement to a signature and agreed examples
public class RestateDemo { // Heard: "Return the topper from a list of marks." // Restated and agreed: marks has at least one value; return the INDEX of the // highest mark; on a tie, return the first such index. static int topperIndex(int[] marks) { int best = 0; for (int i = 1; i < marks.length; i++) { if (marks[i] > marks[best]) { best = i; } } return best; }
public static void main(String[] args) { System.out.println(topperIndex(new int[] {72, 95, 88}) + " (expected 1)"); System.out.println(topperIndex(new int[] {90, 90}) + " (expected 0, tie -> first)"); System.out.println(topperIndex(new int[] {50}) + " (expected 0, one student)"); }}1 (expected 1) 0 (expected 0, tie -> first) 0 (expected 0, one student)
What this code does
- The comments record the restated contract: index not mark, at least one value, first index on a tie. The strict
>in the code is that tie rule. - The agreed examples become test calls in
main, each printed next to its expected answer.
A good restatement names the input, the output and the tie rule: "I get an int[] marks with at least one value and return the index of the highest mark; on a tie, the first one?" Agree on two examples with exact answers, one of them tricky, and write them down. They become your test calls later.
Revise: Restate the problem and write examples (opens in a new tab)
Say these four things, in this order:
- The input type and shape: array, string, list, tree; sorted or not.
- The output exactly: value or index, count or list, and what to return if nothing is found.
- Two examples with their answers, one normal and one tricky.
- Only then, your approach.
Order of execution
Your first two minutes
Put the opening of a coding round in the order a strong candidate uses.
The standard clarifying questions
A clarifying question is a short question you ask before coding to remove doubt about the input, the output or the rules of the problem.
One statement can have two correct answers. Example 2 counts the unique words of the same sentence and gets 5 or 2, depending on two answers nobody asked for.
Example 2 · Why the questions matter: one statement, two answers
import java.util.HashSet;import java.util.Set;
public class AskFirstDemo { static int uniqueWords(String text, boolean ignoreCase, boolean stripPunctuation) { Set<String> seen = new HashSet<>(); for (String w : text.trim().split("\\s+")) { if (stripPunctuation) { w = w.replaceAll("[^A-Za-z0-9]", ""); } if (ignoreCase) { w = w.toLowerCase(); } if (!w.isEmpty()) { seen.add(w); } } return seen.size(); }
public static void main(String[] args) { String text = "Java java JAVA! Python, python"; System.out.println("Case-sensitive, keep punctuation: " + uniqueWords(text, false, false)); System.out.println("Ignore case, strip punctuation: " + uniqueWords(text, true, true)); }}Case-sensitive, keep punctuation: 5 Ignore case, strip punctuation: 2
What this code does
- "Count the unique words" gives 5 or 2 depending on two answers you might never think to ask: is it case-sensitive, and does punctuation count?
- Asking first, or stating your assumption, avoids writing a correct solution to the wrong problem.
Six questions cover most problems. Ask only the ones that change your solution, and keep each one short:
- Size: how large can n be? (10³ allows O(n²); 10⁵ or more needs O(n log n) or O(n).)
- Range: can values be negative or zero? How large? (Sums may need
long.) - Duplicates: can values repeat? What if the answer is ambiguous?
- Order: is the input sorted? May I modify or sort it?
- Nulls and empty: can the input be null or empty? What should I return?
- Output format: indices or values? Any order? One answer or all?
Size and range decide the time limit you must beat and whether int can overflow; duplicates, order and nulls decide the algorithm and the edge cases.
Revise: From constraints to complexity (opens in a new tab)
Listing edge cases before coding
An edge case is an input at the boundary of what is allowed: empty, one item, the largest value, or a case with no answer.
Under pressure, edge cases are the first thing people forget. Example 3 lists them before the code and then runs each one as a test.
Example 3 · Edge cases as ready-made tests
public class EdgeCaseTestsDemo { // Best Time to Buy and Sell Stock: one buy, one later sell; 0 if no profit. static int maxProfit(int[] prices) { int minSoFar = Integer.MAX_VALUE; int best = 0; for (int p : prices) { minSoFar = Math.min(minSoFar, p); best = Math.max(best, p - minSoFar); } return best; }
static void test(String name, int[] prices, int expected) { int actual = maxProfit(prices); System.out.println((actual == expected ? "PASS " : "FAIL ") + name + " -> " + actual); }
public static void main(String[] args) { test("normal", new int[] {7, 1, 5, 3, 6, 4}, 5); test("empty", new int[] {}, 0); test("one day", new int[] {5}, 0); test("only falling", new int[] {9, 7, 4, 1}, 0); test("all equal", new int[] {3, 3, 3}, 0); }}PASS normal -> 5 PASS empty -> 0 PASS one day -> 0 PASS only falling -> 0 PASS all equal -> 0
What this code does
- The edge-case list (empty, one item, falling prices, all equal) was written before coding, so the solution handles each by design:
beststarts at 0 and never goes negative. - Running the list at the end turns "I think it works" into evidence the interviewer can see.
Write the list before you code so the solution handles each case by design, not by luck, and so you own ready-made tests for the end. The usual list: empty input, a single element, all elements equal, sorted or reverse sorted, negatives and zero, very large values (overflow), duplicates, and "no answer exists". For strings add spaces, upper and lower case and repeated characters.
Find the bug
Which edge case breaks it?
Each method works on the normal example. Click the line that fails on an edge case.
Largest mark. It fails when every mark is negative.
Round 1 of 2Worked example: two sum
An assumption is the choice you state aloud when the interviewer leaves a detail open, ideally written as a comment at the top of your code.
Two Sum has five details to settle before coding. Example 4 puts every agreed answer into the code and prints the result for each case.
Example 4 · Two sum with every clarification in the code
import java.util.Arrays;import java.util.HashMap;import java.util.Map;
public class TwoSumDemo { // Agreed: return the two indices in increasing order; empty array if no pair; // one element cannot be used twice; values may be negative or repeated. static int[] twoSum(int[] nums, int target) { Map<Integer, Integer> seen = new HashMap<>(); for (int i = 0; i < nums.length; i++) { Integer j = seen.get(target - nums[i]); // look up BEFORE inserting if (j != null) { return new int[] {j, i}; } seen.put(nums[i], i); } return new int[0]; }
public static void main(String[] args) { System.out.println(Arrays.toString(twoSum(new int[] {2, 7, 11, 15}, 9))); System.out.println(Arrays.toString(twoSum(new int[] {3, 3}, 6))); System.out.println(Arrays.toString(twoSum(new int[] {-3, 4, 3, 90}, 0))); System.out.println(Arrays.toString(twoSum(new int[] {3, 5}, 6))); System.out.println(Arrays.toString(twoSum(new int[] {}, 1))); }}[0, 1] [0, 1] [0, 2] [] []
What this code does
- Looking up before inserting means
[3, 5]with target 6 cannot pair 3 with itself, while[3, 3]correctly pairs two different indices. - Negatives work because the map stores any int, and the agreed "no pair" answer is an empty array rather than null or an exception.
Two Sum: "given an array and a target, find two numbers that add up to the target". Good questions: return indices or values? Exactly one answer, or possibly none? Can the same element be used twice? Negatives? Duplicates like [3, 3] with target 6?
Say the agreed answers aloud: "return the two indices in increasing order, an empty array if there is no pair, and never use one element twice". Each answer shows up in the code: the map stores indices, the lookup happens before inserting the current element, and the not-found case returns new int[0].
Predict the output
Lookup before or after insert?
Both loops look for a partner for each number, target 6. Predict what each loop prints.
Round 1 of 2
Look up first, then insert (the agreed order). What prints?
Worked example: longest substring without repeating characters
Case, spaces and the empty string all change the answer here. Example 5 prints the agreed result for seven inputs, each one a clarified rule.
Example 5 · Longest substring without repeating characters
import java.util.HashMap;import java.util.Map;
public class LongestUniqueDemo { // Agreed: contiguous substring, case-sensitive, every character counts, "" -> 0. static int longestUnique(String s) { Map<Character, Integer> lastSeen = new HashMap<>(); int start = 0; int best = 0; for (int end = 0; end < s.length(); end++) { char c = s.charAt(end); Integer prev = lastSeen.get(c); if (prev != null && prev >= start) { start = prev + 1; // jump past the earlier copy } lastSeen.put(c, end); best = Math.max(best, end - start + 1); } return best; }
public static void main(String[] args) { String[] tests = {"abcabcbb", "bbbbb", "pwwkew", "", " ", "aAbB", "abba"}; for (String t : tests) { System.out.println("\"" + t + "\" -> " + longestUnique(t)); } }}"abcabcbb" -> 3 "bbbbb" -> 1 "pwwkew" -> 3 "" -> 0 " " -> 1 "aAbB" -> 4 "abba" -> 2
What this code does
- The answers to the clarifying questions are test cases:
"aAbB"is 4 because the search is case-sensitive, and" "is 1 because a space counts. "abba"checks theprev >= startcondition: the secondawas last seen before the window started, so the window must not move back.
Longest Substring Without Repeating Characters: "return the length of the longest substring with all distinct characters". Ask: substring (contiguous) or subsequence? Is it case-sensitive, so are a and A different? Do spaces and digits count? What is the answer for an empty string?
With the answers "contiguous, case-sensitive, every character counts, empty gives 0", the edge-case list writes itself: "", " ", "bbbbb", "aAbB" and "abba", where the repeated a lies outside the current window.
Next step
Check your understanding
12 quick questions