<commit_before>= Two Sum
:hp-tags: coding_problem, medium

This is my breakdown of the `Two Sum` problem. It can be found here on link:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted[leetcode] and a bunch of other websites.

=== Problem Description

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

Note: Allowed to assume that each input has exactly one solution.

=== Process

==== Bruteforce
The obvious and naive way is to bruteforce. The general idea would be to keep generating a pair of numbers from the array until we get one that sums to our target value.

In code it would look something like this
[source,python]
----
def two_sum(numbers, target):
   for i in range(0, len(numbers) - 1):
      for k in range(i + 1, len(numbers)):
         if numbers[i] + numbers[k] == target:
            return [i, k]
   return [None, None]
----

In the code above we start from the beginning of the list and check every pair of numbers moving towards the end of the list. Note, we are given a constraint `index1 < index2` which is why the inner loop iterates from `i + 1`, this insures that one index is less than the other.

The code above will run in `O(n^2)` time with `O(1)` space. For a problem like this `O(n^2)` is pretty poor performance. 

You may have noticed the code above doesn't take advantage of the fact that the array is already sorted. We can do better!

=== Optimization #1

We know that the array is already sorted, with this knowledge we can cut down the number of iterations executed. If we traverse the loops in the same fashion as above but we only continue incrementing if the sum of the numbers is less than the target. Once we reach a sum that is greater than the `target`, we can guarentee on the current iteration the other pair of numbers will also be greater than the sum because the array is ordered in increasing order. Thus, we have cut out some of the iterations.

[source,python]
----
def two_sum(numbers, target):
   current_sum = 0
   for i in range(0, len(numbers) - 1):
      for k in range(i + 1, len(numbers)):
         current_sum = 0
         if current_sum == target:
            return [i, k]
         elif current_sum > target:
            break
         else:
            continue
   return [None, None]
----

The above code is still `O(n^2)` but because this code will run `N^2` times if the target is the sum of the last two numbers. But on average case this code will perform better than the bruteforce above.

=== Optimization #2

Let's really make use of the fact that the array is sorted. In this approach we use two pointers starting on each end and step towards the middle of the array. Have any clues?
Hint: We can make the sum converge.
[source,python]
----
def two_sum(numbers, target):
   left = 0, right = len(numbers) - 1
   current_sum = 0
   while left < right:
   	  current_sum = numbers[left] + numbers[right]
      if current_sum > target:
         right -= 1
      elif current_sum < target:
         left += 1
      else
         return [left, right]
   return [None, None]
----

Since we we start on the ends of the array we begin by finding the sum of the maximun and minimum values of the array. Notice that as the right pointer moves from the end of the array towards the middle the values decrease.
In contrast as the left pointer moves from the beginning of the array to the middle the values increase. So if we find the sum of our two numbers to be greater than the target our only option is to move in a direction that would decrease the sum, thus we move the right pointer towards the middle of the array. Similarily, if we find the sum of the two numbers to be less than the target then we increase the sum, by moving the left pointer towards the middle.

This solution has `O(n)` time complexity and `O(1)` space complexity. <commit_msg>Update 2016-09-05-Two-Sum.adoc<commit_after>= Two Sum
:hp-tags: coding_problem, medium

This is my breakdown of the `Two Sum` problem. It can be found here on link:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted[leetcode] and a bunch of other websites.

=== Problem Description

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

Note: Allowed to assume that each input has exactly one solution.

=== Process

==== Bruteforce
The obvious and naive way is to bruteforce. The general idea would be to keep generating a pair of numbers from the array until we get one that sums to our target value.

In code it would look something like this
[source,python]
----
def two_sum(numbers, target):
   for i in range(0, len(numbers) - 1):
      for k in range(i + 1, len(numbers)):
         if numbers[i] + numbers[k] == target:
            return [i + 1, k + 1]
   return [None, None]
----

In the code above we start from the beginning of the list and check every pair of numbers moving towards the end of the list. Note, we are given a constraint `index1 < index2` which is why the inner loop iterates from `i + 1`, this insures that one index is less than the other.

The code above will run in `O(n^2)` time with `O(1)` space. For a problem like this `O(n^2)` is pretty poor performance. 

You may have noticed the code above doesn't take advantage of the fact that the array is already sorted. We can do better!

=== Optimization #1

We know that the array is already sorted, with this knowledge we can cut down the number of iterations executed. If we traverse the loops in the same fashion as above but we only continue incrementing if the sum of the numbers is less than the target. Once we reach a sum that is greater than the `target`, we can guarentee on the current iteration the other pair of numbers will also be greater than the sum because the array is ordered in increasing order. Thus, we have cut out some of the iterations.

[source,python]
----
def two_sum(numbers, target):
   current_sum = 0
   for i in range(0, len(numbers) - 1):
      for k in range(i + 1, len(numbers)):
         current_sum = 0
         if current_sum == target:
            return [i + 1, k + 1]
         elif current_sum > target:
            break
         else:
            continue
   return [None, None]
----

The above code is still `O(n^2)` but because this code will run `N^2` times if the target is the sum of the last two numbers. But on average case this code will perform better than the bruteforce above.

=== Optimization #2

Let's really make use of the fact that the array is sorted. In this approach we use two pointers starting on each end and step towards the middle of the array. Have any clues?
Hint: We can make the sum converge.
[source,python]
----
def two_sum(numbers, target):
   left = 0, right = len(numbers) - 1
   current_sum = 0
   while left < right:
   	  current_sum = numbers[left] + numbers[right]
      if current_sum > target:
         right -= 1
      elif current_sum < target:
         left += 1
      else
         return [left + 1, right + 1]
   return [None, None]
----

Since we we start on the ends of the array we begin by finding the sum of the maximun and minimum values of the array. Notice that as the right pointer moves from the end of the array towards the middle the values decrease.
In contrast as the left pointer moves from the beginning of the array to the middle the values increase. So if we find the sum of our two numbers to be greater than the target our only option is to move in a direction that would decrease the sum, thus we move the right pointer towards the middle of the array. Similarily, if we find the sum of the two numbers to be less than the target then we increase the sum, by moving the left pointer towards the middle.

This solution has `O(n)` time complexity and `O(1)` space complexity. 
{'fraction_non_alphanumeric': 0.06328809895520596, 'fraction_numerical': 0.008406388855530203, 'mean_word_length': 3.2685802152742185, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 7, 'https://': 2, '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}}
{'dir': 'git-commits-cleaned', 'id': '2988297', 'n_tokens_mistral': 2278, 'n_tokens_neox': 2186, 'n_words': 1327}