Real-Time List Filter with Dynamic Maximum Highlighting
Data Structure DesignModel answerLast updated
Create a filterable transaction list that automatically highlights entries with the highest amount among currently visible results.
Design and implement a transaction list component that displays items with a name and numeric amount. The component must support:
- Display all transactions in a list format
- Text filtering via a search input that matches transaction names using case-insensitive substring search
- Numeric filtering via a minimum amount input that shows only transactions at or above the threshold
- Dynamic highlighting that marks all transaction names having the maximum amount among currently visible (filtered) results
Behavior requirements:
- When multiple transactions share the maximum amount in the filtered view, highlight all of them
- As filters change, immediately recalculate which transactions have the maximum amount and update highlighting accordingly
- When no transactions match the filters, display an appropriate empty state with no highlights
- Handle edge cases: empty datasets, ties, invalid numeric inputs, special characters in names
Design considerations:
Explain your approach to state management (what to store vs. derive), how you efficiently compute the maximum during filtering, and the time/space complexity of your solution. Discuss how you would test the component, including edge cases like extremely large datasets, concurrent filter updates, internationalized text, and boundary conditions in numeric comparisons.
Provide a working implementation demonstrating the core logic.
Hints
Hint 1
Compute derived values (filtered list, maximum, highlights) from source state rather than storing them separately to avoid synchronization bugs
Hint 2
Combine filtering and maximum-finding in a single iteration to avoid redundant passes over the data
Hint 3
Use stable identifiers (indices or IDs) to track which items should be highlighted, not just name matching
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The fundamental challenge is maintaining consistency between three moving parts: the visible items, the current maximum, and the highlighting. The cleanest solution treats everything except user input as derived state.
State Architecture
Store only the minimal inputs:
- The source data (usually a prop)
- The current search query string
- The current minimum amount input string
Everything else—filtered results, maximum value, highlight indicators—gets computed from these inputs on every change. This eliminates the classic bug where highlight state lags behind filter changes because separate state updates arrive in the wrong order.
Core Algorithm
Process the data in a single pass that simultaneously filters and identifies the maximum:
def compute_view(items, query, min_threshold):
normalized_query = normalize(query)
threshold = parse_numeric(min_threshold)
visible = []
max_amount = -infinity
max_indices = set()
for i, item in enumerate(items):
# Apply both filters
if not matches_name(item.name, normalized_query):
continue
if threshold is not None and item.amount < threshold:
continue
# Track this item
visible.append(i)
# Update maximum tracking
if item.amount > max_amount:
max_amount = item.amount
max_indices = {i}
elif item.amount == max_amount:
max_indices.add(i)
return visible, max_indices
This avoids a second scan to find the maximum. The key insight: when processing filtered items sequentially, maintain the running maximum and the set of indices achieving it. When a larger value appears, previous candidates are no longer maximal, so replace the set. When a tie appears, add to the set.
Text Normalization
For robust international text support, normalize both stored names and the query:
import unicodedata
def normalize(text):
# Canonical decomposition, then case fold
return unicodedata.normalize('NFC', text).casefold()
Precompute normalized names when the data changes, so each keystroke only normalizes the query. This is O(n·L) once rather than on every filter update.
Note: JavaScript's toLowerCase() doesn't handle all Unicode correctly (e.g., German ß). Document this limitation or use a proper Unicode case-folding library for production.
Numeric Input Parsing
Handle malformed input gracefully:
def parse_numeric(raw_input):
cleaned = raw_input.strip()
if not cleaned:
return None # Empty input = no filter
try:
value = float(cleaned)
return value if math.isfinite(value) else None
except ValueError:
return None # Invalid input = no filter
Treat "", "-", "abc", "NaN", "Infinity" all as "no minimum filter" rather than blocking all results.
Implementation in React
import { useMemo, useState } from 'react';
function TransactionList({ transactions }) {
const [searchText, setSearchText] = useState('');
const [minAmountRaw, setMinAmountRaw] = useState('');
// Precompute normalized names
const normalizedNames = useMemo(
() => transactions.map(t =>
t.name.normalize('NFC').toLocaleLowerCase()
),
[transactions]
);
// Derive the view
const view = useMemo(() => {
const query = searchText.trim().normalize('NFC').toLocaleLowerCase();
const minAmount = minAmountRaw.trim() === ''
? null
: parseFloat(minAmountRaw);
const visible = [];
let max = -Infinity;
let maxSet = new Set();
transactions.forEach((txn, idx) => {
if (!normalizedNames[idx].includes(query)) return;
if (minAmount !== null &&
isFinite(minAmount) &&
txn.amount < minAmount) return;
visible.push(idx);
if (txn.amount > max) {
max = txn.amount;
maxSet = new Set([idx]);
} else if (txn.amount === max) {
maxSet.add(idx);
}
});
return { visible, maxSet };
}, [transactions, normalizedNames, searchText, minAmountRaw]);
return (
<div>
<input
value={searchText}
onChange={e => setSearchText(e.target.value)}
placeholder="Search names..."
/>
<input
value={minAmountRaw}
onChange={e => setMinAmountRaw(e.target.value)}
placeholder="Min amount"
/>
{view.visible.length === 0 ? (
<p>No transactions match your filters</p>
) : (
<ul>
{view.visible.map(idx => (
<li
key={idx}
className={view.maxSet.has(idx) ? 'highlighted' : ''}
>
{transactions[idx].name}: ${transactions[idx].amount}
</li>
))}
</ul>
)}
</div>
);
}
For rapid typing, consider useDeferredValue(searchText) to keep the input responsive while the expensive computation catches up.
Complexity Analysis
Given n transactions, average name length L, query length q:
- Preprocessing (on data change): O(n·L) to normalize all names
- Per filter update: O(n·L) worst case for substring checks, O(n) for numeric comparisons and max tracking
- Space: O(n·L) for normalized names, O(k) for visible indices where k ≤ n
No sorting needed (which would be O(k log k)). The single-pass algorithm is optimal for this problem.
For very large datasets (100k+ items), the bottleneck becomes rendering, not computation. Use virtualization libraries (react-window, react-virtuoso) to render only ~50 visible rows while the filter still processes all data in milliseconds.
Edge Cases and Testing
Empty scenarios:
- Zero transactions: show empty state, no crash
- All filtered out: show "no matches" message
Numeric boundaries:
- Negative amounts: valid, maximum still well-defined
- Zero: valid filter threshold, use >= comparison not >
- Ties: all items at max highlighted, including duplicate names with different amounts
- Initialize max to
-Infinity, not 0, to handle all-negative datasets
Text handling:
- Non-ASCII: "Café" matches "café" and "CAFÉ"
- Composed vs decomposed Unicode: é (single char) matches e + combining accent
- Empty query: matches everything (empty string is substring of all strings)
- Leading/trailing whitespace: trim before matching
Input validation:
- Don't confuse empty string with zero:
""means no filter,"0"is a real threshold - Handle
"-",".","1e999"gracefully as no-filter - Never use truthy/falsy checks on parsed numbers (0 is falsy but valid)
Concurrency:
- With synchronous derivation, newer inputs always produce newer outputs
- If filtering becomes async (server-side), tag requests with query IDs and discard out-of-order responses
Performance test:
- 100k items with 20-char names filters in ~5-10ms on modern hardware
- Rapid typing (10 keys/sec) should stay smooth with deferred updates
Floating-point:
- For financial data, use integer cents to avoid
0.1 + 0.2 !== 0.3breaking ties - If using floats, document that near-equal values may not highlight consistently
The solution is correct, efficient, and robust across edge cases when following the single-source-of-truth principle and defensive input parsing.