Arrays: Core Techniques

Master traversal, in-place updates, rotation, Kadane's algorithm and the classic array problems that open almost every OA.

Beginner · about 8 hours · difficulty 2/5

Learn first: Time and Space Complexity

Arrays appear in nearly every coding round. Most array questions reduce to a handful of reusable ideas.

Key patterns

  • Running state in one pass: track max, min, sum or best-so-far while scanning (Best Time to Buy and Sell Stock).
  • Kadane's algorithm: maximum subarray sum in O(n) by deciding at each index whether to extend or restart.
  • In-place rearrangement: Dutch national flag for Sort Colors, moving zeroes, rotating by reversal (reverse all, then reverse each part).
  • Index as hash: when values are in 1..n, mark visited by negating or swapping into place (Find the Duplicate Number, First Missing Positive).
  • Matrix traversal: spiral order, transpose then reverse rows to rotate 90 degrees.

Classic problems

Two Sum (brute force first), Maximum Subarray, Best Time to Buy and Sell Stock, Sort Colors, Rotate Array, Next Permutation, Majority Element (Boyer-Moore voting), Spiral Matrix, Set Matrix Zeroes.

Pitfalls

  • Off-by-one errors at the boundaries. Dry-run on arrays of size 0, 1 and 2.
  • Kadane's with all negative numbers: initialise the answer to the first element, not 0.
  • Modifying an array while iterating over it in a way that skips elements.

You are ready to move on when you can solve Maximum Subarray, Sort Colors and Next Permutation from scratch and explain each in one sentence.

Key concepts

  • Traversal and running state
  • Kadane's algorithm
  • Dutch national flag
  • Rotation by reversal
  • Boyer-Moore majority vote
  • Index marking for 1..n values
  • Matrix traversal and rotation

Mini project

Solve these 10 in 7 days and log time taken plus the pattern used: Two Sum, Best Time to Buy and Sell Stock, Maximum Subarray, Sort Colors, Move Zeroes, Rotate Array, Majority Element, Next Permutation, Spiral Matrix, Set Matrix Zeroes.

Check yourself

Why does Kadane's algorithm fail if you initialise the best sum to 0, and on what input does it fail?

Free resources