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
INPUTMAPREDUCERESULT1234Array: [1,2,3,4]Threads: 21Partition DataSplit into chunks2Parallel MapSquare each number3Local ReduceSum within threads4Final ReduceCombine partial sumsT1: [1,2]T2: [3,4]Sum: 5Sum: 2530Final Result5 + 25 = 30Key Insight:Each thread processes its chunk independently and computes local results,then we simply combine the partial sums for maximum parallelism.TutorialsPoint - MapReduce Framework | Multi-threaded Processing
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen