FastPrepBalanced File Partitions Without Splitting Lines

Balanced File Partitions Without Splitting Lines

Together AI logoTogether AI● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

A text file arrives through an iterator as the ordered string chunks chunks. Chunk boundaries are arbitrary and may occur in the middle of a line. Split the logical file into exactly partCount consecutive parts.

  • A newline character ends a line and is not included in that line's text.
  • A final nonempty suffix without a newline is also a line.
  • A trailing newline does not create an extra empty line.
  • No line may be split between parts.
  • The numbers of lines in any two parts must differ by at most one. Give the earlier parts the extra lines.
  • Represent each part by joining its lines with \n. Empty parts are empty strings.

Function

splitFileIntoBalancedParts(chunks: String[], partCount: int) → String[]

Examples

Example 1

chunks = ["alpha\nbe","ta\ngamma\n"]partCount = 2return = ["alpha\nbeta","gamma"]

The middle line crosses an iterator boundary. Three complete lines split as two then one.

Example 2

chunks = ["a\nb"]partCount = 4return = ["a","b","",""]

Parts are retained even when there are fewer lines than parts.

Constraints

  • 1 <= chunks.length <= 100000.
  • The total input length is at most 1000000.
  • 1 <= partCount <= 100000.
  • Input contains no carriage-return characters.

More Together AI problems

See Together AI hiring insights
public String[] splitFileIntoBalancedParts(String[] chunks, int partCount) {
    // Write your solution here.
}
chunks["alpha\nbe","ta\ngamma\n"]
partCount2
expected["alpha\nbeta", "gamma"]
Checking account…