← Google bank

Google · Question 20 · Strings

Encode and Decode Strings

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

Problem

Design an algorithm to encode a list of strings to a single string and decode it back.

Approach

Use length - prefixed encoding to avoid delimiter issues.

Time O(n)Space O(n)

How it works

  1. 1Encode each string with its length and a delimiter.
  2. 2During decode, read the length, then extract the substring.
  3. 3Avoid delimiter collision via the length prefix.
  4. 4Reconstruct the original list accurately.

Sample input / output

Input:
2
hello world
Output:
['hello', 'world']

Constraints

0 <= strs.length <= 200; 0 <= strs[i].length <= 200; strings contain any UTF-8 chars.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 1Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyesnoSTARTstrsRETURN''.join(f"{len(s)}#{s}" fors in strs)DEFINE decode(s)res, i = [], 0while i < len(s)j = s.find('#', i)length = int(s[i:j])res.append(s[j + 1:j + 1 +length])i = j + 1 + lengthRETURN resDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))strs = [next(it) for _ inrange(n)]print(decode(encode(strs)))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/20

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