Elements of Programming Challenges

Challenge 1 Two Sum

  • ✑ Problem 1-1. Given an array of \(n\) integers and a number \(k\), determine whether there is a pair of elements in the array that sums to exactly \(k\).

  • Solution. Let us assume that

    • (Pisymbol) the same element cannot be used twice, i.e. the pair should consist of two different array elements.

    • (Pisymbol) the elements can be positive, negative or zero.

    • (Pisymbol) the array may contain duplicates.

    • (Pisymbol) there is only one such pair if at all.

1.1 Brute Force

We can try all the pairs in the array and see if any of these add up to the number \(k\).

bool hasPairSum(const std::vector<int> & arr, int k)
{
    std::size_t len = arr.size();

      for(int i = 0; i < len; i++)
      {
          for(int j = i + 1; j < len; j++)
          {
              if (arr[i] + arr[j] == k)
                  return true;
          }
      }
      return false;
}

Since there are \(\Theta (n^2)\) possible pairs, time complexity of this approach is \(\bigO (n^2)\). Space complexity is \(\bigO (1)\).