Problem: Minimums in Array

You are given two arrays A and B each containing N numbers. You need to choose exactly one number from A and exactly one number from B such that the index of the two chosen numbers is not same and the sum of the 2 chosen values is minimum. Formally, if you chose ith element from A whose value is x and jth element from B whose value is y, you need to minimize the value of (x+y) such that i is not equal to j.
Your objective is to find this minimum value.
The first line of input contains an integer denoting the test cases,t. The first line of each test case contains an integer N denoting the size of two arrays. Then each of the next two lines contains N space separated integers denoting values of the array A[] and B[] respectively.
Print the minimum sum which can be obtained under the conditions mentioned in the problem statement.If not possible print “-1” without quotes.
1<= N <=100000
1< =Array elements < =100000

5 4 3 2 1
1 2 3 4 5

Minimum sum will be obtained by choosing number at the last index of first array i.e. 5th element of the first array(1) and first index of the second array ie first element of second array (1).

Sum=1+1=2 as their indexes are different but sum is minimum.


Using a fast sorting algorithm (merge sort, quick sort,…), keep track of information of indexes.

Implementation: Python 2.7

def quick_sort(data, low, high):
    if low < high:
        p = partition(data, low, high)
        quick_sort(data, low, p-1)
        quick_sort(data, p+1, high)

def partition(data, low, high):
    pivot = data[high][1]
    i = low
    for j in range(low, high):
        if data[j][1] <= pivot:
            data[i], data[j] = data[j], data[i]
            i += 1
    data[i], data[high] = data[high], data[i]
    return i

def minimumsIn(arr1, arr2, index1, index2):
    #check for exception (arr1 and arr2 only contains 1 element)
    if len(arr1) == 1 and len(arr2) == 1: 
        return -1
    #the first element of arr1 and arr2 is index
    if arr1[index1][0] != arr2[index2][0]:
        return arr1[index1][1] + arr2[index2][1]
        # check for out of range
        if index1+1 < len(arr1) and index2+1 < len(arr2):
            if arr1[index1+1][1] < arr2[index2+1][1]:
                return minimumsIn(arr1, arr2, index1 + 1, index2)
                return minimumsIn(arr1, arr2, index1, index2 + 1)

if __name__ == '__main__':
    t = input()
    for _ in range(t):
        n = input()
        list1 = map(int, raw_input().strip().split())
        list2 = map(int, raw_input().strip().split())
        arr1, arr2 = [], []
        for index, each_element in enumerate(zip(list1, list2)):
            arr1.append((index, each_element[0]))
            arr2.append((index, each_element[1]))
        quick_sort(arr1, 0, len(arr1)-1)
        quick_sort(arr2, 0, len(arr2)-1)
        #print arr1
        #print arr2
        print minimumsIn(arr1, arr2, 0, 0)