Render an ASCII Grid Plot for Time-Price Data

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You receive an unordered sequence time_price_pairs where each item [timestamp, price] records an integer timestamp and an integer price observation. Produce a framed ASCII scatter grid of the series and return the chart from top to bottom as a List[str].

If time_price_pairs is empty, return []. Otherwise, determine the bounding intervals across all input pairs:

  • Horizontal axis (columns): Every integer timestamp from min_time up to max_time in left-to-right order, even when a timestamp has zero observations.
  • Vertical axis (interior rows): Every integer price from max_price down to min_price in top-to-bottom order, even when a price level has zero observations.

Format the rectangular grid using 5-character column cells separated by '+' characters:

  • Top and bottom border strings: Begin with '+' followed by "-----+" repeated once per timestamp column (for example, "+-----+-----+" for 2 columns).
  • Interior price rows: Join one 5-character cell per timestamp column with '+' dividers and place '+' on both outer ends:
    • Use " * " (two spaces, '*', two spaces) when at least one input entry matches (timestamp, price). Duplicate entries at identical coordinates collapse into a single " * " cell.
    • Use " " (five spaces) when no input entry matches (timestamp, price).

Examples

Example 1

Input: time_price_pairs = [[2, 10], [5, 12], [3, 13], [2, 10]]

Output:
[
  "+-----+-----+-----+-----+",
  "+     +  *  +     +     +",
  "+     +     +     +  *  +",
  "+     +     +     +     +",
  "+  *  +     +     +     +",
  "+-----+-----+-----+-----+"
]

Explanation: Columns cover timestamps 2, 3, 4, 5 (4 columns, including unobserved t = 4), and interior rows cover prices 13, 12, 11, 10 (4 rows, including unobserved price = 11). The repeated observation [2, 10] draws a single '*' in column 2, row 10.

Example 2

Input: time_price_pairs = [[4, 8]]

Output:
[
  "+-----+",
  "+  *  +",
  "+-----+"
]

Explanation: A single point spans 1 timestamp column (4) and 1 price row (8).

Example 3

Input: time_price_pairs = [[-3, 1], [-1, -1], [-3, -1]]

Output:
[
  "+-----+-----+-----+",
  "+  *  +     +     +",
  "+     +     +     +",
  "+  *  +     +  *  +",
  "+-----+-----+-----+"
]

Explanation: Columns span timestamps -3, -2, -1 and interior rows span prices 1, 0, -1. Unobserved t = -2 and price = 0 appear as blank cells.

Constraints

  • 0 <= len(time_price_pairs) <= 10^4
  • Each element of time_price_pairs contains 2 integers [timestamp, price] (negative, zero, or positive).
  • Grid dimensions (max_time - min_time + 1) * (max_price - min_price + 1) fit comfortably in memory when time_price_pairs is non-empty.

Step-by-step walkthrough

  1. Read the exact grid layout from the examples

    We receive an unordered list of [timestamp, price] integer pairs and need to return an ASCII chart as a list of strings (one string per line).

    Whenever an ASCII-art specification has subtle formatting details, inspect an example output character by character. Here is Example 1 for [[2, 10], [5, 12], [3, 13], [2, 10]]:

    col time ->     2     3     4     5
                 +-----+-----+-----+-----+   <- top border
    price = 13   +     +  *  +     +     +   <- point (3, 13)
    price = 12   +     +     +     +  *  +   <- point (5, 12)
    price = 11   +     +     +     +     +   <- no point at price 11, still drawn!
    price = 10   +  *  +     +     +     +   <- repeated [2, 10] drawn once
                 +-----+-----+-----+-----+   <- bottom border
    

    Notice five rules locked down by the layout:

    • Cell width is always 5 characters: "-----" on borders, " " (5 spaces) for an empty cell, and " * " (2 spaces, *, 2 spaces) for an observed point.
    • + separates every adjacent cell on both border lines and interior rows (not just the outer left and right edges).
    • Every integer in range gets a row or column: timestamp 4 has no data points, and price 11 has no data points, yet both appear as blank columns and rows so the axes stay evenly spaced.
    • Duplicate points collapse: [2, 10] appears twice in Example 1, yet its cell shows a single " * ".
    • Empty input: if time_price_pairs is [], there is no minimum or maximum to frame, so we return [].
  2. Map timestamps and prices to row and column order

    In a standard plot, time increases from left to right and price increases from bottom to top. However, we build our list of strings from top line to bottom line:

    Text line order (top -> bottom)      Chart y-axis (high -> low)
    -------------------------------      --------------------------
    chart_lines[0]                       top border
    chart_lines[1]                       max_price      (highest price first)
    chart_lines[2]                       max_price - 1
    ...                                  ...
    chart_lines[P]                       min_price      (lowest price last)
    chart_lines[P + 1]                   bottom border
    

    That inverted y-axis is the key coordinate rule: - The outer loop walks price downward from max_price down to min_price. - The inner loop walks timestamp upward from min_time up to max_time.

    Because every coordinate is visited relative to min_time..max_time and max_price..min_price, negative timestamps and negative prices work automatically without special cases.

  3. Deduplicate points and find bounds in one pass

    Suppose the chart spans T = max_time - min_time + 1 columns and P = max_price - min_price + 1 price rows. If we checked each (timestamp, price) cell by scanning all n input pairs from scratch, drawing the grid would take O(n * T * P) time.

    Instead, we put every observed point into a hash set (a collection backed by a hash table that checks membership in O(1) average time and ignores duplicates). Two Python details matter here: 1. Input items are lists like [2, 10]. Lists are mutable and cannot be placed in a set, so we unpack timestamp, price and store an immutable tuple (timestamp, price). 2. We can track min_time, max_time, min_price, and max_price in the exact same loop, avoiding extra temporary lists.

    def render_ascii_chart(time_price_pairs: List[List[int]]) -> List[str]:
        # With no data points there is no min/max range to frame, so return an empty chart.
        if not time_price_pairs:
            return []
    
        # Phase 1: Deduplicate points in a hash set and find axis bounds in one pass.
        # observed_points: set of (timestamp, price) tuples, e.g. {(2, 10), (3, 13)}.
        # Lists are unhashable in Python, so each [t, p] pair is stored as a tuple.
        first_time, first_price = time_price_pairs[0]
        min_time = first_time
        max_time = first_time
        min_price = first_price
        max_price = first_price
    
        observed_points: Set[Tuple[int, int]] = set()
        for timestamp, price in time_price_pairs:
            observed_points.add((timestamp, price))
            min_time = min(min_time, timestamp)
            max_time = max(max_time, timestamp)
            min_price = min(min_price, price)
            max_price = max(max_price, price)
    
  4. Build the borders and each price row

    With num_columns = max_time - min_time + 1, both the top and bottom borders are "+" followed by "-----+" repeated num_columns times.

    For each price from max_price down to min_price, we collect one 5-character string per timestamp into row_cells, join those cells with "+", and add "+" at both ends. Pay close attention to the range() endpoints: - range(max_price, min_price - 1, -1) steps by -1 and stops just before min_price - 1, which means min_price is included. - range(min_time, max_time + 1) steps by +1 and stops just before max_time + 1, which means max_time is included.

    BORDER_CELL = "-----"
    EMPTY_CELL = "     "
    POINT_CELL = "  *  "
    
    def _build_chart_lines(
        observed_points: Set[Tuple[int, int]],
        min_time: int,
        max_time: int,
        min_price: int,
        max_price: int,
    ) -> List[str]:
        num_columns = max_time - min_time + 1
        border_line = "+" + (BORDER_CELL + "+") * num_columns
    
        chart_lines: List[str] = [border_line]
        for price in range(max_price, min_price - 1, -1):
            row_cells: List[str] = []
            for timestamp in range(min_time, max_time + 1):
                if (timestamp, price) in observed_points:
                    row_cells.append(POINT_CELL)
                else:
                    row_cells.append(EMPTY_CELL)
            chart_lines.append("+" + "+".join(row_cells) + "+")
    
        chart_lines.append(border_line)
        return chart_lines
    
  5. Trace Example 3 step by step

    Let us trace time_price_pairs = [[-3, 1], [-1, -1], [-3, -1]]:

    1. Single pass over input:
       observed_points = {(-3, 1), (-1, -1), (-3, -1)}
       min_time = -3, max_time = -1  -> timestamps: -3, -2, -1 (num_columns = 3)
       min_price = -1, max_price = 1 -> prices:      1,  0, -1 (3 interior rows)
    
    2. Border line:
       "+" + "-----+" * 3  ->  "+-----+-----+-----+"
    
    3. Interior rows (price from 1 down to -1, timestamp from -3 up to -1):
       price =  1: (-3, 1) hit, (-2, 1) miss, (-1, 1) miss  -> "+  *  +     +     +"
       price =  0: all 3 miss                               -> "+     +     +     +"
       price = -1: (-3,-1) hit, (-2,-1) miss, (-1,-1) hit   -> "+  *  +     +  *  +"
    
    4. Append bottom border "+-----+-----+-----+" -> 5 lines total, matching Example 3.
    
  6. Complete solution

    Putting all three phases together inside render_ascii_chart gives the complete solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Every timestamp column is 5 characters wide between '+' dividers.
    BORDER_CELL = "-----"
    EMPTY_CELL = "     "
    POINT_CELL = "  *  "
    
    
    def render_ascii_chart(time_price_pairs: List[List[int]]) -> List[str]:
        # With no data points there is no min/max range to frame, so return an empty chart.
        if not time_price_pairs:
            return []
    
        # Phase 1: Deduplicate points in a hash set and find axis bounds in one pass.
        # observed_points: set of (timestamp, price) tuples, e.g. {(2, 10), (3, 13)}.
        # Lists are unhashable in Python, so each [t, p] pair is stored as a tuple.
        first_time, first_price = time_price_pairs[0]
        min_time = first_time
        max_time = first_time
        min_price = first_price
        max_price = first_price
    
        observed_points: Set[Tuple[int, int]] = set()
        for timestamp, price in time_price_pairs:
            observed_points.add((timestamp, price))
            min_time = min(min_time, timestamp)
            max_time = max(max_time, timestamp)
            min_price = min(min_price, price)
            max_price = max(max_price, price)
    
        # Phase 2: Build the reusable top and bottom horizontal frame line.
        # Example for 2 columns: "+" + "-----+" * 2 -> "+-----+-----+"
        num_columns = max_time - min_time + 1
        border_line = "+" + (BORDER_CELL + "+") * num_columns
    
        # Phase 3: Render each integer price row from highest (top) down to lowest (bottom).
        # Stop at min_price - 1 because Python's range() excludes its stop value.
        chart_lines: List[str] = [border_line]
        for price in range(max_price, min_price - 1, -1):
            row_cells: List[str] = []
            # Walk every integer timestamp from left to right, including empty gap columns.
            for timestamp in range(min_time, max_time + 1):
                if (timestamp, price) in observed_points:
                    row_cells.append(POINT_CELL)
                else:
                    row_cells.append(EMPTY_CELL)
            chart_lines.append("+" + "+".join(row_cells) + "+")
    
        chart_lines.append(border_line)
        return chart_lines
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of plotting observations onto pre-ruled graph paper. First, you scan your points to find the earliest and latest timestamps and the lowest and highest prices so you know how many columns and rows of graph paper to cut out. Next, you drop every (timestamp, price) pair into a hash set — a lookup table that answers "was an observation recorded at this exact coordinate?" in constant (O(1)) average time and automatically merges duplicates. Finally, you print the sheet one horizontal strip at a time from the highest price at the top down to the lowest price at the bottom, stamping " * " when the coordinate is in the set and " " otherwise.

Two naive shortcuts fail here. If you only create columns and rows for timestamps and prices that actually appear in the input, any missing integer in between disappears and warps the visual spacing of the chart. And if you create the full grid but scan the entire n-element input list to check each of the T * P grid cells, the runtime balloons to O(n * T * P) instead of O(n + T * P).

Walk through Example 3 with [[-3, 1], [-1, -1], [-3, -1]]: 1. Scanning the 3 pairs builds observed_points = {(-3, 1), (-1, -1), (-3, -1)}, min_time = -3, max_time = -1 (columns -3, -2, -1), and min_price = -1, max_price = 1 (rows 1, 0, -1). 2. With 3 columns, both the top and bottom borders are "+-----+-----+-----+". 3. Walking price downward 1 -> 0 -> -1 and timestamp across -3 -> -2 -> -1: - price = 1: (-3, 1) is in the set -> "+ * + + +" - price = 0: no hits (gap row kept!) -> "+ + + +" - price = -1: (-3, -1) and (-1, -1) hit -> "+ * + + * +"

Complexity

Let n be len(time_price_pairs), u be the number of distinct points (u <= min(n, T * P)), T = max_time - min_time + 1 be the number of timestamp columns, and P = max_price - min_price + 1 be the number of integer price levels.

  • Time: O(n + T * P) — We scan the n input pairs once to populate observed_points (O(1) average hash insert per pair) and update the four min/max bounds. Then we visit each of the T * P cells once, doing an O(1) average set lookup per cell, and join P + 2 lines of length 6 * T + 1. Because the returned chart itself contains (P + 2) * (6 * T + 1) characters, no algorithm can beat O(n + T * P) time.
  • Space: O(u + T * P) — observed_points stores u distinct 2-tuples (at most n), and the output list chart_lines holds P + 2 strings of 6 * T + 1 characters each (O(T * P) characters).

Edge cases

  • Empty input ([]): With zero pairs there is no defined time or price interval, so returning [] avoids crashing on time_price_pairs[0] or min().
  • Single data point ([[4, 8]]): min_time == max_time and min_price == max_price, producing a 1-column, 1-interior-row chart ["+-----+", "+ * +", "+-----+"].
  • Duplicate coordinates: Inserting into observed_points collapses any number of identical [timestamp, price] entries into a single " * " cell.
  • Missing intermediate timestamps or prices: Unobserved integers inside [min_time, max_time] and [min_price, max_price] still render as blank columns and blank rows.
  • All points on one timestamp or one price: Renders cleanly as a single vertical column (T = 1) or a single horizontal interior row (P = 1).
  • Negative timestamps and prices: Range iteration from min_time to max_time and max_price down to min_price works identically for negative, zero, and positive integers.

Common mistakes

  • Rendering prices from min_price up to max_price: Text lines print from top to bottom, whereas chart y-axes put larger values higher up. Iterating upward prints the chart upside down.
  • Off-by-one range() stop bounds: Writing range(max_price, min_price, -1) omits min_price, and range(min_time, max_time) omits max_time. Downward range needs min_price - 1; upward range needs max_time + 1.
  • Adding raw input lists to a set: Each element of time_price_pairs is a list ([t, p]), which raises TypeError: unhashable type: 'list'. Always convert to (timestamp, price) tuples first.
  • Omitting + dividers between interior cells: Every column cell is separated from adjacent cells by '+' on interior rows just like on the horizontal borders.
  • Concatenating strings with += inside the inner loop: Building row_cells as a list and calling "+".join(row_cells) once per row keeps string construction cleanly linear in row width.

Alternative approaches

  • Pre-allocate a 2D character buffer: Create P + 2 lists of 6 * T + 1 characters initialized to spaces, draw + at every index divisible by 6 and - along the top and bottom rows, then stamp * directly at row 1 + (max_price - price) and column 6 * (timestamp - min_time) + 3 for each input pair. This avoids building a hash set (O(T * P) total memory including output) and has the same O(n + T * P) time complexity.
  • Sort distinct points by (-price, timestamp): Sort unique points in O(n log n) time and walk a pointer alongside the (price, timestamp) grid loops. This uses no hash table, though sorting adds an unnecessary log n factor.

Follow-up questions

  • How would you adapt the chart if timestamps are Unix epoch seconds spanning an entire year? A year has about 3.15 * 10^7 seconds, so creating one column per integer second would allocate gigabytes of spaces per row. Instead, fix a target terminal resolution of C columns by R rows and bucket (group nearby continuous values into fixed-width intervals): map each point to column (timestamp - min_time) * (C - 1) // (max_time - min_time) (guarding against division by zero when max_time == min_time) and similarly bucket prices across R rows. That caps both time and memory at O(n + C * R) regardless of coordinate magnitude.

  • How would you support fractional prices such as 19.95 and 19.99 without floating-point lookup bugs? Choose an explicit price tick size tick (such as 0.01 for cents or 0.50 for half-dollars) and convert every price to an integer tick index via round(price / tick) before running the exact same integer-grid algorithm. Converting to integer tick indices avoids floating-point representation drift where 0.1 + 0.2 != 0.3 would cause direct float set lookups to miss.

  • How would you connect adjacent observations into a continuous ASCII line plot instead of isolated stars? Aggregate multiple prices at the same timestamp (for instance keeping the closing or mean price), sort those points by timestamp in O(n log n) time, and for each adjacent pair (t1, p1) and (t2, p2) interpolate intermediate columns t between t1 and t2 by rounding the linear price estimate p1 + (p2 - p1) * (t - t1) / (t2 - t1) and drawing vertical connector characters (|) when consecutive columns jump across multiple rows.

Follow-up questions

Similar questions

More Fanatics interview questions

All 3 Fanatics questions →