Plot ASCII chart for time-price pairs
Company: Fanatics
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates skills in array manipulation, coordinate mapping, and ASCII-based data visualization, focusing on transforming unsorted time-price pairs into a fixed 2D grid and handling point collisions and empty cells.
Constraints
- 0 <= len(points) <= 10000
- -10000 <= timestamp, price <= 10000
- If points is non-empty, the rendered ranges are manageable: max(timestamp) - min(timestamp) <= 100 and max(price) - min(price) <= 100
- Input may be unsorted and may contain duplicate pairs
Examples
Input: [(1, 2), (6, 3), (4, 5), (2, 2)]
Expected Output: ['+-----+-----+-----+-----+-----+-----+', '+ + + + * + + +', '+ + + + + + +', '+ + + + + + * +', '+ * + * + + + + +', '+-----+-----+-----+-----+-----+-----+']
Explanation: Timestamps span 1 through 6 and prices span 5 down to 2. Stars appear at (4,5), (6,3), (1,2), and (2,2).
Input: [(-1, 0), (1, -1), (-1, 0), (0, -1)]
Expected Output: ['+-----+-----+-----+', '+ * + + +', '+ + * + * +', '+-----+-----+-----+']
Explanation: This checks negative values and duplicates. The duplicate (-1, 0) still produces only one star in that cell.
Input: []
Expected Output: []
Explanation: With no points, there is no chart to draw.
Input: [(3, 7)]
Expected Output: ['+-----+', '+ * +', '+-----+']
Explanation: A single point produces one column, one price row, and matching top and bottom borders.
Solution
def solution(points):
if not points:
return []
point_set = {tuple(point) for point in points}
min_ts = min(t for t, _ in point_set)
max_ts = max(t for t, _ in point_set)
min_price = min(p for _, p in point_set)
max_price = max(p for _, p in point_set)
num_cols = max_ts - min_ts + 1
border = "+" + "+".join(["-----"] * num_cols) + "+"
chart = [border]
for price in range(max_price, min_price - 1, -1):
cells = []
for ts in range(min_ts, max_ts + 1):
if (ts, price) in point_set:
cells.append(" * ")
else:
cells.append(" ")
chart.append("+" + "+".join(cells) + "+")
chart.append(border)
return chartTime complexity: O(n + T * P), where n is the number of input pairs, T is the number of timestamp columns, and P is the number of price rows.. Space complexity: O(n + T * P), counting the set of unique points and the output chart..
Hints
- First normalize the chart bounds by finding the minimum and maximum timestamp and price.
- Use a set of pairs so you can test whether a cell should contain '*' in O(1) average time.