Skip to the solution
EasyFrontend10 min read

Build a Generate Table (rows x columns)

1.1k views

The problem

Question presented to candidate: "Build a small form with two number inputs, Rows and Columns, and a Generate button. When the user submits, render a table of that size filled with the numbers 1 to rows times columns. The numbers go down the first column, then up the second column, down the third, and so on, like a snake."

Requirements:

  • Two labelled number inputs (1 to 20) and a Generate button; Enter in either input submits.
  • The table only changes when the form is submitted, not while typing.
  • Cell values snake through the columns: for 4 x 5 the first row is 1 8 9 16 17.
  • Invalid input (empty, 0, decimals, above 20) shows an error per field, marks it invalid, and keeps the last valid table on screen.

What a strong answer should cover:

  • Separate draft state (what is in the inputs, as typed) from committed state (the last valid size); the grid is derived from the committed size.
  • A closed-form formula for each cell: even column col * rows + row + 1, odd column col * rows + (rows - row).
  • Number input quirks: the DOM value is a string, empty inputs, decimals, and framework conversions (Vue v-model and Angular ngModel hand back numbers).
  • Accessible errors with aria-invalid and aria-describedby, a <caption>, and a form submit handler rather than a click handler.
  • Stable keys when rendering rows and cells, and an upper bound to keep the DOM small.

Clarifying questions expected:

  • "Is the snake order column-wise or row-wise, and does it start at 1?"
  • "What are the maximum sizes, and should the table update live as I type?"

Code / implementation expected: Yes. A form with validation and a generated table in the framework of your choice.

  • Rendering
  • Lists
  • Forms

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read ยท 9 sections

React solution

Every file of the working solution. Open it in the playground to run and change it.

ReactComplete solution
import TableGenerator from "./src/components/TableGenerator";

export default function App() {
  return (
    <main className="app">
      <h1>Generate table</h1>
      <TableGenerator />
    </main>
  );
}

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 4 of 107 in Machine coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Build a Like Button

Continue