Question Bank
JavaScript Take-Out-and-Rest Array: Two Approaches Quiz
Difficulty: Medium
Two seeded approaches to build a map of each-element-to-the-rest (reduce + filter and forEach + filter), plus two companions on slice + concat and a complexity discussion.
JavaScript Take-Out-and-Rest Array: Two Approaches Quiz
Two seeded approaches to build a map of each-element-to-the-rest (reduce + filter and forEach + filter), plus two companions on slice + concat and a complexity discussion.
454 views
9
Implement getRestItems(arr) that returns an object whose keys are each element and whose value is the array with that element removed. Solve it with reduce and filter.
Examples
Example 1:
Input: [1, 2, 3, 4]
Output: { 1: [2,3,4], 2: [1,3,4], 3: [1,2,4], 4: [1,2,3] }
Explanation: Each key maps to the array with that value filtered out.Example 2:
Input: ['a', 'b', 'c']
Output: { a: ['b','c'], b: ['a','c'], c: ['a','b'] }
Explanation: Same shape for strings; the keys become the property names.Re-implement getRestItems with forEach instead of reduce. When would you prefer this version over the reduce one?
Examples
Example 1:
Input: [1, 2, 3]
Output: { 1: [2,3], 2: [1,3], 3: [1,2] }
Explanation: Same output as Q1; only the iteration helper changes.Build the same map using slice + spread concat by INDEX (not value). Why is the index-based version more robust on arrays with duplicates?
Examples
Example 1:
Input: [1, 1, 2]
Output: { 0: [1, 2], 1: [1, 2], 2: [1, 1] }
Explanation: Keying by index distinguishes the two `1` entries; keying by value would collapse them.Big-O question: what is the time and space complexity of the reduce + filter solution from Q1 on an input of length n? Pick the tightest correct bound.
Examples
Example 1:
Input: n = 1000
Output: O(n^2) time, O(n^2) space
Explanation: n filter passes each producing an O(n) rest-array yields n^2 work AND n^2 retained cells across all values.