FastPrepEncode or Decode Message

Encode or Decode Message

Goldman Sachs logoGoldman Sachs● EasyOA
Learn

Problem statement

Encode or decode a message using the decimal digits of a positive integer key.

Encoding

When operation == 1, process message characters from left to right. Repeat character i according to key digit i. If the key ends first, copy the remaining message characters once. For example, encoding Open with key 123 produces Oppeeen.

Decoding

When operation == 2, consume one equal-character group for each key digit and append one copy of that character. If the key ends first, copy the remaining suffix unchanged. For example, decoding Oppeeen with key 123 produces Open.

Return -1 when the operation is unsupported, a used key digit is zero, or a required decoding group is missing or contains different characters.

Function

encodeOrDecode(operation: int, message: String, key: int) → String

Examples

Example 1

operation = 1message = "Open"key = 123return = "Oppeeen"

Repeat O once, p twice, and e three times. The key then ends, so n is copied once, producing Oppeeen.

Example 2

operation = 2message = "Oppeeen"key = 123return = "Open"

Consume one O, two p characters, and three e characters. The remaining n is copied unchanged, producing Open.

Constraints

  • operation is an integer.
  • message is a string.
  • key is a positive 32-bit integer.

More Goldman Sachs problems

See Goldman Sachs hiring insights
public String encodeOrDecode(int operation, String message, int key) {
  // write your code here
}
operation1
message"Open"
key123
expected"Oppeeen"
Checking account…