code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
# Python program to merge # two sorted arrays # with O(1) extra space. # Merge ar1[] and ar2[] # with O(1) extra space def merge(ar1, ar2, m, n): # Iterate through all # elements of ar2[] starting from # the last element for i in range(n-1, -1, -1): # Find the smallest element # greater than ar2[i]. Move all # elements one position ahead # till the smallest greater # element is not found last = ar1[m-1] j=m-2 while(j >= 0 and ar1[j] > ar2[i]): ar1[j+1] = ar1[j] j-=1 # If there was a greater element if (last > ar2[i]): ar1[j+1] = ar2[i] ar2[i] = last # Driver program ar1 = [1, 5, 9, 10, 15, 20] ar2 = [2, 3, 8, 13] m = len(ar1) n = len(ar2) merge(ar1, ar2, m, n) print("After Merging \nFirst Array:", end="") for i in range(m): print(ar1[i] , " ", end="") print("\nSecond Array: ", end="") for i in range(n): print(ar2[i] , " ", end="") # This code is contributed # by Anant Agarwal.
constant
quadratic
# Python program for the above approach arr1 = [1, 5, 9, 10, 15, 20] arr2 = [2, 3, 8, 13] # Function to merge two arrays def merge(n, m): i = 0 j = 0 k = n - 1 while (i <= k and j < m): if (arr1[i] < arr2[j]): i += 1 else: temp = arr2[j] arr2[j] = arr1[k] arr1[k] = temp j += 1 k -= 1 arr1.sort() arr2.sort() # Driver code if __name__ == '__main__': merge(len(arr1), len(arr2)) print("After Merging \nFirst Array: ") print(','.join(str(x) for x in arr1)) print("Second Array: ") print(','.join(str(x) for x in arr2)) # This code is contributed by gauravrajput1
constant
nlogn
arr1 = [1, 5, 9, 10, 15, 20 ]; arr2 =[ 2, 3, 8, 13 ]; def merge(n, m): i = 0; temp = 0; # While loop till last element # of array 1(sorted) # is greater than first element # of array 2(sorted) while (arr1[n - 1] > arr2[0]): if (arr1[i] > arr2[0]): # Swap arr1[i] with first element # of arr2 and sorting the updated # arr2(arr1 is already sorted) # swap(arr1[i],arr2[0]); temp = arr1[i]; arr1[i] = arr2[0]; arr2[0] = temp; arr2.sort(); i+=1; # Driver code if __name__ == '__main__': merge(len(arr1), len(arr2)); print("After Merging \nFirst Array: "); print((arr1)); print("Second Array: "); print((arr2)); # This code contributed by gauravrajput1
constant
linear
# Python program to merge # two sorted arrays # with O(1) extra space. # Merge ar1[] and ar2[] # with O(1) extra space def rotate(a, n, idx): for i in range((int)(idx/2)): a[i], a[idx-1-i] = a[idx-1-i], a[i] for i in range(idx, (int)((n+idx)/2)): a[i], a[n-1-(i-idx)] = a[n-1-(i-idx)], a[i] for i in range((int)(n/2)): a[i], a[n-1-i] = a[n-1-i], a[i] def sol(a1, a2, n, m): l = 0 h = n-1 idx = 0 while (l <= h): c1 = (int)((l+h)/2) c2 = n-c1-1 l1 = a1[c1] l2 = a2[c2-1] r1 = sys.maxint if c1 == n-1 else a1[c1+1] r2 = sys.maxint if c2 == m else a2[c2] if l1 > r2: h = c1-1 if h == -1: idx = 0 elif l2 > r1: l = c1+1 if l == n-1: idx = n else: idx = c1+1 break for i in range(idx, n): a1[i], a2[i-idx] = a2[i-idx], a1[i] a1.sort() a2.sort() def merge(a1, a2, n, m): if n > m: sol(a2, a1, m, n) rotate(a1, n, n-m) for i in range(m): a1[i], a2[i] = a2[i], a1[i] else: sol(a1, a2, n, m) # Driver program ar1 = [1, 5, 9, 10, 15, 20] ar2 = [2, 3, 8, 13] m = len(ar1) n = len(ar2) merge(ar1, ar2, m, n) print("After Merging \nFirst Array:", end="") for i in range(m): print(ar1[i], " ", end="") print("\nSecond Array: ", end="") for i in range(n): print(ar2[i], " ", end="") # This code is contributed # by Aditya Anand.
constant
nlogn
# code contributed by mahee96 # "Insertion sort of list 2 with swaps from list 1" # # swap elements to get list 1 correctly, meanwhile # place the swapped item in correct position of list 2 # eventually list 2 is also sorted # Time = O(m*n) or O(n*m) # AUX = O(1) def merge(arr1, arr2): x = arr1; y = arr2 end = len(arr1) i = 0 while(i < end): # O(m) or O(n) if(x[i] > y[0]): swap(x,y,i,0) insert(y,0) # O(n) or O(m) number of shifts i+=1 # O(n): def insert(y, i): orig = y[i] i+=1 while (i<len(y) and y[i]<orig): y[i-1] = y[i] i+=1 y[i-1] = orig def swap(x,y,i,j): temp = x[i] x[i] = y[j] y[j] = temp def test(): c1 = [2, 3, 8, 13] c2 = [1, 5, 9, 10, 15, 20 ] for _ in range(2): merge(c1,c2) print(c1,c2) c1, c2 = c2, c1 test()
constant
quadratic
# Python program to merge two sorted arrays without using extra space def merge(arr1, arr2, n, m): # three pointers to iterate i = 0 j = 0 k = 0 # for euclid's division lemma x = 10e7 + 1 # in this loop we are rearranging the elements of arr1 while i < n and (j < n and k < m): # if both arr1 and arr2 elements are modified if arr1[j] >= x and arr2[k] >= x: if arr1[j] % x <= arr2[k] % x: arr1[i] += (arr1[j] % x) * x j += 1 else: arr1[i] += (arr2[k] % x) * x k += 1 # if only arr1 elements are modified elif arr1[j] >= x: if arr1[j] % x <= arr2[k]: arr1[i] += (arr1[j] % x) * x j += 1 else: arr1[i] += (arr2[k] % x) * x k += 1 # if only arr2 elements are modified elif arr2[k] >= x: if arr1[j] <= arr2[k] % x: arr1[i] += (arr1[j] % x) * x j += 1 else: arr1[i] += (arr2[k] % x) * x k += 1 # if none elements are modified else: if arr1[j] <= arr2[k]: arr1[i] += (arr1[j] % x) * x j += 1 else: arr1[i] += (arr2[k] % x) * x k += 1 i += 1 # we can copy the elements directly as the other array # is exchausted while j < n and i < n: arr1[i] += (arr1[j] % x) * x i += 1 j += 1 while k < m and i < n: arr1[i] += (arr2[k] % x) * x i += 1 k += 1 # we need to reset i i = 0 # in this loop we are rearranging the elements of arr2 while i < m and (j < n and k < m): # if both arr1 and arr2 elements are modified if arr1[j] >= x and arr2[k] >= x: if arr1[j] % x <= arr2[k] % x: arr2[i] += (arr1[j] % x) * x j += 1 else: arr2[i] += (arr2[k] % x) * x k += 1 # if only arr1 elements are modified elif arr1[j] >= x: if arr1[j] % x <= arr2[k]: arr2[i] += (arr1[j] % x) * x j += 1 else: arr2[i] += (arr2[k] % x) * x k += 1 # if only arr2 elements are modified elif arr2[k] >= x: if arr1[j] <= arr2[k] % x: arr2[i] += (arr1[j] % x) * x j += 1 else: arr2[i] += (arr2[k] % x) * x k += 1 else: # if none elements are modified if arr1[j] <= arr2[k]: arr2[i] += (arr1[j] % x) * x j += 1 else: arr2[i] += (arr2[k] % x) * x k += 1 i += 1 # we can copy the elements directly as the other array # is exhausted while j < n and i < m: arr2[i] += (arr1[j] % x) * x i += 1 j += 1 while k < m and i < m: arr2[i] += (arr2[k] % x) * x i += 1 k += 1 # we need to reset i i = 0 # we need to divide the whole arr1 by x while i < n: arr1[i] /= x i += 1 # we need to reset i i = 0 # we need to divide the whole arr2 by x while i < m: arr2[i] /= x i += 1 # Driver program ar1 = [1, 5, 9, 10, 15, 20] ar2 = [2, 3, 8, 13] m = len(ar1) n = len(ar2) merge(ar1, ar2, m, n) print("After Merging \nFirst Array:", end=" ") for i in range(m): print(int(ar1[i]), end=" ") print("\nSecond Array:", end=" ") for i in range(n): print(int(ar2[i]), end=" ") # This code is contributed by Tapesh(tapeshdua420)
constant
linear
# A Python program to find the to # calculate the product of max # element of first array and min # element of second array # Function to calculate the product def minmaxProduct(arr1, arr2, n1, n2): # Sort the arrays to find the # maximum and minimum elements # in given arrays arr1.sort() arr2.sort() # Return product of maximum # and minimum. return arr1[n1 - 1] * arr2[0] # Driver Program arr1 = [10, 2, 3, 6, 4, 1] arr2 = [5, 1, 4, 2, 6, 9] n1 = len(arr1) n2 = len(arr2) print(minmaxProduct(arr1, arr2, n1, n2)) # This code is contributed by Shrikant13.
constant
nlogn
# Python3 program to find the to # calculate the product of # max element of first array # and min element of second array # Function to calculate the product def minMaxProduct(arr1, arr2, n1, n2) : # Initialize max of first array max = arr1[0] # initialize min of second array min = arr2[0] i = 1 while (i < n1 and i < n2) : # To find the maximum # element in first array if (arr1[i] > max) : max = arr1[i] # To find the minimum # element in second array if (arr2[i] < min) : min = arr2[i] i += 1 # Process remaining elements while (i < n1) : if (arr1[i] > max) : max = arr1[i] i += 1 while (i < n2): if (arr2[i] < min) : min = arr2[i] i += 1 return max * min # Driver code arr1 = [10, 2, 3, 6, 4, 1 ] arr2 = [5, 1, 4, 2, 6, 9 ] n1 = len(arr1) n2 = len(arr1) print(minMaxProduct(arr1, arr2, n1, n2)) # This code is contributed by Smitha
constant
linear
# python 3 program to implement # binary search in sorted array def binarySearch(arr, low, high, key): mid = (low + high)/2 if (key == arr[int(mid)]): return mid if (key > arr[int(mid)]): return binarySearch(arr, (mid + 1), high, key) if (key < arr[int(mid)]): return binarySearch(arr, low, (mid-1), key) return 0 # Driver code if __name__ == "__main__": # Let us search 3 in below array arr = [5, 6, 7, 8, 9, 10] n = len(arr) key = 10 # Function call print("Index:", int(binarySearch(arr, 0, n-1, key))) # This code is contributed by # Smitha Dinesh Semwal
logn
logn
# Python3 program to implement insert # operation in an sorted array. # Inserts a key in arr[] of given capacity. # n is current size of arr[]. This function # returns n+1 if insertion is successful, else n. def insertSorted(arr, n, key, capacity): # Cannot insert more elements if n is # already more than or equal to capacity if (n >= capacity): return n i = n - 1 while i >= 0 and arr[i] > key: arr[i + 1] = arr[i] i -= 1 arr[i + 1] = key return (n + 1) # Driver Code if __name__ == "__main__": arr = [12, 16, 20, 40, 50, 70] for i in range(20): arr.append(0) capacity = len(arr) n = 6 key = 26 print("Before Insertion: ", end=" ") for i in range(n): print(arr[i], end=" ") # Function call n = insertSorted(arr, n, key, capacity) print("\nAfter Insertion: ", end="") for i in range(n): print(arr[i], end=" ") # This code is contributed by Mohit Kumar
constant
linear
# Python program to implement delete operation in a # sorted array # /* Function to delete an element */ def deleteElement(arr, n, key): # Find position of element to be deleted pos = binarySearch(arr, 0, n - 1, key) if (pos == -1): print("Element not found") return n # Deleting element for i in range(pos, n - 1): arr[i] = arr[i + 1] return n - 1 # To search a key to be deleted def binarySearch(arr, low, high, key): if (high < low): return -1 mid = (low + high) // 2 if (key == arr[mid]): return mid if (key > arr[mid]): return binarySearch(arr, (mid + 1), high, key) return binarySearch(arr, low, (mid - 1), key) # Driver code if __name__ == "__main__": arr = [10, 20, 30, 40, 50] n = len(arr) key = 30 print("Array before deletion") for i in range(n): print(arr[i], end=" ") # Function call n = deleteElement(arr, n, key) print("\n\nArray after deletion") for i in range(n): print(arr[i], end=" ") # This code is contributed by shubhamsingh10
logn
linear
# This python program tells if there exists a pair in array whose sum results in x. # Function to find and print pair def chkPair(A, size, x): for i in range(0, size - 1): for j in range(i + 1, size): if (A[i] + A[j] == x): return 1 return 0 if __name__ == "__main__": A = [0, -1, 2, -3, 1] x = -2 size = len(A) if (chkPair(A, size, x)): print("Yes") else: print("No") # This code is contributed by rakeshsahni
constant
quadratic
# Python program to check for the sum # condition to be satisfied def hasArrayTwoCandidates(A, arr_size, sum): # sort the array quickSort(A, 0, arr_size-1) l = 0 r = arr_size-1 # traverse the array for the two elements while l < r: if (A[l] + A[r] == sum): return 1 elif (A[l] + A[r] < sum): l += 1 else: r -= 1 return 0 # Implementation of Quick Sort # A[] --> Array to be sorted # si --> Starting index # ei --> Ending index def quickSort(A, si, ei): if si < ei: pi = partition(A, si, ei) quickSort(A, si, pi-1) quickSort(A, pi + 1, ei) # Utility function for partitioning # the array(used in quick sort) def partition(A, si, ei): x = A[ei] i = (si-1) for j in range(si, ei): if A[j] <= x: i += 1 # This operation is used to swap # two variables is python A[i], A[j] = A[j], A[i] A[i + 1], A[ei] = A[ei], A[i + 1] return i + 1 # Driver program to test the functions A = [1, 4, 45, 6, 10, -8] n = 16 if (hasArrayTwoCandidates(A, len(A), n)): print("Yes") else: print("No") # This code is contributed by __Devesh Agrawal__
constant
nlogn
# Python program to check for the sum # condition to be satisfied def binarySearch(A, low, high, searchKey): m = 0 while (low <= high): m = (high + low) // 2 # Check if searchKey is present at mid if (A[m] == searchKey): return 1 # If searchKey greater, ignore left half if (A[m] < searchKey): low = m + 1 # If searchKey is smaller, ignore right half else: high = m - 1 # if we reach here, then element was # not present return 0 def checkTwoSum(A, arr_size, sum): # sort the array A.sort() l = 0 r = arr_size-1 # Traversing all element in an array search for searchKey i = 0 while i < arr_size-1: searchKey = sum-A[i] # calling binarySearch function if(binarySearch(A, i+1, r, searchKey) == 1): return 1 i = i+1 return 0 # Driver program to test the functions A = [1, 4, 45, 6, 10, -8] n = 14 if (checkTwoSum(A, len(A), n)): print("Yes") else: print("No")
constant
nlogn
# Python program to find if there are # two elements with given sum # function to check for the given sum # in the array def printPairs(arr, arr_size, sum): # Create an empty hash map # using an hashmap allows us to store the indices hashmap = {} for i in range(0, arr_size): temp = sum-arr[i] if (temp in hashmap): print('Yes') return hashmap[arr[i]] = i print("No") # driver code A = [1, 4, 45, 6, 10, 8] n = 16 printPairs(A, len(A), n) # This code will also work in case the array has the same number twice # and target is the sum of those numbers # Eg: Array = [4,6,4] Target = 8 # This code is contributed by __Achyut Upadhyay__
linear
linear
# Code in Python3 to tell if there # exists a pair in array whose # sum results in x. # Function to print pairs def printPairs(a, n, x): rem = [] for i in range(x): # Initializing the rem # values with 0's. rem.append(0) for i in range(n): if (a[i] < x): # Perform the remainder operation # only if the element is x, as # numbers greater than x can't # be used to get a sum x.Updating # the count of remainders. rem[a[i] % x] += 1 # Traversing the remainder list from # start to middle to find pairs for i in range(1, x // 2): if (rem[i] > 0 and rem[x - i] > 0): # The elements with remainders # i and x-i will result to a # sum of x. Once we get two # elements which add up to x, # we print x and break. print("Yes") break # Once we reach middle of # remainder array, we have to # do operations based on x. if (i >= x // 2): if (x % 2 == 0): if (rem[x // 2] > 1): # If x is even and we have more # than 1 elements with remainder # x/2, then we will have two # distinct elements which add up # to x. if we dont have than 1 # element, print "No". print("Yes") else: print("No") else: # When x is odd we continue # the same process which we # did in previous loop. if (rem[x // 2] > 0 and rem[x - x // 2] > 0): print("Yes") else: print("No") # Driver Code A = [1, 4, 45, 6, 10, 8] n = 16 arr_size = len(A) # Function calling printPairs(A, arr_size, n) # This code is contributed by subhammahato348
constant
linear
# Python 3 program to search an element in an array # where difference between adjacent elements is atmost k # x is the element to be searched in arr[0..n-1] # such that all elements differ by at-most k. def search(arr, n, x, k): # Traverse the given array starting from # leftmost element i = 0 while (i < n): # If x is found at index i if (arr[i] == x): return i # Jump the difference between current # array element and x divided by k # We use max here to make sure that i # moves at-least one step ahead. i = i + max(1, int(abs(arr[i] - x) / k)) print("number is not present!") return -1 # Driver program to test above function arr = [2, 4, 5, 7, 7, 6] x = 6 k = 2 n = len(arr) print("Element", x, "is present at index",search(arr, n, x, k)) # This code is contributed # by Smitha Dinesh Semwal
constant
linear
# Python 3 program for above approach import sys # This function prints # common elements in ar1 def findCommon(ar1, ar2, ar3, n1, n2, n3): # Initialize starting indexes # for ar1[], ar2and # ar3[] i = 0 j = 0 k = 0 # Declare three variables prev1, # prev2, prev3 to track # previous element # Initialize prev1, prev2, # prev3 with INT_MIN prev1 = prev2 = prev3 = -sys.maxsize - 1 # Iterate through three arrays # while all arrays have # elements while (i < n1 and j < n2 and k < n3): # If ar1[i] = prev1 and i < n1, # keep incrementing i while (ar1[i] == prev1 and i < n1-1): i += 1 # If ar2[j] = prev2 and j < n2, # keep incrementing j while (ar2[j] == prev2 and j < n2): j += 1 # If ar3[k] = prev3 and k < n3, # keep incrementing k while (ar3[k] == prev3 and k < n3): k += 1 # If x = y and y = z, pr # any of them, update # prev1 prev2, prev3 and move # ahead in each array if (ar1[i] == ar2[j] and ar2[j] == ar3[k]): print(ar1[i], end=" ") prev1 = ar1[i] prev2 = ar2[j] prev3 = ar3[k] i += 1 j += 1 k += 1 # If x < y, update prev1 # and increment i elif (ar1[i] < ar2[j]): prev1 = ar1[i] i += 1 # If y < z, update prev2 # and increment j elif (ar2[j] < ar3[k]): prev2 = ar2[j] j += 1 # We reach here when x > y # and z < y, i.e., z is # smallest update prev3 # and increment k else: prev3 = ar3[k] k += 1 # Driver code ar1 = [1, 5, 10, 20, 40, 80, 80] ar2 = [6, 7, 20, 80, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 80, 120] n1 = len(ar1) n2 = len(ar2) n3 = len(ar3) print("Common Elements are ") findCommon(ar1, ar2, ar3, n1, n2, n3) # This code is contributed by splevel62.
constant
linear
# Python implementation of the approach def findCommon(a, b, c, n1, n2, n3): # three sets to maintain frequency of elements uset = set() uset2 = set() uset3 = set() for i in range(n1): uset.add(a[i]) for i in range(n2): uset2.add(b[i]) # checking if elements of 3rd array are present in first 2 sets for i in range(n3): if(c[i] in uset and c[i] in uset2): # using a 3rd set to prevent duplicates if c[i] not in uset3: print(c[i], end = " ") uset3.add(c[i]) # Driver code ar1 = [ 1, 5, 10, 20, 40, 80 ] ar2 = [ 6, 7, 20, 80, 100 ] ar3 = [ 3, 4, 15, 20, 30, 70, 80, 120 ] n1 = len(ar1) n2 = len(ar2) n3 = len(ar3) print("Common Elements are ") findCommon(ar1, ar2, ar3, n1, n2, n3) # This code is contributed by shinjanpatra.
linear
linear
# Python3 program to find the only # repeating element in an array where # elements are from 1 to N-1. def findRepeating(arr, N): for i in range(N): for j in range(i + 1, N): if (arr[i] == arr[j]): return arr[i] # Driver's Code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed by Arpit Jain
constant
quadratic
# Python3 program to find the only # repeating element in an array where # elements are from 1 to N-1. def findRepeating(arr, N): arr.sort() for i in range(1, N): if(arr[i] != i+1): return arr[i] # Driver's Code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed by Arpit Jain
constant
nlogn
# Python3 program to find the only # repeating element in an array # where elements are from 1 to n-1. def findRepeating(arr, N): s = set() for i in range(N): if arr[i] in s: return arr[i] s.add(arr[i]) # If input is correct, we should # never reach here return -1 # Driver code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed # by Shrikant13
linear
linear
# Python3 program to find the only # repeating element in an array where # elements are from 1 to N-1. def findRepeating(arr, N): # Find array sum and subtract sum # first n-1 natural numbers from it # to find the result. return sum(arr) - (((N - 1) * N) // 2) # Driver's Code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed # by mohit kumar
constant
linear
# Python3 program to find the only # repeating element in an array where # elements are from 1 to N-1. def findRepeating(arr, N): # res is going to store value of # 1 ^ 2 ^ 3 .. ^ (N-1) ^ arr[0] ^ # arr[1] ^ .... arr[n-1] res = 0 for i in range(0, N-1): res = res ^ (i+1) ^ arr[i] res = res ^ arr[N-1] return res # Driver code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed by Smitha Dinesh Semwal.
constant
linear
# Python3 program to find the only # repeating element in an array # where elements are from 1 to N-1. # Function to find repeated element def findRepeating(arr, N): missingElement = 0 # indexing based for i in range(0, N): element = arr[abs(arr[i])] if(element < 0): missingElement = arr[i] break arr[abs(arr[i])] = -arr[abs(arr[i])] return abs(missingElement) # Driver code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed by Smitha Dinesh Semwal.
constant
linear
class GFG : @staticmethod def findDuplicate( nums) : slow = nums[0] fast = nums[0] while True : slow = nums[slow] fast = nums[nums[fast]] if((slow != fast) == False) : break fast = nums[0] while (slow != fast) : slow = nums[slow] fast = nums[fast] return slow @staticmethod def main( args) : arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] # Function call ans = GFG.findDuplicate(arr) print(ans) if __name__=="__main__": GFG.main([]) # This code is contributed by aadityaburujwale.
constant
linear
# Python code to find the array element that appears only once # Function to find the array # element that appears only once def findSingle(A, ar_size): # iterate over every element for i in range(ar_size): # Initialize count to 0 count = 0 for j in range(ar_size): # Count the frequency # of the element if(A[i] == A[j]): count += 1 # If the frequency of # the element is one if(count == 1): return A[i] # If no element exist # at most once return -1 ar = [2, 3, 5, 4, 5, 3, 4] n = len(ar) # Function call print("Element occurring once is", findSingle(ar, n)) # This code is contributed by lokesh
constant
quadratic
# function to find the once # appearing element in array def findSingle( ar, n): res = ar[0] # Do XOR of all elements and return for i in range(1,n): res = res ^ ar[i] return res # Driver code ar = [2, 3, 5, 4, 5, 3, 4] print "Element occurring once is", findSingle(ar, len(ar)) # This code is contributed by __Devesh Agrawal__
constant
linear
# Python3 program to find # element that appears once # function which find number def singleNumber(nums): # applying the formula. return 2 * sum(set(nums)) - sum(nums) # driver code a = [2, 3, 5, 4, 5, 3, 4] print (int(singleNumber(a))) a = [15, 18, 16, 18, 16, 15, 89] print (int(singleNumber(a))) # This code is contributed by "Abhishek Sharma 44"
linear
nlogn
def singleelement(arr, n): low = 0 high = n - 2 mid = 0 while (low <= high): mid = (low + high) // 2 if (arr[mid] == arr[mid ^ 1]): low = mid + 1 else: high = mid - 1 return arr[low] # Driver code arr = [2, 3, 5, 4, 5, 3, 4] size = len(arr) arr.sort() print(singleelement(arr, size)) # This code is contributed by shivanisingh
constant
nlogn
# Python Program to find max # subarray sum excluding some # elements # Function to check the element # present in array B INT_MIN = -2147483648 def isPresent(B, m, x): for i in range(0, m): if B[i] == x: return True return False # Utility function for findMaxSubarraySum() # with the following parameters # A => Array A, # B => Array B, # n => Number of elements in Array A, # m => Number of elements in Array B def findMaxSubarraySumUtil(A, B, n, m): # set max_so_far to INT_MIN max_so_far = INT_MIN curr_max = 0 for i in range(0, n): if isPresent(B, m, A[i]) == True: curr_max = 0 continue # Proceed as in Kadane's Algorithm curr_max = max(A[i], curr_max + A[i]) max_so_far = max(max_so_far, curr_max) return max_so_far # Wrapper for findMaxSubarraySumUtil() def findMaxSubarraySum(A, B, n, m): maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m) # This case will occur when all # elements of A are present # in B, thus no subarray can be # formed if maxSubarraySum == INT_MIN: print('Maximum Subarray Sum cant be found') else: print('The Maximum Subarray Sum =', maxSubarraySum) # Driver code A = [3, 4, 5, -4, 6] B = [1, 8, 5] n = len(A) m = len(B) # Function call findMaxSubarraySum(A, B, n, m) # This code is contributed # by sahil shelangia
constant
quadratic
# Python Program to find max subarray # sum excluding some elements # Utility function for findMaxSubarraySum() # with the following parameters # A => Array A, # B => Array B, # n => Number of elements in Array A, # m => Number of elements in Array B import sys def binary_search(B, m, target): start,end = 0,m - 1 # Iterate while start not meets end while (start <= end): # Find the mid index mid = (start + end) // 2 # If element is present at mid, return True if (B[mid] == target): return True # Else look in left or right half accordingly elif (B[mid] < target): start = mid + 1 else: end = mid - 1 return False def findMaxSubarraySumUtil(A, B, n, m): # set max_so_far to INT_MIN max_so_far,curr_max = -sys.maxsize - 1,0 for i in range(n): # if the element is present in B, # set current max to 0 and move to # the next element if (binary_search(B, m, A[i])): curr_max = 0 continue # Proceed as in Kadane's Algorithm curr_max = max(A[i], curr_max + A[i]) max_so_far = max(max_so_far, curr_max) return max_so_far # Wrapper for findMaxSubarraySumUtil() def findMaxSubarraySum(A,B,n,m): # sort array B to apply Binary Search B.sort() maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m) # This case will occur when all elements # of A are present in B, thus no subarray # can be formed if (maxSubarraySum == -sys.maxsize - 1): print("Maximum subarray sum cant be found") else: print(f"The Maximum subarray sum = {maxSubarraySum}") # Driver Code A = [ 3, 4, 5, -4, 6 ] B = [ 1, 8, 5 ] n = len(A) m = len(B) # Function call findMaxSubarraySum(A, B, n, m) # This code is contributed by shinjanpatra
constant
nlogn
# Python3 program implementation of the # above idea import sys # Function to calculate the max sum of # contiguous subarray of B whose elements # are not present in A def findMaxSubarraySum(A, B): m = dict() # Mark all the elements present in B for i in range(len(B)): if B[i] not in m: m[B[i]] = 0 m[B[i]] = 1 # Initialize max_so_far with INT_MIN max_so_far = -sys.maxsize - 1 currmax = 0 # Traverse the array A for i in range(len(A)): if (currmax < 0 or (A[i] in m and m[A[i]] == 1)): currmax = 0 continue currmax = max(A[i], A[i] + currmax) # If current max is greater than # max so far then update max so far if (max_so_far<currmax): max_so_far = currmax return max_so_far # Driver Code if __name__=='__main__': a = [ 3, 4, 5, -4, 6 ] b = [ 1, 8, 5 ] # Function call print(findMaxSubarraySum(a, b)) # This code is contributed by rutvik_56
linear
linear
# Python 3 program to find maximum # equilibrium sum. import sys # Function to find maximum equilibrium sum. def findMaxSum(arr, n): res = -sys.maxsize - 1 for i in range(n): prefix_sum = arr[i] for j in range(i): prefix_sum += arr[j] suffix_sum = arr[i] j = n - 1 while(j > i): suffix_sum += arr[j] j -= 1 if (prefix_sum == suffix_sum): res = max(res, prefix_sum) return res # Driver Code if __name__ == '__main__': arr = [-2, 5, 3, 1, 2, 6, -4, 2] n = len(arr) print(findMaxSum(arr, n)) # This code is contributed by # Surendra_Gangwar
linear
quadratic
# Python3 program to find # maximum equilibrium sum. # Function to find maximum # equilibrium sum. def findMaxSum(arr, n): # Array to store prefix sum. preSum = [0 for i in range(n)] # Array to store suffix sum. suffSum = [0 for i in range(n)] # Variable to store maximum sum. ans = -10000000 # Calculate prefix sum. preSum[0] = arr[0] for i in range(1, n): preSum[i] = preSum[i - 1] + arr[i] # Calculate suffix sum and compare # it with prefix sum. Update ans # accordingly. suffSum[n - 1] = arr[n - 1] if (preSum[n - 1] == suffSum[n - 1]): ans = max(ans, preSum[n - 1]) for i in range(n - 2, -1, -1): suffSum[i] = suffSum[i + 1] + arr[i] if (suffSum[i] == preSum[i]): ans = max(ans, preSum[i]) return ans # Driver Code if __name__=='__main__': arr = [-2, 5, 3, 1,2, 6, -4, 2] n = len(arr) print(findMaxSum(arr, n)) # This code is contributed by pratham76
linear
linear
# Python3 program to find # maximum equilibrium sum. import sys # Function to find # maximum equilibrium sum. def findMaxSum(arr,n): ss = sum(arr) prefix_sum = 0 res = -sys.maxsize for i in range(n): prefix_sum += arr[i] if prefix_sum == ss: res = max(res, prefix_sum); ss -= arr[i]; return res # Driver code if __name__=="__main__": arr = [ -2, 5, 3, 1, 2, 6, -4, 2 ] n = len(arr) print(findMaxSum(arr, n)) # This code is contributed by rutvik_56
constant
linear
# Python3 program to find equilibrium # index of an array # function to find the equilibrium index def equilibrium(arr): leftsum = 0 rightsum = 0 n = len(arr) # Check for indexes one by one # until an equilibrium index is found for i in range(n): leftsum = 0 rightsum = 0 # get left sum for j in range(i): leftsum += arr[j] # get right sum for j in range(i + 1, n): rightsum += arr[j] # if leftsum and rightsum are same, # then we are done if leftsum == rightsum: return i # return -1 if no equilibrium index is found return -1 # Driver code if __name__ == "__main__": arr = [-7, 1, 5, 2, -4, 3, 0] # Function call print(equilibrium(arr)) # This code is contributed by Abhishek Sharama
constant
quadratic
# Python program to find the equilibrium # index of an array # Function to find the equilibrium index def equilibrium(arr): # finding the sum of whole array total_sum = sum(arr) leftsum = 0 for i, num in enumerate(arr): # total_sum is now right sum # for index i total_sum -= num if leftsum == total_sum: return i leftsum += num # If no equilibrium index found, # then return -1 return -1 # Driver code if __name__ == "__main__": arr = [-7, 1, 5, 2, -4, 3, 0] # Function call print('First equilibrium index is ', equilibrium(arr)) # This code is contributed by Abhishek Sharma
constant
linear
# Python3 program to find the equilibrium # index of an array # Function to find the equilibrium index def equilibrium(arr): left_sum = [] right_sum = [] # Iterate from 0 to len(arr) for i in range(len(arr)): # If i is not 0 if(i): left_sum.append(left_sum[i-1]+arr[i]) right_sum.append(right_sum[i-1]+arr[len(arr)-1-i]) else: left_sum.append(arr[i]) right_sum.append(arr[len(arr)-1]) # Iterate from 0 to len(arr) for i in range(len(arr)): if(left_sum[i] == right_sum[len(arr) - 1 - i]): return(i) # If no equilibrium index found,then return -1 return -1 # Driver code if __name__ == "__main__": arr = [-7, 1, 5, 2, -4, 3, 0] # Function call print('First equilibrium index is ', equilibrium(arr)) # This code is contributed by Lokesh Sharma
linear
linear
# Python Function to print leaders in array def printLeaders(arr,size): for i in range(0, size): for j in range(i+1, size): if arr[i]<=arr[j]: break if j == size-1: # If loop didn't break print (arr[i],end=' ') # Driver function arr=[16, 17, 4, 3, 5, 2] printLeaders(arr, len(arr)) # This code is contributed by _Devesh Agrawal__
constant
quadratic
# Python function to print leaders in array def printLeaders(arr, size): max_from_right = arr[size-1] print (max_from_right,end=' ') for i in range( size-2, -1, -1): if max_from_right < arr[i]: print (arr[i],end=' ') max_from_right = arr[i] # Driver function arr = [16, 17, 4, 3, 5, 2] printLeaders(arr, len(arr)) # This code contributed by _Devesh Agrawal__
constant
linear
# Python Function to print leaders in an array def printLaders(arr, size): # create stack to store leaders sk = [] sk.append(arr[size - 1]) for i in range(size - 2, -1, -1): if(arr[i] >= sk[len(sk) - 1]): sk.append(arr[i]) # print stack elements # run loop till stack is not empty while(len(sk) != 0): print(sk[len(sk)-1],end = ' ') sk.pop() # Driver program to test above function if __name__ == "__main__": arr = [16,17,4,3,5,2] n = len(arr) printLaders(arr,n) # This code is contributed by ajaymakvana
linear
linear
# Function to get index of ceiling of x in arr[low..high] */ def ceilSearch(arr, low, high, x): # If x is smaller than or equal to first element, # then return the first element */ if x <= arr[low]: return low # Otherwise, linearly search for ceil value */ i = low for i in range(high): if arr[i] == x: return i # if x lies between arr[i] and arr[i+1] including # arr[i+1], then return arr[i+1] */ if arr[i] < x and arr[i+1] >= x: return i+1 # If we reach here then x is greater than the last element # of the array, return -1 in this case */ return -1 # Driver program to check above functions */ arr = [1, 2, 8, 10, 10, 12, 19] n = len(arr) x = 3 index = ceilSearch(arr, 0, n-1, x); if index == -1: print ("Ceiling of %d doesn't exist in array "% x) else: print ("ceiling of %d is %d"%(x, arr[index])) # This code is contributed by Shreyanshi Arun
constant
linear
# Function to get index of ceiling of x in arr[low..high]*/ def ceilSearch(arr, low, high, x): # If x is smaller than or equal to the first element, # then return the first element */ if x <= arr[low]: return low # If x is greater than the last element, then return -1 */ if x > arr[high]: return -1 # get the index of middle element of arr[low..high]*/ mid = (low + high)/2; # low + (high - low)/2 */ # If x is same as middle element, then return mid */ if arr[mid] == x: return mid # If x is greater than arr[mid], then either arr[mid + 1] # is ceiling of x or ceiling lies in arr[mid+1...high] */ elif arr[mid] < x: if mid + 1 <= high and x <= arr[mid+1]: return mid + 1 else: return ceilSearch(arr, mid+1, high, x) # If x is smaller than arr[mid], then either arr[mid] # is ceiling of x or ceiling lies in arr[low...mid-1] */ else: if mid - 1 >= low and x > arr[mid-1]: return mid else: return ceilSearch(arr, low, mid - 1, x) # Driver program to check above functions arr = [1, 2, 8, 10, 10, 12, 19] n = len(arr) x = 20 index = ceilSearch(arr, 0, n-1, x); if index == -1: print ("Ceiling of %d doesn't exist in array "% x) else: print ("ceiling of %d is %d"%(x, arr[index])) # This code is contributed by Shreyanshi Arun
constant
logn
# Function to get index of ceiling of x in arr[low..high] def ceilSearch(arr, low, high, x): # base condition if length of arr == 0 then return -1 if (x == 0): return -1 """this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling""" while (low <= high): mid = low + (high - low) / 2 mid = int(mid) if (arr[mid] == x): return mid elif (x < arr[mid]): high = mid - 1 else: low = mid + 1 return low """ step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target """ # Driver program to check above functions arr = [1, 2, 8, 10, 10, 12, 19] n = len(arr) x = 8 index = ceilSearch(arr, 0, n - 1, x) if (index == -1): print("Ceiling of", x, "does not exist in an array") else: print("Ceiling of", x, "is", arr[index])
constant
logn
# Python3 program to find Majority # element in an array # Function to find Majority # element in an array def findMajority(arr, n): maxCount = 0 index = -1 # sentinels for i in range(n): count = 0 for j in range(n): if(arr[i] == arr[j]): count += 1 # update maxCount if count of # current element is greater if(count > maxCount): maxCount = count index = i # if maxCount is greater than n/2 # return the corresponding element if (maxCount > n//2): print(arr[index]) else: print("No Majority Element") # Driver code if __name__ == "__main__": arr = [1, 1, 2, 1, 3, 5, 1] n = len(arr) # Function calling findMajority(arr, n) # This code is contributed # by ChitraNayal
constant
quadratic
# Python3 program to demonstrate insert operation in binary # search tree. # class for creating node class Node(): def __init__(self, data): self.data = data self.left = None self.right = None self.count = 1 # count of number of times data is inserted in tree # class for binary search tree # it initialises tree with None root # insert function inserts node as per BST rule # and also checks for majority element # if no majority element is found yet, it returns None class BST(): def __init__(self): self.root = None def insert(self, data, n): out = None if (self.root == None): self.root = Node(data) else: out = self.insertNode(self.root, data, n) return out def insertNode(self, currentNode, data, n): if (currentNode.data == data): currentNode.count += 1 if (currentNode.count > n//2): return currentNode.data else: return None elif (currentNode.data < data): if (currentNode.right): self.insertNode(currentNode.right, data, n) else: currentNode.right = Node(data) elif (currentNode.data > data): if (currentNode.left): self.insertNode(currentNode.left, data, n) else: currentNode.left = Node(data) # Driver code # declaring an array arr = [3, 2, 3] n = len(arr) # declaring None tree tree = BST() flag = 0 for i in range(n): out = tree.insert(arr[i], n) if (out != None): print(arr[i]) flag = 1 break if (flag == 0): print("No Majority Element")
linear
quadratic
# Program for finding out majority element in an array # Function to find the candidate for Majority def findCandidate(A): maj_index = 0 count = 1 for i in range(len(A)): if A[maj_index] == A[i]: count += 1 else: count -= 1 if count == 0: maj_index = i count = 1 return A[maj_index] # Function to check if the candidate occurs more than n/2 times def isMajority(A, cand): count = 0 for i in range(len(A)): if A[i] == cand: count += 1 if count > len(A)/2: return True else: return False # Function to print Majority Element def printMajority(A): # Find the candidate for Majority cand = findCandidate(A) # Print the candidate if it is Majority if isMajority(A, cand) == True: print(cand) else: print("No Majority Element") # Driver code A = [1, 3, 3, 1, 2] # Function call printMajority(A)
constant
linear
# Python3 program for finding out majority # element in an array def findMajority(arr, size): m = {} for i in range(size): if arr[i] in m: m[arr[i]] += 1 else: m[arr[i]] = 1 count = 0 for key in m: if m[key] > size / 2: count = 1 print("Majority found :-",key) break if(count == 0): print("No Majority element") # Driver code arr = [2, 2, 2, 2, 5, 5, 2, 3, 3] n = len(arr) # Function calling findMajority(arr, n) # This code is contributed by ankush_953
linear
linear
# Python3 program to find Majority # element in an array # Function to find Majority element # in an array # it returns -1 if there is no majority element def majorityElement(arr, n) : # sort the array in O(nlogn) arr.sort() count, max_ele, temp, f = 1, -1, arr[0], 0 for i in range(1, n) : # increases the count if the same element occurs # otherwise starts counting new element if(temp == arr[i]) : count += 1 else : count = 1 temp = arr[i] # sets maximum count # and stores maximum occurred element so far # if maximum count becomes greater than n/2 # it breaks out setting the flag if(max_ele < count) : max_ele = count ele = arr[i] if(max_ele > (n//2)) : f = 1 break # returns maximum occurred element # if there is no such element, returns -1 if f == 1 : return ele else : return -1 # Driver code arr = [1, 1, 2, 1, 3, 5, 1] n = len(arr) # Function calling print(majorityElement(arr, n)) # This code is contributed by divyeshrabadiya07
constant
nlogn
# Hashing based Python # program to find if # there is a majority # element in input array. # Returns true if there # is a majority element # in a[] def isMajority(a): # Insert all elements # in a hash table mp = {} for i in a: if i in mp: mp[i] += 1 else: mp[i] = 1 # Check if frequency # of any element is # n/2 or more. for x in mp: if mp[x] >= len(a)//2: return True return False # Driver code a = [ 2, 3, 9, 2, 2 ] print("Yes" if isMajority(a) else "No") #This code is contributed by Ansu Kumari
linear
linear
# A python3 program to find a peak # element using divide and conquer # A binary search based function # that returns index of a peak element def findPeakUtil(arr, low, high, n): # Find index of middle element # low + (high - low) / 2 mid = low + (high - low)/2 mid = int(mid) # Compare middle element with its # neighbours (if neighbours exist) if ((mid == 0 or arr[mid - 1] <= arr[mid]) and (mid == n - 1 or arr[mid + 1] <= arr[mid])): return mid # If middle element is not peak and # its left neighbour is greater # than it, then left half must # have a peak element elif (mid > 0 and arr[mid - 1] > arr[mid]): return findPeakUtil(arr, low, (mid - 1), n) # If middle element is not peak and # its right neighbour is greater # than it, then right half must # have a peak element else: return findPeakUtil(arr, (mid + 1), high, n) # A wrapper over recursive # function findPeakUtil() def findPeak(arr, n): return findPeakUtil(arr, 0, n - 1, n) # Driver code arr = [1, 3, 20, 4, 1, 0] n = len(arr) print("Index of a peak point is", findPeak(arr, n)) # This code is contributed by # Smitha Dinesh Semwal
logn
logn
# A Python program to find a peak element # using divide and conquer # A binary search based function # that returns index of a peak element def findPeak(arr, n): l = 0 r = n-1 while(l <= r): # finding mid by binary right shifting. mid = (l + r) >> 1 # first case if mid is the answer if((mid == 0 or arr[mid - 1] <= arr[mid]) and (mid == n - 1 or arr[mid + 1] <= arr[mid])): break # move the right pointer if(mid > 0 and arr[mid - 1] > arr[mid]): r = mid - 1 # move the left pointer else: l = mid + 1 return mid # Driver Code arr = [1, 3, 20, 4, 1, 0] n = len(arr) print(f"Index of a peak point is {findPeak(arr, n)}") # This code is contributed by Rajdeep Mallick (rajdeep999)
constant
logn
# Python3 program to Find the two # repeating elements in a given array def printRepeating(arr, size): print("Repeating elements are", end=' ') for i in range(0, size-1): for j in range(i + 1, size): if arr[i] == arr[j]: print(arr[i], end=' ') # Driver code arr = [4, 2, 4, 5, 2, 3, 1] arr_size = len(arr) printRepeating(arr, arr_size) # This code is contributed by Smitha Dinesh Semwal
constant
quadratic
# Python3 code for Find the two repeating # elements in a given array def printRepeating(arr, size): count = [0] * size print(" Repeating elements are ", end="") for i in range(0, size): if(count[arr[i]] == 1): print(arr[i], end=" ") else: count[arr[i]] = count[arr[i]] + 1 # Driver code arr = [4, 2, 4, 5, 2, 3, 1] arr_size = len(arr) printRepeating(arr, arr_size) # This code is contributed by Nikita Tiwari.
linear
linear
# Python3 code for Find the two repeating # elements in a given array import math def printRepeating(arr, size): # S is for sum of elements in arr[] S = 0 # P is for product of elements in arr[] P = 1 n = size - 2 # Calculate Sum and Product # of all elements in arr[] for i in range(0, size): S = S + arr[i] P = P * arr[i] # S is x + y now S = S - n * (n + 1) // 2 # P is x*y now P = P // fact(n) # D is x - y now D = math.sqrt(S * S - 4 * P) x = (D + S) // 2 y = (S - D) // 2 print("Repeating elements are ", (int)(x), " ", (int)(y)) def fact(n): if(n == 0): return 1 else: return(n * fact(n - 1)) # Driver code arr = [4, 2, 4, 5, 2, 3, 1] arr_size = len(arr) printRepeating(arr, arr_size) # This code is contributed by Nikita Tiwari.
constant
linear
# Python3 code to Find the # two repeating elements # in a given array def printRepeating(arr, size): # Will hold xor # of all elements xor = arr[0] n = size - 2 x = 0 y = 0 # Get the xor of all # elements in arr[] # and 1, 2 .. n for i in range(1, size): xor ^= arr[i] for i in range(1, n + 1): xor ^= i # Get the rightmost set # bit in set_bit_no set_bit_no = xor & ~(xor-1) # Now divide elements in two # sets by comparing rightmost # set bit of xor with bit at # same position in each element. for i in range(0, size): if(arr[i] & set_bit_no): # XOR of first # set in arr[] x = x ^ arr[i] else: # XOR of second # set in arr[] y = y ^ arr[i] for i in range(1, n + 1): if(i & set_bit_no): # XOR of first set # in arr[] and # 1, 2, ...n x = x ^ i else: # XOR of second set # in arr[] and # 1, 2, ...n y = y ^ i print("Repeating elements are", y, x) # Driver code arr = [4, 2, 4, 5, 2, 3, 1] arr_size = len(arr) printRepeating(arr, arr_size) # This code is contributed # by Smitha
constant
linear
# Python3 code for Find the two repeating # elements in a given array def printRepeating(arr, size): print("Repeating elements are", end=" ") for i in range(0, size): if(arr[abs(arr[i])] > 0): arr[abs(arr[i])] = (-1) * arr[abs(arr[i])] else: print(abs(arr[i]), end=" ") # Driver code arr = [4, 2, 4, 5, 2, 3, 1] arr_size = len(arr) printRepeating(arr, arr_size) # This code is contributed by Nikita Tiwari.
constant
linear
# Python program for the above approach def twoRepeated(arr, N): m = N - 1 for i in range(N): arr[arr[i] % m - 1] += m if ((arr[arr[i] % m - 1] // m) == 2): print(arr[i] % m, end=" ") # Driver Code arr = [4, 2, 4, 5, 2, 3, 1] n = len(arr) print("Repeating elements are ", end="") twoRepeated(arr, n) # This code is contributed by Shubham Singh
constant
linear
# Python3 program to find the two repeating # elements in a given array def printRepeating(arr, size): s = set() print("Repeating elements are ", end="") for i in range(size): if (len(s) and arr[i] in s): print(arr[i], end=" ") s.add(arr[i]) # Driver code arr = [4, 2, 4, 5, 2, 3, 1] arr_size = len(arr) printRepeating(arr, arr_size) # This code is contributed by Shubham Singh
linear
linear
# A simple program to print subarray with sum as given sum # Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result def subArraySum(arr, n, sum): # Pick a starting point for i in range(0,n): currentSum = arr[i] if(currentSum == sum): print("Sum found at indexes",i) return else: # Try all subarrays starting with 'i' for j in range(i+1,n): currentSum += arr[i] if(currentSum == sum): print("Sum found between indexes",i,"and",j) return print("No Subarray Found") # Driver Code if __name__ == "__main__": arr = [15,2,4,8,9,5,10,23] n = len(arr) sum = 23 subArraySum(arr, n, sum) # This code is contributed by ajaymakvana
constant
quadratic
# An efficient program # to print subarray # with sum as given sum # Returns true if the # there is a subarray # of arr[] with sum # equal to 'sum' # otherwise returns # false. Also, prints # the result. def subArraySum(arr, n, sum_): # Initialize currentSum as # value of first element # and starting point as 0 currentSum = arr[0] start = 0 # Add elements one by # one to currentSum and # if the currentSum exceeds # the sum, then remove # starting element i = 1 while i <= n: # If currentSum exceeds # the sum, then remove # the starting elements while currentSum > sum_ and start < i-1: currentSum = currentSum - arr[start] start += 1 # If currentSum becomes # equal to sum, then # return true if currentSum == sum_: print("Sum found between indexes % d and % d" % (start, i-1)) return 1 # Add this element # to currentSum if i < n: currentSum = currentSum + arr[i] i += 1 # If we reach here, # then no subarray print("No subarray found") return 0 # Driver program if __name__ == '__main__': arr = [15, 2, 4, 8, 9, 5, 10, 23] n = len(arr) sum_ = 23 subArraySum(arr, n, sum_) # This code is Contributed by shreyanshi_arun.
constant
linear
# Python3 implementation of smallest # difference triplet # Function to find maximum number def maximum(a, b, c): return max(max(a, b), c) # Function to find minimum number def minimum(a, b, c): return min(min(a, b), c) # Finds and prints the smallest # Difference Triplet def smallestDifferenceTriplet(arr1, arr2, arr3, n): # sorting all the three arrays arr1.sort() arr2.sort() arr3.sort() # To store resultant three numbers res_min = 0; res_max = 0; res_mid = 0 # pointers to arr1, arr2, # arr3 respectively i = 0; j = 0; k = 0 # Loop until one array reaches to its end # Find the smallest difference. diff = 2147483647 while (i < n and j < n and k < n): sum = arr1[i] + arr2[j] + arr3[k] # maximum number max = maximum(arr1[i], arr2[j], arr3[k]) # Find minimum and increment its index. min = minimum(arr1[i], arr2[j], arr3[k]) if (min == arr1[i]): i += 1 else if (min == arr2[j]): j += 1 else: k += 1 # Comparing new difference with the # previous one and updating accordingly if (diff > (max - min)): diff = max - min res_max = max res_mid = sum - (max + min) res_min = min # Print result print(res_max, ",", res_mid, ",", res_min) # Driver code arr1 = [5, 2, 8] arr2 = [10, 7, 12] arr3 = [9, 14, 6] n = len(arr1) smallestDifferenceTriplet(arr1, arr2, arr3, n) # This code is contributed by Anant Agarwal.
constant
nlogn
# A simple Python 3 program # to find three elements whose # sum is equal to zero # Prints all triplets in # arr[] with 0 sum def findTriplets(arr, n): found = False for i in range(0, n-2): for j in range(i+1, n-1): for k in range(j+1, n): if (arr[i] + arr[j] + arr[k] == 0): print(arr[i], arr[j], arr[k]) found = True # If no triplet with 0 sum # found in array if (found == False): print(" not exist ") # Driver code arr = [0, -1, 2, -3, 1] n = len(arr) findTriplets(arr, n) # This code is contributed by Smitha Dinesh Semwal
constant
cubic
# Python3 program to find triplets # in a given array whose sum is zero # function to print triplets with 0 sum def findTriplets(arr, n): found = False for i in range(n - 1): # Find all pairs with sum # equals to "-arr[i]" s = set() for j in range(i + 1, n): x = -(arr[i] + arr[j]) if x in s: print(x, arr[i], arr[j]) found = True else: s.add(arr[j]) if found == False: print("No Triplet Found") # Driver Code arr = [0, -1, 2, -3, 1] n = len(arr) findTriplets(arr, n) # This code is contributed by Shrikant13
linear
quadratic
# python program to find triplets in a given # array whose sum is zero # function to print triplets with 0 sum def findTriplets(arr, n): found = False # sort array elements arr.sort() for i in range(0, n-1): # initialize left and right l = i + 1 r = n - 1 x = arr[i] while (l < r): if (x + arr[l] + arr[r] == 0): # print elements if it's sum is zero print(x, arr[l], arr[r]) l += 1 r -= 1 found = True # If sum of three elements is less # than zero then increment in left elif (x + arr[l] + arr[r] < 0): l += 1 # if sum is greater than zero then # decrement in right side else: r -= 1 if (found == False): print(" No Triplet Found") # Driven source arr = [0, -1, 2, -3, 1] n = len(arr) findTriplets(arr, n) # This code is contributed by Smitha Dinesh Semwal
constant
quadratic
# Python program to rotate a matrix # Function to rotate a matrix def rotateMatrix(mat): if not len(mat): return """ top : starting row index bottom : ending row index left : starting column index right : ending column index """ top = 0 bottom = len(mat)-1 left = 0 right = len(mat[0])-1 while left < right and top < bottom: # Store the first element of next row, # this element will replace first element of # current row prev = mat[top+1][left] # Move elements of top row one step right for i in range(left, right+1): curr = mat[top][i] mat[top][i] = prev prev = curr top += 1 # Move elements of rightmost column one step downwards for i in range(top, bottom+1): curr = mat[i][right] mat[i][right] = prev prev = curr right -= 1 # Move elements of bottom row one step left for i in range(right, left-1, -1): curr = mat[bottom][i] mat[bottom][i] = prev prev = curr bottom -= 1 # Move elements of leftmost column one step upwards for i in range(bottom, top-1, -1): curr = mat[i][left] mat[i][left] = prev prev = curr left += 1 return mat # Utility Function def printMatrix(mat): for row in mat: print row # Test case 1 matrix =[ [1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ] # Test case 2 """ matrix =[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] """ matrix = rotateMatrix(matrix) # Print modified matrix printMatrix(matrix)
constant
quadratic
# Python3 program to rotate a matrix by 90 degrees N = 4 # An Inplace function to rotate # N x N matrix by 90 degrees in # anti-clockwise direction def rotateMatrix(mat): # Consider all squares one by one for x in range(0, int(N / 2)): # Consider elements in group # of 4 in current square for y in range(x, N-x-1): # store current cell in temp variable temp = mat[x][y] # move values from right to top mat[x][y] = mat[y][N-1-x] # move values from bottom to right mat[y][N-1-x] = mat[N-1-x][N-1-y] # move values from left to bottom mat[N-1-x][N-1-y] = mat[N-1-y][x] # assign temp to left mat[N-1-y][x] = temp # Function to print the matrix def displayMatrix(mat): for i in range(0, N): for j in range(0, N): print(mat[i][j], end=' ') print("") # Driver Code if __name__ == "__main__": mat = [[0 for x in range(N)] for y in range(N)] mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function call rotateMatrix(mat) # Print rotated matrix displayMatrix(mat) # This code is contributed by saloni1297
constant
quadratic
# Python program to rotate # a matrix by 90 degrees def rotateMatrix(mat): # reversing the matrix for i in range(len(mat)): mat[i].reverse() # make transpose of the matrix for i in range(len(mat)): for j in range(i, len(mat)): # swapping mat[i][j] and mat[j][i] mat[i][j], mat[j][i] = mat[j][i], mat[i][j] # Function to print the matrix def displayMatrix(mat): for i in range(0, len(mat)): for j in range(0, len(mat)): print(mat[i][j], end=' ') print() # Driver code if __name__ == "__main__": mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function call rotateMatrix(mat) # Print rotated matrix displayMatrix(mat) # This code is contributed by shivambhagat02(CC).
constant
quadratic
# Python3 program to # rotate a matrix by # 180 degrees N = 3; # Function to Rotate # the matrix by 180 degree def rotateMatrix(mat): # Simply print from # last cell to first cell. i = N - 1; while(i >= 0): j = N - 1; while(j >= 0): print(mat[i][j], end = " "); j = j - 1; print(); i = i - 1; # Driven code mat = [[1, 2, 3], [ 4, 5, 6 ], [ 7, 8, 9 ]]; rotateMatrix(mat); # This code is contributed # by mits
constant
quadratic
# Python3 program for left rotation of matrix by 180 R = 4 C = 4 # Function to rotate the matrix by 180 degree def reverseColumns(arr): for i in range(C): j = 0 k = C-1 while j < k: t = arr[j][i] arr[j][i] = arr[k][i] arr[k][i] = t j += 1 k -= 1 # Function for transpose of matrix def transpose(arr): for i in range(R): for j in range(i, C): t = arr[i][j] arr[i][j] = arr[j][i] arr[j][i] = t # Function for display the matrix def printMatrix(arr): for i in range(R): for j in range(C): print(arr[i][j], end = " "); print(); # Function to anticlockwise rotate matrix # by 180 degree def rotate180(arr): transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); # Driven code arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ]; rotate180(arr); printMatrix(arr);
constant
quadratic
# Reverse Row at specified index in the matrix def reverseRow(data, index): cols = len(data[index]) for i in range(cols // 2): temp = data[index][i] data[index][i] = data[index][cols - i - 1] data[index][cols - i - 1] = temp return data # Print Matrix data def printMatrix(data): for i in range(len(data)): for j in range(len(data[0])): print(data[i][j], end = ' ') print() # Rotate Matrix by 180 degrees def rotateMatrix(data): rows = len(data) cols = len(data[0]) if (rows % 2): # If N is odd reverse the middle # row in the matrix data = reverseRow(data, len(data) // 2) # Swap the value of matrix [i][j] with # [rows - i - 1][cols - j - 1] for half # the rows size. for i in range(rows // 2): for j in range(cols): temp = data[i][j] data[i][j] = data[rows - i - 1][cols - j - 1] data[rows - i - 1][cols - j - 1] = temp return data # Driver Code data = [ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 10 ], [ 11, 12, 13, 14, 15 ], [ 16, 17, 18, 19, 20 ], [ 21, 22, 23, 24, 25 ] ] # Rotate Matrix data = rotateMatrix(data) # Print Matrix printMatrix(data) # This code is contributed by rohitsingh07052
constant
quadratic
# Python3 program to check if all rows # of a matrix are rotations of each other MAX = 1000 # Returns true if all rows of mat[0..n-1][0..n-1] # are rotations of each other. def isPermutedMatrix(mat, n) : # Creating a string that contains # elements of first row. str_cat = "" for i in range(n) : str_cat = str_cat + "-" + str(mat[0][i]) # Concatenating the string with itself # so that substring search operations # can be performed on this str_cat = str_cat + str_cat # Start traversing remaining rows for i in range(1, n) : # Store the matrix into vector # in the form of strings curr_str = "" for j in range(n) : curr_str = curr_str + "-" + str(mat[i][j]) # Check if the current string is present # in the concatenated string or not if (str_cat.find(curr_str)) : return True return False # Driver code if __name__ == "__main__" : n = 4 mat = [[1, 2, 3, 4], [4, 1, 2, 3], [3, 4, 1, 2], [2, 3, 4, 1]] if (isPermutedMatrix(mat, n)): print("Yes") else : print("No") # This code is contributed by Ryuga
linear
cubic
# Python3 implementation to sort # the given matrix SIZE = 10 # Function to sort the given matrix def sortMat(mat, n) : # Temporary matrix of size n^2 temp = [0] * (n * n) k = 0 # Copy the elements of matrix # one by one into temp[] for i in range(0, n) : for j in range(0, n) : temp[k] = mat[i][j] k += 1 # sort temp[] temp.sort() # copy the elements of temp[] # one by one in mat[][] k = 0 for i in range(0, n) : for j in range(0, n) : mat[i][j] = temp[k] k += 1 # Function to print the given matrix def printMat(mat, n) : for i in range(0, n) : for j in range( 0, n ) : print(mat[i][j] , end = " ") print() # Driver program to test above mat = [ [ 5, 4, 7 ], [ 1, 3, 8 ], [ 2, 9, 6 ] ] n = 3 print( "Original Matrix:") printMat(mat, n) sortMat(mat, n) print("\nMatrix After Sorting:") printMat(mat, n) # This code is contributed by Nikita Tiwari.
quadratic
quadratic
# Python program to find median of matrix # sorted row wise from bisect import bisect_right as upper_bound MAX = 100; # Function to find median in the matrix def binaryMedian(m, r, d): mi = m[0][0] mx = 0 for i in range(r): if m[i][0] < mi: mi = m[i][0] if m[i][d-1] > mx : mx = m[i][d-1] desired = (r * d + 1) // 2 while (mi < mx): mid = mi + (mx - mi) // 2 place = [0]; # Find count of elements smaller than or equal to mid for i in range(r): j = upper_bound(m[i], mid) place[0] = place[0] + j if place[0] < desired: mi = mid + 1 else: mx = mid print ("Median is", mi) return # Driver code r, d = 3, 3 m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]] binaryMedian(m, r, d) # This code is contributed by Sachin BIsht
constant
nlogn
# Recursive code for Matrix Multiplication MAX = 100 i = 0 j = 0 k = 0 def multiplyMatrixRec(row1, col1, A, row2, col2, B, C): # Note that below variables are static # i and j are used to know current cell of # result matrix C[][]. k is used to know # current column number of A[][] and row # number of B[][] to be multiplied global i global j global k # If all rows traversed. if (i >= row1): return # If i < row1 if (j < col2): if (k < col1): C[i][j] += A[i][k] * B[k][j] k += 1 multiplyMatrixRec(row1, col1, A, row2, col2,B, C) k = 0 j += 1 multiplyMatrixRec(row1, col1, A, row2, col2, B, C) j = 0 i += 1 multiplyMatrixRec(row1, col1, A, row2, col2, B, C) # Function to multiply two matrices # A[][] and B[][] def multiplyMatrix(row1, col1, A, row2, col2, B): if (row2 != col1): print("Not Possible") return C = [[0 for i in range(MAX)] for i in range(MAX)] multiplyMatrixRec(row1, col1, A, row2, col2, B, C) # Print the result for i in range(row1): for j in range(col2): print( C[i][j], end = " ") print() # Driver Code A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] row1 = 3 col1 = 3 row2 = 3 col2 = 3 multiplyMatrix(row1, col1, A, row2, col2, B) # This code is contributed by sahilshelangia
logn
quadratic
# Python3 program to print Lower # triangular and Upper triangular # matrix of an array # Function to form lower triangular # matrix def lower(matrix, row, col): for i in range(0, row): for j in range(0, col): if (i < j): print("0", end = " "); else: print(matrix[i][j], end = " " ); print(" "); # Function to form upper triangular matrix def upper(matrix, row, col): for i in range(0, row): for j in range(0, col): if (i > j): print("0", end = " "); else: print(matrix[i][j], end = " " ); print(" "); # Driver Code matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; row = 3; col = 3; print("Lower triangular matrix: "); lower(matrix, row, col); print("Upper triangular matrix: "); upper(matrix, row, col); # This code is contributed by # Shivi_Aggarwal
constant
quadratic
# python3 program for the above approach def spiralOrder(matrix): ans = [] if (len(matrix) == 0): return ans m = len(matrix) n = len(matrix[0]) seen = [[0 for i in range(n)] for j in range(m)] dr = [0, 1, 0, -1] dc = [1, 0, -1, 0] x = 0 y = 0 di = 0 # Iterate from 0 to R * C - 1 for i in range(m * n): ans.append(matrix[x][y]) seen[x][y] = True cr = x + dr[di] cc = y + dc[di] if (0 <= cr and cr < m and 0 <= cc and cc < n and not(seen[cr][cc])): x = cr y = cc else: di = (di + 1) % 4 x += dr[di] y += dc[di] return ans # Driver code if __name__ == "__main__": a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function call for x in spiralOrder(a): print(x, end=" ") print()
linear
linear
# Python3 program to print # given matrix in spiral form def spiralPrint(m, n, a): k = 0 l = 0 ''' k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ''' while (k < m and l < n): # Print the first row from # the remaining rows for i in range(l, n): print(a[k][i], end=" ") k += 1 # Print the last column from # the remaining columns for i in range(k, m): print(a[i][n - 1], end=" ") n -= 1 # Print the last row from # the remaining rows if (k < m): for i in range(n - 1, (l - 1), -1): print(a[m - 1][i], end=" ") m -= 1 # Print the first column from # the remaining columns if (l < n): for i in range(m - 1, k - 1, -1): print(a[i][l], end=" ") l += 1 # Driver Code a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] R = 4 C = 4 # Function Call spiralPrint(R, C, a) # This code is contributed by Nikita Tiwari.
constant
quadratic
# Python3 program for the above approach # Function for printing matrix in spiral # form i, j: Start index of matrix, row # and column respectively m, n: End index # of matrix row and column respectively def printdata(arr, i, j, m, n): # If i or j lies outside the matrix if (i >= m or j >= n): return # Print First Row for p in range(i, n): print(arr[i][p], end=" ") # Print Last Column for p in range(i + 1, m): print(arr[p][n - 1], end=" ") # Print Last Row, if Last and # First Row are not same if ((m - 1) != i): for p in range(n - 2, j - 1, -1): print(arr[m - 1][p], end=" ") # Print First Column, if Last and # First Column are not same if ((n - 1) != j): for p in range(m - 2, i, -1): print(arr[p][j], end=" ") printdata(arr, i + 1, j + 1, m - 1, n - 1) # Driver code if __name__ == "__main__": R = 4 C = 4 arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function Call printdata(arr, 0, 0, R, C) # This code is contributed by avsadityavardhan
constant
quadratic
# Python3 program for the above approach R = 4 C = 4 def isInBounds(i, j): global R global C if (i < 0 or i >= R or j < 0 or j >= C): return False return True # Check if the position is blocked def isBlocked(matrix, i, j): if (not isInBounds(i, j)): return True if (matrix[i][j] == -1): return True return False # DFS code to traverse spirally def spirallyDFSTravserse(matrix, i, j, Dir, res): if (isBlocked(matrix, i, j)): return allBlocked = True for k in range(-1, 2, 2): allBlocked = allBlocked and isBlocked( matrix, k + i, j) and isBlocked(matrix, i, j + k) res.append(matrix[i][j]) matrix[i][j] = -1 if (allBlocked): return # dir: 0 - right, 1 - down, 2 - left, 3 - up nxt_i = i nxt_j = j nxt_dir = Dir if (Dir == 0): if (not isBlocked(matrix, i, j + 1)): nxt_j += 1 else: nxt_dir = 1 nxt_i += 1 elif(Dir == 1): if (not isBlocked(matrix, i + 1, j)): nxt_i += 1 else: nxt_dir = 2 nxt_j -= 1 elif(Dir == 2): if (not isBlocked(matrix, i, j - 1)): nxt_j -= 1 else: nxt_dir = 3 nxt_i -= 1 elif(Dir == 3): if (not isBlocked(matrix, i - 1, j)): nxt_i -= 1 else: nxt_dir = 0 nxt_j += 1 spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res) # To traverse spirally def spirallyTraverse(matrix): res = [] spirallyDFSTravserse(matrix, 0, 0, 0, res) return res # Driver code if __name__ == "__main__": a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function Call res = spirallyTraverse(a) print(*res) # This code is contributed by rag2127
constant
quadratic
# Python program to find unique element in matrix # function that calculate unique element def unique(mat, r, c) -> int: # declare map for hashing mp = {} for i in range(r): for j in range(c): # increase freq of mat[i][j] in map if mat[i][j] not in mp: mp[mat[i][j]] = 1 else: mp[mat[i][j]] += 1 flag = False # print unique element for p in mp: if mp[p] == 1: print(p, end=" ") flag = True if flag == False: print("No unique element in the matrix") # Driver program if __name__ == "__main__": mat = [[1, 2, 3, 20], [5, 6, 20, 25], [1, 3, 5, 6], [6, 7, 8, 15]] # function that calculate unique element unique(mat, 4, 4) # This code is contributed by ajaymakvana
quadratic
quadratic
# Python3 Program to swap diagonal of a matrix # size of square matrix N = 3 # Function to swap diagonal of matrix def swapDiagonal(matrix): for i in range(N): matrix[i][i], matrix[i][N-i-1] = \ matrix[i][N-i-1], matrix[i][i] # Driver Code matrix = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] # swap diagonals of matrix swapDiagonal(matrix); # Displaying modified matrix for i in range(N): for j in range(N): print(matrix[i][j], end = ' ') print()
constant
quadratic
# Python 3 program for finding max path in matrix # To calculate max path in matrix def findMaxPath(mat): for i in range(1, N): res = -1 for j in range(M): # When all paths are possible if (j > 0 and j < M - 1): mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])) # When diagonal right is not possible else if (j > 0): mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]) # When diagonal left is not possible else if (j < M - 1): mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]) # Store max path sum res = max(mat[i][j], res) return res # Driver program to check findMaxPath N=4 M=6 mat = ([[ 10, 10, 2, 0, 20, 4 ], [ 1, 0, 0, 30, 2, 5 ], [ 0, 10, 4, 0, 2, 0 ], [ 1, 0, 2, 20, 0, 4 ]]) print(findMaxPath(mat)) # This code is contributed by Azkia Anam.
constant
quadratic
# Python3 code to move matrix elements # in given direction with add # element with same value MAX = 50 # Function to shift the matrix # in the given direction def moveMatrix(d, n, a): # For right shift move. if (d[0] == 'r'): # For each row from # top to bottom for i in range(n): v = [] w = [] # For each element of # row from right to left for j in range(n - 1, -1, -1): # if not 0 if (a[i][j]): v.append(a[i][j]) # For each temporary array j = 0 while (j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each row element to 0. for j in range(n): a[i][j] = 0 j = n - 1 # Copying the temporary # array to the current row. for it in w: a[i][j] = it j -= 1 # For left shift move elif (d[0] == 'l'): # For each row for i in range(n): v = [] w = [] # For each element of the # row from left to right for j in range(n): # If not 0 if (a[i][j]): v.append(a[i][j]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each row element to 0. for j in range(n): a[i][j] = 0 j = 0 for it in w: a[i][j] = it j += 1 # For down shift move. elif (d[0] == 'd'): # For each column for i in range(n): v = [] w = [] # For each element of # column from bottom to top for j in range(n - 1, -1, -1): # If not 0 if (a[j][i]): v.append(a[j][i]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j <len( v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each column element to 0. for j in range(n): a[j][i] = 0 j = n - 1 # Copying the temporary array # to the current column for it in w: a[j][i] = it j -= 1 # For up shift move elif (d[0] == 'u'): # For each column for i in range(n): v = [] w = [] # For each element of column # from top to bottom for j in range(n): # If not 0 if (a[j][i]): v.append(a[j][i]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each column element to 0. for j in range(n): a[j][i] = 0 j = 0 # Copying the temporary array # to the current column for it in w: a[j][i] = it j += 1 # Driver Code if __name__ == "__main__": d = ["l"] * 2 n = 5 a = [ [ 32, 3, 3, 3, 3 ], [ 0, 0, 1, 0, 0 ], [ 10, 10, 8, 1, 2 ], [ 0, 0, 0, 0, 1 ], [ 4, 5, 6, 7, 8 ] ] moveMatrix(d, n, a) # Printing the final array for i in range(n): for j in range(n): print(a[i][j], end = " ") print() # This code is contributed by chitranayal
linear
quadratic
# Python3 program to find number of subarrays # having product exactly equal to k. # Function to find number of subarrays # having product equal to 1. def countOne(arr, n) : i = 0 # To store number of ones in # current segment of all 1s. Len = 0 # To store number of subarrays # having product equal to 1. ans = 0 while(i < n) : # If current element is 1, then # find length of segment of 1s # starting from current element. if(arr[i] == 1) : Len = 0 while(i < n and arr[i] == 1) : i += 1 Len += 1 # add number of possible # subarrays of 1 to result. ans += (Len*(Len+1)) // 2 i += 1 return ans # Function to find number of subarrays having # product exactly equal to k. def findSubarrayCount(arr, n, k) : start, endval, p, countOnes, res = 0, 0, 1, 0, 0 while (endval < n) : p = p * (arr[endval]) # If product is greater than k then we need to decrease # it. This could be done by shifting starting point of # sliding window one place to right at a time and update # product accordingly. if(p > k) : while(start <= endval and p > k) : p = p // arr[start] start += 1 if(p == k) : # Count number of succeeding ones. countOnes = 0 while endval + 1 < n and arr[endval + 1] == 1 : countOnes += 1 endval += 1 # Update result by adding both new subarray # and effect of succeeding ones. res += (countOnes + 1) # Update sliding window and result according # to change in sliding window. Here preceding # 1s have same effect on subarray as succeeding # 1s, so simply add. while(start <= endval and arr[start] == 1 and k!=1) : res += (countOnes + 1) start += 1 # Move start to correct position to find new # subarray and update product accordingly. p = p // arr[start] start += 1 endval += 1 return res arr1 = [ 2, 1, 1, 1, 3, 1, 1, 4 ] n1 = len(arr1) k = 1 if(k != 1) : print(findSubarrayCount(arr1, n1, k)) else : print(countOne(arr1, n1)) arr2 = [ 2, 1, 1, 1, 4, 5] n2 = len(arr2) k = 4 if(k != 1) : print(findSubarrayCount(arr2, n2, k)) else : print(countOne(arr2, n2)) # This code is contributed by divyesh072019
constant
linear
# The function checks if the array elements # are consecutive. If elements are consecutive, # then returns true, else returns false def areConsecutive(arr, n): # Sort the array arr.sort() # checking the adjacent elements for i in range (1,n): if(arr[i]!=arr[i-1]+1): return False; return True; # Driver Code arr = [5, 4, 2, 3, 1, 6] n = len(arr) if(areConsecutive(arr, n) == True): print("Array elements are consecutive ") else: print("Array elements are not consecutive ") # This code is contributed by Aarti_Rathi
constant
nlogn
# Helper functions to get Minimum and # Maximum in an array # The function checks if the array elements # are consecutive. If elements are consecutive, # then returns true, else returns false def areConsecutive(arr, n): if ( n < 1 ): return False # 1) Get the Minimum element in array */ Min = min(arr) # 2) Get the Maximum element in array */ Max = max(arr) # 3) Max - Min + 1 is equal to n, # then only check all elements */ if (Max - Min + 1 == n): # Create a temp array to hold visited # flag of all elements. Note that, calloc # is used here so that all values are # initialized as false visited = [False for i in range(n)] for i in range(n): # If we see an element again, # then return false */ if (visited[arr[i] - Min] != False): return False # If visited first time, then mark # the element as visited */ visited[arr[i] - Min] = True # If all elements occur once, # then return true */ return True return False # if (Max - Min + 1 != n) # Driver Code arr = [5, 4, 2, 3, 1, 6] n = len(arr) if(areConsecutive(arr, n) == True): print("Array elements are consecutive ") else: print("Array elements are not consecutive ") # This code is contributed by mohit kumar
linear
linear
# Helper functions to get minimum and # maximum in an array # The function checks if the array # elements are consecutive. If elements # are consecutive, then returns true, # else returns false def areConsecutive(arr, n): if ( n < 1 ): return False # 1) Get the minimum element in array min = getMin(arr, n) # 2) Get the maximum element in array max = getMax(arr, n) # 3) max - min + 1 is equal to n # then only check all elements if (max - min + 1 == n): for i in range(n): if (arr[i] < 0): j = -arr[i] - min else: j = arr[i] - min # if the value at index j is negative # then there is repetition if (arr[j] > 0): arr[j] = -arr[j] else: return False # If we do not see a negative value # then all elements are distinct return True return False # if (max - min + 1 != n) # UTILITY FUNCTIONS def getMin(arr, n): min = arr[0] for i in range(1, n): if (arr[i] < min): min = arr[i] return min def getMax(arr, n): max = arr[0] for i in range(1, n): if (arr[i] > max): max = arr[i] return max # Driver Code if __name__ == "__main__": arr = [1, 4, 5, 3, 2, 6] n = len(arr) if(areConsecutive(arr, n) == True): print(" Array elements are consecutive ") else: print(" Array elements are not consecutive ") # This code is contributed by ita_c
constant
linear
# Function to Check if array # elements are consecutive def areConsecutive(arr, n): min_ele = arr.index(min(arr)) num = 0 for i in range(0, n): num ^= arr[min_ele] ^ arr[i] arr[min_ele] += 1 if num == 0: return True return False # Driver program to test above # functions if __name__ == "__main__": arr = [1, 4, 5, 3, 2, 6] n = len(arr) if areConsecutive(arr, n) == True: print(" Array elements are consecutive ", end=' ') else: print(" Array elements are not consecutive ", end=' ') # This code is contributed by Aarti_Rathi
constant
linear
# Python 3 program to find whether an array # is subset of another array # Return 1 if arr2[] is a subset of # arr1[] def isSubset(arr1, arr2, m, n): i = 0 j = 0 for i in range(n): for j in range(m): if(arr2[i] == arr1[j]): break # If the above inner loop was # not broken at all then arr2[i] # is not present in arr1[] if (j == m): return 0 # If we reach here then all # elements of arr2[] are present # in arr1[] return 1 # Driver code if __name__ == "__main__": arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) if(isSubset(arr1, arr2, m, n)): print("arr2[] is subset of arr1[] ") else: print("arr2[] is not a subset of arr1[]") # This code is contributed by ita_c
constant
quadratic
# Python3 program to find whether an array # is subset of another array # Return 1 if arr2[] is a subset of arr1[] def isSubset(arr1, arr2, m, n): i = 0 quickSort(arr1, 0, m-1) for i in range(n): if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1): return 0 # If we reach here then all elements # of arr2[] are present in arr1[] return 1 # FOLLOWING FUNCTIONS ARE ONLY FOR # SEARCHING AND SORTING PURPOSE # Standard Binary Search function def binarySearch(arr, low, high, x): if(high >= low): mid = (low + high)//2 # Check if arr[mid] is the first # occurrence of x. # arr[mid] is first occurrence if x is # one of the following # is true: # (i) mid == 0 and arr[mid] == x # (ii) arr[mid-1] < x and arr[mid] == x if((mid == 0 or x > arr[mid-1]) and (arr[mid] == x)): return mid elif(x > arr[mid]): return binarySearch(arr, (mid + 1), high, x) else: return binarySearch(arr, low, (mid - 1), x) return -1 def partition(A, si, ei): x = A[ei] i = (si - 1) for j in range(si, ei): if(A[j] <= x): i += 1 A[i], A[j] = A[j], A[i] A[i + 1], A[ei] = A[ei], A[i + 1] return (i + 1) # Implementation of Quick Sort # A[] --> Array to be sorted # si --> Starting index # ei --> Ending index def quickSort(A, si, ei): # Partitioning index if(si < ei): pi = partition(A, si, ei) quickSort(A, si, pi - 1) quickSort(A, pi + 1, ei) # Driver code arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) if(isSubset(arr1, arr2, m, n)): print("arr2[] is subset of arr1[] ") else: print("arr2[] is not a subset of arr1[] ") # This code is contributed by chandan_jnu
linear
nlogn
# Python3 program to find whether an array # is subset of another array # Return 1 if arr2[] is a subset of arr1[] */ def isSubset(arr1, arr2, m, n): i = 0 j = 0 if m < n: return 0 arr1.sort() arr2.sort() while i < n and j < m: if arr1[j] < arr2[i]: j += 1 elif arr1[j] == arr2[i]: j += 1 i += 1 elif arr1[j] > arr2[i]: return 0 return False if i < n else True # Driver code arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) if isSubset(arr1, arr2, m, n) == True: print("arr2 is subset of arr1 ") else: printf("arr2 is not a subset of arr1 ") # This code is contributed by Shrikant13
constant
nlogn
# Python3 program to find whether an array # is subset of another array # Return true if arr2[] is a subset # of arr1[] def isSubset(arr1, m, arr2, n): # Using STL set for hashing hashset = set() # hset stores all the values of arr1 for i in range(0, m): hashset.add(arr1[i]) # Loop to check if all elements # of arr2 also lies in arr1 for i in range(0, n): if arr2[i] in hashset: continue else: return False return True # Driver Code if __name__ == '__main__': arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) if (isSubset(arr1, m, arr2, n)): print("arr2[] is subset of arr1[] ") else: print("arr2[] is not a subset of arr1[] ") # This code is contributed by akhilsaini
linear
nlogn
# Python3 code arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) s = set() for i in range(m): s.add(arr1[i]) p = len(s) for i in range(n): s.add(arr2[i]) if (len(s) == p): print("arr2[] is subset of arr1[] ") else: print("arr2[] is not subset of arr1[] ") # This code is contributed by divyeshrabadiya07.
linear
linear
# Python3 program to find whether an array # is subset of another array # Return true if arr2[] is a subset of arr1[] def isSubset(arr1, m, arr2, n): # Create a Frequency Table using STL frequency = {} # Increase the frequency of each element # in the frequency table. for i in range(0, m): if arr1[i] in frequency: frequency[arr1[i]] = frequency[arr1[i]] + 1 else: frequency[arr1[i]] = 1 # Decrease the frequency if the # element was found in the frequency # table with the frequency more than 0. # else return 0 and if loop is # completed return 1. for i in range(0, n): if (frequency[arr2[i]] > 0): frequency[arr2[i]] -= 1 else: return False return True # Driver Code if __name__ == '__main__': arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) if (isSubset(arr1, m, arr2, n)): print("arr2[] is subset of arr1[] ") else: print("arr2[] is not a subset of arr1[] ") # This code is contributed by akhilsaini
linear
linear
# Python program to find all those # elements of arr1[] that are not # present in arr2[] def relativeComplement(arr1, arr2, n, m): i = 0 j = 0 while (i < n and j < m): # If current element in arr2[] is # greater, then arr1[i] can't be # present in arr2[j..m-1] if (arr1[i] < arr2[j]): print(arr1[i] , " ", end="") i += 1 # Skipping smaller elements of # arr2[] elif (arr1[i] > arr2[j]): j += 1 # Equal elements found (skipping # in both arrays) elif (arr1[i] == arr2[j]): i += 1 j += 1 # Printing remaining elements of # arr1[] while (i < n): print(arr1[i] , " ", end="") # Driver code arr1= [3, 6, 10, 12, 15] arr2 = [1, 3, 5, 10, 16] n = len(arr1) m = len(arr2) relativeComplement(arr1, arr2, n, m) # This code is contributed # by Anant Agarwal.
constant
linear
# Python3 Program to make all array equal # function for calculating min operations def minOps(arr, n, k): # max elements of array max1 = max(arr) res = 0 # iterate for all elements for i in range(0, n): # check if element can make equal to # max or not if not then return -1 if ((max1 - arr[i]) % k != 0): return -1 # else update res for # required operations else: res += (max1 - arr[i]) / k # return result return int(res) # driver program arr = [21, 33, 9, 45, 63] n = len(arr) k = 6 print(minOps(arr, n, k)) # This code is contributed by # Smitha Dinesh Semwal
constant
linear
# python code for above approach. def solve(A, B, C): # assigning the length -1 value # to each of three variables i = len(A) - 1 j = len(B) - 1 k = len(C) - 1 # calculating min difference # from last index of lists min_diff = abs(max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) while i != -1 and j != -1 and k != -1: current_diff = abs(max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) # checking condition if current_diff < min_diff: min_diff = current_diff # calculating max term from list max_term = max(A[i], B[j], C[k]) # Moving to smaller value in the # array with maximum out of three. if A[i] == max_term: i -= 1 elif B[j] == max_term: j -= 1 else: k -= 1 return min_diff # driver code A = [ 5, 8, 10, 15 ] B = [ 6, 9, 15, 78, 89 ] C = [ 2, 3, 6, 6, 8, 8, 10 ] print(solve(A, B, C))
constant
linear
# Program to convert binary tree to BST # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Helper function to store the inorder traversal of a tree def storeInorder(root, inorder): # Base Case if root is None: return # First store the left subtree storeInorder(root.left, inorder) # Copy the root's data inorder.append(root.data) # Finally store the right subtree storeInorder(root.right, inorder) # A helper function to count nodes in a binary tree def countNodes(root): if root is None: return 0 return countNodes(root.left) + countNodes(root.right) + 1 # Helper function that copies contents of sorted array # to Binary tree def arrayToBST(arr, root): # Base Case if root is None: return # First update the left subtree arrayToBST(arr, root.left) # now update root's data delete the value from array root.data = arr[0] arr.pop(0) # Finally update the right subtree arrayToBST(arr, root.right) # This function converts a given binary tree to BST def binaryTreeToBST(root): # Base Case: Tree is empty if root is None: return # Count the number of nodes in Binary Tree so that # we know the size of temporary array to be created n = countNodes(root) # Create the temp array and store the inorder traversal # of tree arr = [] storeInorder(root, arr) # Sort the array arr.sort() # copy array elements back to binary tree arrayToBST(arr, root) # Print the inorder traversal of the tree def printInorder(root): if root is None: return printInorder(root.left) print (root.data,end=" ") printInorder(root.right) # Driver program to test above function root = Node(10) root.left = Node(30) root.right = Node(15) root.left.left = Node(20) root.right.right = Node(5) # Convert binary tree to BST binaryTreeToBST(root) print ("Following is the inorder traversal of the converted BST") printInorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
linear
nlogn