mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-28 18:26:54 +00:00
2.5 KiB
2.5 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 69bc6cb30c1d112a2e110a08 | Challenge 251: Array Sum Finder | 29 | 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--
find_sum([1, 3, 5, 7], 6) should return [1, 5].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_sum([1, 3, 5, 7], 6), [1, 5])`)
}})
find_sum([1, 2, 3, 4, 5], 5) should return [1, 4].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_sum([1, 2, 3, 4, 5], 5), [1, 4])`)
}})
find_sum([1, 2, 3, 4, 5], 6) should return [1, 2, 3].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_sum([1, 2, 3, 4, 5], 6), [1, 2, 3])`)
}})
find_sum([-1, -2, 3, 4], 1) should return [-1, -2, 4].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_sum([-1, -2, 3, 4], 1), [-1, -2, 4])`)
}})
find_sum([3, 1, 4, 1, 5, 9, 2, 6], 10) should return [3, 1, 4, 2].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_sum([3, 1, 4, 1, 5, 9, 2, 6], 10), [3, 1, 4, 2])`)
}})
find_sum([1, 2, 3, 4, 5, 6, 7, 8, 9], 20) should return [1, 2, 3, 5, 9].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_sum([1, 2, 3, 4, 5, 6, 7, 8, 9], 20), [1, 2, 3, 5, 9])`)
}})
find_sum([7, 9, 4, 2, 5], 10) should return "Sum not found".
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_sum([7, 9, 4, 2, 5], 10), "Sum not found")`)
}})
--seed--
--seed-contents--
def find_sum(arr, target):
return arr
--solutions--
def find_sum(arr, target):
def search(start, remaining, current):
if remaining == 0 and len(current) >= 2:
return current
if start >= len(arr):
return None
for i in range(start, len(arr)):
result = search(i + 1, remaining - arr[i], current + [arr[i]])
if result is not None:
return result
return None
return search(0, target, []) or "Sum not found"