Chunked Stream Parser and Debt Settlement
StringsAuto-graded · 22 test casesLast updated
Tests buffered string parsing over an incremental data source combined with greedy net-balance clearing across a set of financial transfers.
Part 1: Reconstruct Lines from a Chunked Text Stream
A text source delivers data in arbitrary-sized chunks. Each chunk is a plain string that may contain zero or more newline characters (\n). When all chunks are joined together, the result is a sequence of logical lines separated by \n.
You receive the chunks as a list chunks. Reconstruct every logical line and return them in order as a list of strings. Do not include the newline characters themselves in the returned strings.
Rules for edge cases:
- An empty chunk has no effect.
- Two consecutive newlines produce an empty line between them.
- If the concatenated text ends with a newline, do not append a phantom empty line after it.
- If the text does not end with a newline, the remaining characters after the last newline form the final line.
- If
chunksis empty, return an empty list.
You must process chunks one at a time and carry only the unfinished tail of the current line across iterations (O(L_max) extra memory, where L_max is the length of the longest single line).
Part 2: Settle Debts with Payback Transfers
You are given a list of money transfers transactions, where each entry [sender, receiver, amount] means sender paid receiver exactly amount units.
Compute each person's net balance:
- Every amount sent reduces the sender's balance.
- Every amount received increases the receiver's balance.
Then produce a list of payback transfers [payer, recipient, amount] such that, after applying the paybacks on top of the original transactions, every person's net balance is exactly zero. You do not need to minimize the number of payback transfers; any valid set is acceptable as long as it fully clears all balances.
Rules:
- Use a greedy two-pointer approach: match the current net-debtor (negative balance) against the current net-creditor (positive balance), transfer
min(|debtor balance|, creditor balance), and advance whichever pointer reaches zero (advance both if they reach zero simultaneously). - Build the debtor list and creditor list in the order people first appear in
transactions(dictionary insertion order). - Use integers only; do not introduce floating-point arithmetic.
- If all balances are already zero (including when
transactionsis empty), return an empty list for the paybacks.
Return value
Return a list of exactly two elements:
[lines, paybacks]
lines— the list of reconstructed strings from Part 1.paybacks— the list of[payer, recipient, amount]payback transfers from Part 2.
Constraints
0 ≤ len(chunks) ≤ 10^4- Each chunk is a string of printable ASCII characters and/or
\n; total characters across all chunks ≤ 10^6. 0 ≤ len(transactions) ≤ 10^4- Each transaction is
[sender, receiver, amount]wheresenderandreceiverare non-empty strings and1 ≤ amount ≤ 10^9. - The input guarantees that all balances are integers and that total debts equal total credits.
Examples
Example 1
Input: parse_chunks_and_settle(['one\\ntw', 'o\\n', 'three\\nfour', '\\nfi', 've'], [['A', 'B', 10], ['B', 'C', 5], ['A', 'C', 5]])
Output: [['one\\ntwo\\nthree\\nfour\\nfive'], [['A', 'B', 5], ['A', 'C', 10]]]
Example 2
Input: parse_chunks_and_settle(['alpha\\n', 'beta'], [])
Output: [['alpha\\nbeta'], []]
Hints
Hint 1
For Part 1, keep a single string variable that holds the characters after the last newline seen so far. When you process a new chunk, prepend that variable to the chunk and split on newline — everything except the last piece is a complete line.
Hint 2
For Part 2, individual transfers don't matter — only each person's final net position does. Compute one balance per person, then separate everyone into two groups: those who owe money and those who are owed money.
Hint 3
For the greedy matching in Part 2, use two pointers, one into each group. At each step, move min(debt, credit) from the debtor to the creditor, reduce both by that amount, and advance the pointer that hit zero. Because total debt always equals total credit, both pointers will reach the end at the same time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1 — line reconstruction
The core insight is maintaining a single invariant: pending always holds the characters that appeared after the last \n seen so far (and before any \n in the current chunk). Because pending never contains a newline, it is always a prefix fragment of exactly one line, so it uses at most O(L_max) memory regardless of how many chunks have been processed.
For each chunk:
- Prepend
pendingto the chunk and split on\n. - Every resulting piece except the last one was followed by a
\nin the combined string, so it is a complete line — add it tolines. - The last piece had no
\nafter it, so it becomes the newpending.
After all chunks are consumed, if pending is non-empty it is the final line (the stream ended without a trailing newline). If pending is empty the stream ended with a newline and no phantom line is added — matching the edge-case rule.
Edge cases handled automatically:
- Empty chunk →
pending + ""changes nothing. - Consecutive newlines → split produces an empty string between them, which is correctly kept as an empty line.
- Trailing newline →
pendingis""after the last chunk, so nothing extra is appended.
Complexity: O(N) time where N is the total number of characters; O(L_max) extra space (excluding output).
Part 2 — debt settlement
Individual transfers are irrelevant to settlement; only each person's net position matters. A single pass over transactions builds a balance map where sending subtracts and receiving adds.
People with a negative net balance are debtors; people with a positive net balance are creditors. Because every transaction moves the same amount out of one balance and into another, the sum of all balances is always zero — total debt equals total credit exactly.
The greedy two-pointer loop exploits this:
- Take the current debtor
i(owesd) and the current creditorj(is owedc). - Transfer
min(d, c)— this fully resolves at least one of them. - Decrement both by that amount; advance whichever pointer hit zero (advance both if they hit zero together).
Because each step eliminates at least one entry, the loop runs at most |debtors| + |creditors| - 1 iterations and terminates with every balance cleared.
Why the lists are built in insertion order: Python dicts (3.7+) remember insertion order, so iterating balances.items() visits people in the order they first appear in transactions. This matches the expected test output.
Complexity: O(T + n) time where T is the number of transactions and n is the number of distinct people; O(n) extra space.
Reference solution
from typing import List
def parse_chunks_and_settle(chunks: List[str], transactions: List[List]) -> List[List]:
# ------------------------------------------------------------------
# Part 1: reconstruct lines from chunks
# ------------------------------------------------------------------
lines = []
pending = "" # characters after the last newline seen so far
for chunk in chunks:
parts = (pending + chunk).split("\n")
# Every part except the last was terminated by a newline -> complete line
lines.extend(parts[:-1])
# The last part has no newline yet -> carry it forward
pending = parts[-1]
# If the stream did not end with a newline, pending holds the final line
if pending:
lines.append(pending)
# ------------------------------------------------------------------
# Part 2: net balance computation + greedy debtor/creditor settlement
# ------------------------------------------------------------------
balances: dict = {}
for sender, receiver, amount in transactions:
balances[sender] = balances.get(sender, 0) - amount
balances[receiver] = balances.get(receiver, 0) + amount
# Preserve first-appearance order (Python 3.7+ dict insertion order)
debtors = [[person, -bal] for person, bal in balances.items() if bal < 0]
creditors = [[person, bal] for person, bal in balances.items() if bal > 0]
paybacks = []
i = j = 0
while i < len(debtors) and j < len(creditors):
amount = min(debtors[i][1], creditors[j][1])
paybacks.append([debtors[i][0], creditors[j][0], amount])
debtors[i][1] -= amount
creditors[j][1] -= amount
if debtors[i][1] == 0:
i += 1
if creditors[j][1] == 0:
j += 1
return [lines, paybacks]