Your question is Optimize for Time and Space. Take a moment with it on the right.
Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).
Navan's expense report view renders a table of a traveler's expense line items, with the overall total repeated in the last column of every row. On reports with a few hundred line items — common for a multi-week business trip — typing in the search box makes the whole page visibly lag. Optimize this component for time and space complexity, and explain what you'd change.
import { useState } from "react";
type Expense = { id: string; merchant: string; amount: number };
function ExpenseTable({ expenses }: { expenses: Expense[] }) {
const [search, setSearch] = useState("");
const [history, setHistory] = useState<Expense[][]>([]);
const filtered = expenses.filter((e) =>
e.merchant.toLowerCase().includes(search.toLowerCase())
);
const seen: string[] = [];
const deduped = filtered.filter((e) => {
if (seen.includes(e.id)) return false;
seen.push(e.id);
return true;
});
return (
<div>
<input
value={search}
onChange={(e) => {
setSearch(e.target.value);
setHistory((prev) => [...prev, JSON.parse(JSON.stringify(expenses))]);
}}
/>
<table>
<tbody>
{deduped.map((expense) => (
<tr key={expense.id}>
<td>{expense.merchant}</td>
<td>{expense.amount}</td>
<td>
{deduped.reduce((sum, e) => sum + e.amount, 0)}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
Explain what you would change to fix the time and space complexity here, referencing specific lines.