← Meta (Facebook) bank

Meta (Facebook) · Question 28 · Stacks

Decode String

StacksPythoncode⏱ O(n)💾 O(n)
Product-based

Problem

You are given an encoded string with pattern k[encoded_string]. Decode and return the string.

Approach

Two stacks track repeat counts and outer strings; expand on ']'.

Time O(n)Space O(n)

How it works

  1. 1Push counts and outer strings at '['.
  2. 2On ']', repeat the inner block and reattach.

Sample input / output

Input:
3[a]2[bc]
Output:
aaabcbc

Constraints

1 <= s.length <= 30; digits, letters, brackets; valid encoding.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 5Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesno↻ repeatyesnoSTARTscountSt = []strSt = []current = ""k = 0for c in sif c.isdigit()k = k * 10 + int(c)elif c == '['countSt.append(k)strSt.append(current)current = ""k = 0elif c == ']'temp = currentcurrent = strSt.pop()count = countSt.pop()current += temp * countELSEcurrent += cRETURN currentDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)s = next(it)print(decodeString(s))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/30

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits