Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Split into two equal halves

Medium · Target 15 minutes · Dynamic programming · Type asked atAmazonMetaBloomberg

Given positive integers nums, return true if they can be divided into two groups whose sums are equal, every number going into exactly one group.

Examples

InputOutputWhy
nums = [1,5,11,5]true{1, 5, 5} and {11}.
nums = [1,2,3,5]falseThe total, 11, is odd.
nums = [3,3,3,4,5]true{3, 3, 3} and {4, 5}.

Constraints

  • 1 ≤ nums.length ≤ 200
  • 1 ≤ nums[i] ≤ 100

Hints

Hint 1

If the total is odd, the answer is no.

Hint 2

Otherwise the question is whether some subset sums to half the total: subset sum.

Hint 3

A boolean array up to total / 2, filled downwards per number.

Where people lose marks

  • Forgetting the odd-total shortcut (correct either way, but it is the first thing to say).
  • Sorting and splitting greedily, which fails on [3, 3, 3, 4, 5].
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.