Select table cells and set a color
I was asked this
No reports yet. Sign in to say where you were asked it.
Design a Table class for a whiteboard app. A table has a fixed number of rows and columns. A user selects part of the table and sets a color on everything selected.
Every cell starts with the empty color "". Only one selection is active at a time, and each select* call replaces the previous selection. Selecting does not change any color. Rows and columns are 0-indexed.
Implement:
-
Table(numRows, numColumns): create the table. All cells have color"". -
selectTable(): select every cell. -
selectRow(row): select every cell in one row. -
selectCell(row, col): select one cell. -
setColor(color): setcoloron every selected cell. The selection stays active afterwards. If nothing has been selected yet, do nothing. -
getColor(row, col): return the current color of one cell.
The most recent setColor that covers a cell decides its color. An out-of-range row or column should raise an error.
Constraints
-
1 <= numRows, numColumns <= 10^6, so the table may have far too many cells to store one by one. - Up to
10^5calls in total. - Aim for
O(1)time per call (amortized is fine).
Example 1
t = Table(2, 3)
t.selectRow(0)
t.setColor("teal")
t.selectCell(0, 1)
t.setColor("gold")
t.getColor(0, 1) -> "gold"
t.getColor(0, 2) -> "teal"
t.getColor(1, 1) -> ""
Example 2
t = Table(4, 4)
t.selectCell(3, 3)
t.setColor("navy")
t.selectTable()
t.setColor("white")
t.getColor(3, 3) -> "white"
t.selectRow(2)
t.setColor("plum")
t.getColor(2, 0) -> "plum"
t.getColor(3, 3) -> "white"
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
