{"id":134,"date":"2019-01-21T21:27:20","date_gmt":"2019-01-22T02:27:20","guid":{"rendered":"https:\/\/resrvoir.com\/?page_id=134"},"modified":"2025-06-07T08:57:14","modified_gmt":"2025-06-07T12:57:14","slug":"pair-sum-is-n","status":"publish","type":"page","link":"https:\/\/resrvoir.com\/?page_id=134","title":{"rendered":"Pair Sum is N"},"content":{"rendered":"\r\n<p>Given a number N and an array of numbers, determine if any pair of numbers in the array has a sum equal to N.<br \/><br \/>One approach is to sort the array and then do a binary search for the difference of N and the ith element for all i. Sorting is O(n log n) and searching for a pair for all elements is also O(n log n).<br \/><br \/>A faster approach is to maintain a set of visited elements and determine if the difference of N and the ith element exists in the set. This runs in a single pass of the array, or O(n) time.<\/p>\r\n\r\n\r\n\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-linenumbers=\"false\">function pairSum(n, numbers) {\r\n  const set = new Set();\r\n  \r\n  if (numbers.length &lt; 2) {\r\n    return false;\r\n  }\r\n\r\n  set.add(numbers[0]);\r\n\r\n  for (let i = 1; i &lt; numbers.length; i++) {\r\n    const m = numbers[i];\r\n    const difference = n - m;\r\n    \r\n    if (set.has(difference)) {\r\n      return true;\r\n    }\r\n\r\n    set.add(m);\r\n  }\r\n\r\n  return false;\r\n}\r\n<\/pre>\r\n<p>&nbsp;<\/p>\r\n\r\n\r\n\r\n<p>&nbsp;<\/p>\r\n","protected":false},"excerpt":{"rendered":"<p>Given a number N and an array of numbers, determine if any pair of numbers in the array has a sum equal to N. One approach is to sort the array and then do a binary search for the difference of N and the ith element for all i. Sorting is O(n log n) and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":2,"menu_order":3,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"_links":{"self":[{"href":"https:\/\/resrvoir.com\/index.php?rest_route=\/wp\/v2\/pages\/134"}],"collection":[{"href":"https:\/\/resrvoir.com\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/resrvoir.com\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/resrvoir.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/resrvoir.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=134"}],"version-history":[{"count":19,"href":"https:\/\/resrvoir.com\/index.php?rest_route=\/wp\/v2\/pages\/134\/revisions"}],"predecessor-version":[{"id":1376,"href":"https:\/\/resrvoir.com\/index.php?rest_route=\/wp\/v2\/pages\/134\/revisions\/1376"}],"up":[{"embeddable":true,"href":"https:\/\/resrvoir.com\/index.php?rest_route=\/wp\/v2\/pages\/2"}],"wp:attachment":[{"href":"https:\/\/resrvoir.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=134"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}