{"id":25473,"date":"2024-08-22T00:30:39","date_gmt":"2024-08-21T15:30:39","guid":{"rendered":"http:\/\/www.tyosuke20xx.com\/blog\/?p=25473"},"modified":"2024-08-22T00:31:14","modified_gmt":"2024-08-21T15:31:14","slug":"solve-the-two-sum-problem-in-python","status":"publish","type":"post","link":"http:\/\/www.tyosuke20xx.com\/blog\/?p=25473","title":{"rendered":"Solve the Two Sum problem in Python"},"content":{"rendered":"\n<p>Solve the Two Sum problem in Python<\/p>\n\n\n\n<p>\u56de\u7b54<\/p>\n\n\n\n<p>Certainly, I&#8217;ll provide a solution to the Two Sum problem in Python. This problem is a common interview question where you&#8217;re given an array of integers and a target sum, and you need to find two numbers in the array that add up to the target.<\/p>\n\n\n\n<p>Here&#8217;s a step-by-step approach:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li><strong>Use a Hash Map<\/strong>: This approach allows for O(n) time complexity, where n is the number of elements in the array.<\/li>\n\n\n\n<li><strong>Iterate Through the Array<\/strong>: For each number, calculate what the other number should be to reach the target sum.<\/li>\n\n\n\n<li><strong>Check if the Complement Exists<\/strong>: If the complement exists in the hash map, return the indices of both numbers.<\/li>\n<\/ol>\n\n\n\n<p>Here&#8217;s the implementation:<\/p>\n\n\n\n<p>python<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def two_sum(nums, target):\n    # Dictionary to store the number and its index\n    num_dict = {}\n    \n    # Iterate through the list\n    for i, num in enumerate(nums):\n        # Calculate the complement\n        complement = target - num\n        \n        # If the complement exists in the dictionary, return the indices\n        if complement in num_dict:\n            return [num_dict[complement], i]\n        \n        # If not, add the current number and its index to the dictionary\n        num_dict[num] = i\n    \n    # If no solution is found, return an empty list or raise an exception\n    return []  # or raise ValueError(\"No two sum solution\")\n\n# Example usage\nnums = [2, 7, 11, 15]\ntarget = 9\nresult = two_sum(nums, target)\nprint(result)  # Should print [0, 1] because nums[0] + nums[1] == 9<\/pre>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We use a dictionary (num_dict) to keep track of numbers we&#8217;ve seen and their indices.<\/li>\n\n\n\n<li>As we iterate through the list:\n<ul class=\"wp-block-list\">\n<li>We calculate what number, when added to the current number, would give us the target.<\/li>\n\n\n\n<li>If this number exists in our dictionary, we&#8217;ve found our pair, and we return their indices.<\/li>\n\n\n\n<li>If not, we add the current number and its index to the dictionary.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<p>This solution ensures that we only traverse the list once, making it efficient with a time complexity of O(n). The space complexity is also O(n) in the worst case where all numbers are unique.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Solve the Two Sum problem in Python \u56de\u7b54 Certainly, I&#8217;ll provide a solution to the Two Sum problem in Pyth &hellip; <a href=\"http:\/\/www.tyosuke20xx.com\/blog\/?p=25473\" class=\"more-link\"><span class=\"screen-reader-text\">&#8220;Solve the Two Sum problem in Python&#8221; \u306e<\/span>\u7d9a\u304d\u3092\u8aad\u3080<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[4,65],"tags":[3,39],"class_list":["post-25473","post","type-post","status-publish","format-standard","hentry","category-programming","category-python","tag-programming","tag-python"],"aioseo_notices":[],"jetpack_featured_media_url":"","_links":{"self":[{"href":"http:\/\/www.tyosuke20xx.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/25473","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.tyosuke20xx.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.tyosuke20xx.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.tyosuke20xx.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.tyosuke20xx.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=25473"}],"version-history":[{"count":2,"href":"http:\/\/www.tyosuke20xx.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/25473\/revisions"}],"predecessor-version":[{"id":25475,"href":"http:\/\/www.tyosuke20xx.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/25473\/revisions\/25475"}],"wp:attachment":[{"href":"http:\/\/www.tyosuke20xx.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=25473"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.tyosuke20xx.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=25473"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.tyosuke20xx.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=25473"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}