posted by 귀염둥이채원 2021. 9. 15. 11:02

Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[]. The array might also contain duplicates. You may assume that both x and y are different and present in arr[].

 

Example

Input: arr[] = {1, 2}, x = 1, y = 2
Output: Minimum distance between 1 
and 2 is 1.
Explanation: 1 is at index 0 and 2 is at 
index 1, so the distance is 1

Input: arr[] = {3, 4, 5}, x = 3, y = 5
Output: Minimum distance between 3 
and 5 is 2.
Explanation:3 is at index 0 and 5 is at 
index 2, so the distance is 2

Input: 
arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3},  
x = 3, y = 6
Output: Minimum distance between 3 
and 6 is 4.
Explanation:3 is at index 0 and 6 is at 
index 5, so the distance is 4

Input: arr[] = {2, 5, 3, 5, 4, 4, 2, 3}, 
x = 3, y = 2
Output: Minimum distance between 3 
and 2 is 1.
Explanation:3 is at index 7 and 2 is at 
index 6, so the distance is 1
# Python3 code to Find the minimum
# distance between two numbers
 
 
def minDist(arr, n, x, y):
    min_dist = 99999999
    for i in range(n):
        for j in range(i + 1, n):
            if (x == arr[i] and y == arr[j] or
                    y == arr[i] and x == arr[j]) and min_dist > abs(i-j):
                min_dist = abs(i-j)
        return min_dist
 
 
# Driver code
arr = [3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3]
n = len(arr)
x = 3
y = 6
print("Minimum distance between ", x, " and ",
      y, "is", minDist(arr, n, x, y))
import sys
 
def minDist(arr, n, x, y):
     
    #previous index and min distance
    i=0
    p=-1
    min_dist = sys.maxsize;
     
    for i in range(n):
     
        if(arr[i] ==x or arr[i] == y):
         
            #we will check if p is not equal to -1 and
            #If the element at current index matches with
            #the element at index p , If yes then update
            #the minimum distance if needed
            if(p != -1 and arr[i] != arr[p]):
                min_dist = min(min_dist,i-p)
              
            #update the previous index
            p=i
         
     
    #If distance is equal to int max
    if(min_dist == sys.maxsize):
       return -1
    return min_dist
 
  
# Driver program to test above function */
arr = [3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3]
n = len(arr)
x = 3
y = 6
print ("Minimum distance between %d and %d is %d\n"%( x, y,minDist(arr, n, x, y)));

 

 

posted by 귀염둥이채원 2021. 9. 15. 10:55

Given two sorted arrays, find their union and intersection.

Input : arr1[] = {1, 3, 4, 5, 7}
        arr2[] = {2, 3, 5, 6} 
Output : Union : {1, 2, 3, 4, 5, 6, 7} 
         Intersection : {3, 5}

Input : arr1[] = {2, 5, 6}
        arr2[] = {4, 6, 8, 10} 
Output : Union : {2, 4, 5, 6, 8, 10} 
         Intersection : {6}
# Python program to find union of
# two sorted arrays
# Function prints union of arr1[] and arr2[]
# m is the number of elements in arr1[]
# n is the number of elements in arr2[]
def printUnion(arr1, arr2, m, n):
    i, j = 0, 0
    while i < m and j < n:
        if arr1[i] < arr2[j]:
            print(arr1[i])
            i += 1
        elif arr2[j] < arr1[i]:
            print(arr2[j])
            j+= 1
        else:
            print(arr2[j])
            j += 1
            i += 1
 
    # Print remaining elements of the larger array
    while i < m:
        print(arr1[i])
        i += 1
 
    while j < n:
        print(arr2[j])
        j += 1
 
# Driver program to test above function
arr1 = [1, 2, 4, 5, 6]
arr2 = [2, 3, 5, 7]
m = len(arr1)
n = len(arr2)
printUnion(arr1, arr2, m, n)
# Python3 program to find union of two
# sorted arrays (Handling Duplicates)
def UnionArray(arr1, arr2):
     
    # Taking max element present in either array
    m = arr1[-1]
    n = arr2[-1]
    ans = 0
         
    if m > n:
        ans = m
    else:
        ans = n
         
    # Finding elements from 1st array
    # (non duplicates only). Using
    # another array for storing union
    # elements of both arrays
    # Assuming max element present
    # in array is not more than 10 ^ 7
    newtable = [0] * (ans + 1)
         
    # First element is always
    # present in final answer
    print(arr1[0], end = " ")
         
    # Incrementing the First element's count
    # in it's corresponding index in newtable
    newtable[arr1[0]] += 1
         
    # Starting traversing the first
    # array from 1st index till last
    for i in range(1, len(arr1)):
         
        # Checking whether current element
        # is not equal to it's previous element
        if arr1[i] != arr1[i - 1]:
             
            print(arr1[i], end = " ")
            newtable[arr1[i]] += 1
             
    # Finding only non common
    # elements from 2nd array        
    for j in range(0, len(arr2)):
         
        # By checking whether it's already
        # present in newtable or not
        if newtable[arr2[j]] == 0:
             
            print(arr2[j], end = " ")
            newtable[arr2[j]] += 1
     
# Driver Code
if __name__ == "__main__":
     
    arr1 = [1, 2, 2, 2, 3]
    arr2 = [2, 3, 4, 5]
         
    UnionArray(arr1, arr2)
# Python3 program to find Intersection of two
# Sorted Arrays (Handling Duplicates)
def IntersectionArray(a, b, n, m):
    '''
    :param a: given sorted array a
    :param n: size of sorted array a
    :param b: given sorted array b
    :param m: size of sorted array b
    :return: array of intersection of two array or -1
    '''
 
    Intersection = []
    i = j = 0
     
    while i < n and j < m:
        if a[i] == b[j]:
 
            # If duplicate already present in Intersection list
            if len(Intersection) > 0 and Intersection[-1] == a[i]:
                i+= 1
                j+= 1
 
            # If no duplicate is present in Intersection list
            else:
                Intersection.append(a[i])
                i+= 1
                j+= 1
        elif a[i] < b[j]:
            i+= 1
        else:
            j+= 1
             
    if not len(Intersection):
        return [-1]
    return Intersection
 
# Driver Code
if __name__ == "__main__":
 
    arr1 = [1, 2, 2, 3, 4]
    arr2 = [2, 2, 4, 6, 7, 8]
     
    l = IntersectionArray(arr1, arr2, len(arr1), len(arr2))
    print(*l)

 

 

posted by 귀염둥이채원 2021. 9. 15. 10:46

Given two binary arrays, arr1[] and arr2[] of the same size n. Find the length of the longest common span (i, j) where j >= i such that arr1[i] + arr1[i+1] + …. + arr1[j] = arr2[i] + arr2[i+1] + …. + arr2[j].
The expected time complexity is Θ(n).

Examples:

Input: arr1[] = {0, 1, 0, 0, 0, 0};
arr2[] = {1, 0, 1, 0, 0, 1};
Output: 4
The longest span with same sum is from index 1 to 4.

Input: arr1[] = {0, 1, 0, 1, 1, 1, 1};
arr2[] = {1, 1, 1, 1, 1, 0, 1};
Output: 6
The longest span with same sum is from index 1 to 6.

Input: arr1[] = {0, 0, 0};
arr2[] = {1, 1, 1};
Output: 0

Input: arr1[] = {0, 0, 1, 0};
arr2[] = {1, 1, 1, 1};
Output: 1
We strongly recommend that you click here and practice it, before moving on to the solution.
Method 1 (Simple Solution)
One by one by consider same subarrays of both arrays. For all subarrays, compute sums and if sums are same and current length is more than max length, then update max length. Below is C++ implementation of the simple approach.


Method 1 (Simple Solution)

# A Simple python program to find longest common
# subarray of two binary arrays with same sum

# Returns length of the longest common subarray
# with same sum
def longestCommonSum(arr1, arr2, n):

	# Initialize result
	maxLen = 0

	# One by one pick all possible starting points
	# of subarrays
	for i in range(0,n):

		# Initialize sums of current subarrays
		sum1 = 0
		sum2 = 0

		# Consider all points for starting with arr[i]
		for j in range(i,n):
	
			# Update sums
			sum1 += arr1[j]
			sum2 += arr2[j]

			# If sums are same and current length is
			# more than maxLen, update maxLen
			if (sum1 == sum2):
				len = j-i+1
				if (len > maxLen):
					maxLen = len
	
	return maxLen


# Driver program to test above function
arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
n = len(arr1)
print("Length of the longest common span with same "
			"sum is",longestCommonSum(arr1, arr2, n))


Method 2 (Using Auxiliary Array)

# Python program to find longest common
# subarray of two binary arrays with
# same sum

def longestCommonSum(arr1, arr2, n):

	# Initialize result
	maxLen = 0
	
	# Initialize prefix sums of two arrays
	presum1 = presum2 = 0
	
	# Create a dictionary to store indices
	# of all possible sums
	diff = {}
	
	# Traverse both arrays
	for i in range(n):
	
		# Update prefix sums
		presum1 += arr1[i]
		presum2 += arr2[i]
		
		# Compute current diff which will be
		# used as index in diff dictionary
		curr_diff = presum1 - presum2
		
		# If current diff is 0, then there
		# are same number of 1's so far in
		# both arrays, i.e., (i+1) is
		# maximum length.
		if curr_diff == 0:
			maxLen = i+1
		elif curr_diff not in diff:
			# save the index for this diff
			diff[curr_diff] = i
		else:				
			# calculate the span length
			length = i - diff[curr_diff]
			maxLen = max(maxLen, length)
		
	return maxLen

# Driver program
arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
print("Length of the longest common",
	" span with same", end = " ")
print("sum is",longestCommonSum(arr1,
				arr2, len(arr1)))



Method 3 (Using Hashing)

# Python program to find largest subarray
# with equal number of 0's and 1's.

# Returns largest common subarray with equal
# number of 0s and 1s
def longestCommonSum(arr1, arr2, n):
	
	# Find difference between the two
	arr = [0 for i in range(n)]
	
	for i in range(n):
		arr[i] = arr1[i] - arr2[i];
	
	# Creates an empty hashMap hM
	hm = {}
	sum = 0	 # Initialize sum of elements
	max_len = 0	 #Initialize result
	
	# Traverse through the given array
	for i in range(n):
		
		# Add current element to sum
		sum += arr[i]
		
		# To handle sum=0 at last index
		if (sum == 0):
			max_len = i + 1
		
		# If this sum is seen before,
		# then update max_len if required
		if sum in hm:
			max_len = max(max_len, i - hm[sum])
		else: # Else put this sum in hash table
			hm[sum] = i
	return max_len

# Driver code
arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
n = len(arr1)
print(longestCommonSum(arr1, arr2, n))