{"id":6,"date":"2023-03-10T16:54:25","date_gmt":"2023-03-10T16:54:25","guid":{"rendered":"https:\/\/vmlogger.com\/algorithms\/?p=6"},"modified":"2023-03-27T13:00:43","modified_gmt":"2023-03-27T13:00:43","slug":"two-number-sum","status":"publish","type":"post","link":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/","title":{"rendered":"Two Number sum from an Array of Integers"},"content":{"rendered":"

An Introduction<\/h2>\n

This is a very common algorithm question. Although it sounds very easy at first while writing the code for such problems might trick you a little bit. This problem is commonly used in technical interviews and is a great way to demonstrate a programmer’s problem-solving skills. In this article, we will explore the problem in depth, discuss various approaches to solving it, and provide some tips on how to tackle similar algorithm problems.<\/p>\n

Before we go to the solutions for each of these problems, let me explain the problem statement with an example. Also, this problem can be of summing 3 numbers, 4 numbers, etc. As the total count of numbers increases, complexity increases. <\/p>\n

\nWrite a function that takes two parameters 1. a non-empty array of unique integers 2. An integer (Target Sum).
\nIf any two of the numbers from the input array sum up to the Target Sum, the function should return those two numbers in an array in any order.
\nAssumption: <\/strong>There is utmost a single pair of integers whose sum will be equal to the integer provided as an input in the function.<\/p>\n

Example:<\/strong>
\nintArray = [1, 4, 3, 6, 8, 2]
\nTargetSum = 11
\nOutput = [3, 8] or [8, 3]\n<\/div>\n

Solution – 1 – Brute Force Method<\/h2>\n

In this approach, we compare every pair of numbers in the array until we find the two numbers that add up to the target sum. This method has a time complexity of O(n^2) as it requires two nested loops to traverse the array.<\/p>\n

\nAt first, you are traversing the entire array for each of its elements and comparing the sum if it is equal to the given targetSum. The moment, it matches, breaks out inner and outer loops, and returns the result array.<\/p>\n

\r\n# Time Complexity = O(n^2)\r\ndef twoNumberSum(array, targetSum):\r\n    result = []\r\n    for i in range(0, len(array),1):\r\n        for j in range(i+1, len(array), 1):\r\n            if array[i] + array[j] == targetSum:\r\n                result.append(array[i])\r\n                result.append(array[j])\r\n                break\r\n        if result != []:\r\n            break\r\n    return result\r\n<\/pre>\n
\nAbove solution has time complexity O(n^2) where n is the size of the array.<\/strong>\n<\/div>\n

Solution – 2 [Better Solution]<\/h2>\n

The following is a better solution from a time complexity perspective. Instead of traversing the entire array for each element, traverse the array only once. For each number, calculate the expected second number needed in order to make the sum equal to targetSum. Now using, python’s built function check if that number exists in the array. If yes, then return those two values as an array. At last, if found nothing, an empty array will be returned. <\/p>\n

\r\n# Time Complexity = O(n)\r\ndef twoNumberSum(array, targetSum):\r\n    for iNum in array:\r\n        expectedNum = targetSum - iNum\r\n        if (expectedNum in array) and (expectedNum is not iNum):\r\n            return [iNum, temp]\r\n    return []\r\n<\/pre>\n
\nAbove solution has time complexity O(n) where n is the size of the array.<\/strong>\n<\/div>\n
\n

Info<\/h3>\n

The classic two-number sum algorithm problem is a fundamental problem in computer science that can be solved using multiple approaches. The brute force method is the simplest but least efficient approach, while the second solution is more efficient. By understanding the problem statement and using the right approach, you can solve this problem efficiently and demonstrate your problem-solving skills to potential employers.<\/p>\n

\nIf you like these solutions, share them with your friends, and colleagues. If you find any other solutions, please post them in the comment, I may put them in the main article here so that others can also get benefitted from all different types of solutions.<\/p>\n<\/div>\n<\/span>","protected":false},"excerpt":{"rendered":"

An Introduction This is a very common algorithm question. Although it sounds very easy at first while writing the code for such problems might trick you a little bit. This problem is commonly used in technical interviews and is a great way to demonstrate a programmer’s problem-solving skills. In this article, we will explore the […]<\/p>\n","protected":false},"author":45,"featured_media":137,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"off","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[3],"tags":[],"class_list":["post-6","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-easy"],"yoast_head":"\nTwo Number sum from an Array of Integers - Algorithms<\/title>\n<meta name=\"description\" content=\"Google interview questions | Easy Algorithms with multiple solutions in Python. | Two Number sum from an Array of Integers | Learn Algorithms\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Two Number sum from an Array of Integers\" \/>\n<meta property=\"og:description\" content=\"Google interview questions | Easy Algorithms with multiple solutions in Python. | Two Number sum from an Array of Integers | Learn Algorithms\" \/>\n<meta property=\"og:url\" content=\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/\" \/>\n<meta property=\"og:site_name\" content=\"Algorithms\" \/>\n<meta property=\"article:publisher\" content=\"http:\/\/www.facebook.com\/vmlogger\" \/>\n<meta property=\"article:author\" content=\"http:\/\/www.facebook.com\/vmlogger\" \/>\n<meta property=\"article:published_time\" content=\"2023-03-10T16:54:25+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-03-27T13:00:43+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/two-number-sum.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2560\" \/>\n\t<meta property=\"og:image:height\" content=\"1440\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Vishwamitra Mishra\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/www.twitter.com\/learnexcelmacro\" \/>\n<meta name=\"twitter:site\" content=\"@learnexcelmacro\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Vishwamitra Mishra\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/\"},\"author\":{\"name\":\"Vishwamitra Mishra\",\"@id\":\"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/7500a107b0b2d35a8492acf0d11fc8e5\"},\"headline\":\"Two Number sum from an Array of Integers\",\"datePublished\":\"2023-03-10T16:54:25+00:00\",\"dateModified\":\"2023-03-27T13:00:43+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/\"},\"wordCount\":509,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/7500a107b0b2d35a8492acf0d11fc8e5\"},\"image\":{\"@id\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/two-number-sum.png\",\"articleSection\":[\"Easy\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/\",\"url\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/\",\"name\":\"Two Number sum from an Array of Integers - Algorithms\",\"isPartOf\":{\"@id\":\"https:\/\/vmlogger.com\/algorithms\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/two-number-sum.png\",\"datePublished\":\"2023-03-10T16:54:25+00:00\",\"dateModified\":\"2023-03-27T13:00:43+00:00\",\"description\":\"Google interview questions | Easy Algorithms with multiple solutions in Python. | Two Number sum from an Array of Integers | Learn Algorithms\",\"breadcrumb\":{\"@id\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#primaryimage\",\"url\":\"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/two-number-sum.png\",\"contentUrl\":\"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/two-number-sum.png\",\"width\":2560,\"height\":1440,\"caption\":\"Two number sum algorithm\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/vmlogger.com\/algorithms\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Two Number sum from an Array of Integers\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/vmlogger.com\/algorithms\/#website\",\"url\":\"https:\/\/vmlogger.com\/algorithms\/\",\"name\":\"Algorithms\",\"description\":\"Welcome to the World of Algorithms\",\"publisher\":{\"@id\":\"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/7500a107b0b2d35a8492acf0d11fc8e5\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/vmlogger.com\/algorithms\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/7500a107b0b2d35a8492acf0d11fc8e5\",\"name\":\"Vishwamitra Mishra\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/welcome-1.png\",\"contentUrl\":\"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/welcome-1.png\",\"width\":1963,\"height\":843,\"caption\":\"Vishwamitra Mishra\"},\"logo\":{\"@id\":\"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/image\/\"},\"description\":\"My name is Vishwamitra Mishra. Friends Call me Vishwa. I hold a Bachelor\u2019s Degree in Computer Science from D.A.V.V. Indore & currently working as a Technical Lead having over 7 years of experience.\",\"sameAs\":[\"http:\/\/www.learnexcelmacro.com\",\"http:\/\/www.facebook.com\/vmlogger\",\"https:\/\/x.com\/https:\/\/www.twitter.com\/learnexcelmacro\",\"https:\/\/www.youtube.com\/c\/VMLogger\"],\"url\":\"https:\/\/vmlogger.com\/algorithms\/author\/vishwamitra\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Two Number sum from an Array of Integers - Algorithms","description":"Google interview questions | Easy Algorithms with multiple solutions in Python. | Two Number sum from an Array of Integers | Learn Algorithms","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/","og_locale":"en_US","og_type":"article","og_title":"Two Number sum from an Array of Integers","og_description":"Google interview questions | Easy Algorithms with multiple solutions in Python. | Two Number sum from an Array of Integers | Learn Algorithms","og_url":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/","og_site_name":"Algorithms","article_publisher":"http:\/\/www.facebook.com\/vmlogger","article_author":"http:\/\/www.facebook.com\/vmlogger","article_published_time":"2023-03-10T16:54:25+00:00","article_modified_time":"2023-03-27T13:00:43+00:00","og_image":[{"width":2560,"height":1440,"url":"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/two-number-sum.png","type":"image\/png"}],"author":"Vishwamitra Mishra","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/www.twitter.com\/learnexcelmacro","twitter_site":"@learnexcelmacro","twitter_misc":{"Written by":"Vishwamitra Mishra","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#article","isPartOf":{"@id":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/"},"author":{"name":"Vishwamitra Mishra","@id":"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/7500a107b0b2d35a8492acf0d11fc8e5"},"headline":"Two Number sum from an Array of Integers","datePublished":"2023-03-10T16:54:25+00:00","dateModified":"2023-03-27T13:00:43+00:00","mainEntityOfPage":{"@id":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/"},"wordCount":509,"commentCount":0,"publisher":{"@id":"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/7500a107b0b2d35a8492acf0d11fc8e5"},"image":{"@id":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#primaryimage"},"thumbnailUrl":"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/two-number-sum.png","articleSection":["Easy"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/","url":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/","name":"Two Number sum from an Array of Integers - Algorithms","isPartOf":{"@id":"https:\/\/vmlogger.com\/algorithms\/#website"},"primaryImageOfPage":{"@id":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#primaryimage"},"image":{"@id":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#primaryimage"},"thumbnailUrl":"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/two-number-sum.png","datePublished":"2023-03-10T16:54:25+00:00","dateModified":"2023-03-27T13:00:43+00:00","description":"Google interview questions | Easy Algorithms with multiple solutions in Python. | Two Number sum from an Array of Integers | Learn Algorithms","breadcrumb":{"@id":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#primaryimage","url":"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/two-number-sum.png","contentUrl":"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/two-number-sum.png","width":2560,"height":1440,"caption":"Two number sum algorithm"},{"@type":"BreadcrumbList","@id":"https:\/\/vmlogger.com\/algorithms\/2023\/03\/10\/two-number-sum\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/vmlogger.com\/algorithms\/"},{"@type":"ListItem","position":2,"name":"Two Number sum from an Array of Integers"}]},{"@type":"WebSite","@id":"https:\/\/vmlogger.com\/algorithms\/#website","url":"https:\/\/vmlogger.com\/algorithms\/","name":"Algorithms","description":"Welcome to the World of Algorithms","publisher":{"@id":"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/7500a107b0b2d35a8492acf0d11fc8e5"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/vmlogger.com\/algorithms\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/7500a107b0b2d35a8492acf0d11fc8e5","name":"Vishwamitra Mishra","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/image\/","url":"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/welcome-1.png","contentUrl":"https:\/\/vmlogger.com\/algorithms\/wp-content\/uploads\/sites\/15\/2023\/03\/welcome-1.png","width":1963,"height":843,"caption":"Vishwamitra Mishra"},"logo":{"@id":"https:\/\/vmlogger.com\/algorithms\/#\/schema\/person\/image\/"},"description":"My name is Vishwamitra Mishra. Friends Call me Vishwa. I hold a Bachelor\u2019s Degree in Computer Science from D.A.V.V. Indore & currently working as a Technical Lead having over 7 years of experience.","sameAs":["http:\/\/www.learnexcelmacro.com","http:\/\/www.facebook.com\/vmlogger","https:\/\/x.com\/https:\/\/www.twitter.com\/learnexcelmacro","https:\/\/www.youtube.com\/c\/VMLogger"],"url":"https:\/\/vmlogger.com\/algorithms\/author\/vishwamitra\/"}]}},"_links":{"self":[{"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/posts\/6"}],"collection":[{"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/users\/45"}],"replies":[{"embeddable":true,"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/comments?post=6"}],"version-history":[{"count":51,"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/posts\/6\/revisions"}],"predecessor-version":[{"id":221,"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/posts\/6\/revisions\/221"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/media\/137"}],"wp:attachment":[{"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/media?parent=6"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/categories?post=6"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/vmlogger.com\/algorithms\/wp-json\/wp\/v2\/tags?post=6"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}