Mixed set: medium
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Medium problems form the core of online coding rounds and technical interviews. Unlike easy problems where one straightforward loop suffices, a medium problem usually hides its pattern behind a twist — negative remainders, rotated order, duplicate skipping, or a monotonic greedy choice.
Ten unlabelled medium problems
Name the pattern of each of these ten medium problems before looking at the answer in brackets.
- Longest Substring Without Repeating Characters (0 ≤ |s| ≤ 5 × 10⁴): Find the length of the longest substring with all unique characters. (Pattern: Variable Sliding Window with
lastSeen[128], O(n) time, O(1) space.) - Container With Most Water (2 ≤ n ≤ 10⁵): Choose two vertical lines i < j maximizing (j - i) × min(h[i], h[j]). (Pattern: Opposite-End Two Pointers advancing the shorter line, O(n) time, O(1) space.)
- Subarray Sums Divisible by K (1 ≤ n ≤ 3 × 10⁴,
-10^4 <= a[i] <= 10^4): Count contiguous subarrays whose sum is divisible by K. (Pattern: Prefix Sum + Remainder Frequency Table with((sum % k) + k) % k, O(n + k) time, O(k) space.) - Search in Rotated Sorted Array (1 ≤ n ≤ 5000, distinct values): Find
targetin an array rotated at an unknown pivot. (Pattern: Modified Binary Search identifying the sorted half at each step, O(log n) time, O(1) space.) - 3Sum (3 ≤ n ≤ 3000): Find all unique triplets
a[i] + a[j] + a[k] == 0. (Pattern: Sort + Outer Loop + Opposite Two Pointers skipping duplicates, O(n²) time, O(1) extra space.) - Minimum Size Subarray Sum ≥ target (1 ≤ n ≤ 10⁵, positive
a[i]): Shortest subarray with sum ≥ target, or0. (Pattern: Variable Sliding Window, O(n) time, O(1) space.) - Product of Array Except Self (2 ≤ n ≤ 10⁵, no
/): Returnans[i]equal to the product of all elements excepta[i]. (Pattern: Prefix and Suffix Running Products, O(n) time, O(1) extra space.) - Combination Sum (1 ≤ n ≤ 30, positive distinct candidates): All unique combinations summing to
targetwith unlimited reuse. (Pattern: Backtracking passing start indexi.) - Single Number III (2 ≤ n ≤ 3 × 10⁴): Two elements appear once; all others appear twice. (Pattern: XOR + Lowest Set Bit Split
diff & -diff, O(n) time, O(1) space.) - Range Addition / Flight Bookings (1 ≤ n, q ≤ 2 × 10⁴): Apply q range additions
[L, R, inc]and return the final array. (Pattern: Difference Array + Prefix Sum, O(n + q) time.)
Model solutions for six of the problems
These solutions cover problems 1, 2, 3, 4, 7 and 10. Problem 7 is solved three ways, from brute force to optimal.
Example 1 · Brute force, Problem 7: multiply all the others (O(n²) time, O(1) extra space)
import java.util.Arrays;
public class ProductExceptSelfBrute { public static int[] productExceptSelf(int[] nums) { int[] ans = new int[nums.length]; for (int i = 0; i < nums.length; i++) { int product = 1; for (int j = 0; j < nums.length; j++) { if (j != i) { product *= nums[j]; } } ans[i] = product; } return ans; }
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}))); }}[24, 12, 8, 6] [0, 0, 9, 0, 0]
What this code does
- For every index the inner loop multiplies every other element, so the work grows with n × n.
- It handles zeros without division, but 10⁵ elements would need about 10¹⁰ multiplications.
Example 2 · Better, Problem 7: prefix and suffix product arrays (O(n) time, O(n) space)
import java.util.Arrays;
public class ProductExceptSelfArrays { public static int[] productExceptSelf(int[] nums) { int n = nums.length; int[] left = new int[n]; int[] right = new int[n]; left[0] = 1; for (int i = 1; i < n; i++) { left[i] = left[i - 1] * nums[i - 1]; } right[n - 1] = 1; for (int i = n - 2; i >= 0; i--) { right[i] = right[i + 1] * nums[i + 1]; } int[] ans = new int[n]; for (int i = 0; i < n; i++) { ans[i] = left[i] * right[i]; } return ans; }
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}))); }}[24, 12, 8, 6] [0, 0, 9, 0, 0]
What this code does
left[i]is the product of everything before i andright[i]is the product of everything after i, soans[i] = left[i] * right[i].- It is faster than the brute force because each product is built once from its neighbour. The price is two extra arrays.
Example 3 · Problems 1 and 2: Sliding Window and Opposite Two Pointers
import java.util.Arrays;
public class MediumWindowAndContainerDemo { // Problem 1: Longest Substring Without Repeating Characters — O(n) time, O(1) space public static int lengthOfLongestSubstring(String s) { int[] lastSeen = new int[128]; Arrays.fill(lastSeen, -1); int left = 0; int best = 0; for (int right = 0; right < s.length(); right++) { char c = s.charAt(right); if (lastSeen[c] >= left) { left = lastSeen[c] + 1; } lastSeen[c] = right; best = Math.max(best, right - left + 1); } return best; }
// Problem 2: Container With Most Water — O(n) time, O(1) space public static int maxArea(int[] height) { int left = 0; int right = height.length - 1; int best = 0; while (left < right) { int h = Math.min(height[left], height[right]); best = Math.max(best, h * (right - left)); if (height[left] < height[right]) { left++; } else { right--; } } return best; }
public static void main(String[] args) { System.out.println("Problem 1 (\"abcabcbb\", \"abba\"): " + lengthOfLongestSubstring("abcabcbb") + ", " + lengthOfLongestSubstring("abba")); System.out.println("Problem 2 ([1,8,6,2,5,4,8,3,7]): " + maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7})); }}Problem 1 ("abcabcbb", "abba"): 3, 2
Problem 2 ([1,8,6,2,5,4,8,3,7]): 49What this code does
- On
"abba", when the second'a'arrives at index 3,lastSeen['a']is0, which is< left(2), soif (lastSeen[c] >= left)preventsleftfrom jumping backward! - In
maxArea, the width shrinks every step, so the only way to beat the current area is to replace the shorter wall (height[left] < height[right] ? left++ : right--).
Example 4 · Optimal, Problems 3 and 7: prefix remainder counts and running prefix/suffix products (O(n) time)
import java.util.Arrays;
public class MediumPrefixDemo { // Problem 3: Subarray Sums Divisible by K — O(n + k) time, O(k) space public static int subarraysDivByK(int[] nums, int k) { int[] remFreq = new int[k]; remFreq[0] = 1; int prefix = 0; int count = 0; for (int x : nums) { prefix += x; int rem = ((prefix % k) + k) % k; count += remFreq[rem]; remFreq[rem]++; } return count; }
// Problem 7: Product of Array Except Self — O(n) time, O(1) extra space public static int[] productExceptSelf(int[] nums) { int n = nums.length; int[] res = new int[n]; res[0] = 1; for (int i = 1; i < n; i++) { res[i] = res[i - 1] * nums[i - 1]; } int suffix = 1; for (int i = n - 1; i >= 0; i--) { res[i] *= suffix; suffix *= nums[i]; } return res; }
public static void main(String[] args) { System.out.println("Problem 3 ([4,5,0,-2,-3,1], k=5): " + subarraysDivByK(new int[]{4, 5, 0, -2, -3, 1}, 5)); System.out.println("Problem 7 ([1,2,3,4]): " + Arrays.toString(productExceptSelf(new int[]{1, 2, 3, 4}))); System.out.println("Problem 7 ([-1,1,0,-3,3]): " + Arrays.toString(productExceptSelf(new int[]{-1, 1, 0, -3, 3}))); }}Problem 3 ([4,5,0,-2,-3,1], k=5): 7 Problem 7 ([1,2,3,4]): [24, 12, 8, 6] Problem 7 ([-1,1,0,-3,3]): [0, 0, 9, 0, 0]
What this code does
- Two prefix sums Pⱼ and Pᵢ have (Pⱼ - Pᵢ) divisible by k if and only if they have the same non-negative remainder modulo k.
productExceptSelfhandles single or multiple zeros naturally without division because it multiplies the prefix product to the left ofiby the suffix product to the right ofi.- The optimal product version reuses the answer array for the left products and one running variable for the right products, so the extra space drops to O(1).
Example 5 · Problems 4 and 10: Rotated Binary Search and Difference Array
import java.util.Arrays;
public class MediumBinarySearchAndDiffDemo { // Problem 4: Search in Rotated Sorted Array — O(log n) time, O(1) space public static int searchRotated(int[] nums, int target) { int low = 0; int high = nums.length - 1; while (low <= high) { int mid = low + ((high - low) >>> 1); if (nums[mid] == target) return mid; if (nums[low] <= nums[mid]) { if (nums[low] <= target && target < nums[mid]) { high = mid - 1; } else { low = mid + 1; } } else { if (nums[mid] < target && target <= nums[high]) { low = mid + 1; } else { high = mid - 1; } } } return -1; }
// Problem 10: Corporate Flight Bookings (Difference Array) — O(n + q) time public static int[] corpFlightBookings(int[][] bookings, int n) { int[] ans = new int[n]; for (int[] b : bookings) { int first = b[0] - 1; int last = b[1] - 1; int seats = b[2]; ans[first] += seats; if (last + 1 < n) { ans[last + 1] -= seats; } } for (int i = 1; i < n; i++) { ans[i] += ans[i - 1]; } return ans; }
public static void main(String[] args) { System.out.println("Problem 4 ([4,5,6,7,0,1,2], target=0): " + searchRotated(new int[]{4, 5, 6, 7, 0, 1, 2}, 0)); int[][] bookings = {{1, 2, 10}, {2, 3, 20}, {2, 5, 25}}; System.out.println("Problem 10: " + Arrays.toString(corpFlightBookings(bookings, 5))); }}Problem 4 ([4,5,6,7,0,1,2], target=0): 4 Problem 10: [10, 55, 45, 25, 25]
What this code does
- In a rotated sorted array with distinct elements, at least one of the two halves
[low..mid]or[mid..high]is guaranteed to be strictly sorted. - In
corpFlightBookings, accumulating the difference array in place insideansavoids allocating a separatediffarray.
Complexity and Tests for Every Answer
On medium problems, passing the sample test case is only half the battle — hidden tests probe negative numbers, zeros, duplicates, and no-solution paths. For every problem you solve, write a 3-test harness in main before moving on:
public class ThreeTests { static int subarraysDivByK(int[] nums, int k) { int[] seen = new int[k]; seen[0] = 1; int sum = 0, count = 0; for (int x : nums) { sum = ((sum + x) % k + k) % k; count += seen[sum]++; } return count; } public static void main(String[] args) { System.out.println(subarraysDivByK(new int[] {4, 5, 0, -2, -3, 1}, 5)); // standard System.out.println(subarraysDivByK(new int[] {3}, 2)); // no answer System.out.println(subarraysDivByK(new int[] {-1, 2, 9}, 2)); // negatives }}7 0 2
- Standard case: The sample input from the problem statement.
- Boundary / No-answer case: Minimum length (n = 1 or 2), target not found (returns
0,-1, or[]). - Adversarial case: Negative numbers in modular division, zeros in array product, or all-duplicate elements in 3Sum.
- In Problem 3 (Subarrays Divisible by K), always test an array with negative numbers like
[-1, 2, 9]withk = 2to verify((sum % k) + k) % k. - In Problem 7 (Product Except Self), always test an array with one zero (
[-1, 1, 0, -3, 3]) and an array with two zeros ([0, 4, 0]). - State amortized complexity clearly: in Sliding Window,
leftandrighteach advance at most n times, so total work is 2n = O(n), not O(n²).
Comparing with a Model Solution and Logging Missed Patterns
After your code passes all three test cases, compare it line by line against the model solution. Even when your code is correct, ask: Did I use an extra O(n) array or HashMap where O(1) variables or a fixed-size array sufficed? Did I need three separate if branches where one loop invariant handled them all?
Whenever you misidentified a pattern (for example, trying Sliding Window on Subarray Sums Divisible by K when negative numbers exist), add one row to your Missed Pattern Log:
- Column 1 — Problem: e.g., Subarray Sums Divisible by K.
- Column 2 — What I Tried First: Variable Sliding Window.
- Column 3 — Why It Failed: Negative numbers mean expanding right does not monotonically change the sum or remainder.
- Column 4 — Clue to Spot Next Time: "Subarray sum divisible by K" + negative numbers -> two prefix sums have difference divisible by K iff they have the same remainder mod K!
Next step
Check your understanding
10 quick questions