dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
92 lines
2.0 KiB
Markdown
92 lines
2.0 KiB
Markdown
---
|
|
id: 69bc6cb30c1d112a2e110a08
|
|
title: "Challenge 251: Array Sum Finder"
|
|
challengeType: 28
|
|
dashedName: challenge-251
|
|
---
|
|
|
|
# --description--
|
|
|
|
Given an array of numbers and a target number, return the first subset of two or more numbers that adds up to the target.
|
|
|
|
- The "first" subset is the one whose elements have the lowest possible indices, prioritizing the earliest index first.
|
|
- Each number in the array may only be used once.
|
|
- If no valid subset exists, return `"Sum not found"`.
|
|
|
|
Return the matching numbers as an array in the order they appear in the original array.
|
|
|
|
# --hints--
|
|
|
|
`findSum([1, 3, 5, 7], 6)` should return `[1, 5]`.
|
|
|
|
```js
|
|
assert.deepEqual(findSum([1, 3, 5, 7], 6), [1, 5]);
|
|
```
|
|
|
|
`findSum([1, 2, 3, 4, 5], 5)` should return `[1, 4]`.
|
|
|
|
```js
|
|
assert.deepEqual(findSum([1, 2, 3, 4, 5], 5), [1, 4]);
|
|
```
|
|
|
|
`findSum([1, 2, 3, 4, 5], 6)` should return `[1, 2, 3]`.
|
|
|
|
```js
|
|
assert.deepEqual(findSum([1, 2, 3, 4, 5], 6), [1, 2, 3]);
|
|
```
|
|
|
|
`findSum([-1, -2, 3, 4], 1)` should return `[-1, -2, 4]`.
|
|
|
|
```js
|
|
assert.deepEqual(findSum([-1, -2, 3, 4], 1), [-1, -2, 4]);
|
|
```
|
|
|
|
`findSum([3, 1, 4, 1, 5, 9, 2, 6], 10)` should return `[3, 1, 4, 2]`.
|
|
|
|
```js
|
|
assert.deepEqual(findSum([3, 1, 4, 1, 5, 9, 2, 6], 10), [3, 1, 4, 2]);
|
|
```
|
|
|
|
`findSum([1, 2, 3, 4, 5, 6, 7, 8, 9], 20)` should return `[1, 2, 3, 5, 9]`.
|
|
|
|
```js
|
|
assert.deepEqual(findSum([1, 2, 3, 4, 5, 6, 7, 8, 9], 20), [1, 2, 3, 5, 9]);
|
|
```
|
|
|
|
`findSum([7, 9, 4, 2, 5], 10)` should return `"Sum not found"`.
|
|
|
|
```js
|
|
assert.equal(findSum([7, 9, 4, 2, 5], 10), "Sum not found");
|
|
```
|
|
|
|
# --seed--
|
|
|
|
## --seed-contents--
|
|
|
|
```js
|
|
function findSum(arr, target) {
|
|
|
|
return arr;
|
|
}
|
|
```
|
|
|
|
# --solutions--
|
|
|
|
```js
|
|
function findSum(arr, target) {
|
|
function search(start, remaining, current) {
|
|
if (remaining === 0 && current.length >= 2) return current;
|
|
if (start >= arr.length) return null;
|
|
|
|
for (let i = start; i < arr.length; i++) {
|
|
const result = search(i + 1, remaining - arr[i], [...current, arr[i]]);
|
|
if (result) return result;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
return search(0, target, []) ?? "Sum not found";
|
|
}
|
|
```
|