call(back)
Algorithms & Data Structureshard

Stream Line Reader

You are given an API you cannot modify:

readChunk() -> string    // next chunk of a log stream; "" means end of stream

Chunks split arbitrarily: one chunk may contain several lines, and one line may span several chunks. Implement a LineReader class whose readLine() returns the next complete line WITHOUT the newline; the final line may lack a trailing newline; return null once the stream is exhausted. Call readChunk lazily — only when you do not already have a complete line buffered.

Example:

chunks: ["ab", "c\nde", "f\n"]      ->  readLine(): "abc", then "def", then null
chunks: ["a\n\nb"]                  ->  "a", "" (empty line preserved), "b"

Part 2 (as actually reported): each line of the stream is payer,payee,amount. Implement settleFromStream(readChunk): parse the stream with your LineReader, compute each person's net balance, and return the minimum number of transactions needed to settle everyone.

Asked at