Beyond Big O

Framed message decoder

Framed message decoder

Medium

Solution guide

Reveal solution guide — spoilers

Approach

  1. Append incoming bytes to retained input and keep a cursor for the next frame header. Require both header bytes before decoding a big-endian payload length.
  2. Reject an oversized declared length as soon as the complete header is available. Otherwise require the whole header plus payload before emitting a frame; do not confuse an incomplete payload with a complete frame.
  3. Advance over each complete frame, including empty frames, and retain the unconsumed suffix exactly. Return the contract’s frames, remaining bytes and explicit error outcome.

Why it works

The cursor advances only over complete frames, preserving incomplete header and payload bytes for later input. Header-plus-payload checks prevent slicing beyond available input. Testing declared length before waiting for payload makes oversized input fail at the correct boundary.

Complexity

O(B + F) time for B total bytes and F emitted frames when buffering and cursor movement avoid repeated copying; O(B + F) retained input/output space in the bounded exercise. Repeatedly copying the full retained buffer can be quadratic across many small chunks.

Edge cases to check

  • A header may be split across chunks, and one chunk may contain several frames.
  • A zero-length frame is complete after its header; an incomplete final frame remains buffered.
  • A length one above the configured maximum is rejected without consuming the invalid tail.
Editor options
Typing preferences

Saved in this browser.

Restoring local drafts…