Interview OS
Back to Coding Prep

Coding

Arrays

Index math, prefix sums, and in-place rearrangement.

Coding pattern

Overview

Array problems test whether you can process a contiguous block of elements efficiently. The core challenge is replacing brute-force nested loops with a single pass using prefix sums, hashing, or pointer tricks, while carefully handling bounds, duplicates, and whether the input is sorted.

How it works

Coding pattern
InputPatternOptimizeOutputArray inn elementsPick techniqueprefix sumSingle passO(n) timeReturn resultO(1) extra
ClientServiceEdgeData

Step by step, with examples

  1. 1

    Array in

    • Read the array; clarify sorted, duplicates, and bounds.
  2. 2

    Pick technique

    • Choose prefix sums, hashing, or two-pointers to avoid O(n²).
  3. 3

    Single pass

    • Track running state so each element is touched once.
  4. 4

    Return result

    • Return an index, value, or rebuilt array.
    • Example: Kadane's max subarray

When to reach for it

  • Contiguous data
  • Running totals / ranges
  • In-place O(1) space asks

Example problem

Maximum subarray sum (Kadane's algorithm).

Approach

  • Track a running sum, reset when it goes negative
  • Keep the best seen so far

Solution

function maxSubArray(nums) {
  let best = nums[0], cur = nums[0];
  for (let i = 1; i < nums.length; i++) {
    cur = Math.max(nums[i], cur + nums[i]);
    best = Math.max(best, cur);
  }
  return best;
}

Complexity

Time O(n), Space O(1).

Common pitfalls

  • Forgetting all-negative arrays
  • Off-by-one on window edges

Where this content comes from

For full transparency, this content is curated and verified from these sources:

Curated company-tagged problem banksRecurring interview pattern librariesOppZen-authored drills & solutions