Question Bank
Array Cross-Reference and Lookup Challenges
Difficulty: Medium
Six lookup-and-filter drills: id-to-id matching with Sets, random sampling without duplicates, valid-only filtering, numeric-only extraction, value-by-row matching, and rest-parameter multipliers.
Array Cross-Reference and Lookup Challenges
Six lookup-and-filter drills: id-to-id matching with Sets, random sampling without duplicates, valid-only filtering, numeric-only extraction, value-by-row matching, and rest-parameter multipliers.
1,094 views
27
Given array_A (array of objects with _id) and array_B (array of id strings), return the _id values from array_A that are also present in array_B. Aim for O(n + m).
Examples
Example 1:
Input: array_A = [{ _id: 'a' }, { _id: 'b' }, { _id: 'c' }], array_B = ['b', 'd', 'a']
Output: ['a', 'b']
Explanation: Build a Set of `array_B` for O(1) lookups, then filter `array_A` by membership.Implement generateRandomItems(arr, n) returning n unique random items from arr. Reject when n is out of range.
Examples
Example 1:
Input: generateRandomItems(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3)
Output: e.g. ['b', 'e', 'a']
Explanation: Pick random indices until you have `n` distinct items. Return `[]` when `n` is invalid.Implement filterMembers(members) that returns only members whose expiryDate is in the future and masks all but the last three digits of memberId with #.
Examples
Example 1:
Input: filterMembers([{ name: 'bar', memberId: 'ABC456789123', expiryDate: '02-11-2099' }])
Output: [{ name: 'bar', memberId: '#########123', expiryDate: '02-11-2099' }]
Explanation: Compare `new Date(expiryDate)` to `Date.now()`; mask via `slice(-3).padStart(length, '#')`.Write mapOnlyNumbers(arr) that returns only the values that can be parsed as numbers, converted to Number. Strings like '-20' count; words like 'abc' don't.
Examples
Example 1:
Input: mapOnlyNumbers(['-20', '-40', 33, -10, 'abc', 'zero', 0, '1', 12.532])
Output: [-20, -40, 33, -10, 0, 1, 12.532]
Explanation: Use `parseFloat` (handles ints and floats) and `!isNaN` to drop unparseable strings.Given an array of [key, value] pairs and a search value, return an object mapping each matching key to that value (stringified).
Examples
Example 1:
Input: findBy([['name', 'foo'], ['age', '29'], ['nickname', 'bar'], ['likes', '131'], ['followers', '29']], 29)
Output: { age: '29', followers: '29' }
Explanation: Iterate; collect each pair whose value equals `String(searchValue)`.Implement multiply(...arr) that uses the first element as a multiplier and returns a new array of the rest multiplied by it.
Examples
Example 1:
Input: multiply(2, 1, 2, 3)
Output: [2, 4, 6]
Explanation: Rest parameters split off the first arg cleanly; map the rest by the multiplier.