<jupyter_start><jupyter_text>Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return the answer in any order. Example 1:Input: nums = [2,7,11,15], target = 9Output: [0,1]Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].Example 2:Input: nums = [3,2,4], target = 6Output: [1,2]Example 3:Input: nums = [3,3], target = 6Output: [0,1] Constraints:2 <= nums.length <= 104-109 <= nums[i] <= 109-109 <= target <= 109Only one valid answer exists. Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?<jupyter_code># obvious solution
# nested loop - O(n^2) time complexity
def two_sum(nums = [2,7,11,15], target=9):
    for i,n in enumerate(nums):
        for j,m in enumerate(nums[i+1:]):
            if n + m == target:
                return [i,i+j+1]
two_sum()
two_sum([2,5,8,4,9], 17)
# better solution
# one loop - store each number has gone through as dict's key to quickly lookup and get the index
def two_sum(nums = [2,7,11,15], target=9):
    d = dict()
    for i,num in enumerate(nums):
        finding_num = target - num
        if finding_num in d.keys():
            return [d[finding_num], i]
        else:
            d[num] = i
two_sum()
two_sum([2,5,8,4,9], 17)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13137665967854648, 'fraction_numerical': 0.053109713487071976, 'mean_word_length': 3.58974358974359, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '425661', 'license': 'Apache-2.0', 'n_tokens_mistral': 532, 'n_tokens_neox': 489, 'n_words': 176, 'path': 'two_sum.ipynb', 'repo_name': 'MaiaNgo/algorithm_python', 'size': '1431'}