Skip to lesson

Practice: arrays and strings

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 individual array and string moves is only half the battle; in interviews and coding assessments, you must recognize which move fits a problem and state its exact time and space cost. This practice lesson puts together single-pass array scans, matrix boundaries, prefix/suffix passes, and StringBuilder accumulators.

Single-Pass Scans: Second Largest and Array Leaders

Second Largest and Array Leaders both start as O(n log n) or O(n²) ideas and shrink to one O(n) pass with running variables. The code below solves both.

To find the second largest distinct element, track two variables: first and second, both initialized to a sentinel (or Long.MIN_VALUE). When x > first, demote first to second and set first = x. When x < first && x > second, update second = x. Skipping x == first guarantees that duplicate maximums (like [10, 10, 5]) do not overwrite second with 10.

Example 1 · Second Largest Distinct Element and Array Leaders

ArrayScanPractice.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class ArrayScanPractice {    // Time: O(n), Auxiliary Space: O(1)    public static int secondLargest(int[] nums) {        long first = Long.MIN_VALUE;        long second = Long.MIN_VALUE;        for (int x : nums) {            if (x > first) {                second = first;                first = x;            } else if (x < first && x > second) {                second = x;            }        }        return second == Long.MIN_VALUE ? -1 : (int) second;    }
    // Time: O(n), Auxiliary Space: O(1) excluding result list    public static List<Integer> leaders(int[] nums) {        List<Integer> result = new ArrayList<>();        int maxRight = Integer.MIN_VALUE;        for (int i = nums.length - 1; i >= 0; i--) {            if (nums[i] >= maxRight) {                result.add(nums[i]);                maxRight = nums[i];            }        }        Collections.reverse(result);        return result;    }
    public static void main(String[] args) {        System.out.println("Second largest in [12,35,1,10,34,1]: " + secondLargest(new int[]{12, 35, 1, 10, 34, 1}));        System.out.println("Second largest in [10,10,10]: " + secondLargest(new int[]{10, 10, 10}));        System.out.println("Leaders in [16,17,4,3,5,2]: " + leaders(new int[]{16, 17, 4, 3, 5, 2}));    }}
Output
Second largest in [12,35,1,10,34,1]: 34
Second largest in [10,10,10]: -1
Leaders in [16,17,4,3,5,2]: [17, 5, 2]

What this code does

  • Long.MIN_VALUE safely acts as a sentinel even if the input array contains Integer.MIN_VALUE.
  • Scanning right-to-left finds leaders in reverse order; a single Collections.reverse(result) restores left-to-right order in O(n) time.

Many array questions ask for elements that stand out relative to their neighbors or the rest of the array. A brute-force approach sorts the array in O(n log n) time or scans the remaining elements for every index in O(n²) time. Both problems collapse to O(n) time and O(1) auxiliary space when you maintain running state in a single pass.

To find all leaders in an array (elements greater than or equal to every element to their right), scanning left-to-right forces you to look ahead repeatedly. Scanning right-to-left while tracking maxRight lets you identify every leader in O(1) per step.

  • Second largest distinct: 1 left-to-right pass, O(n) time and O(1) space.
  • Array leaders: 1 right-to-left pass tracking maxRight, O(n) time and O(1) extra space (beyond the output list).
  • Always clarify whether duplicates count as distinct or whether leaders use > or >=.

Longest Common Prefix and String Compression

Longest Common Prefix scans column by column and stops at the first mismatch, while String Compression builds output with a StringBuilder. The code below solves both.

For Run-Length String Compression, maintain a read index i and count how many consecutive positions equal s.charAt(i). Append the character and its run length to a StringBuilder. Because the inner loop only advances i forward, each character is visited a constant number of times, running in O(n) time and O(n) output space.

Example 2 · Longest Common Prefix and String Compression

StringPracticeDemo.javaJava
public class StringPracticeDemo {    // Time: O(m * L) where m = number of strings, L = min string length. Space: O(1) auxiliary.    public static String longestCommonPrefix(String[] strs) {        if (strs == null || strs.length == 0) {            return "";        }        for (int col = 0; col < strs[0].length(); col++) {            char c = strs[0].charAt(col);            for (int r = 1; r < strs.length; r++) {                if (col == strs[r].length() || strs[r].charAt(col) != c) {                    return strs[0].substring(0, col);                }            }        }        return strs[0];    }
    // Time: O(n), Space: O(n) for the StringBuilder output    public static String compress(String s) {        StringBuilder sb = new StringBuilder();        int i = 0;        while (i < s.length()) {            char current = s.charAt(i);            int count = 0;            while (i < s.length() && s.charAt(i) == current) {                count++;                i++;            }            sb.append(current).append(count);        }        return sb.toString();    }
    public static void main(String[] args) {        System.out.println("LCP of [flower, flow, flight]: " + longestCommonPrefix(new String[]{"flower", "flow", "flight"}));        System.out.println("Compressed aaabbcdddd: " + compress("aaabbcdddd"));    }}
Output
LCP of [flower, flow, flight]: fl
Compressed aaabbcdddd: a3b2c1d4

What this code does

  • Vertical LCP scanning exits immediately if one of the strings is empty or mismatches in column 0.
  • In compress, even though there is a nested while loop, i only increments from 0 to s.length(), making the total time O(n).

String manipulation problems test whether you avoid quadratic string concatenation and handle mismatched lengths cleanly. For Longest Common Prefix (LCP) across an array of m strings of minimum length L, vertical scanning checks column col across all strings before advancing to col + 1. As soon as any string ends or mismatches strs[0].charAt(col), you return strs[0].substring(0, col) in O(m · L) worst-case time and O(1) auxiliary space.

  1. Check for empty input arrays or empty strings before accessing strs[0].
  2. In vertical LCP scanning, stop at the first index where col == strs[r].length() or characters differ.
  3. In string compression, use a while loop to advance across identical characters and append the group once.
  4. Convert the StringBuilder to a String only once at the end.

Product of Array Except Self and Matrix Traversals

Product of Array Except Self cannot use division, because a zero breaks it. Each answer is a prefix product times a suffix product. The code below builds both in one array.

You can compute all prefix products directly into the answer array in a left-to-right pass, then multiply each answer[i] by a single running suffix variable in a right-to-left pass. This achieves O(n) time and O(1) auxiliary space (since the output array does not count toward extra space).

Example 3 · Brute force: multiply all the other numbers for each index (O(n²) time, O(1) space)

ProductBruteDemo.javaJava
import java.util.Arrays;
public class ProductBruteDemo {    // Time: O(n^2), Auxiliary Space: O(1) excluding the output array    public static int[] productExceptSelf(int[] nums) {        int n = nums.length;        int[] answer = new int[n];        for (int i = 0; i < n; i++) {            int product = 1;            for (int j = 0; j < n; j++) {                if (j != i) {                    product *= nums[j];                }            }            answer[i] = product;        }        return answer;    }
    public static void main(String[] args) {        System.out.println("Product [1,2,3,4]: " + Arrays.toString(productExceptSelf(new int[]{1, 2, 3, 4})));        System.out.println("Product [-1,1,0,-3,3]: " + Arrays.toString(productExceptSelf(new int[]{-1, 1, 0, -3, 3})));    }}
Output
Product [1,2,3,4]: [24, 12, 8, 6]
Product [-1,1,0,-3,3]: [0, 0, 9, 0, 0]

What this code does

  • For each index the inner loop multiplies every other number, so zeros are handled and no division is used.
  • The cost is n × n steps, which is O(n²) and too slow for large arrays.

Example 4 · Better: left and right product arrays (O(n) time, O(n) space)

ProductPrefixSuffixDemo.javaJava
import java.util.Arrays;
public class ProductPrefixSuffixDemo {    // Time: O(n), Extra Space: O(n) for the left and right arrays    public static int[] productExceptSelf(int[] nums) {        int n = nums.length;        int[] left = new int[n];        int[] right = new int[n];        int[] answer = 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];        }        for (int i = 0; i < n; i++) {            answer[i] = left[i] * right[i];        }        return answer;    }
    public static void main(String[] args) {        System.out.println("Product [1,2,3,4]: " + Arrays.toString(productExceptSelf(new int[]{1, 2, 3, 4})));        System.out.println("Product [-1,1,0,-3,3]: " + Arrays.toString(productExceptSelf(new int[]{-1, 1, 0, -3, 3})));    }}
Output
Product [1,2,3,4]: [24, 12, 8, 6]
Product [-1,1,0,-3,3]: [0, 0, 9, 0, 0]

What this code does

  • Each answer is the product on its left times the product on its right, and each of those is built once in a single pass.
  • That removes the inner loop, so the time drops to O(n), at the price of two extra arrays.

Example 5 · Optimal: left products in the answer, then a running right product (O(n) time, O(1) extra space)

ProductExceptSelfDemo.javaJava
import java.util.Arrays;
public class ProductExceptSelfDemo {    // Time: O(n), Auxiliary Space: O(1) excluding the output array    public static int[] productExceptSelf(int[] nums) {        int n = nums.length;        int[] answer = new int[n];
        // Pass 1: answer[i] holds the product of all elements to the left of i        answer[0] = 1;        for (int i = 1; i < n; i++) {            answer[i] = answer[i - 1] * nums[i - 1];        }
        // Pass 2: multiply each answer[i] by the product of all elements to the right of i        int suffix = 1;        for (int i = n - 1; i >= 0; i--) {            answer[i] *= suffix;            suffix *= nums[i];        }        return answer;    }
    public static void main(String[] args) {        System.out.println("Product [1,2,3,4]: " + Arrays.toString(productExceptSelf(new int[]{1, 2, 3, 4})));        System.out.println("Product [-1,1,0,-3,3]: " + Arrays.toString(productExceptSelf(new int[]{-1, 1, 0, -3, 3})));    }}
Output
Product [1,2,3,4]: [24, 12, 8, 6]
Product [-1,1,0,-3,3]: [0, 0, 9, 0, 0]

What this code does

  • For [-1, 1, 0, -3, 3], no division by zero ever occurs: only index 2 (where the 0 sits) receives a non-zero product (-1 * 1) * (-3 * 3) = 9.
  • Using a single scalar suffix variable in the second pass avoids allocating separate left[] and right[] arrays.
  • It is leaner than the two-array version because the answer array holds the left products and one variable, suffix, replaces the whole right array.

When a problem asks for answer[i] equal to the product of all elements except nums[i] without using division, multiplying the whole array and dividing by nums[i] fails both the rule and any test case containing 0. Instead, notice that every answer[i] is the product of two parts: the prefix product nums[0] * ... * nums[i - 1] and the suffix product nums[i + 1] * ... * nums[n - 1].

Similarly, matrix rotation (transpose + row reversal) and spiral traversal (four shrinking wall pointers top, bottom, left, right) visit each of the R × C cells a constant number of times in O(R · C) time and O(1) extra space.

In interviews, always state explicitly whether you are counting the required output container in your space complexity: 'O(1) auxiliary space, or O(n) including the output array.'

Finish up

Mark complete & continue

Next: The two pointers idea