Banana-Leopard/TASTY huggingface dataset:
# Python3 program to count minimum number of
# operations to get the given target array
 
# Returns count of minimum operations to
# convert a zero array to target array
# with increment and doubling operations.
# This function computes count by doing reverse
# steps, i.e., convert target to zero array.
def countMinOperations(target, n):
     
    # Initialize result (Count of minimum moves)
    result = 0;
 
    # Keep looping while all elements of
    # target don't become 0.
    while (True):
         
        # To store count of zeroes in
        # current target array
        zero_count = 0;
     
        # To find first odd element
        i = 0;
        while (i < n):
             
            # If odd number found
            if ((target[i] & 1) > 0):
                break;
 
            # If 0, then increment
            # zero_count
            elif (target[i] == 0):
                zero_count += 1;
            i += 1;
 
        # All numbers are 0
        if (zero_count == n):
            return result;
 
        # All numbers are even
        if (i == n):
             
            # Divide the whole array by 2
            # and increment result
            for j in range(n):
                target[j] = target[j] // 2;
            result += 1;
 
        # Make all odd numbers even by
        # subtracting one and increment result.
        for j in range(i, n):
            if (target[j] & 1):
                target[j] -= 1;
                result += 1;
 
# Driver Code
arr = [16, 16, 16];
n = len(arr);
print("Minimum number of steps required to",
          "\nget the given target array is",
                countMinOperations(arr, n));
 
# This code is contributed by mits

Time complexity: linear
Space complexity: constant
# Python program to find number of operations
# to make an array palindrome
 
# Returns minimum number of count operations
# required to make arr[] palindrome
def findMinOps(arr, n):
    ans = 0 # Initialize result
 
    # Start from two corners
    i,j = 0,n-1
    while i<=j:
        # If corner elements are same,
        # problem reduces arr[i+1..j-1]
        if arr[i] == arr[j]:
            i += 1
            j -= 1
 
        # If left element is greater, then
        # we merge right two elements
        elif arr[i] > arr[j]:
            # need to merge from tail.
            j -= 1
            arr[j] += arr[j+1]
            ans += 1
 
        # Else we merge left two elements
        else:
            i += 1
            arr[i] += arr[i-1]
            ans += 1
 
    return ans
 
 
# Driver program to test above
arr = [1, 4, 5, 9, 1]
n = len(arr)
print("Count of minimum operations is " + str(findMinOps(arr, n)))
 
# This code is contributed by Pratik Chhajer

Time complexity: linear
Space complexity: constant
# Python3 program to find the smallest
# positive value that cannot be
# represented as sum of subsets
# of a given sorted array
 
# Returns the smallest number
# that cannot be represented as sum
# of subset of elements from set
# represented by sorted array arr[0..n-1]
def findSmallest(arr, n):
 
    res = 1 #Initialize result
 
    # Traverse the array and increment
    # 'res' if arr[i] is smaller than
    # or equal to 'res'.
    for i in range (0, n ):
        if arr[i] <= res:
            res = res + arr[i]
        else:
            break
    return res
 
 
# Driver program to test above function
arr1 = [1, 3, 4, 5]
n1 = len(arr1)
print(findSmallest(arr1, n1))
 
arr2= [1, 2, 6, 10, 11, 15]
n2 = len(arr2)
print(findSmallest(arr2, n2))
 
arr3= [1, 1, 1, 1]
n3 = len(arr3)
print(findSmallest(arr3, n3))
 
arr4 = [1, 1, 3, 4]
n4 = len(arr4)
print(findSmallest(arr4, n4))
 
# This code is.contributed by Smitha Dinesh Semwal

Time complexity: nlogn
Space complexity: constant
# Python3 program to print largest contiguous array sum
 
from sys import maxsize
 
# Function to find the maximum contiguous subarray
# and print its starting and end index
def maxSubArraySum(a,size):
 
    max_so_far = -maxsize - 1
    max_ending_here = 0
    start = 0
    end = 0
    s = 0
 
    for i in range(0,size):
 
        max_ending_here += a[i]
 
        if max_so_far < max_ending_here:
            max_so_far = max_ending_here
            start = s
            end = i
 
        if max_ending_here < 0:
            max_ending_here = 0
            s = i+1
 
    return (end - start + 1)
 
# Driver program to test maxSubArraySum
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print(maxSubArraySum(a,len(a)))

Time complexity: linear
Space complexity: constant
# Python implementation of simple method to find
# minimum difference between any pair
 
# Returns minimum difference between any pair
 
 
def findMinDiff(arr, n):
    # Initialize difference as infinite
    diff = 10**20
 
    # Find the min diff by comparing difference
    # of all possible pairs in given array
    for i in range(n-1):
        for j in range(i+1, n):
            if abs(arr[i]-arr[j]) < diff:
                diff = abs(arr[i] - arr[j])
 
    # Return min diff
    return diff
 
 
# Driver code
if __name__ == "__main__":
    arr = [1, 5, 3, 19, 18, 25]
    n = len(arr)
 
    # Function call
    print("Minimum difference is " + str(findMinDiff(arr, n)))
 
# This code is contributed by Pratik Chhajer

Time complexity: quadratic
Space complexity: constant
# Python3 program to find minimum difference between
# any pair in an unsorted array
 
# Returns minimum difference between any pair
 
 
def findMinDiff(arr, n):
 
    # Sort array in non-decreasing order
    arr = sorted(arr)
 
    # Initialize difference as infinite
    diff = 10**20
 
    # Find the min diff by comparing adjacent
    # pairs in sorted array
    for i in range(n-1):
        if arr[i+1] - arr[i] < diff:
            diff = arr[i+1] - arr[i]
 
    # Return min diff
    return diff
 
 
# Driver code
if __name__ == "__main__":
    arr = [1, 5, 3, 19, 18, 25]
    n = len(arr)
 
    # Function call
    print("Minimum difference is " + str(findMinDiff(arr, n)))
 
# This code is contributed by Pratik Chhajer

Time complexity: nlogn
Space complexity: constant
# 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))
 
# This code is contributed by
# Smitha Dinesh Semwal

Time complexity: quadratic
Space complexity: constant
# 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)))
 
# This code is contributed by Abhijeet Nautiyal

Time complexity: linear
Space complexity: linear
# 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))
 
# This code is contributed by rag2127

Time complexity: linear
Space complexity: linear
# Python 3 program to print an array
# in alternate sorted manner.
 
# Function to print alternate sorted
# values
def alternateSort(arr, n):
 
    # Sorting the array
    arr.sort()
 
    # Printing the last element of array
    # first and then first element and then
    # second last element and then second
    # element and so on.
    i = 0
    j = n-1
     
    while (i < j):
     
        print(arr[j], end =" ")
        j-= 1
        print(arr[i], end =" ")
        i+= 1
 
    # If the total element in array is odd
    # then print the last middle element.
    if (n % 2 != 0):
        print(arr[i])
 
 
# Driver code
arr = [1, 12, 4, 6, 7, 10]
n = len(arr)
 
alternateSort(arr, n)
 
# This code is contributed by
# Smitha Dinesh Semwal

Time complexity: nlogn
Space complexity: constant
# Function to sort an array using
# insertion sort
 
def insertionSort(A, size):
    i, key, j = 0, 0, 0
    for i in range(size):
        key = A[i]
        j = i-1
 
        # Move elements of A[0..i-1], that are
        # greater than key, to one position
        # ahead of their current position.
        # This loop will run at most k times
        while j >= 0 and A[j] > key:
            A[j + 1] = A[j]
            j = j - 1
        A[j + 1] = key

Time complexity: constant
Space complexity: constant
# A Python3 program to sort a
# nearly sorted array.
 
from heapq import heappop, heappush, heapify
 
 
# A utility function to print
# array elements
def print_array(arr: list):
    for elem in arr:
        print(elem, end=' ')
 
# Given an array of size n, where every
# element is k away from its target
# position, sorts the array in O(nLogk) time.
 
 
def sort_k(arr: list, n: int, k: int):
    """
    :param arr: input array
    :param n: length of the array
    :param k: max distance, which every
     element is away from its target position.
    :return: None
    """
    # List of first k+1 items
    heap = arr[:k + 1]
 
    # using heapify to convert list
    # into heap(or min heap)
    heapify(heap)
 
    # "rem_elmnts_index" is index for remaining
    # elements in arr and "target_index" is
    # target index of for current minimum element
    # in Min Heap "heap".
    target_index = 0
    for rem_elmnts_index in range(k + 1, n):
        arr[target_index] = heappop(heap)
        heappush(heap, arr[rem_elmnts_index])
        target_index += 1
 
    while heap:
        arr[target_index] = heappop(heap)
        target_index += 1
 
 
# Driver Code
k = 3
arr = [2, 6, 3, 12, 56, 8]
n = len(arr)
sort_k(arr, n, k)
 
print('Following is sorted array')
print_array(arr)
 
# This code is contributed by
# Veerat Beri(viratberi)

Time complexity: nlogn
Space complexity: logn
# Python function to sort the array arr[0..n-1] in wave form,
# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]
def sortInWave(arr, n):
     
    #sort the array
    arr.sort()
    
    # Swap adjacent elements
    for i in range(0,n-1,2):
        arr[i], arr[i+1] = arr[i+1], arr[i]
 
# Driver program
arr = [10, 90, 49, 2, 1, 5, 23]
sortInWave(arr, len(arr))
for i in range(0,len(arr)):
    print (arr[i],end=" ")
     
# This code is contributed by __Devesh Agrawal__

Time complexity: nlogn
Space complexity: constant
# Python function to sort the array arr[0..n-1] in wave form,
# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]
 
 
def sortInWave(arr, n):
 
    # Traverse all even elements
    for i in range(0, n - 1, 2):
 
        # If current even element is smaller than previous
        if (i > 0 and arr[i] < arr[i-1]):
            arr[i], arr[i-1] = arr[i-1], arr[i]
 
        # If current even element is smaller than next
        if (i < n-1 and arr[i] < arr[i+1]):
            arr[i], arr[i+1] = arr[i+1], arr[i]
 
 
# Driver program
arr = [10, 90, 49, 2, 1, 5, 23]
sortInWave(arr, len(arr))
for i in range(0, len(arr)):
    print(arr[i], end=" ")
 
# This code is contributed by __Devesh Agrawal__

Time complexity: linear
Space complexity: constant
# Python program to Merge an array of
# size n into another array of size m + n
 
NA = -1
 
# Function to move m elements
# at the end of array mPlusN[]
 
 
def moveToEnd(mPlusN, size):
 
    i = 0
    j = size - 1
    for i in range(size-1, -1, -1):
        if (mPlusN[i] != NA):
 
            mPlusN[j] = mPlusN[i]
            j -= 1
 
# Merges array N[]
# of size n into array mPlusN[]
# of size m+n
 
 
def merge(mPlusN, N, m, n):
 
    i = n  # Current index of i/p part of mPlusN[]
    j = 0  # Current index of N[]
    k = 0  # Current index of output mPlusN[]
    while (k < (m+n)):
 
        # Take an element from mPlusN[] if
        # a) value of the picked
        # element is smaller and we have
        # not reached end of it
        # b) We have reached end of N[] */
        if ((j == n) or (i < (m+n) and mPlusN[i] <= N[j])):
 
            mPlusN[k] = mPlusN[i]
            k += 1
            i += 1
 
        else:  # Otherwise take element from N[]
 
            mPlusN[k] = N[j]
            k += 1
            j += 1
 
# Utility that prints
# out an array on a line
 
 
def printArray(arr, size):
 
    for i in range(size):
        print(arr[i], " ", end="")
 
    print()
 
 
# Driver function to
# test above functions
 
# Initialize arrays
mPlusN = [2, 8, NA, NA, NA, 13, NA, 15, 20]
N = [5, 7, 9, 25]
n = len(N)
 
m = len(mPlusN) - n
 
# Move the m elements
# at the end of mPlusN
moveToEnd(mPlusN, m+n)
 
# Merge N[] into mPlusN[]
merge(mPlusN, N, m, n)
 
# Print the resultant mPlusN
printArray(mPlusN, m+n)
 
# This code is contributed
# by Anant Agarwal.

Time complexity: linear
Space complexity: constant
# Python 3 program to test whether an array
# can be sorted by swapping adjacent
# elements using a boolean array
 
 
# Return true if array can be
# sorted otherwise false
def sortedAfterSwap(A, B, n) :
 
    # Check bool array B and sorts
    # elements for continuous sequence of 1
    for i in range(0, n - 1) :
        if (B[i]== 1) :
            j = i
            while (B[j]== 1) :
                j = j + 1
  
            # Sort array A from i to j
            A = A[0:i] + sorted(A[i:j + 1]) + A[j + 1:]
            i = j
         
         
    # Check if array is sorted or not
    for i in range(0, n) :
        if (A[i] != i + 1) :
            return False
     
  
    return True
 
  
# Driver program to test sortedAfterSwap()
A = [ 1, 2, 5, 3, 4, 6 ]
B = [ 0, 1, 1, 1, 0 ]
n = len(A)
 
if (sortedAfterSwap(A, B, n)) :
    print("A can be sorted")
else :
    print("A can not be sorted")
     
 
# This code is contributed
# by Nikita Tiwari.

Time complexity: quadratic
Space complexity: constant
# Python3 program to test whether array
# can be sorted by swapping adjacent
# elements using boolean array
 
# Return true if array can be
# sorted otherwise false
def sortedAfterSwap(A,B,n):
    for i in range(0,n-1):
        if B[i]:
            if A[i]!=i+1:
                A[i], A[i+1] = A[i+1], A[i]
 
    # Check if array is sorted or not
    for i in range(n):
        if A[i]!=i+1:
            return False
    return True
 
# Driver program
if __name__=='__main__':
    A = [1, 2, 5, 3, 4, 6]
    B = [0, 1, 1, 1, 0]
    n =len(A)
    if (sortedAfterSwap(A, B, n)) :
        print("A can be sorted")
    else :
        print("A can not be sorted")
 
# This code is contributed by
# Shrikant13

Time complexity: linear
Space complexity: constant
# Python3 program to sort an array with
# two types of values in one traversal.
 
# Method for segregation 0 and
# 1 given input array
def segregate0and1(arr, n):
 
    type0 = 0; type1 = n - 1
 
    while (type0 < type1):
        if (arr[type0] == 1):
            arr[type0], arr[type1] = arr[type1], arr[type0]
            type1 -= 1
         
        else:
            type0 += 1
         
# Driver Code
arr = [1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1]
n = len(arr)
segregate0and1(arr, n)
for i in range(0, n):
    print(arr[i], end = " ")
 
# This code is contributed by Smitha Dinesh Semwal

Time complexity: linear
Space complexity: constant
# Python3 program that performs the following
# operations: Sort elements by frequency. If two elements
# have same count, then put the elements that appears first
 
# Used for sorting
 
 
class ele:
    def __init__(self):
 
        self.count = 0
        self.index = 0
        self.val = 0
 
 
def mycomp(a):
    return a.val
 
# Used for sorting by frequency. And if frequency is same,
# then by appearance
 
 
def mycomp2(a):
    # using negative value for a.index
    # since the sorting should be in
    # descending order
    return (a.count, -a.index)
 
 
def sortByFrequency(arr, n):
    element = [None for _ in range(n)]
    for i in range(n):
 
        element[i] = ele()
 
        # Fill Indexes
        element[i].index = i
 
        # Initialize counts as 0
        element[i].count = 0
 
        # Fill values in structure
        # elements
        element[i].val = arr[i]
 
    # Sort the structure elements according to value,
    # we used stable sort so relative order is maintained.
    #
    element.sort(key=mycomp)
 
    # initialize count of first element as 1
    element[0].count = 1
 
    # Count occurrences of remaining elements
    for i in range(1, n):
 
        if (element[i].val == element[i - 1].val):
            element[i].count += element[i - 1].count + 1
 
            # Set count of previous element as -1, we are
            #  doing this because we'll again sort on the
            #  basis of counts (if counts are equal than on
            # the basis of index)*/
            element[i - 1].count = -1
 
            # Retain the first index (Remember first index
            #  is always present in the first duplicate we
            #  used stable sort. */
            element[i].index = element[i - 1].index
 
        # Else If previous element is not equal to current
        #  so set the count to 1
        else:
            element[i].count = 1
 
    # Now we have counts and first index for each element
    # so now sort on the basis of count and in case of tie
    # use index to sort.*/
    element.sort(key=mycomp2)
 
    index = 0
    for i in range(n - 1, -1, -1):
        if (element[i].count != -1):
            for j in range(element[i].count):
                arr[index] = element[i].val
                index += 1
 
 
# Driver code
arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]
n = len(arr)
 
# Function call
sortByFrequency(arr, n)
 
print(*arr)
 
# This code is contributed by phasing17

Time complexity: nlogn
Space complexity: linear
# Python3 program for above approach
 
from collections import defaultdict
 
# Sort by Frequency
 
 
def sortByFreq(arr, n):
    # arr -> Array to be sorted
    # n   -> Length of Array
 
    # d is a hashmap(referred as dictionary in python)
    d = defaultdict(lambda: 0)
    for i in range(n):
        d[arr[i]] += 1
 
    # Sorting the array 'arr' where key
    # is the function based on which
    # the array is sorted
    # While sorting we want to give
    # first priority to Frequency
    # Then to value of item
    arr.sort(key=lambda x: (-d[x], x))
 
    return (arr)
 
 
# Driver code
if __name__ == "__main__":
    arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]
    n = len(arr)
 
    # Function call
    solution = sortByFreq(arr, n)
    print(*solution)

Time complexity: nlogn
Space complexity: linear
# Python3 program to count
# inversions in an array
 
 
def getInvCount(arr, n):
 
    inv_count = 0
    for i in range(n):
        for j in range(i + 1, n):
            if (arr[i] > arr[j]):
                inv_count += 1
 
    return inv_count
 
 
# Driver Code
arr = [1, 20, 6, 4, 5]
n = len(arr)
print("Number of inversions are",
      getInvCount(arr, n))
 
# This code is contributed by Smitha Dinesh Semwal

Time complexity: quadratic
Space complexity: constant
# Python 3 program to count inversions in an array
 
# Function to Use Inversion Count
 
 
def mergeSort(arr, n):
    # A temp_arr is created to store
    # sorted array in merge function
    temp_arr = [0]*n
    return _mergeSort(arr, temp_arr, 0, n-1)
 
# This Function will use MergeSort to count inversions
 
 
def _mergeSort(arr, temp_arr, left, right):
 
    # A variable inv_count is used to store
    # inversion counts in each recursive call
 
    inv_count = 0
 
    # We will make a recursive call if and only if
    # we have more than one elements
 
    if left < right:
 
        # mid is calculated to divide the array into two subarrays
        # Floor division is must in case of python
 
        mid = (left + right)//2
 
        # It will calculate inversion
        # counts in the left subarray
 
        inv_count += _mergeSort(arr, temp_arr,
                                left, mid)
 
        # It will calculate inversion
        # counts in right subarray
 
        inv_count += _mergeSort(arr, temp_arr,
                                mid + 1, right)
 
        # It will merge two subarrays in
        # a sorted subarray
 
        inv_count += merge(arr, temp_arr, left, mid, right)
    return inv_count
 
# This function will merge two subarrays
# in a single sorted subarray
 
 
def merge(arr, temp_arr, left, mid, right):
    i = left     # Starting index of left subarray
    j = mid + 1  # Starting index of right subarray
    k = left     # Starting index of to be sorted subarray
    inv_count = 0
 
    # Conditions are checked to make sure that
    # i and j don't exceed their
    # subarray limits.
 
    while i <= mid and j <= right:
 
        # There will be no inversion if arr[i] <= arr[j]
 
        if arr[i] <= arr[j]:
            temp_arr[k] = arr[i]
            k += 1
            i += 1
        else:
            # Inversion will occur.
            temp_arr[k] = arr[j]
            inv_count += (mid-i + 1)
            k += 1
            j += 1
 
    # Copy the remaining elements of left
    # subarray into temporary array
    while i <= mid:
        temp_arr[k] = arr[i]
        k += 1
        i += 1
 
    # Copy the remaining elements of right
    # subarray into temporary array
    while j <= right:
        temp_arr[k] = arr[j]
        k += 1
        j += 1
 
    # Copy the sorted subarray into Original array
    for loop_var in range(left, right + 1):
        arr[loop_var] = temp_arr[loop_var]
 
    return inv_count
 
 
# Driver Code
# Given array is
arr = [1, 20, 6, 4, 5]
n = len(arr)
result = mergeSort(arr, n)
print("Number of inversions are", result)
 
# This code is contributed by ankush_953

Time complexity: nlogn
Space complexity: linear