FastPrepBalanced File Partitions Without Splitting Lines
Problems/Balanced File Partitions Without Splitting Lines

Balanced File Partitions Without Splitting Lines

Together AI logoTogether AI● MediumNEW GRADPHONE SCREEN
QuestionFunctionExamplesConstraints

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

  • Time-Indexed Key-Value StoreONSITE INTERVIEW · Seen Sep 2026
  • Find GPU Capacity and Drain a NodePHONE SCREEN · Seen Jul 2026
See Together AI hiring insights
Saved
class Solution {
    public String[] splitFileIntoBalancedParts(String[] chunks, int partCount) {
        // Write your solution here.
    }
}
Checking account…