01

1. Restate the contract before coding

Write down what enters the function, what must come out, and what conditions are guaranteed. Separate facts from guesses. In algorithm problems, clarify empty inputs, duplicates, ordering, overflow, mutability, and whether one or many answers may exist.

A precise contract prevents you from solving a nearby problem instead of the actual one.

02

2. Start with the simplest correct model

Describe the brute-force solution first, even if you will not implement it. It gives you a correctness baseline and exposes the repeated work that an optimization must remove.

For example, Two Sum's nested loop repeatedly searches for a complement. Naming that repeated search suggests a hash map. Optimization becomes a reasoned transformation rather than a remembered trick.

03

3. State the invariant

An invariant is what remains true while the algorithm changes state. A sliding window might always contain a valid substring. A binary-search interval might always contain every possible answer. A stack might remain monotonic.

If you cannot say what your loop preserves, the code is probably still being written by intuition alone. One clear invariant often replaces several patches.

04

4. Use names that carry reasoning

Names such as left, right, remaining, best, and lastSeen tell the reader what role a value plays. Names such as a, temp2, and x1 force the reader to reconstruct that role repeatedly.

Keep functions small enough to have one job. Extract a helper when it creates a useful concept, not merely to reduce line count.

  • Name booleans as claims: isValid, hasCycle, canFinish
  • Name collections by contents: positionsByValue, pendingNodes
  • Prefer early returns when they remove nested branches
  • Comment the reason or invariant, not a translation of the next line
05

5. Test boundaries before the happy path feels finished

Use a tiny normal example, the smallest legal input, duplicates, an already-sorted or reversed case, and an input where the answer sits at the boundary. Trace variables by hand for one example before trusting the runtime.

Finally, compare the implementation against the stated complexity. A loop hidden inside a loop, a costly slice, or a repeated search can quietly invalidate the intended bound.

06

The effective-coding loop

  • Understand the contract
  • Model a simple correct approach
  • Identify repeated work
  • Choose a data structure and state the invariant
  • Implement in small verifiable steps
  • Test boundaries
  • Review clarity and complexity