[c] Algorithm Problem

Discussion in 'Programming' started by thomaaaa, Feb 15, 2013.

  1. #1
    Given two sorted arrays of integers of size n,
    i.e. a[n] and b[n], please find all pairs <value_1, value_2>

    so that value from a[n], value_2 from b[n]
    and value_1+ value_2=Constant, e.g. Constant=100.
    and n<100.

    Constraint: O(n) time, O(1) extra space

    i cant think of any way of not using nested loop:(
    pls help me
     
    thomaaaa, Feb 15, 2013 IP
  2. filali.zakariae

    filali.zakariae Member

    Messages:
    44
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #2
    too loops and it's done
     
    filali.zakariae, Feb 24, 2013 IP
  3. traxport121

    traxport121 Active Member

    Messages:
    1,201
    Likes Received:
    8
    Best Answers:
    1
    Trophy Points:
    63
    #3
    This is possible with O(n) time complexity but with O(n) space complexity as well.
     
    traxport121, Feb 26, 2013 IP
  4. RAND0M1ZER

    RAND0M1ZER Active Member

    Messages:
    142
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    60
    #4
    The key part is that the arrays come pre sorted. If they were unsorted then it would be O(n^2) - which is using two simple nested loops checking every possible combination. Since they are sorted though, you can stop checking once your reach a number that is smaller. So your first loop is going through the a[] forwards, while the second loop is going to be going through b[] backwards. That way as the first loop gets closer to the end of a[], the second loop will get shorter and shorter because you will stop looping b[] when !(a > b[j]). So as you are increased the number of elements in both arrays your algorithm is increasing linearly. Hope this helps!
     
    RAND0M1ZER, Feb 26, 2013 IP