A text source is supplied as an array of strings, chunks. This array is a replayable stand-in for the original iterator, so it may be inspected more than once. Chunk boundaries are arbitrary and may cut through the middle of a line.
Implement split_balanced_lines so it divides the fully concatenated content into exactly parts ordered strings while never breaking a line. Balance is measured by line count. If the combined stream contains lines and parts has value , then every output string must contain either or lines. Each output string is the concatenation of consecutive whole lines in their original order. Any arrangement of the larger-sized groups is acceptable. Always return exactly parts strings; groups assigned zero lines are represented by "".
String[] split_balanced_lines(String[] chunks, int parts)
Line handling rules:
\n character terminates a line and remains attached to that line.\n is still considered one line.\n does not create an additional empty line after it.\r, are treated as literal content. Do not normalize line endings.Example 1:
Input: chunks = ["hel", "lo\nwo", "rld\nfoo\n", "bar"], parts = 2
Output: ["hello\nworld\n", "foo\nbar"]
Explanation: The combined stream is "hello\nworld\nfoo\nbar", which has four lines, so each output part receives exactly two whole lines.
Example 2:
Input: chunks = ["one\ntw", "o\nthree\nfour\n", "five"], parts = 3
Output: ["one\n", "two\nthree\n", "four\nfive"]
Explanation: The full text is "one\ntwo\nthree\nfour\nfive" with five lines. The chosen layout assigns one line to the first part and two lines to each later part, satisfying the floor/ceil requirement. Other balanced layouts are also valid.
Example 3:
Input: chunks = ["", "", "x"], parts = 4
Output: ["x", "", "", ""]
Explanation: The stream contains only one line, so one output part holds that line while the remaining parts stay empty.
Constraints:
Your answer should state the time and memory complexity. In a real one-pass iterator setting where the total line count is unknown ahead of time, explain why exact final balance may require buffering/spooling or a preliminary counting pass. Do not claim that already-emitted group boundaries can always be repaired with constant memory.