FastPrepMinimum Data Chunks with an Indivisible Header

Minimum Data Chunks with an Indivisible Header

Google logoGoogle● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

You are sending a payload of data bytes with a leading header of header bytes. Split the transmission into the fewest possible chunks, each containing at most maxChunkSize bytes, and return their sizes in transmission order.

The payload may be split at any integer byte boundary. The entire header must be in the first chunk, and payload bytes may share that chunk. A header of size 0 represents a transmission without a header. Every returned chunk must have positive size, and the sizes must sum to data + header.

Use this deterministic allocation among solutions with the minimum number of chunks:

  • If the total size is 0, return an empty array.
  • If one chunk is sufficient, return the total size as its only element.
  • Otherwise, let K be the minimum chunk count and T = data + header. Set the first size to max(header, floor(T / K)).
  • Divide the remaining bytes as evenly as possible among the remaining K - 1 chunks. Their sizes differ by at most 1; place smaller sizes before larger sizes.

Function

splitDataWithHeader(data: int, header: int, maxChunkSize: int) → int[]

Examples

Example 1

data = 1800header = 0maxChunkSize = 700return = [600,600,600]

Two chunks hold at most 1400 bytes, so three are necessary. Without a header, the evenly divided sizes are [600,600,600].

Example 2

data = 300header = 600maxChunkSize = 700return = [600,300]

The total is 900 bytes, requiring two chunks. The first chunk must contain the intact 600-byte header, so the remaining 300 bytes form the second chunk.

Example 3

data = 7header = 4maxChunkSize = 6return = [5,6]

The total is 11 bytes, requiring two chunks. The first size is max(4, floor(11 / 2)) = 5, which contains the entire header and one payload byte. The remaining 6 bytes use the second chunk.

Constraints

  • 0 <= data, header <= 10^9.
  • 1 <= maxChunkSize <= 10^9.
  • header <= maxChunkSize, so the header fits in one chunk.
  • All sizes are integer byte counts.
  • The minimum required chunk count is at most 10000.

More Google problems

See Google hiring insights
public int[] splitDataWithHeader(int data, int header, int maxChunkSize) {
    // write your code here
}
data1800
header0
maxChunkSize700
expected[600,600,600]
Checking account…