Skip to content
Interview strategy

How to Remember LeetCode Solutions: Patterns, Re-Solves and Flashcards

To remember LeetCode solutions, stop trying to remember the code. Store three things per problem instead: the trigger that tells you which pattern applies, the invariant that makes the pattern correct, and the pitfall that broke your first attempt. Then re-solve the problem from a blank file on a widening schedule. This guide explains why a problem you solved last month feels new today, shows five example flashcards for coding patterns, gives a re-solve protocol and a tracker you can copy, and says where cards stop helping and typing code has to take over.

By Published

11 min readEditorial analysisUpdated
  • LeetCode
  • spaced repetition
  • coding interview
  • Anki
  • study method
What to remember

You forget solutions because reading and one-time solving feel like learning but give memory little retrieval practice. Keep a short card per pattern (trigger, invariant, complexity, pitfall), re-code missed problems from a blank file after about 1, 3, 7 and 21 days, and judge progress by cold re-solves, not by the solved counter.

Why LeetCode solutions fade after you solve them

A problem you solved three weeks ago looks unfamiliar for a simple reason: solving it once, or reading an editorial until it made sense, built familiarity rather than retrieval. Roediger and Karpicke tested the difference in 2006 with students learning short prose passages. In their first experiment, a passage that students studied twice was recalled better five minutes later than a passage they studied once and then wrote down from memory: 81 percent of the idea units against 75 percent. Two days later the order had flipped, 54 percent against 68 percent, and after a week it was 42 percent against 56 percent.

The second experiment adds the part that matters for LeetCode. Students who studied a passage in four periods were more confident that they would remember it than students who studied it once and recalled it three times. A week later the first group recalled 40 percent and the second 61 percent. An accepted submission followed by a skim of the top solutions is the rereading condition: fluent, satisfying and weak a week later. The study used prose, not algorithm problems, so the percentages illustrate the mechanism; they do not forecast your next interview.

Remember the trigger, pattern and invariant, not the code

Code is the least durable layer of a solution and the least useful one to keep. An interviewer will rarely ask the exact problem you practiced; they ask a relative of it, and what transfers is recognition (which family is this?) and the invariant (why does the loop stay correct?). LeetCode's own study plans are organized the same way: as of November 14, 2026, its study plan page describes the dynamic programming plan as “10 Essential DP Patterns” and the binary search plan as “8 Patterns, 42 Qs”.

So store five short lines per pattern: the trigger, the pattern's one-line skeleton, the invariant, the complexity with its reason, and your pitfall. The trigger is the phrase or constraint that should bring the pattern to mind. The invariant is one sentence that is true every time the loop body finishes; if you can say it, you can usually rebuild the code, and if you cannot, memorized code will break on the first variation. The pitfall is personal: write the bug you actually hit, not a generic warning.

What one good LeetCode flashcard looks like

A useful card for a coding problem does not put the problem statement on the front and thirty lines of code on the back. The front describes the situation in your own words, short enough to read in five seconds; pasting the statement copies someone else's text and trains you to recognize a title instead of a situation. The back has five labeled lines. If you cannot write the invariant in one sentence, the card is not ready; go back to the problem.

Here are five cards in that format: sliding window, two pointers, binary search on the answer, monotonic stack and one-dimensional dynamic programming. To use a card, cover the back, say the pattern and the invariant aloud, then check. Grade yourself on the invariant, not on whether the name came to mind.

CARD 1
Front: Longest contiguous run of a string that satisfies a limit
       (for example, at most k distinct characters).
Trigger:    "longest/shortest contiguous" + a condition that breaks as the run grows
Pattern:    variable sliding window: grow right, shrink left while invalid
Invariant:  after the inner loop, s[left..right] satisfies the limit
Complexity: O(n) time, each index enters and leaves once; O(k) space
Pitfall:    I updated the best length before shrinking

CARD 2
Front: Sorted array; find two values that add up to a target with O(1) extra space.
Trigger:    sorted input + a condition on a pair
Pattern:    two pointers from both ends; sum too small -> lo += 1, too big -> hi -= 1
Invariant:  no valid pair uses an index outside [lo, hi]
Complexity: O(n) time, O(1) space
Pitfall:    input was not sorted; that case needs a hash map instead

CARD 3
Front: Smallest capacity (or speed) that still finishes the work within a deadline.
Trigger:    "minimum X such that it is possible" and feasibility is monotonic in X
Pattern:    binary search on the answer with a greedy feasible(X) check
Invariant:  everything below lo is infeasible; hi is feasible
Complexity: O(n log R), R = size of the answer range
Pitfall:    lower bound too small (capacity must be at least the largest item)

CARD 4
Front: For every element, find the next larger element to its right.
Trigger:    "next greater/smaller", "days until", spans
Pattern:    stack of indices still waiting for an answer; pop while current is larger
Invariant:  values at the stacked indices never increase from bottom to top
Complexity: O(n) time, each index is pushed and popped at most once; O(n) space
Pitfall:    stored values instead of indices, so I could not compute distances

CARD 5
Front: Row of non-negative numbers; pick some with no two adjacent, maximize the sum.
Trigger:    take-or-skip choices along a line; best answer for a prefix
Pattern:    1-D DP: best[i] = max(best[i-1], best[i-2] + a[i])
Invariant:  best[i] is the optimum using only items 0..i
Complexity: O(n) time, O(1) space with two variables
Pitfall:    forgot the base cases for zero and one item

A re-solve protocol: same day, then 1, 3, 7 and 21 days

Cards protect recognition; only re-solving protects execution. For every problem you could not solve cleanly (you needed a hint, ran out of time or shipped a bug), re-code it from a blank file at widening gaps. The ladder of 1, 3, 7 and 21 days after the miss is our rule of thumb, not a figure from a study. What research supports is the shape. Cepeda and colleagues taught facts to more than 1,350 people, gave them one review session and tested them later. The best gap before the review was about 20 to 40 percent of the delay when the test came a week later, and about 5 to 10 percent when it came a year later. Their material was facts, not code, but for an interview a few weeks out the result points to gaps of days, not hours.

Two rules make the protocol work. First, attempt before you look. Kornell, Hays and Bjork found that trying to answer before seeing the answer improved later learning even when the attempt failed. Their materials were made-up general-knowledge questions and word pairs, not code, so treat this as an extrapolation. Set a timer, and if you are stuck, read only the step you are missing, then close the solution. Second, let results move the problem: a clean pass sends it to the next gap, a failure sends it back one step. Problems you solved cleanly the first time need only the card and one check about a week later.

Re-solve protocol for a problem you missed
WhenWhat to doA pass meansIf you fail
Same dayClose the solution; re-code from a blank fileIt runs on your own tests without peekingRead the stuck step only; retry in an hour
+1 daySay trigger and invariant aloud, then codeNo hints, inside your time limitStay at +1 day
+3 daysCode it again, then change one constraintYou explain the complexity while typingBack to +1 day
+7 daysSolve a different problem of the same patternYou name the pattern within two minutesBack to +3 days
+21 daysCold re-solve inside a mixed, timed setClean code and a clear explanationBack to +7 days

When flashcards do not help: code you have to type

A card can make you say “variable window, shrink while invalid” and still leave you unable to write the loop under pressure. The errors that sink a coding round are small: an off-by-one in the window length, a count that is never deleted when it reaches zero, an answer updated in the wrong place. Only typing exposes them. Below is a re-solve of the first card, written without a reference and run against invented cases.

Run with Python 3.12.8, the script prints 3, 3, 0 and 0. The first two are the windows “ece” and “aaa”; the last two are the edge cases, k equal to zero and an empty string. The k = 0 case is correct only because the shrink loop runs before the answer is updated, which is exactly the pitfall on the card. Cards also do not train thinking aloud, debugging a failing case or managing the clock, so keep timed sets and mock interviews as separate, scheduled work.

from collections import Counter


def longest_with_k_distinct(s: str, k: int) -> int:
    """Length of the longest substring with at most k distinct characters."""
    counts = Counter()
    best = left = 0
    for right, ch in enumerate(s):
        counts[ch] += 1                      # grow: take s[right] into the window
        while len(counts) > k:               # shrink until the invariant holds again
            counts[s[left]] -= 1
            if counts[s[left]] == 0:
                del counts[s[left]]
            left += 1
        best = max(best, right - left + 1)   # window s[left..right] is valid here
    return best


print(longest_with_k_distinct("eceba", 2))
print(longest_with_k_distinct("aaabbcc", 1))
print(longest_with_k_distinct("abc", 0))
print(longest_with_k_distinct("", 3))

A tracker table, and Anki settings for LeetCode

The tracker is one row per missed problem. Label problems in your own words, record the pattern and what went wrong, and keep one date: the next re-solve. A spreadsheet is enough.

For the cards, many people use Anki. As of November 14, 2026, Anki's documentation says its default scheduler is based on SM-2 and that FSRS is an optional alternative you switch on in deck options, with desired retention defaulting to 90 percent. The manual also warns about volume: learn 20 new cards a day and you can expect roughly 200 reviews a day. A card that keeps failing becomes a leech; by default Anki tags it and suspends it after 8 lapses.

A spaced-repetition app such as RecallDeck can hold the concept side of preparation (complexity, data structure behavior, language semantics) while the tracker holds the problems you must re-code.

  • Add one card per pattern or per real mistake, not one per problem; reviews compound quickly.
  • Keep the default scheduler settings at first. If you enable FSRS, stay near the 90 percent default; the manual says workload increases drastically as desired retention approaches 100 percent and recommends keeping it below 97 percent.
  • Treat a leech as a message: rewrite the card, or go back and re-solve the problem, because the idea has probably not been understood yet.
  • When overdue reviews pile up, stop adding new cards until you catch up, as the manual recommends.
Sample re-solve tracker (labels are your own words, not problem statements)
Problem labelPatternFirst resultNext re-solveStatus
At most k distinct charactersVariable windowNeeded a hint+3 days2 clean passes
Ship everything within D daysBinary search on the answerWrong lower bound+1 dayReset once
Next warmer dayMonotonic stackSolved in 40 minutes+7 days1 clean pass
Non-adjacent maximum sum1-D DPClean, in timeCard onlyDone

A weekly routine that keeps old problems alive

Dunlosky and colleagues reviewed ten study techniques in 2013 and gave two of them a high utility rating: practice testing and distributed practice. Interleaved practice, mixing problem types instead of working one type in a block, was rated moderate: promising, with less evidence behind it. For interview preparation the argument for mixing is practical: the interviewer does not tell you which pattern applies. Once a week, pull four or five old problems from different patterns, hide the labels, and solve them against a clock.

In a normal session, do things in this order: due cards first, due re-solves second, new problems last. New problems feel like progress and re-solves feel like repetition, so the order protects the work that prevents forgetting. As a rule of thumb, once the tracker has a backlog, give re-solves about a third of your coding time.

  • Per new problem: write the five-line card before you close the tab.
  • Weekly: delete or rewrite cards you failed twice for wording reasons.

Quick answers

Frequently asked questions

How do I stop forgetting LeetCode solutions?

Re-solve instead of rereading. After a miss, re-code the problem from a blank file the same day and again roughly 1, 3, 7 and 21 days later (a rule of thumb, not a studied schedule), and keep a five-line card for the pattern. In Roediger and Karpicke's 2006 experiments with prose passages, practicing recall beat restudying on tests two days and a week later.

Should I memorize LeetCode solutions?

Not the code, because memorized code fails on the first variation. Memorize the trigger that identifies the pattern, the invariant that keeps it correct, the complexity and your own pitfall. Then prove you can rebuild the code by typing it without a reference.

Is Anki good for LeetCode?

It is good for the recognition layer: triggers, invariants, complexity and pitfalls, with one card per pattern or real mistake. It does not train typing a solution under time pressure, so pair it with scheduled re-solves, and add cards sparingly so the daily reviews stay finishable.

How do I remember LeetCode patterns instead of individual problems?

Write one card per pattern with its trigger and invariant, then practice recognition directly: once a week, take old problems from several patterns with the labels hidden and name the pattern before coding. Solving a different problem of the same pattern is a better test than repeating the original.

Source notes

References and review policy

Information checked on November 14, 2026. Section links identify sources for factual claims and technical explanations. Interpretations, practice scenarios and preparation recommendations are RecallDeck’s editorial work.

From reading to recall

Practice the full interview loop.

RecallDeck schedules the concepts you miss and keeps coding, design, and behavioral fundamentals available when the interviewer changes direction.

Start studying

Keep going

Interview strategy3 min

How to Prepare for a System Design Interview

Prepare for a system design interview with a repeatable framework for requirements, estimates, architecture, data, failure, and trade-offs.

2 quick answers