Elements of Programming Challenges

1.2 Sort and Binary Search

We can sort the array and search for the pair by traversing the array element-wise and look ahead for its complement using binary search.
bool hasPairSum(std::vector<int> & arr, int k)
{
    std::sort(arr.begin(), arr.end());

      std::size_t len = arr.size();

      for(int i = 0; i < len; i++)
      {
          if(std::binary_search(arr.begin() + i, arr.end(), k - arr[i]))
          return true;
      }
      return false;
}

Time complexity of \(n\) binary searches is \(\bigO (n\log n)\). Time complexity of sorting process depends on the sorting algorithm : \(\bigO (n\log n)\) in case of Merge Sort or Heap Sort. \(\bigO (n^2)\) in case of Quick Sort.

Space complexity for \(n\) binary searches is \(\bigO (n)\). Space complexity is \(\bigO (n)\) for Merge Sort, \(\bigO (1)\) for Heap Sort and \(\bigO (\log n)\) for Quick Sort. Hence overall space complexity is \(\bigO (n)\). 1

1 std::sort uses Introspective Sort with time complexity as \(\bigO (n\log n)\) and space complexity as \(\bigO (\log n)\).