4. Improve a function
Problem statement
excludeItems tasked with filtering an array of items by removing those that meet specific exclusion criteria. This function plays a pivotal role in data processing, enabling the refinement of datasets based on dynamic conditions.
Function Input
- items (Array of Objects): A collection of items, each represented as an object with various properties such as color, type, and age.
- excludes (Array of Objects): Criteria for exclusion, with each criterion as an object containing properties k (the property name to consider for exclusion) and v (the value of that property leading to exclusion).
Function Output
Returns a filtered array comprising items that do not align with the specified exclusion criteria.
Example
Consider the following items array and excludes criteria:
const items = [
{ color: 'red', type: 'tv', age: 18 },
{ color: 'silver', type: 'phone', age: 20 },
{ color: 'blue', type: 'book', age: 17 }
];
const excludes = [
{ k: 'color', v: 'blue' },
{ k: 'type', v: 'phone' }
];
Executing excludeItems(items, excludes) should yield:
[{ color: 'red', type: 'tv', age: 18 }]
This output represents the items array after the exclusion of items with a color of ‘blue’ and type of ‘phone’, based on the specified criteria.
Objective
The goal is to implement a versatile function capable of sifting through an array of objects and excluding those that meet certain key-value criteria, thus refining the dataset for subsequent processing or analysis.
How to approach 4. Improve a function
The strategy an interviewer expects you to reach for.
Exclude-items looks like nested loops until you notice the real bottleneck: checking every item against every exclusion rule. Naive move For each item, scan all excludes. Correct, but O(N×M) — ten thousand items and a thousand rules freezes a tab. Where it breaks Interviewers want the complexity conversation. Also watch mutation: filtering should return a new list unless told otherwise. The fix Build a lookup Map/Set from exclusion criteria first (keyed by the fields you match on). Then filter items in linear time with O(1) membership checks. Remember: Precompute a lookup for excludes — do not nest the hot loops. Say this in the interview: I'd build an exclusion lookup map up front, then filter items in linear time so we avoid the O(N×M) nested scan.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.