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_timeup tomax_timein left-to-right order, even when a timestamp has zero observations. - Vertical axis (interior rows): Every integer price from
max_pricedown tomin_pricein 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,"+-----+-----+"for2columns). - 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).
- Use
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_pairscontains2integers[timestamp, price](negative, zero, or positive). - Grid dimensions
(max_time - min_time + 1) * (max_price - min_price + 1)fit comfortably in memory whentime_price_pairsis non-empty.
Step-by-step walkthrough
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 borderNotice 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
4has no data points, and price11has 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_pairsis[], there is no minimum or maximum to frame, so we return[].
- Cell width is always 5 characters:
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 borderThat inverted y-axis is the key coordinate rule: - The outer loop walks
pricedownward frommax_pricedown tomin_price. - The inner loop walkstimestampupward frommin_timeup tomax_time.Because every coordinate is visited relative to
min_time..max_timeandmax_price..min_price, negative timestamps and negative prices work automatically without special cases.Deduplicate points and find bounds in one pass
Suppose the chart spans
T = max_time - min_time + 1columns andP = max_price - min_price + 1price rows. If we checked each(timestamp, price)cell by scanning allninput pairs from scratch, drawing the grid would takeO(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 aset, so we unpacktimestamp, priceand store an immutable tuple(timestamp, price). 2. We can trackmin_time,max_time,min_price, andmax_pricein 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)Build the borders and each price row
With
num_columns = max_time - min_time + 1, both the top and bottom borders are"+"followed by"-----+"repeatednum_columnstimes.For each
pricefrommax_pricedown tomin_price, we collect one 5-character string per timestamp intorow_cells, join those cells with"+", and add"+"at both ends. Pay close attention to therange()endpoints: -range(max_price, min_price - 1, -1)steps by-1and stops just beforemin_price - 1, which meansmin_priceis included. -range(min_time, max_time + 1)steps by+1and stops just beforemax_time + 1, which meansmax_timeis 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_linesTrace 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.Complete solution
Putting all three phases together inside
render_ascii_chartgives 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 theninput pairs once to populateobserved_points(O(1)average hash insert per pair) and update the four min/max bounds. Then we visit each of theT * Pcells once, doing anO(1)average set lookup per cell, and joinP + 2lines of length6 * T + 1. Because the returned chart itself contains(P + 2) * (6 * T + 1)characters, no algorithm can beatO(n + T * P)time. - Space:
O(u + T * P)—observed_pointsstoresudistinct 2-tuples (at mostn), and the output listchart_linesholdsP + 2strings of6 * T + 1characters each (O(T * P)characters).
Edge cases
- Empty input (
[]): With zero pairs there is no defined time or price interval, so returning[]avoids crashing ontime_price_pairs[0]ormin(). - Single data point (
[[4, 8]]):min_time == max_timeandmin_price == max_price, producing a 1-column, 1-interior-row chart["+-----+", "+ * +", "+-----+"]. - Duplicate coordinates: Inserting into
observed_pointscollapses 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_timetomax_timeandmax_pricedown tomin_priceworks identically for negative, zero, and positive integers.
Common mistakes
- Rendering prices from
min_priceup tomax_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: Writingrange(max_price, min_price, -1)omitsmin_price, andrange(min_time, max_time)omitsmax_time. Downwardrangeneedsmin_price - 1; upwardrangeneedsmax_time + 1. - Adding raw input lists to a
set: Each element oftime_price_pairsis alist([t, p]), which raisesTypeError: 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: Buildingrow_cellsas 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 + 2lists of6 * T + 1characters initialized to spaces, draw+at every index divisible by6and-along the top and bottom rows, then stamp*directly at row1 + (max_price - price)and column6 * (timestamp - min_time) + 3for each input pair. This avoids building a hash set (O(T * P)total memory including output) and has the sameO(n + T * P)time complexity. - Sort distinct points by
(-price, timestamp): Sort unique points inO(n log n)time and walk a pointer alongside the(price, timestamp)grid loops. This uses no hash table, though sorting adds an unnecessarylog nfactor.
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^7seconds, so creating one column per integer second would allocate gigabytes of spaces per row. Instead, fix a target terminal resolution ofCcolumns byRrows 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 whenmax_time == min_time) and similarly bucket prices acrossRrows. That caps both time and memory atO(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 as0.01for cents or0.50for half-dollars) and convert every price to an integer tick index viaround(price / tick)before running the exact same integer-grid algorithm. Converting to integer tick indices avoids floating-point representation drift where0.1 + 0.2 != 0.3would 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 columnstbetweent1andt2by rounding the linear price estimatep1 + (p2 - p1) * (t - t1) / (t2 - t1)and drawing vertical connector characters (|) when consecutive columns jump across multiple rows.
Follow-up questions
- How would you adapt the chart if timestamps are Unix epoch seconds spanning an entire year?
- How would you support fractional prices such as 19.95 and 19.99 without floating-point lookup bugs?
- How would you connect adjacent observations into a continuous ASCII line plot instead of isolated stars?
Similar questions
- Clarifying Prior Microsoft Contract Scope and Engineering Impact
- Consumer Stock Brokerage Platform
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance