5 kyu

Sum of Pairs

12,168 of 27,231AlejandorLazaro

Description:


Sum of Pairs

Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.

If there are two or more pairs with the required sum, the pair whose second element has the smallest index is the solution.

sum_pairs([11, 3, 7, 5],         10)
#              ^--^      3 + 7 = 10
== [3, 7]

sum_pairs([4, 3, 2, 3, 4],         6)
#          ^-----^         4 + 2 = 6, indices: 0, 2 *
#             ^-----^      3 + 3 = 6, indices: 1, 3
#                ^-----^   2 + 4 = 6, indices: 2, 4
#  * the correct answer is the pair whose second value has the smallest index
== [4, 2]

sum_pairs([0, 0, -2, 3], 2)
#  there are no pairs of values that can be added to produce 2.
== None/nil/undefined/Nothing (Based on the language)

sum_pairs([10, 5, 2, 3, 7, 5],         10)
#              ^-----------^   5 + 5 = 10, indices: 1, 5
#                    ^--^      3 + 7 = 10, indices: 3, 4 *
#  * the correct answer is the pair whose second value has the smallest index
== [3, 7]

Negative numbers and duplicate numbers can and will appear.

NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out.

Memoization
Fundamentals
Performance

More By Author:

Check out these other kata created by AlejandorLazaro

Stats:

CreatedFeb 9, 2015
PublishedFeb 9, 2015
Warriors Trained103870
Total Skips25872
Total Code Submissions201383
Total Times Completed27231
Python Completions12168
JavaScript Completions11903
Ruby Completions1282
Elixir Completions128
Rust Completions1126
TypeScript Completions1089
Haskell Completions18
Total Stars3483
% of votes with a positive feedback rating88% of 2913
Total "Very Satisfied" Votes2370
Total "Somewhat Satisfied" Votes402
Total "Not Satisfied" Votes141
Ad
Contributors
  • AlejandorLazaro Avatar
  • jhoffner Avatar
  • GiacomoSorbi Avatar
  • jcsahnwaldt Avatar
  • firewatcher Avatar
  • JohanWiltink Avatar
  • White-Oak Avatar
  • Avanta Avatar
  • FArekkusu Avatar
  • user3029010 Avatar
  • JOLee83 Avatar
  • Wei-Ting Yang Avatar
  • tobeannouncd Avatar
Ad