Array and String Fundamentals

Understand contiguous memory, dynamic arrays and string representation, and practise in-place manipulation such as reversal, rotation and partitioning.

Beginner · about 8 hours · difficulty 2/5

Learn first: Complexity Analysis

Arrays store elements in contiguous memory, which gives O(1) indexed access and excellent cache performance. Inserting or deleting in the middle costs O(n) because elements must shift. Dynamic arrays (vector, ArrayList, Python list) grow by doubling, which makes appends O(1) amortized.

Strings are arrays of characters. In Java and Python they are immutable, so each modification creates a new string; in C++ std::string is mutable. Know how your language handles characters: c - 'a' gives an index 0-25, which enables fixed-size frequency arrays that are faster than hash maps.

Techniques to practise

  • In-place reversal with two indices.
  • Rotation by k using three reversals.
  • Partitioning (Dutch National Flag) to sort 0s, 1s and 2s in one pass.
  • Kadane's algorithm for maximum subarray sum: keep the best sum ending at the current index.
  • Matrix traversal: spiral order, transpose, rotate 90 degrees.
  • Simulation carefully following rules without off-by-one errors.

Pitfalls

Off-by-one errors at boundaries, modifying a collection while iterating over it, and forgetting empty or single-element inputs. Always test with n = 0, n = 1 and all-equal elements.

Good enough to move on: you can solve easy array problems in under 15 minutes and explain the complexity of each operation you use.

Key concepts

  • Static vs dynamic arrays
  • Character arithmetic and frequency arrays
  • In-place reversal and rotation
  • Dutch National Flag partition
  • Kadane's algorithm
  • 2D matrix traversal: Spiral, rotate, transpose
  • String immutability and builders

Mini project

Solve 10 problems: Rotate Array, Sort Colors, Maximum Subarray, Best Time to Buy and Sell Stock, Move Zeroes, Spiral Matrix, Rotate Image, Valid Palindrome, Longest Common Prefix, and Product of Array Except Self.

Check yourself

How does Kadane's algorithm decide whether to extend the current subarray or start a new one, and what happens when all numbers are negative?

Free resources