Sobes.tech
Middle

Do you have ideas on how to avoid nested loops (O(n²)) when searching for users by ID? How can the search be optimized?

sobes.tech AI

Answer from AI

To avoid nested loops (O(n²)) when searching for users by ID, you can use a data structure with fast key-based access, such as an object (Map) in JavaScript. Instead of searching for each user by ID through iteration, create a dictionary where the key is the ID and the value is the user. Then, the search will be O(1) for each ID, and the overall complexity will decrease to O(n).

Example:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

// Create a Map for quick lookup
const userMap = new Map(users.map(user => [user.id, user]));

const idsToFind = [2, 3];
const foundUsers = idsToFind.map(id => userMap.get(id));
console.log(foundUsers); // [{id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}]

This approach significantly optimizes the search.