Custom Data Structures
An advanced pattern from Educative Grokking for Custom Data Structures.
Recognition
- The problem asks for relationships between positions, windows, or ordered state.
- A brute-force nested loop can be reduced by maintaining local pointers or state.
When not to use it
Do not force this pattern when the input is unordered and hashing is enough.
Avoid coding the template before naming the invariant you need to preserve.
Logic template
Python
# To be added
passJavaScript
// To be added
Typically better than the obvious O(N^2) approach; verify with the template.
- Name what stays true after every move.
- Track the exact condition that lets you discard work safely.
Worked example
Recognition drill
Identify the reusable state and the rule that advances it.
- Restate the goal in one sentence.
- Name the moving parts and what they represent.
- Write the loop invariant before coding.
- Trace one failing case that breaks a naive approach.
Result: You can explain when to reach for the pattern and when to abandon it.
Common pitfalls
- Off-by-one updates on loop bounds.
- Updating state after comparing instead of before.
- Confusing “solved once” with pattern mastery.