Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Stack
MediumLC 394

Decode String (LeetCode 394)

Target Frequency:GoogleAmazonMetaMicrosoft

You get a string s written in a compact code: k[text] means text written out k times in a row, and text may itself contain more codes, so brackets can sit inside brackets. Expand every code and return the resulting plain string.

Every input keeps a few promises: s is always a correctly formed code, with no stray spaces and a ] for every [; each k is a positive whole number; and digits only ever appear as repeat counts, so the decoded text has no digits of its own (you will never see something like 3a or 2[4]). The inputs are also chosen so that the decoded string is at most 105 characters long.

Worked Examples

Example 1
Input:s = "3[a]2[bc]"
Output:"aaabcbc"
30[1a2]324[5b6c7]8pushpoppushpop
Explanation: 3[a] gives aaa and 2[bc] gives bcbc; written one after the other they make aaabcbc.
Example 2
Input:s = "3[a2[c]]"
Output:"accaccacc"
30[1a223[4c5]6]7pushpushpoppop
Explanation: The inner 2[c] becomes cc, so the outer bracket holds acc, and three copies of acc make accaccacc.
Example 3
Input:s = "2[abc]3[cd]ef"
Output:"abcabccdcdcdef"
20[1a2b3c4]536[7c8d9]10e11f12pushpoppushpop
Explanation: abc twice, then cd three times, then the plain letters ef at the end.

⚖️Formal Constraints & Bounds

  • 1 <= s.length <= 30

  • s consists of lowercase English letters, digits, and square brackets '[]'.

  • s is guaranteed to be a valid input.

  • All the integers in s are in the range [1, 300].

Deep-Dive & Conceptual Insights

Core Insight

Brackets close in the reverse order they open, so a stack of saved (cur, num) pairs always has the context of the bracket being closed on top: push it at [, pop it and fold the inner text back in at ].

Real-World Scenario & Production Applications

Anything that nests needs this bookkeeping: a JSON or XML parser returning to the parent object when a child closes, a template engine expanding a loop inside a loop, a compiler checking that blocks close in the order they opened. Each open level saves where the outer level was, and closing the level resumes exactly there.

Step-by-Step Execution Trace Table

Example 2, s = "3[a2[c]]" (the trap case):

chBranchWhat the code doesstack aftercurnum
3digitnum = 0 * 10 + 3[]""3
[openpush ("", 3), then reset[("", 3)]""0
alettercur += "a"[("", 3)]"a"0
2digitnum = 0 * 10 + 2[("", 3)]"a"2
[openpush ("a", 2), then reset: cur must not keep "a"[("", 3), ("a", 2)]""0
clettercur += "c"[("", 3), ("a", 2)]"c"0
]closepop ("a", 2): cur = "a" + "c" * 2[("", 3)]"acc"0
]closepop ("", 3): cur = "" + "acc" * 3[]"accaccacc"0

The loop ends and return cur gives "accaccacc".

Code Shape
Archetype Code Shape
Python
1A `[` opens a smaller problem inside the current one, and the outer text has to wait for it: save the outer state before you go in, and restore it when the bracket closes.
2`stack` holds one saved `(cur, num)` per `[` still open, innermost on top: brackets close in reverse order, so the top is always the context the next `]` needs.
3Loop `for ch in s` with four branches: a digit extends `num`, `[` pushes, `]` pops and folds with `cur = prev + cur * k`, a letter does `cur += ch`; `return cur` at the end.
4The trap: right after `stack.append((cur, num))`, reset `cur, num = "", 0`, or the outer text is repeated inside the bracket and the next count's digits are glued onto the old one.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Brackets inside brackets look like they need recursion: decode the inside first, then come back out. The Nesting Stack does the same work in one loop. A [ starts a smaller problem inside the current one, so the outer text and its repeat count are put aside on stack, and the inner text starts empty. A ] finishes the most recent [, so the pair on top of stack is exactly the one to come back to: pop it, and put the inner text back in, k times, after the outer text.

📞 The Analogy: Calls on Hold

You are on a phone call when a second call comes in. You put the first caller on hold, noting where you were, and answer the new one. A third call arrives, so the second goes on hold too. When a call ends, you always go back to the caller you put on hold most recently, and carry on exactly where you left off. The hold list is stack, the current call is cur, and hanging up is ]. The one thing you must never do is carry the old conversation into the new call: after putting a caller on hold, you start the new call fresh.

🔑 Why It Works

Brackets close in the reverse order they open, so the top of stack always belongs to the bracket being closed; everything below it waits untouched for its own ]. The reset right after the push is what keeps the levels apart: without cur, num = "", 0 the outer text would be repeated inside the bracket.

  • Not resetting after the push: stack.append((cur, num)) must be followed by cur, num = "", 0. Keep cur and "3[a2[c]]" returns "aacacaacacaacac"; keep num and the inner count is read as 32.

  • Reading only one digit: num = int(ch) keeps only the last digit of a count, so "10[a]" repeats a zero times. Use num = num * 10 + int(ch).

  • Folding in the wrong order: the saved text came before the [, so it goes first: cur = prev + cur * k, not cur * k + prev ("a2[c]" is "acc", not "cca").

  • One saved context instead of a stack: a single saved text works for one level only; a bracket inside a bracket overwrites it and the outer text is lost. One saved pair per open [ is what stack gives.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"k[text] repeats text k times" and brackets that can sit inside brackets: an inner part has to be decoded completely before the text around it can continue. Nesting where the last bracket opened is the first one closed is the signal for the Nesting Stack.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Decision rule, one character at a time: at [, stack.append((cur, num)), then cur, num = "", 0; at ], prev, k = stack.pop(), then cur = prev + cur * k; a digit extends num, a letter extends cur.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • num = num * 10 + int(ch), not num = int(ch): counts go up to 300, so "10[a]" must repeat 10 times, not 0.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use a Nesting Stack. Each bracket is a smaller problem inside the current one, and the outer text has to wait until it is finished. So I keep cur, the text of the innermost open bracket, and num, the count I'm reading. I scan once. A digit extends num: times ten plus the digit, so counts like twelve work. A letter goes onto cur. At an open bracket I push the pair cur and num onto the stack, then reset both, so the inner text starts empty. Forgetting that reset is the classic bug: the outer text would be repeated inside. At a close bracket I pop the saved text and count, and set cur to the saved text plus cur repeated k times. Brackets close in reverse order, so the top of the stack is always the one I need. Time is O(N times L), where L is the output length, and space is O(N plus L).

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N * L)

Look at the code: for ch in s runs N times. A digit costs O(1), and a [ pushes one pair and resets two variables, also O(1). A letter runs cur += ch, which may copy cur, and a ] builds prev + cur * k, a new string. Both results are pieces of the decoded string, so each is at most L characters, and each such step costs at most O(L). Total: at most N steps of O(L), so O(N * L).

SPACE COMPLEXITY

O(N + L)

stack holds at most one pair per [, so at most N pairs. Their saved texts are different pieces of the decoded string that do not overlap (each is the text before a different open [), so together with cur they hold at most L characters. Space: O(N + L), and the returned string is L of it.

Formal Recurrence Relation

T(N, L) = N · O(L) = O(N · L)

Derivation Progression

Start

O(1)

stack = [], cur = "" and num = 0 are three assignments.

Character loop

N iterations

for ch in s reads each character once.

Digit or [

O(1) per character

num = num * 10 + int(ch), or one push of (cur, num) and the reset cur, num = "", 0.

Letter or ]

O(L) per character at most

cur += ch and cur = prev + cur * k each build a string that is part of the decoded string, so at most L characters.

Total

O(N · L)

At most N steps, each at most O(L).

Variable Definitions

NNN

Length of the input, len(s) (at most 30)

LLL

Length of the decoded string (at most 10^5)

kkk

A repeat count popped at ] (1 to 300)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative, no recursion

🔵 Auxiliary Heap

O(N + L): at most N saved pairs whose texts, with cur, total at most L characters

🟢 Output Space

O(L): the decoded string

Boundary Best / Worst Cases

Best Case

O(N+L)O(N + L)O(N+L): one bracket with nothing before it, such as 300[z]: only the final prev + cur * k builds a long string

Average Case

Between the two; at LeetCode's limits (N <= 30, L <= 10^5) it is at most about 3 · 10^6 character copies

Worst Case

O(N⋅L)O(N \cdot L)O(N⋅L): a long text rebuilt at many ], such as 100[a]1[b]1[c]1[d]1[e]1[f]: every later ] copies the long prev again

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "k[text] means text written k times", "brackets can sit inside brackets". An inner part must be finished before the text around it can continue, and the last bracket opened is the first one closed: a Nesting Stack of saved (cur, num) pairs.

CONSTRAINTS & BOUNDS

N≤30N \le 30N≤30 input characters but up to L=105L = 10^5L=105 output characters, so the cost is in building the output, not in reading s. Each step builds at most LLL characters: O(N⋅L)O(N \cdot L)O(N⋅L) time at worst, about 3×1063 \times 10^63×106 character copies at these limits, and O(N+L)O(N + L)O(N+L) space.

FAANG PRODUCTION TRAPS & EDGE CASES

At scale the danger is the output, not the input: 26 characters, 10[10[10[10[abcdefghij]]]], decode to 10510^5105, so a decoder that accepts untrusted input checks the decoded size before it builds it. A recursive decoder uses the call stack as its stack; the explicit stack keeps deep nesting from overflowing it.

Core Algorithmic State Invariants

  1. Valid Input Is What Makes pop Safe

LeetCode promises a valid string, so every ] finds a saved pair and stack is empty at the end. A decoder for untrusted text checks stack before stack.pop() and after the loop, and rejects the input instead of crashing.

  1. Letters After ] Need No Special Case

After ], cur is the outer text again with the decoded bracket folded in, so a letter that follows, as in "2[a]b", simply goes onto cur and lands at the right level: "aab".

Theory Context•Stack
MediumLC 394

Decode String (LeetCode 394)

Target Frequency:GoogleAmazonMetaMicrosoft

You get a string s written in a compact code: k[text] means text written out k times in a row, and text may itself contain more codes, so brackets can sit inside brackets. Expand every code and return the resulting plain string.

Every input keeps a few promises: s is always a correctly formed code, with no stray spaces and a ] for every [; each k is a positive whole number; and digits only ever appear as repeat counts, so the decoded text has no digits of its own (you will never see something like 3a or 2[4]). The inputs are also chosen so that the decoded string is at most 105 characters long.

Worked Examples

Example 1
Input:s = "3[a]2[bc]"
Output:"aaabcbc"
30[1a2]324[5b6c7]8pushpoppushpop
Explanation: 3[a] gives aaa and 2[bc] gives bcbc; written one after the other they make aaabcbc.
Example 2
Input:s = "3[a2[c]]"
Output:"accaccacc"
30[1a223[4c5]6]7pushpushpoppop
Explanation: The inner 2[c] becomes cc, so the outer bracket holds acc, and three copies of acc make accaccacc.
Example 3
Input:s = "2[abc]3[cd]ef"
Output:"abcabccdcdcdef"
20[1a2b3c4]536[7c8d9]10e11f12pushpoppushpop
Explanation: abc twice, then cd three times, then the plain letters ef at the end.

⚖️Formal Constraints & Bounds

  • 1 <= s.length <= 30

  • s consists of lowercase English letters, digits, and square brackets '[]'.

  • s is guaranteed to be a valid input.

  • All the integers in s are in the range [1, 300].

Deep-Dive & Conceptual Insights

Core Insight

Brackets close in the reverse order they open, so a stack of saved (cur, num) pairs always has the context of the bracket being closed on top: push it at [, pop it and fold the inner text back in at ].

Real-World Scenario & Production Applications

Anything that nests needs this bookkeeping: a JSON or XML parser returning to the parent object when a child closes, a template engine expanding a loop inside a loop, a compiler checking that blocks close in the order they opened. Each open level saves where the outer level was, and closing the level resumes exactly there.

Step-by-Step Execution Trace Table

Example 2, s = "3[a2[c]]" (the trap case):

chBranchWhat the code doesstack aftercurnum
3digitnum = 0 * 10 + 3[]""3
[openpush ("", 3), then reset[("", 3)]""0
alettercur += "a"[("", 3)]"a"0
2digitnum = 0 * 10 + 2[("", 3)]"a"2
[openpush ("a", 2), then reset: cur must not keep "a"[("", 3), ("a", 2)]""0
clettercur += "c"[("", 3), ("a", 2)]"c"0
]closepop ("a", 2): cur = "a" + "c" * 2[("", 3)]"acc"0
]closepop ("", 3): cur = "" + "acc" * 3[]"accaccacc"0

The loop ends and return cur gives "accaccacc".

Code Shape
Archetype Code Shape
Python
1A `[` opens a smaller problem inside the current one, and the outer text has to wait for it: save the outer state before you go in, and restore it when the bracket closes.
2`stack` holds one saved `(cur, num)` per `[` still open, innermost on top: brackets close in reverse order, so the top is always the context the next `]` needs.
3Loop `for ch in s` with four branches: a digit extends `num`, `[` pushes, `]` pops and folds with `cur = prev + cur * k`, a letter does `cur += ch`; `return cur` at the end.
4The trap: right after `stack.append((cur, num))`, reset `cur, num = "", 0`, or the outer text is repeated inside the bracket and the next count's digits are glued onto the old one.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Brackets inside brackets look like they need recursion: decode the inside first, then come back out. The Nesting Stack does the same work in one loop. A [ starts a smaller problem inside the current one, so the outer text and its repeat count are put aside on stack, and the inner text starts empty. A ] finishes the most recent [, so the pair on top of stack is exactly the one to come back to: pop it, and put the inner text back in, k times, after the outer text.

📞 The Analogy: Calls on Hold

You are on a phone call when a second call comes in. You put the first caller on hold, noting where you were, and answer the new one. A third call arrives, so the second goes on hold too. When a call ends, you always go back to the caller you put on hold most recently, and carry on exactly where you left off. The hold list is stack, the current call is cur, and hanging up is ]. The one thing you must never do is carry the old conversation into the new call: after putting a caller on hold, you start the new call fresh.

🔑 Why It Works

Brackets close in the reverse order they open, so the top of stack always belongs to the bracket being closed; everything below it waits untouched for its own ]. The reset right after the push is what keeps the levels apart: without cur, num = "", 0 the outer text would be repeated inside the bracket.

  • Not resetting after the push: stack.append((cur, num)) must be followed by cur, num = "", 0. Keep cur and "3[a2[c]]" returns "aacacaacacaacac"; keep num and the inner count is read as 32.

  • Reading only one digit: num = int(ch) keeps only the last digit of a count, so "10[a]" repeats a zero times. Use num = num * 10 + int(ch).

  • Folding in the wrong order: the saved text came before the [, so it goes first: cur = prev + cur * k, not cur * k + prev ("a2[c]" is "acc", not "cca").

  • One saved context instead of a stack: a single saved text works for one level only; a bracket inside a bracket overwrites it and the outer text is lost. One saved pair per open [ is what stack gives.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"k[text] repeats text k times" and brackets that can sit inside brackets: an inner part has to be decoded completely before the text around it can continue. Nesting where the last bracket opened is the first one closed is the signal for the Nesting Stack.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Decision rule, one character at a time: at [, stack.append((cur, num)), then cur, num = "", 0; at ], prev, k = stack.pop(), then cur = prev + cur * k; a digit extends num, a letter extends cur.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • num = num * 10 + int(ch), not num = int(ch): counts go up to 300, so "10[a]" must repeat 10 times, not 0.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use a Nesting Stack. Each bracket is a smaller problem inside the current one, and the outer text has to wait until it is finished. So I keep cur, the text of the innermost open bracket, and num, the count I'm reading. I scan once. A digit extends num: times ten plus the digit, so counts like twelve work. A letter goes onto cur. At an open bracket I push the pair cur and num onto the stack, then reset both, so the inner text starts empty. Forgetting that reset is the classic bug: the outer text would be repeated inside. At a close bracket I pop the saved text and count, and set cur to the saved text plus cur repeated k times. Brackets close in reverse order, so the top of the stack is always the one I need. Time is O(N times L), where L is the output length, and space is O(N plus L).

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N * L)

Look at the code: for ch in s runs N times. A digit costs O(1), and a [ pushes one pair and resets two variables, also O(1). A letter runs cur += ch, which may copy cur, and a ] builds prev + cur * k, a new string. Both results are pieces of the decoded string, so each is at most L characters, and each such step costs at most O(L). Total: at most N steps of O(L), so O(N * L).

SPACE COMPLEXITY

O(N + L)

stack holds at most one pair per [, so at most N pairs. Their saved texts are different pieces of the decoded string that do not overlap (each is the text before a different open [), so together with cur they hold at most L characters. Space: O(N + L), and the returned string is L of it.

Formal Recurrence Relation

T(N, L) = N · O(L) = O(N · L)

Derivation Progression

Start

O(1)

stack = [], cur = "" and num = 0 are three assignments.

Character loop

N iterations

for ch in s reads each character once.

Digit or [

O(1) per character

num = num * 10 + int(ch), or one push of (cur, num) and the reset cur, num = "", 0.

Letter or ]

O(L) per character at most

cur += ch and cur = prev + cur * k each build a string that is part of the decoded string, so at most L characters.

Total

O(N · L)

At most N steps, each at most O(L).

Variable Definitions

NNN

Length of the input, len(s) (at most 30)

LLL

Length of the decoded string (at most 10^5)

kkk

A repeat count popped at ] (1 to 300)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative, no recursion

🔵 Auxiliary Heap

O(N + L): at most N saved pairs whose texts, with cur, total at most L characters

🟢 Output Space

O(L): the decoded string

Boundary Best / Worst Cases

Best Case

O(N+L)O(N + L)O(N+L): one bracket with nothing before it, such as 300[z]: only the final prev + cur * k builds a long string

Average Case

Between the two; at LeetCode's limits (N <= 30, L <= 10^5) it is at most about 3 · 10^6 character copies

Worst Case

O(N⋅L)O(N \cdot L)O(N⋅L): a long text rebuilt at many ], such as 100[a]1[b]1[c]1[d]1[e]1[f]: every later ] copies the long prev again

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "k[text] means text written k times", "brackets can sit inside brackets". An inner part must be finished before the text around it can continue, and the last bracket opened is the first one closed: a Nesting Stack of saved (cur, num) pairs.

CONSTRAINTS & BOUNDS

N≤30N \le 30N≤30 input characters but up to L=105L = 10^5L=105 output characters, so the cost is in building the output, not in reading s. Each step builds at most LLL characters: O(N⋅L)O(N \cdot L)O(N⋅L) time at worst, about 3×1063 \times 10^63×106 character copies at these limits, and O(N+L)O(N + L)O(N+L) space.

FAANG PRODUCTION TRAPS & EDGE CASES

At scale the danger is the output, not the input: 26 characters, 10[10[10[10[abcdefghij]]]], decode to 10510^5105, so a decoder that accepts untrusted input checks the decoded size before it builds it. A recursive decoder uses the call stack as its stack; the explicit stack keeps deep nesting from overflowing it.

Core Algorithmic State Invariants

  1. Valid Input Is What Makes pop Safe

LeetCode promises a valid string, so every ] finds a saved pair and stack is empty at the end. A decoder for untrusted text checks stack before stack.pop() and after the loop, and rejects the input instead of crashing.

  1. Letters After ] Need No Special Case

After ], cur is the outer text again with the decoded bracket folded in, so a letter that follows, as in "2[a]b", simply goes onto cur and lands at the right level: "aab".

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•