Skip to the solution
MediumDSAAsked in 20246 min read

Partition Array

342 views

The problem

Problem, as an interviewer would state it: "Split an array into two lists: one with the elements that satisfy a predicate and one with those that do not. Support asynchronous predicates."

Examples:

Code
partition([1, 2, 3, 4, 5, 6], n => n % 2 === 0); // [[2, 4, 6], [1, 3, 5]]
await partitionAsync(users, u => isActive(u.id)); // [[active...], [inactive...]]

Clarifying questions expected:

  • Must the original order be preserved inside each group?
  • For an async predicate, should the checks run in parallel or one at a time, and what happens if one rejects?
  • Is it acceptable to call the predicate twice per element (for example by filtering twice)?

Code / implementation expected: Yes — real, direct proof for both versions, including the out-of-order-completion and rejection cases.

  • array

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: sync and async partition preserve order, call the predicate once, and avoid the filter(async) trap that keeps every element

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 118 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement LRU Cache (get/put with O(1))

Continue