Chat app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-271strings
A messaging service sends several short texts to a phone in one network packet. The sender writes each text as its length, then the character #, then the text itself, and joins all of them without a gap.
A text can hold any letter, digit or #. So the receiver cannot cut the packet at the # marks: only the length says where a text ends.
A packet can hold up to 2,000,000 characters. A text can also be empty.
Write decode_packet(packet).
packet is a valid packet: for each text it holds the length in digits, a #, and exactly that many characters.# after it begins.Input: packet = "5#hello5#world"
Output: ["hello", "world"]The decoder reads a length, then takes that many characters.
| Position | Length | Text |
|---|---|---|
| 0 | 5 | hello |
| 7 | 5 | world |
Input: packet = "3#a#13#3#x"
Output: ["a#1", "3#x"]The first text holds a # and a digit. The second text starts with a digit and holds a # too. Both are cut by length only.
Input: packet = ""
Output: []An empty packet holds no text.
0 ≤ packet.length ≤ 2,000,000 (characters in the packet)a to z, 0 to 9 and #, and it is always valid.A packet of 1,877,249 characters holds 180,000 texts of up to 16 characters each. Cutting each text off the front of a string copies everything that is left: 168,849,928,296 character copies for that packet.
Keep a position instead. Each text is read in one jump, and every character is looked at once.