Skip to lesson

Build speed and confidence on ten unlabelled easy problems drawn from every module of Section 05. On each problem, pause before coding to state the brute force, name the optimal pattern from the clues and constraints, and run the self-review checklist.

Ten unlabelled easy problems

Read each problem below and name its pattern before checking the answer in brackets.

  1. Max Sum of k Consecutive Elements (1 ≤ k ≤ n ≤ 10⁵, -10^4 <= a[i] <= 10^4): Find the maximum sum of any contiguous subarray of length k. (Brute force: O(nk) nested sum; Optimal: Fixed-Size Sliding Window in O(n) time, O(1) space.)
  2. Sorted Pair Sum (2 ≤ n ≤ 10⁵, sorted a): Find two indices i < j with a[i] + a[j] == target. (Brute force: O(n²) pairs; Optimal: Opposite-End Two Pointers in O(n) time, O(1) space.)
  3. Move Zeros in Place (1 ≤ n ≤ 10⁵): Move all 0s to the end while keeping the relative order of non-zero elements. (Brute force: O(n) extra array; Optimal: Read/Write Two Pointers in O(n) time, O(1) space.)
  4. Pivot / Equilibrium Index (1 ≤ n ≤ 10⁵): Return the leftmost index i where the sum of elements strictly to its left equals the sum strictly to its right, or -1. (Brute force: O(n²) re-summing; Optimal: Prefix / Running Sum in O(n) time, O(1) space.)
  5. First Bad Build (1 ≤ n ≤ 2 × 10⁹): Versions 1..n turn bad at some first version v (isBad(x) is false for x < v and true for x ≥ v). Find v. (Brute force: O(n) linear scan; Optimal: Boundary Binary Search in O(log n) time, O(1) space.)
  6. Single Unpaired Number (1 ≤ n ≤ 10⁵): Every element appears twice except one. (Brute force: O(n) HashSet; Optimal: XOR Cancellation in O(n) time, O(1) space.)
  7. Alphanumeric Palindrome (1 ≤ |s| ≤ 10⁵): Check if s reads the same forward and backward ignoring case and non-alphanumeric chars. (Optimal: Inward Two Pointers in O(n) time, O(1) space.)
  8. First Repeated Lowercase Letter (2 ≤ |s| ≤ 10⁵): Return the first letter whose second appearance occurs earliest. (Optimal: Bitmask Seen Flag in O(n) time, O(1) space.)
  9. GCD of Array Min and Max (2 ≤ n ≤ 1000): Return gcd(min(a), max(a)). (Optimal: Single-Pass Min/Max + Euclid's GCD in O(n + log(min)) time, O(1) space.)
  10. Power of Four (-2³¹ ≤ n ≤ 2³¹-1): Check if n = 4ᵏ for some k ≥ 0. (Optimal: Bit Trick n > 0 && (n & (n - 1)) == 0 && (n & 0x55555555) != 0 in O(1) time.)

Model solutions for eight of the problems

These solutions cover problems 1, 2, 4, 6, 7, 8, 9 and 10. Problem 1 is solved three ways, from brute force to optimal.

Fixed window of 3: best sum

Step 1 of 5

Array: 2, 1, 5, 1, 3, 2.
best
0
Problem 1 with k = 3: find the largest sum of 3 neighbouring numbers in 2, 1, 5, 1, 3, 2.

Example 1 · Brute force, Problem 1: add up every window of k (O(n·k) time, O(1) space)

WindowSumsBrute.javaJava
public class WindowSumsBrute {    public static long maxWindowSum(int[] a, int k) {        long best = Long.MIN_VALUE;        for (int start = 0; start + k <= a.length; start++) {            long sum = 0;            for (int i = start; i < start + k; i++) {                sum += a[i];            }            best = Math.max(best, sum);        }        return best;    }
    public static void main(String[] args) {        int[] orders = {2, 1, 5, 1, 3, 2};        System.out.println(maxWindowSum(orders, 3));        System.out.println(maxWindowSum(new int[]{-2, -5, -1, -8}, 2));    }}
Output
9
-6

What this code does

  • For every start position the inner loop adds k numbers again, even though neighbouring windows share k - 1 of them.
  • It handles all-negative arrays correctly because best starts at the smallest long value, but it repeats a lot of work.

Example 2 · Better, Problem 1: prefix sums (O(n) time, O(n) space)

WindowSumsPrefix.javaJava
public class WindowSumsPrefix {    public static long maxWindowSum(int[] a, int k) {        long[] prefix = new long[a.length + 1];        for (int i = 0; i < a.length; i++) {            prefix[i + 1] = prefix[i] + a[i];        }        long best = Long.MIN_VALUE;        for (int start = 0; start + k <= a.length; start++) {            best = Math.max(best, prefix[start + k] - prefix[start]);        }        return best;    }
    public static void main(String[] args) {        int[] orders = {2, 1, 5, 1, 3, 2};        System.out.println(maxWindowSum(orders, 3));        System.out.println(maxWindowSum(new int[]{-2, -5, -1, -8}, 2));    }}
Output
9
-6

What this code does

  • prefix[i] stores the sum of the first i numbers, so any window sum is prefix[start + k] - prefix[start].
  • It is faster than the brute force because each window costs one subtraction instead of k additions. The price is an extra array of n + 1 numbers.

Example 3 · Problems 2, 7, and 9: Two Pointers and Euclid's GCD

EasySetTwoPointersAndGcdDemo.javaJava
import java.util.Arrays;
public class EasySetTwoPointersAndGcdDemo {    // Problem 2: Sorted Pair Sum (Opposite-End Two Pointers, O(n) time, O(1) space)    public static int[] twoSumSorted(int[] nums, int target) {        int left = 0;        int right = nums.length - 1;        while (left < right) {            int sum = nums[left] + nums[right];            if (sum == target) return new int[]{left, right};            if (sum < target) left++;            else right--;        }        return new int[]{-1, -1};    }
    // Problem 7: Valid Alphanumeric Palindrome (Inward Two Pointers, O(n) time, O(1) space)    public static boolean isPalindrome(String s) {        int left = 0;        int right = s.length() - 1;        while (left < right) {            while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;            while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;            if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {                return false;            }            left++;            right--;        }        return true;    }
    // Problem 9: GCD of Array Min and Max (O(n + log(min)) time, O(1) space)    public static int gcdOfMinMax(int[] nums) {        int min = nums[0];        int max = nums[0];        for (int x : nums) {            if (x < min) min = x;            if (x > max) max = x;        }        while (min != 0) {            int r = max % min;            max = min;            min = r;        }        return max;    }
    public static void main(String[] args) {        System.out.println("Problem 2: " + Arrays.toString(twoSumSorted(new int[]{2, 7, 11, 15}, 9)));        System.out.println("Problem 7: " + isPalindrome("A man, a plan, a canal: Panama"));        System.out.println("Problem 9: " + gcdOfMinMax(new int[]{2, 5, 6, 9, 10}));    }}
Output
Problem 2: [0, 1]
Problem 7: true
Problem 9: 2

What this code does

  • All three solutions avoid extra allocations and run in O(1) auxiliary memory.
  • In isPalindrome, skipping non-alphanumeric characters in place avoids building a filtered StringBuilder copy.

Example 4 · Optimal, Problems 1 and 4: fixed sliding window and running prefix pivot (O(n) time, O(1) space)

EasySetWindowAndPrefixDemo.javaJava
public class EasySetWindowAndPrefixDemo {    // Problem 1: Max Sum of k Consecutive Elements (Fixed Sliding Window, O(n) time, O(1) space)    public static long maxSumWindowK(int[] nums, int k) {        long windowSum = 0;        for (int i = 0; i < k; i++) {            windowSum += nums[i];        }        long maxSum = windowSum;        for (int right = k; right < nums.length; right++) {            windowSum += nums[right] - nums[right - k];            maxSum = Math.max(maxSum, windowSum);        }        return maxSum;    }
    // Problem 4: Pivot / Equilibrium Index (Running Prefix Sum, O(n) time, O(1) space)    public static int pivotIndex(int[] nums) {        long total = 0;        for (int x : nums) total += x;        long leftSum = 0;        for (int i = 0; i < nums.length; i++) {            long rightSum = total - leftSum - nums[i];            if (leftSum == rightSum) return i;            leftSum += nums[i];        }        return -1;    }
    public static void main(String[] args) {        System.out.println("Problem 1 (k=3 on [-2, -5, -1, -8]): "            + maxSumWindowK(new int[]{-2, -5, -1, -8}, 3));        System.out.println("Problem 4 ([1, 7, 3, 6, 5, 6]): "            + pivotIndex(new int[]{1, 7, 3, 6, 5, 6}));    }}
Output
Problem 1 (k=3 on [-2, -5, -1, -8]): -8
Problem 4 ([1, 7, 3, 6, 5, 6]): 3

What this code does

  • Initializing maxSum = windowSum (after the first k elements) instead of 0 handles all-negative arrays like [-2, -5, -1, -8] correctly.
  • In pivotIndex, checking leftSum == rightSum before adding nums[i] to leftSum handles the boundary i = 0 when the sum of nums[1..n-1] is 0.
  • It beats the prefix-sum version in memory: the window sum is updated with one add and one drop, so no array is needed.

Example 5 · Problems 6, 8, and 10: XOR, Bitmask Seen Set, and Power of Four

EasySetBitsDemo.javaJava
public class EasySetBitsDemo {    // Problem 6: Single Number (XOR Cancellation, O(n) time, O(1) space)    public static int singleNumber(int[] nums) {        int xor = 0;        for (int x : nums) xor ^= x;        return xor;    }
    // Problem 8: First Letter to Appear Twice (Bitmask Seen Set, O(n) time, O(1) space)    public static char repeatedCharacter(String s) {        int mask = 0;        for (int i = 0; i < s.length(); i++) {            int bit = 1 << (s.charAt(i) - 'a');            if ((mask & bit) != 0) return s.charAt(i);            mask |= bit;        }        return ' ';    }
    // Problem 10: Power of Four (Bit Trick, O(1) time, O(1) space)    public static boolean isPowerOfFour(int n) {        return n > 0 && (n & (n - 1)) == 0 && (n & 0x55555555) != 0;    }
    public static void main(String[] args) {        System.out.println("Problem 6: " + singleNumber(new int[]{4, 1, 2, 1, 2}));        System.out.println("Problem 8: " + repeatedCharacter("abccbaacz"));        System.out.println("Problem 10 (16 vs 8): " + isPowerOfFour(16) + ", " + isPowerOfFour(8));    }}
Output
Problem 6: 4
Problem 8: c
Problem 10 (16 vs 8): true, false

What this code does

  • A power of four is a power of two (n > 0 && (n & (n - 1)) == 0) whose single set 1 bit sits at an even bit index (0, 2, 4, …, 30), tested by the alternating hex mask 0x55555555 (0101...0101_2).
  • repeatedCharacter packs all 26 seen flags into one int bitmask instead of a HashSet<Character>.

Brute Force First, Then Optimal — Naming the Pattern Before Coding

Even on an easy problem, jumping straight into code without naming the pattern causes preventable bugs (such as sorting an array when contiguous indices are required). Spend 30 seconds on a 3-sentence pre-code ritual:

  1. State the brute force and what it repeats: e.g., "In Pivot Index, the O(n²) brute force recomputes leftSum and rightSum from scratch at every index i."
  2. Name the pattern that removes the repetition: e.g., "Using the Running Prefix Sum pattern, rightSum is just totalSum - leftSum - nums[i] in O(1) per index."
  3. Verify constraints: Check whether totalSum can overflow int (use long if n × max |Aᵢ| > 2 × 10⁹).
  1. Hand trace of Pivot Index on nums = [1, 7, 3, 6, 5, 6]: totalSum = 28, leftSum = 0.
  2. i = 0 (1): rightSum = 28 - 0 - 1 = 27 != 0. Update leftSum = 1.
  3. i = 1 (7): rightSum = 28 - 1 - 7 = 20 != 1. Update leftSum = 8.
  4. i = 2 (3): rightSum = 28 - 8 - 3 = 17 != 8. Update leftSum = 11.
  5. i = 3 (6): rightSum = 28 - 11 - 6 = 11 == leftSum! Return 3.

Trace the code

Trace the pivot index

Step through the loop and watch left grow until both sides match.

public class Pivot {
public static void main(String[] args) {
int[] nums = {1, 7, 3, 6, 5, 6};
int total = 0;
for (int x : nums) {
total += x;
}
int left = 0;
int pivot = -1;
for (int i = 0; i < nums.length; i++) {
if (left == total - left - nums[i]) {
pivot = i;
break;
}
left += nums[i];
}
System.out.println(pivot);
}
}

Variables

i
-

Output

(nothing printed yet)

Line 3nums holds six numbers. We look for an index where the sums on both sides are equal.

Step 1 of 12

Self-Review with the Routine Checklist

Before submitting any solution in this set, run your code through the routine self-review checklist:

  • Boundary sizes: Does it work when n = 1, k = 1, or k = n?
  • Value extremes: What if all elements are negative (e.g., initializing maxSum = Long.MIN_VALUE instead of 0)?
  • No-answer path: Does it return -1 or false cleanly when no pivot or pair exists?
  • Overflow & Complexity: Did you use low + ((high - low) >>> 1) and long for sums, and can you state exact time and space complexity?

Next step

Check your understanding

10 quick questions