Search code examples
algorithmlanguage-agnosticdivide-and-conquer

divide et impera problem


Given a set M, find if there is a pair of numbers (a,b), both belong to M, and a+b=x, where x is a previously specified parameter. The problem should be solved using Divide et Impera in O(n * log n). Probably the problem should be split in two half-sized subproblems and then recombine the results in O(n).

I would like a pseudocode for the given problem or a tip for solving it.


Solution

  • Not sure if this fits your requirements, but:

    1. Mergesort the set (this uses divide and conquer).
    2. Start with the first and last elements of the set, and compare their sum to x. If the sum is equal, you are done. If the sum is larger, step down to the second last element, if the sum is smaller, step up to the second element.
    3. Repeat step two, working in from the ends to the center of the sorted set, until the elements summing to x are found, or there are no more elements.

    The divide and conquer sort is O(n lg n), the stepping through the sorted set is O(n), therefore total complexity O(n lg n).

    Ed: sum to x, not M.