Format Transaction Rows as Receipt Blocks

Medium · Data Manipulation (SQL/Python) · Software Engineer · Technical Screen

Problem Statement

You are given rows, a list of string-keyed dictionaries representing raw transaction records parsed from a CSV feed. Every record provides at least four string fields—"Merchant", "Amount", "Date" (YYYY-MM-DD), and "Status"—though extra metadata columns or surrounding whitespace on header keys and cell values may also appear.

Implement format_transactions to turn each record into a four-line receipt card string and return the resulting list of blocks in the exact order the records appear in rows:

---------------------------
| {Merchant} ${Amount} |
| {Date} {Status} |
---------------------------

Formatting rules:

  1. Preserve row sequence: Emit one block per dictionary in the original input order (returning [] when rows is empty), ignoring any columns outside the four required fields.
  2. Strip outer whitespace: Remove leading and trailing whitespace characters (spaces, tabs, newlines) from both dictionary keys and field values before rendering, while keeping interior spaces intact.
  3. Two-decimal currency: Convert "Amount" in base-10 arithmetic to an exact two-decimal dollar figure using half-up rounding to the nearest cent (for example, "42.8" renders as "$42.80", "19" as "$19.00", ".5" as "$0.50", and zero values as "$0.00").
  4. Fixed frame: Top and bottom borders are always 27 hyphens ("-" * 27) regardless of text length, and the four lines of a block are joined by "\n" with no trailing newline.
def format_transactions(rows: List[Dict[str, str]]) -> List[str]:

Examples

Example 1

Input:
rows = [
    {"Merchant": "Metro Transit", "Amount": "3.75", "Date": "2025-03-14", "Status": "settled"}
]

Output:
[
    "---------------------------\n| Metro Transit $3.75 |\n| 2025-03-14 settled |\n---------------------------"
]

Explanation: All fields are already trimmed and "3.75" has two decimal digits, so the single transaction renders into one four-line receipt card framed by 27-hyphen borders.

Example 2

Input:
rows = [
    {"Merchant": "  Fresh Market ", "Amount": " 42.8 ", "Date": " 2025-04-02 ", "Status": " posted "},
    {"Merchant": "Cloud Host", "Amount": "19", "Date": "2025-04-01", "Status": "declined"}
]

Output:
[
    "---------------------------\n| Fresh Market $42.80 |\n| 2025-04-02 posted |\n---------------------------",
    "---------------------------\n| Cloud Host $19.00 |\n| 2025-04-01 declined |\n---------------------------"
]

Explanation: In the first record, outer spaces are stripped (preserving the space inside "Fresh Market") and "42.8" is padded to "$42.80". In the second record, "19" is formatted as "$19.00", and the output keeps the input order even though "2025-04-02" is chronologically later than "2025-04-01".

Constraints

  • 0 <= len(rows) <= 10^4
  • Each dictionary in rows contains "Merchant", "Amount", "Date", and "Status" (after stripping surrounding whitespace from keys).
  • Every trimmed "Amount" is a valid base-10 decimal string.
  • Every trimmed "Date" follows YYYY-MM-DD.

Step-by-step walkthrough

  1. Understand the input, output, and fixed border lines

    The judge passes rows as a list of dictionaries (List[Dict[str, str]]), matching the structure produced by Python's csv.DictReader:

    {"Merchant": "  Fresh Market ", "Amount": " 42.8 ", "Date": " 2025-04-02 ", "Status": " posted "}
    

    For each dictionary in rows, in the exact order given, we must build and return a four-line formatted string:

    ---------------------------   <-- 27 hyphens
    | Fresh Market $42.80 |       <-- "| " + Merchant + " $" + 2-decimal Amount + " |"
    | 2025-04-02 posted |         <-- "| " + Date + " " + Status + " |"
    ---------------------------   <-- 27 hyphens
    

    Notice that every block uses 27 hyphens regardless of whether the inner text is shorter or longer than 27 characters, so the border is a fixed constant rather than dynamically sized.

  2. Plan: break each row's work into three small steps

    Because we must output one block per row in the exact input order, a single loop from first row to last row is already optimal. The real pitfalls are all in data hygiene and string formatting:

    1. Clean the row: strip leading and trailing whitespace from every field (and column header).
    2. Format the dollar amount: pad or round the numeric string to two exact decimal places.
    3. Assemble the four-line block: place pipes, spaces, $, and borders in the exact template positions without adding stray trailing newlines.

    Putting each responsibility in a small helper function keeps every detail easy to verify.

  3. Trim surrounding whitespace from keys and values

    Python's str.strip() removes spaces, tabs (\t), and newlines (\n) from both ends of a string while leaving internal spaces untouched (so " Fresh Market " becomes "Fresh Market").

    We also call key.strip() on the dictionary keys. In real CSV files, a header written with spaces after commas like Merchant, Amount, Date, Status causes csv.DictReader to create keys such as " Amount", which would raise KeyError when looking up "Amount".

    from typing import Dict
    
    
    def clean_row(row: Dict[str, str]) -> Dict[str, str]:
        # cleaned: maps stripped column name -> stripped field text, e.g. {"Merchant": "Fresh Market", ...}
        # Trimming keys too prevents KeyError when a CSV header has spaces like "Merchant, Amount".
        cleaned: Dict[str, str] = {}
        for key, value in row.items():
            cleaned[key.strip()] = value.strip()
        return cleaned
    
  4. Format dollar amounts accurately with Decimal

    Amounts arrive as strings such as "3.75", "42.8", "19", or ".5". Why not simply write f"{float(raw_amount):.2f}"?

    Because Python float values are stored in base 2 (binary floating-point), most decimal fractions cannot be stored exact to the digit. For example, float("2.675") is actually stored slightly below 2.675, so f"{float('2.675'):.2f}" rounds down to "2.67" instead of "2.68".

    Python's standard decimal.Decimal stores base-10 digits exactly. Calling .quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) rounds to the nearest cent using standard half-up rounding (2.675 -> 2.68), and pads whole dollars or tenths ("42.8" -> "42.80", "19" -> "19.00").

    from decimal import Decimal, ROUND_HALF_UP
    
    ONE_CENT = Decimal("0.01")
    
    
    def format_amount(raw_amount: str) -> str:
        # Parse in base-10 with Decimal so values like "2.675" stay exact instead of suffering
        # binary float drift (where float("2.675") rounds down to "2.67").
        rounded_amount = Decimal(raw_amount).quantize(ONE_CENT, rounding=ROUND_HALF_UP)
    
        # Normalize negative zero (e.g., from "-0.001") to positive "0.00" so we never print "$-0.00".
        if rounded_amount == 0:
            rounded_amount = abs(rounded_amount)
    
        return f"{rounded_amount:.2f}"
    
  5. Assemble each four-line transaction block

    With clean fields and a two-decimal amount string in hand, we build the two inner lines and join all four lines with "\n". Using "\n".join(...) puts newlines between the four lines without adding an unwanted newline after the bottom border.

    from typing import Dict, List
    
    BORDER_LINE = "-" * 27
    
    
    def format_transactions(rows: List[Dict[str, str]]) -> List[str]:
        # formatted_blocks: list of 4-line receipt strings in the exact input row order
        formatted_blocks: List[str] = []
    
        for row in rows:
            # Phase 1: Trim surrounding whitespace from all keys and values in this record.
            fields = clean_row(row)
            merchant = fields["Merchant"]
            amount_str = format_amount(fields["Amount"])
            date = fields["Date"]
            status = fields["Status"]
    
            # Phase 2: Build the two pipe-delimited content lines and wrap with 27-hyphen borders.
            top_content_line = f"| {merchant} ${amount_str} |"
            bottom_content_line = f"| {date} {status} |"
            block = "\n".join([BORDER_LINE, top_content_line, bottom_content_line, BORDER_LINE])
            formatted_blocks.append(block)
    
        return formatted_blocks
    
  6. Trace Example 2 row by row

    Let's trace the two dictionaries in Example 2 from raw strings to finished blocks:

    Row 1 raw:     Merchant="  Fresh Market ", Amount=" 42.8 ", Date=" 2025-04-02 ", Status=" posted "
    clean_row:     Merchant="Fresh Market",    Amount="42.8",   Date="2025-04-02",   Status="posted"
    format_amount: "42.8" -> Decimal("42.80") -> "42.80"
    block[0]:
    ---------------------------
    | Fresh Market $42.80 |
    | 2025-04-02 posted |
    ---------------------------
    
    Row 2 raw:     Merchant="Cloud Host", Amount="19", Date="2025-04-01", Status="declined"
    clean_row:     Merchant="Cloud Host", Amount="19", Date="2025-04-01", Status="declined"
    format_amount: "19" -> Decimal("19.00") -> "19.00"
    block[1]:
    ---------------------------
    | Cloud Host $19.00 |
    | 2025-04-01 declined |
    ---------------------------
    
  7. Full solution

    We also include a short if __name__ == "__main__": entry point showing how csv.DictReader feeds a CSV file directly into format_transactions when run as a command-line script.

    from typing import Any, Dict, List, Optional, Set, Tuple
    from decimal import Decimal, ROUND_HALF_UP
    
    # BORDER_LINE: fixed 27-hyphen top and bottom border used by every transaction block
    BORDER_LINE = "-" * 27
    # ONE_CENT: target precision (two decimal places) for rounding monetary amounts
    ONE_CENT = Decimal("0.01")
    
    
    def clean_row(row: Dict[str, str]) -> Dict[str, str]:
        # cleaned: maps stripped column name -> stripped field text, e.g. {"Merchant": "Fresh Market", ...}
        # Trimming keys too prevents KeyError when a CSV header has spaces like "Merchant, Amount".
        cleaned: Dict[str, str] = {}
        for key, value in row.items():
            cleaned[key.strip()] = value.strip()
        return cleaned
    
    
    def format_amount(raw_amount: str) -> str:
        # Parse in base-10 with Decimal so values like "2.675" stay exact instead of suffering
        # binary float drift (where float("2.675") rounds down to "2.67").
        rounded_amount = Decimal(raw_amount).quantize(ONE_CENT, rounding=ROUND_HALF_UP)
    
        # Normalize negative zero (e.g., from "-0.001") to positive "0.00" so we never print "$-0.00".
        if rounded_amount == 0:
            rounded_amount = abs(rounded_amount)
    
        return f"{rounded_amount:.2f}"
    
    
    def format_transactions(rows: List[Dict[str, str]]) -> List[str]:
        # formatted_blocks: list of 4-line receipt strings in the exact input row order
        formatted_blocks: List[str] = []
    
        for row in rows:
            # Phase 1: Trim surrounding whitespace from all keys and values in this record.
            fields = clean_row(row)
            merchant = fields["Merchant"]
            amount_str = format_amount(fields["Amount"])
            date = fields["Date"]
            status = fields["Status"]
    
            # Phase 2: Build the two pipe-delimited content lines and wrap with 27-hyphen borders.
            top_content_line = f"| {merchant} ${amount_str} |"
            bottom_content_line = f"| {date} {status} |"
            block = "\n".join([BORDER_LINE, top_content_line, bottom_content_line, BORDER_LINE])
            formatted_blocks.append(block)
    
        return formatted_blocks
    
    
    if __name__ == "__main__":
        import csv
        import sys
    
        # CLI usage: python solution.py transactions.csv
        with open(sys.argv[1], newline="", encoding="utf-8") as csv_file:
            reader = csv.DictReader(csv_file)
            for transaction_block in format_transactions(list(reader)):
                print(transaction_block)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of this task as running a receipt printer fed by a messy spreadsheet: each spreadsheet row arrives with potential spaces around its text and inconsistent decimal digits on its price, and you want to stamp out a neat four-line receipt card for each row in the exact order they came in. To keep the logic bug-free, we process one row at a time through three clean stages: trim outer whitespace from every field, convert the dollar string into an exact two-decimal fixed-point decimal (a base-10 number representation that stores exact decimal digits rather than binary approximations), and drop the cleaned fields into the fixed four-line template.

Common shortcuts fail on subtle financial and formatting details. Parsing prices with float() uses binary floating-point (base-2 fractions that cannot represent most base-10 decimals exactly), so f"{float('2.675'):.2f}" rounds down to "2.67" instead of "2.68", while str(round(x, 2)) drops trailing zeros so "42.8" stays "42.8" instead of "42.80". Trimming only Merchant or Amount leaves extra spaces around Date or Status, and sorting rows by date or merchant breaks the requirement to preserve input row order.

Walking through a single messy row {"Merchant": " Fresh Market ", "Amount": " 42.8 ", "Date": " 2025-04-02 ", "Status": " posted "}: 1. clean_row strips outer whitespace from keys and values -> Merchant="Fresh Market", Amount="42.8", Date="2025-04-02", Status="posted". 2. format_amount("42.8") parses Decimal("42.8") and quantizes to Decimal("0.01") using round-half-up (the standard everyday rule where exact .005 half-cent ties round away from zero to the next cent) -> "42.80". 3. We build | Fresh Market $42.80 | and | 2025-04-02 posted |, wrap them above and below with 27 hyphens, and append the four-line string to our output list.

Complexity

  • Time: O(C), where C is the total number of characters across all input dictionaries. We visit each row once, strip every key and value once, parse the short amount string with Decimal in time linear in its digits, and join four short strings into a block.
  • Space: O(C) to store formatted_blocks, which holds every cleaned field once plus a constant amount of border and delimiter characters (64 template characters) per row.

Edge cases

  • Empty input ([]): Returns [] immediately with zero blocks.
  • Whole-dollar and leading-dot amounts: "1200", "19", ".5", and "0" format cleanly to "$1200.00", "$19.00", "$0.50", and "$0.00".
  • Sub-cent precision: "1.239" rounds to "$1.24", "9.999" carries cleanly to "$10.00", and tiny negative values like "-0.001" normalize to "$0.00" rather than "$-0.00".
  • Tabs, newlines, and inner spaces: "\t Corner Deli \n" trims outer tabs and newlines while preserving internal spaces as "Corner Deli".
  • Whitespace in CSV column headers: Stripping keys (key.strip()) ensures headers like " Amount " still map to "Amount".
  • Long merchant names: Even when a content line exceeds 27 characters, the top and bottom border stays fixed at 27 hyphens ("-" * 27) to match the template contract.
  • Extra columns: Unrelated keys such as "Id" or "Notes" are ignored without affecting the four formatted fields.

Common mistakes

  • Using float() for currency: Binary float rounding silently mis-rounds boundary values such as "2.675" or "0.125"; always use Decimal or integer cents for money.
  • Using str(round(val, 2)) instead of .2f formatting: round(42.8, 2) produces 42.8, missing the required trailing zero in $42.80.
  • Forgetting to strip Date or Status: Example 2 pads every field with spaces, so skipping .strip() on any of the four columns leaves double spaces inside the pipes.
  • Subtle template typos: Adding a space after $ ($ 3.75), forgetting the space before the closing |, adding a trailing \n at the end of a block, or using the wrong number of hyphens.
  • Sorting the output: Reordering transactions chronologically or alphabetically violates the explicit requirement to preserve input row order.

Follow-up questions

  • How would you adapt this formatter if the input CSV file were tens of gigabytes and could not fit into RAM? Replace list(reader) and the formatted_blocks list with a generator (a function using yield that produces one formatted block at a time on demand). Because csv.DictReader already streams the file line by line, yielding and printing one block per iteration drops memory usage from O(C) to O(longest single row), letting you process billions of rows in constant RAM.
  • What safeguards would you add to handle corrupted or incomplete rows in a production ingestion pipeline? Decide with stakeholders whether the pipeline should fail fast or quarantine bad rows into a dead-letter log while continuing. Specifically, guard against missing columns (where csv.DictReader sets the value to None), extra unquoted commas (where csv.DictReader stores overflow values under key None as a list), invalid numbers (decimal.InvalidOperation), and invalid calendar dates (datetime.date.fromisoformat), logging reader.line_num without crashing the whole batch.
  • How would you extend the amount formatter to include comma thousands separators and display negative refunds as -$5.00? Python's Decimal supports standard format specifiers, so changing f"{rounded_amount:.2f}" to f"{rounded_amount:,.2f}" adds comma separators automatically. To render negative refunds as -$5.00 instead of $-5.00, format abs(rounded_amount) after $ and prepend "-" before "$" whenever rounded_amount < 0.

Follow-up questions

Similar questions

More Kikoff interview questions

All 4 Kikoff questions →