Problem · Array

Encode and Decode a String Stream

Learn this problem
MediumPostman logoPostmanFULLTIMEONSITE INTERVIEW

Problem statement

Implement both directions of a length-prefixed string-stream protocol.

  • When operation is "ENCODE", encode values. Return a one-element array containing the encoded stream.
  • When operation is "DECODE", decode stream. Return the decoded strings and ignore values.

Each value is encoded as its decimal character length, followed by #, followed by its exact characters. Values may be empty and may themselves contain #, digits, spaces, or commas.

For DECODE, the stream is guaranteed to be a valid encoding produced by this protocol.

Function

transformStringStream(operation: String, values: String[], stream: String) → String[]

Examples

Example 1

operation = "ENCODE"values = ["api","","a#b"]stream = ""return = ["3#api0#3#a#b"]

Lengths make the empty string and the embedded delimiter unambiguous.

Example 2

operation = "DECODE"values = []stream = "5#hello5#world0#"return = ["hello","world",""]

Reading the decimal length before each delimiter recovers every original boundary.

Constraints

  • operation is either ENCODE or DECODE.
  • 0 ≤ values.length ≤ 10^5
  • Strings contain printable ASCII characters.
  • The total number of characters in the relevant input is at most 10^6.
  • For DECODE, stream is valid.

More Postman problems

drafts saved locally
public String[] transformStringStream(String operation, String[] values, String stream) {
    // write your code here
}
operation"ENCODE"
values["api","","a#b"]
stream""
expected["3#api0#3#a#b"]
checking account