AlgoMaster Logo
AlgoMasterReassemble TCP Segmentsmedium

Reassemble TCP Segments

medium

TCP exposes an ordered byte stream even though network segments can arrive out of order, overlap, or be duplicated. A receiver can buffer later bytes, but it can advance its acknowledgment only through the contiguous prefix with no gap.

Design a TcpSegmentReassembler class:

  • TcpSegmentReassembler() creates a stateless reassembler.
  • int nextExpected(int[][] segments) returns the first byte sequence number that has not been received contiguously from byte 0.

Each segment is [seq, length] and covers the half-open interval [seq, seq + length). The input can be out of order and intervals can overlap. Do not mutate segments, and treat each call independently.

Example 1:

Input:

Output:

Explanation: The first segment covers bytes [0,3). The second covers [5,7), leaving a gap at bytes 3 and 4, so the receiver still expects byte 3.

Example 2:

Input:

Output:

Explanation: Arrival order does not matter. Sorting reveals [0,3) followed immediately by [3,5), so all bytes before 5 are present.

Constraints

  • 0 <= segments.length <= 10^5
  • segments[i].length == 2
  • 0 <= segments[i][0] <= 10^9
  • 1 <= segments[i][1] <= 10^9
  • segments[i][0] + segments[i][1] <= 2 * 10^9
  • At most 100 calls are made to nextExpected.
Hints

Loading...
CallReturns
new TcpSegmentReassembler()null
nextExpected([[0,3],[5,2]])3

Bytes 0 through 2 are present, but bytes 3 and 4 are missing. The next expected byte is 3.

Run checks these cases. Submit also runs a larger hidden set.