Practice: the full routine
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Knowing the five steps in theory is different from using them under a timer when a blank editor is staring back at you. Turning the five-step routine into a quick comment block at the top of your method makes the habit automatic.
Writing the plan as comments first
Whenever you open a new coding problem, your first keystrokes should be five comment lines: // 1. Restate, // 2. Examples, // 3. Brute force, // 4. Edge cases, and // 5. Optimal plan. Filling in those five lines takes about two minutes.
static int countEven(int[] nums) { // 1. Restate: given int[] nums, return how many values are even, or 0 if empty. // 2. Examples: [2, 5, 8] -> 2 | [-4, 0] -> 2 | [1, 3] -> 0 // 3. Brute force: one loop testing x % 2 == 0 -> O(n) time, O(1) space. // 4. Edge cases: empty array, negatives (-4 % 2 == 0), zero. // 5. Optimal: the single loop is already optimal -> O(n) time, O(1) space. int count = 0; for (int x : nums) { if (x % 2 == 0) count++; } return count;}Once those comments are on screen, writing the Java code is just translating your own plain-English notes line by line. Better yet, if you are in a live interview, the interviewer can read your comment plan as you type and confirm you are on the right track before you spend ten minutes coding.
- // 1. Restate: Given [input], return [output] where [rule], or [fallback].
- // 2. Examples: normal [...], tricky [...], no-match [...].
- // 3. Brute force: [loop idea] -> Time: O(...), Space: O(...). Repeated work: [...].
- // 4. Edge cases: empty, 1 element, all duplicates, negatives/zeros, max int.
- // 5. Optimal: [faster idea] -> Time: O(...), Space: O(...).
A self-check rubric
When you practice alone, it is easy to see green test results and move on even if you skipped planning and got lucky. Use this five-point self-check rubric to score every problem you solve.
A rubric is a simple scorecard with clear criteria. Give yourself 1 point for each item below; aim for at least 4 out of 5 before you call a practice problem finished.
- Point 1 (Restate & Examples): Did I write a one-sentence restatement and 3 small examples (normal, tricky, no-match) before coding?
- Point 2 (Brute Force & Cost): Can I state the brute-force approach, its time complexity, and the exact repeated work?
- Point 3 (Dry Run): Did I trace at least one 3-to-4 element example through my logic using a variable table?
- Point 4 (Edge Cases): Does my code handle empty/minimum sizes, duplicates, negatives, and
longoverflow cleanly? - Point 5 (Optimal & Clean Code): Does my final code match the target complexity with clear variable names and no dead patches?
Five problems solved end to end (Problems 1–3: running state)
The first three problems each replace a repeated scan with one running variable, so every one runs in O(n) time and O(1) space.
Example 1 · End-to-end Problem 1: Second smallest distinct value
public class EndToEndProblem1 { // 1. Restate: Return the 2nd smallest distinct int as a long, or Long.MAX_VALUE if none. // 2. Examples: [7, 2, 5, 2] -> 5 | [4, 4, 4] -> Long.MAX_VALUE | [9] -> Long.MAX_VALUE // 3. Brute force: sort copy and scan past duplicates -> O(n log n) time, O(n) space. // 4. Edge cases: length < 2, all duplicates, Integer.MAX_VALUE in input. // 5. Optimal: track `first` and `second` in a single pass -> O(n) time, O(1) space. public static long secondSmallestDistinct(int[] nums) { if (nums == null || nums.length < 2) { return Long.MAX_VALUE; } long first = Long.MAX_VALUE; long second = Long.MAX_VALUE; for (int n : nums) { if (n < first) { second = first; first = n; } else if (n > first && n < second) { second = n; } } return second; }
public static void main(String[] args) { System.out.println("Normal + dup min: " + secondSmallestDistinct(new int[]{7, 2, 5, 2})); System.out.println("All equal : " + secondSmallestDistinct(new int[]{4, 4, 4})); System.out.println("With MAX_VALUE : " + secondSmallestDistinct(new int[]{1, Integer.MAX_VALUE})); }}Normal + dup min: 5 All equal : 9223372036854775807 With MAX_VALUE : 2147483647
What this code does
- Using
longsentinels (Long.MAX_VALUE) ensures that even if the second smallest value innumsisInteger.MAX_VALUE, it does not collide with our sentinel. - The
else if (n > first && n < second)branch ignores duplicate copies offirst. - Problem: return the second-smallest distinct value (1 ≤ n ≤ 10⁵). Brute force sorts a copy in O(n log n); the optimal pass tracks
firstandsecondin O(n). - Tricky case:
[2, 2, 5]must skip the duplicate minimum 2 and return 5.
Example 2 · End-to-end Problem 2: Best single stock trade
public class EndToEndProblem2 { // 1. Restate: Given int[] prices, return max(prices[j] - prices[i]) for j > i, or 0. // 2. Examples: [7, 1, 5, 3, 6, 4] -> 5 | [9, 6, 3] -> 0 | [5] -> 0 // 3. Brute force: check all pairs (i, j) -> O(n^2) time, O(1) space. // 4. Edge cases: empty, 1 day, strictly decreasing prices. // 5. Optimal: track `minBuy` seen so far -> O(n) time, O(1) space. public static int maxStockProfit(int[] prices) { if (prices == null || prices.length < 2) { return 0; } int minBuy = prices[0]; int bestProfit = 0; for (int i = 1; i < prices.length; i++) { int profitToday = prices[i] - minBuy; if (profitToday > bestProfit) { bestProfit = profitToday; } if (prices[i] < minBuy) { minBuy = prices[i]; } } return bestProfit; }
public static void main(String[] args) { System.out.println("Normal : " + maxStockProfit(new int[]{7, 1, 5, 3, 6, 4})); System.out.println("Decreasing : " + maxStockProfit(new int[]{9, 6, 3, 1})); System.out.println("Single day : " + maxStockProfit(new int[]{10})); }}Normal : 5 Decreasing : 0 Single day : 0
What this code does
- At each day
i, the best buy day beforeiis simply the lowest price in0..i-1, whichminBuytracks in O(1) space. - Initializing
bestProfit = 0ensures we return0when every possible trade loses money. - Problem: the best profit
prices[j] - prices[i]withj > i, or 0 (1 ≤ n ≤ 10⁵). Brute force checks all pairs in O(n²); the optimal pass tracksminBuyin O(n). - Tricky case:
[9, 6, 3, 1]has only falling prices, so the answer is 0, not a negative loss.
Example 3 · End-to-end Problem 3: Maximum adjacent pair sum with negative and large values
public class EndToEndProblem3 { // 1. Restate: Given int[] nums (len >= 2), return max(nums[i] + nums[i+1]) as a long. // 2. Examples: [3, 8, 1, 9] -> 11 | [-10, -20, -5] -> -25 | [2e9, 2e9] -> 4e9 // 3. Brute force / Optimal: single pass over i = 0..n-2 -> O(n) time, O(1) space. // 4. Edge cases: all negatives (don't init best = 0!), large ints (cast to long!). public static long maxAdjacentPairSum(int[] nums) { if (nums == null || nums.length < 2) { throw new IllegalArgumentException("Need at least 2 elements"); } long best = (long) nums[0] + nums[1]; for (int i = 1; i < nums.length - 1; i++) { long pairSum = (long) nums[i] + nums[i + 1]; if (pairSum > best) { best = pairSum; } } return best; }
public static void main(String[] args) { System.out.println("Normal : " + maxAdjacentPairSum(new int[]{3, 8, 1, 9})); System.out.println("Negatives : " + maxAdjacentPairSum(new int[]{-10, -20, -5})); System.out.println("Large ints: " + maxAdjacentPairSum(new int[]{2_000_000_000, 2_000_000_000})); }}Normal : 11 Negatives : -25 Large ints: 4000000000
What this code does
- Initializing
best = (long) nums[0] + nums[1]handles all-negative arrays like{-10, -20, -5}(best = -25). - Casting
nums[i]tolongbefore adding prevents 32-bit overflow when elements are near 2 × 10⁹. - Problem: the largest sum
nums[i] + nums[i + 1]as alongin one O(n) pass (2 ≤ n ≤ 10⁵). - Tricky case:
[-10, -20, -5]has only negative sums, sobestmust start from the first real sum, never 0.
Problem 1 tracks first and second, Problem 2 tracks minBuy, and Problem 3 tracks the best sum so far. In each case the brute force asks the same question again and again, and the running variable carries the answer forward.
Five problems solved end to end (Problems 4–5: hashing and frequency)
Our fourth and fifth end-to-end problems trade O(n) extra memory in a HashMap or HashSet to drop O(n²) nested scans down to O(n) average time.
Example 4 · End-to-end Problem 4: First non-repeating number
import java.util.HashMap;import java.util.Map;
public class EndToEndProblem4 { // 1. Restate: Return the first element in array order with frequency == 1, or -1. // 2. Examples: [9, 4, 9, 6, 7, 4] -> 6 | [5, 5] -> -1 | [] -> -1 // 3. Brute force: for each i, scan all j != i -> O(n^2) time, O(1) space. // 4. Edge cases: empty array, all duplicates, single element. // 5. Optimal: two passes with HashMap frequency table -> O(n) time, O(n) space. public static int firstNonRepeating(int[] nums) { if (nums == null || nums.length == 0) { return -1; } Map<Integer, Integer> freq = new HashMap<>(); for (int n : nums) { freq.put(n, freq.getOrDefault(n, 0) + 1); } for (int n : nums) { if (freq.get(n) == 1) { return n; } } return -1; }
public static void main(String[] args) { System.out.println("Normal : " + firstNonRepeating(new int[]{9, 4, 9, 6, 7, 4})); System.out.println("All dups : " + firstNonRepeating(new int[]{5, 5, 2, 2})); System.out.println("Single : " + firstNonRepeating(new int[]{42})); }}Normal : 6 All dups : -1 Single : 42
What this code does
- Pass 1 builds the counts in O(n) average time; Pass 2 walks
numsfrom left to right and returns the first number whose count is1. - Two sequential O(n) loops still take O(n + n) = O(n) total time—far faster than a nested O(n²) loop.
- Tricky case: scan
nums, notmap.keySet(), in pass 2, so the original left-to-right order is kept.
Example 5 · End-to-end Problem 5: Missing number in 1..n
public class EndToEndProblem5 { // 1. Restate: Given n - 1 distinct ints from 1..n, return the single missing int. // 2. Examples: n=5, [1, 2, 4, 5] -> 3 | n=2, [2] -> 1 | n=2, [1] -> 2 // 3. Brute force: for v=1..n, scan array -> O(n^2) time, O(1) space. // 4. Edge cases: missing 1, missing n, n = 100,000 (n*(n+1)/2 overflows int!). // 5. Optimal: expectedSum - actualSum using long -> O(n) time, O(1) space. public static int findMissingNumber(int[] nums, int n) { long expectedSum = (long) n * (n + 1) / 2; long actualSum = 0L; for (int x : nums) { actualSum += x; } return (int) (expectedSum - actualSum); }
public static void main(String[] args) { System.out.println("Missing middle: " + findMissingNumber(new int[]{1, 2, 4, 5}, 5)); System.out.println("Missing 1 : " + findMissingNumber(new int[]{2, 3}, 3)); System.out.println("Missing n : " + findMissingNumber(new int[]{1, 2}, 3)); }}Missing middle: 3 Missing 1 : 1 Missing n : 3
What this code does
- The sum of
1 + 2 + ... + nis n(n + 1) / 2. Subtracting the sum of the n - 1 present numbers leaves the exact missing number. - Using
(long) n * (n + 1) / 2avoids 32-bit overflow when n = 100,000. - Tricky case:
(long) n * (n + 1) / 2is computed inlong, because for n = 100,000 the sum is about 5 × 10⁹ and overflowsint.
Problem 4 — First Non-Repeating Number: Given int[] nums (0 ≤ n ≤ 10⁵), return the first element (in left-to-right array order) that appears exactly once, or -1 if every element repeats. Brute force rescans the whole array for each index in O(n²); optimal counts frequencies in a HashMap and scans nums a second time in O(n). Problem 5 — Missing Number in 1..n: Given int[] nums containing n - 1 distinct integers from the range 1..n (2 ≤ n ≤ 10⁵), return the single missing number. Brute force checks each number from 1..n by scanning the array (O(n²)); using a HashSet takes O(n) time and O(n) space, and using the long expected sum n(n+1)/2 minus the actual sum takes O(n) time and O(1) space!
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Problem 1 — Majority Element Check
Statement: Given an integer array nums of length n and a candidate integer, return true if candidate appears strictly more than n / 2 times in nums, and false otherwise.
Constraints: 0 <= nums.length <= 100,000, -10^9 <= nums[i], candidate <= 10^9.
Sample I/O: nums = [3, 3, 4, 2, 3, 3, 3], candidate = 3 -> true (5 > 7 / 2); nums = [1, 2, 1, 2], candidate = 1 -> false (2 is not > 2); nums = [], candidate = 1 -> false.
public class MajorityCheckPractice { // 1. Restate: Return true if candidate count > nums.length / 2. // 2. Examples: [3,3,4,2,3,3,3], 3 -> true | [1,2,1,2], 1 -> false | [], 1 -> false // 3. Plan: single O(n) pass counting occurrences of candidate, O(1) space. public static boolean isMajorityElement(int[] nums, int candidate) { // Write your solution here return false; }
public static void main(String[] args) { System.out.println(isMajorityElement(new int[]{3, 3, 4, 2, 3, 3, 3}, 3)); System.out.println(isMajorityElement(new int[]{1, 2, 1, 2}, 1)); System.out.println(isMajorityElement(new int[]{}, 1)); }}true false false
Exercise 2· Easy
Problem 2 — Maximum Consecutive Ones
Statement: Given a binary array bits containing only 0s and 1s, return the maximum number of consecutive 1s in the array.
Constraints: 0 <= bits.length <= 100,000, bits[i] is 0 or 1.
Sample I/O: [1, 1, 0, 1, 1, 1] -> 3; [0, 0, 0] -> 0; [] -> 0.
public class MaxConsecutiveOnesPractice { // 1. Restate: Return the length of the longest contiguous streak of 1s. // 2. Brute force: check every subarray [start..end] in O(n^2). // 3. Optimal: maintain currentStreak and maxStreak in O(n) time, O(1) space. public static int maxConsecutiveOnes(int[] bits) { // Write your solution here return 0; }
public static void main(String[] args) { System.out.println(maxConsecutiveOnes(new int[]{1, 1, 0, 1, 1, 1})); System.out.println(maxConsecutiveOnes(new int[]{0, 0, 0})); System.out.println(maxConsecutiveOnes(new int[]{})); }}3 0 0
Exercise 3· Medium
Problem 3 — First Repeating Element by Earliest Second Appearance
Statement: Given an int[] nums, return the first value that completes a duplicate appearance as you scan from left to right, or -1 if all elements are distinct.
Constraints: 0 <= nums.length <= 100,000, -10^9 <= nums[i] <= 10^9.
Sample I/O: [10, 5, 3, 4, 3, 5, 6] -> 3 (because the second 3 at index 4 appears before the second 5 at index 5); [1, 2, 3] -> -1.
import java.util.HashSet;import java.util.Set;
public class FirstCompletedDuplicatePractice { // 1. Restate: Scan left to right; return the first value already seen earlier, or -1. // 2. Optimal: HashSet<Integer> seen -> O(n) average time, O(n) space. public static int firstCompletedDuplicate(int[] nums) { // Write your solution here return -1; }
public static void main(String[] args) { System.out.println(firstCompletedDuplicate(new int[]{10, 5, 3, 4, 3, 5, 6})); System.out.println(firstCompletedDuplicate(new int[]{1, 2, 3})); System.out.println(firstCompletedDuplicate(new int[]{})); }}3 -1 -1
Exercise 4· Medium
Problem 4 — First Unique Character Index
Statement: Given a lowercase string s, return the 0-based index of the first character that appears exactly once in s, or -1 if no such character exists.
Constraints: 0 <= s.length() <= 100,000, s consists of lowercase English letters 'a'..'z'.
Sample I/O: "leetcode" -> 0 ('l'); "loveleetcode" -> 2 ('v'); "aabb" -> -1; "" -> -1.
public class FirstUniqueCharPractice { // 1. Restate: Return first index i where s.charAt(i) has total frequency 1, or -1. // 2. Brute force: for each i, scan all j != i -> O(n^2) time. // 3. Optimal: two passes using int[26] frequency array -> O(n) time, O(1) space. public static int firstUniqueCharIndex(String s) { // Write your solution here return -1; }
public static void main(String[] args) { System.out.println(firstUniqueCharIndex("leetcode")); System.out.println(firstUniqueCharIndex("loveleetcode")); System.out.println(firstUniqueCharIndex("aabb")); System.out.println(firstUniqueCharIndex("")); }}0 2 -1 -1
Exercise 5· Hard
Problem 5 — Two Sum Returning Original Indices
Statement: Given an int[] nums and an int target, return a 2-element array [i, j] (i < j) of the original indices whose values add up to target, or [-1, -1] if no such pair exists.
Constraints: 0 <= nums.length <= 100,000, -10^9 <= nums[i], target <= 10^9.
Sample I/O: nums = [2, 11, 7, 15], target = 9 -> [0, 2]; nums = [4, 4], target = 8 -> [0, 1]; nums = [5, 1], target = 10 -> [-1, -1].
import java.util.Arrays;import java.util.HashMap;import java.util.Map;
public class TwoSumIndicesPractice { // 1. Restate: Return [i, j] (i < j) with nums[i] + nums[j] == target, or [-1, -1]. // 2. Brute force: nested loops O(n^2) time, O(1) space. // 3. Optimal: HashMap<Long, Integer> storing value -> index, O(n) average time, O(n) space. public static int[] twoSumIndices(int[] nums, int target) { // Watch out: target - nums[i] can overflow int if target and nums[i] have opposite signs near 10^9! return new int[]{-1, -1}; }
public static void main(String[] args) { System.out.println(Arrays.toString(twoSumIndices(new int[]{2, 11, 7, 15}, 9))); System.out.println(Arrays.toString(twoSumIndices(new int[]{4, 4}, 8))); System.out.println(Arrays.toString(twoSumIndices(new int[]{5, 1}, 10))); }}[0, 2] [0, 1] [-1, -1]
Exercise 6· Hard
Problem 6 — Product of Array Except Self (With Zeros & Negatives)
Statement: Given an int[] nums (nums.length >= 2), return a long[] array ans of the same length where ans[i] is the product of all elements in nums except nums[i].
Constraints: 2 <= nums.length <= 18, -10 <= nums[i] <= 10 (note: nums may contain zero, one, or multiple 0s!).
Sample I/O: [1, 2, 3, 4] -> [24, 12, 8, 6]; [-1, 1, 0, -3, 3] -> [0, 0, 9, 0, 0]; [0, 5, 0] -> [0, 0, 0].
import java.util.Arrays;
public class ProductExceptSelfPractice { // 1. Restate: Return long[] where ans[i] is product of all nums[j] for j != i. // 2. Edge cases: zero 0s, exactly one 0, two or more 0s! // 3. Optimal: count zeros and compute product of non-zero elements in O(n) time. public static long[] productExceptSelf(int[] nums) { // Write your solution here return new long[nums.length]; }
public static void main(String[] args) { System.out.println(Arrays.toString(productExceptSelf(new int[]{1, 2, 3, 4}))); System.out.println(Arrays.toString(productExceptSelf(new int[]{-1, 1, 0, -3, 3}))); System.out.println(Arrays.toString(productExceptSelf(new int[]{0, 5, 0}))); }}[24, 12, 8, 6] [0, 0, 9, 0, 0] [0, 0, 0]
Interview questions
Questions interviewers ask on this topic.
What's next
You finished the preview of How to Approach a Problem
Java Programming has 26 sections, 252 modules and 1949 lessons. An account opens every lesson and saves your progress.
Finish up
Mark complete & continue
Next: Why we measure speed