AlgoMaster Logo
AlgoMasterDesign a Parallel Array Mappermedium

Design a Parallel Array Mapper

medium

Design a ParallelMapper that applies a supplied transformation to an array using a fixed number of worker threads.

Implement map(values, workers, transform):

  • Apply transform exactly once to every value.
  • Return the transformed values in the same order as the input, even if callbacks finish out of order.
  • For a non-empty input, create exactly min(workers, values.length) workers.
  • Wait for every worker to finish before returning.
  • Keep all state for one call local so separate calls may run concurrently.

The transformation performs one unit of work and is safe to call concurrently. Do not create one thread per element, and do not use busy-waiting.

If a transformation fails, stop assigning new work after the failure is observed, wait for all workers that were already started, and propagate the first failure. Java, Python, C++, and C# propagate the callback exception. In Go, the transformation and Map return an error; return the first non-nil error and no result.

For an empty input, return an empty result without creating workers or invoking the transformation.

Standard thread, synchronization, collection, callback, and error APIs are preloaded, so you do not need import, include, package, or using statements.

Example 1:

Input:

Output:

Explanation: The callbacks may complete in any order, but each result is written to its input index.

Example 2:

Input:

Output:

Explanation: The mapper joins every started worker and then propagates the first transformation failure.

Constraints

  • 0 <= values.length <= 10000
  • 1 <= workers <= 100
  • -1_000_000 <= values[i] <= 1_000_000
  • The transformation result fits in a signed 32-bit integer.
  • Different map calls on the same ParallelMapper may execute concurrently.
  • The judge may block callbacks temporarily to verify actual parallel execution.
Loading...

Input

values = [4, 1, 3]
workers = 2
transform(x) = x * x

Output

[16, 1, 9]

Run is a quick check against the first couple of scenarios, which is roughly what these examples describe. Submit puts your class under the full set, which stays hidden.