MapReduce Framework - Problem
Build a simple MapReduce framework that distributes map and reduce tasks across multiple threads.
Your framework should:
- Take an input array of integers and a number of threads
- Split the input into chunks for parallel processing
- Apply a map function (square each number) using multiple threads
- Apply a reduce function (sum all results) to combine the outputs
- Return the final reduced result
The framework should handle thread synchronization and data partitioning automatically.
Note: For simplicity, the map function is fixed to square numbers, and the reduce function sums the results.
Input & Output
Example 1 — Basic Case
$
Input:
data = [1,2,3,4], numThreads = 2
›
Output:
30
💡 Note:
Split into [1,2] and [3,4]. Thread 1: 1² + 2² = 5, Thread 2: 3² + 4² = 25. Final: 5 + 25 = 30
Example 2 — Single Thread
$
Input:
data = [2,3], numThreads = 1
›
Output:
13
💡 Note:
Only one thread processes all: 2² + 3² = 4 + 9 = 13
Example 3 — More Threads than Data
$
Input:
data = [5], numThreads = 3
›
Output:
25
💡 Note:
Only one thread needed: 5² = 25. Extra threads remain idle
Constraints
- 1 ≤ data.length ≤ 104
- 1 ≤ numThreads ≤ 16
- -103 ≤ data[i] ≤ 103
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code