Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Stack Medium frequency Solution Available Practice Mode

Decode String LeetCode Solution

Tags: #String #Stack #Recursion

Approach Summary

Use stack to track (current_string, repeat_count). On ], pop and repeat the current segment.

Practice Mode

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Stack Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Stack pattern.

Framework: Stack • Interview Prep: Tested at FAANG • Explore all Stack problems & invariants →

How to Recognize This Pattern

  • Nested repeated patterns
  • k[encoded_string]

Complexity Analysis

Time Complexity

O(n · k)

Space Complexity

O(n)

Tags

String Stack Recursion

Frequently Asked Questions

What is the optimal time and space complexity for Decode String?
The optimal solution for Decode String achieves O(n · k) runtime complexity and requires O(n) auxiliary space. Each character is scanned once and each stack operation is O(1) — but the decoded output can be exponential, so the worst case is O(final output length). The stack holds one pair per nesting level — O(depth).
How do I identify that Decode String requires the Stack pattern?
In technical interviews, look for key problem signals: Nested repeated patterns; k[encoded_string]. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Stack strategy.
What critical edge cases must be handled in Decode String?
Essential edge cases to verify include: Multi-digit repeat counts like 10[a]; Deeply nested patterns like 3[a2[b1[c]]]; Letters before any bracket — appended normally; Empty encoded string. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Decode String?
Decode String is a Medium-difficulty question tagged with medium recurrence. It is actively asked in technical screening and onsite interview loops at Google, Amazon, Bloomberg.
Buy me a coffee
Daily Practice
0/0