Iteration Patterns
iteration-patterns
Algorithms
Iteration Patterns on Arrays/Strings
Look at almost any solved interview problem and you will see the same six or seven shapes of `for` loop reappearing: a single sweep that finds a max, a nested pair that compares every element to every other, a single sweep that fills a frequency table. Before you can recognize when two pointers or sliding window will help, you have to recognize these primitive shapes on sight. **Iteration Patterns on Arrays/Strings** catalogs those shapes. You will work through single-pass templates (running sum, find max/min, counting), nested-loop templates that consider all pairs in `O(n^2)` time, frequency counting with a hash map, early termination with `break`, sentinel values, and the choice between in-place modification and building a new array. Classic transformations like reverse, rotate, and partition appear as named patterns rather than puzzles solved from scratch each time. In **Arrays & Strings**, you saw that arrays give you constant-time indexed access and contiguous memory. This lesson turns that storage model into actual movement: how an index walks across an array, what it costs, and when one walk is enough. Next you will use these patterns directly in **Prefix Sum & Difference Array**, where a single preprocessing pass replaces many later range-sum loops.
Not Started
0%
Code Snippets
Range-Based For Loop Patterns
The range-based `for` loop (C++11) is the idiomatic way to iterate any container or any type with `begin()` / `end()`. This snippet covers the three reference flavours (by value, by const reference, by mutable reference), iterating over arrays and `std::initializer_list`, and how to also access the index when you need it. Get the reference forms right and you avoid both copies and accidental mutations.
Iterating a Map in Go
Maps in Go are unordered: each program run randomises the iteration order to discourage code that relies on it. This snippet shows the basic `for key, value := range m` form, the comma-ok idiom for safe lookup, and the canonical pattern for iterating in sorted order. Internalise these three and you avoid the most common map bugs.
Ruby Hash Iteration Patterns
Ruby hashes preserve insertion order and play beautifully with the same `Enumerable` methods that work on arrays. This snippet covers the basic `each_pair` walk, transforming with `transform_keys` and `transform_values` (Ruby 2.4+/2.5+), and filtering plus reducing into a new hash. Use these to keep hash transformations as concise as their array counterparts.
