Sure! Here's a React + TypeScript based DSA (Data Structures and Algorithms) problem that combines both frontend logic with algorithmic thinking.
🧠 Problem: Live Search with Debounced Input and Sorting
💡 Objective:
Create a searchable list of users where:
- The user types into an input box.
- After the user stops typing for 500ms (debounce), an API call is made to fetch matching users.
- The results are sorted alphabetically by name.
- The UI updates to show the filtered, sorted list.
You’ll implement this in React with TypeScript.
🧩 Requirements
- Use functional components and hooks (
useState, useEffect, etc.).
- Implement debouncing using
setTimeout.
- Sort the results alphabetically before displaying.
- Type everything using TypeScript interfaces.
- Display a loading indicator while fetching data.
- Show an error message if something goes wrong.
📦 Sample Data Structure
ts
interface User {
id: number;
name: string;
}
Assume there’s a mock API like this:
ts
const fetchUsers = async (searchTerm: string): Promise<User[]> => {
// Simulate network delay
await new Promise((resolve) => setTimeout(resolve, 500));
const allUsers: User[] = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
{ id: 4, name: 'David' },
{ id: 5, name: 'Eve' },
{ id: 6, name: 'Frank' },
{ id: 7, name: 'Anna' },
{ id: 8, name: 'Anthony' },
];
return allUsers.filter((user) =>
user.name.toLowerCase().includes(searchTerm.toLowerCase())
);
};
🖥️ UI Mockup
code
Search: [__________]
Loading...
Results:
- Alice
- Anthony
- Anna
✅ Deliverables
Implement a component:
tsx
const UserSearch: React.FC = () => {
// Your code here
};
That satisfies all the requirements above.
🧪 Bonus Challenge
- Add caching so that repeated searches don’t trigger duplicate API calls.
- Add pagination or infinite scroll support.
- Highlight the matched part of the name in bold/with color.
🧾 Solution Outline (Hints)
-
Create state for:
- search term
- loading status
- error message
- results array
-
Use useEffect to debounce the search term:
- Use
setTimeout and clearTimeout.
-
When the debounced search term changes, call fetchUsers.
-
Sort the returned users alphabetically.
-
Update the UI accordingly.
Would you like me to provide a full solution as well?