Banana-Leopard/TASTY huggingface dataset:
# Python3 program to print the maximum elements
# giving second array higher priority
 
# Function to maximize array elements
def maximizeArray(arr1, arr2, n):
     
    # Auxiliary array arr3 to store
    # elements of arr1 & arr2
    arr3 = [0] * (2 * n)
    k = 0
     
    for i in range(n):
        arr3[k] = arr1[i]
        k += 1
         
    for i in range(n):
        arr3[k] = arr2[i]
        k += 1
 
    # Hash table to store n largest
    # unique elements
    hash = {}
 
    # Sorting arr3 in decreasing order
    arr3 = sorted(arr3)
    arr3 = arr3[::-1]
 
    # Finding n largest unique elements
    # from arr3 and storing in hash
    i = 0
    while (len(hash) != n):
 
        # If arr3 element not present in hash,
        # then store this element in hash
        if (arr3[i] not in hash):
            hash[arr3[i]] = 1
 
        i += 1
 
    # Store that elements of arr2 in arr3
    # that are present in hash
    k = 0
    for i in range(n):
 
        # If arr2 element is present in
        # hash, store it in arr3
        if (arr2[i] in hash):
            arr3[k] = arr2[i]
            k += 1
             
            del hash[arr2[i]]
 
    # Store that elements of arr1 in arr3
    # that are present in hash
    for i in range(n):
 
        # If arr1 element is present
        # in hash, store it in arr3
        if (arr1[i] in hash):
            arr3[k] = arr1[i]
            k += 1
             
            del hash[arr1[i]]
 
    # Copying 1st n elements of
    # arr3 to arr1
    for i in range(n):
        arr1[i] = arr3[i]
 
# Function to print array elements
def printArray(arr, n):
     
    for i in arr:
        print(i, end = " ")
         
    print()
 
# Driver Code
if __name__ == '__main__':
     
    array1 = [ 7, 4, 8, 0, 1 ]
    array2 = [ 9, 7, 2, 3, 6 ]
    size = len(array1)
     
    maximizeArray(array1, array2, size)
    printArray(array1, size)
     
# This code is contributed by mohit kumar 29

Time complexity: nlogn
Space complexity: linear
# Python3 implementation to count
# subarrays with equal number
# of 1's and 0's
 
# function to count subarrays with
# equal number of 1's and 0's
 
 
def countSubarrWithEqualZeroAndOne(arr, n):
 
    # 'um' implemented as hash table
    # to store frequency of values
    # obtained through cumulative sum
    um = dict()
    curr_sum = 0
 
    # Traverse original array and compute
    # cumulative sum and increase count
    # by 1 for this sum in 'um'.
    # Adds '-1' when arr[i] == 0
    for i in range(n):
        curr_sum += (-1 if (arr[i] == 0) else arr[i])
        if um.get(curr_sum):
            um[curr_sum] += 1
        else:
            um[curr_sum] = 1
 
    count = 0
 
    # traverse the hash table 'um'
    for itr in um:
 
        # If there are more than one
        # prefix subarrays with a
        # particular sum
        if um[itr] > 1:
            count += ((um[itr] * int(um[itr] - 1)) / 2)
 
    # add the subarrays starting from
    # 1st element and have equal
    # number of 1's and 0's
    if um.get(0):
        count += um[0]
 
    # required count of subarrays
    return int(count)
 
 
# Driver code to test above
arr = [1, 0, 0, 1, 0, 1, 1]
n = len(arr)
print("Count =",
      countSubarrWithEqualZeroAndOne(arr, n))
 
# This code is contributed by "Sharad_Bhardwaj".

Time complexity: linear
Space complexity: linear
# Python3 implementation to count subarrays
# with equal number of 1's and 0's
 
 
def countSubarrWithEqualZeroAndOne(arr, n):
    mp = dict()
    Sum = 0
    count = 0
 
    for i in range(n):
 
        # Replacing 0's in array with -1
        if (arr[i] == 0):
            arr[i] = -1
 
        Sum += arr[i]
 
        # If Sum = 0, it implies number of
        # 0's and 1's are equal from arr[0]..arr[i]
        if (Sum == 0):
            count += 1
 
        if (Sum in mp.keys()):
            count += mp[Sum]
 
        mp[Sum] = mp.get(Sum, 0) + 1
 
    return count
 
 
# Driver Code
arr = [1, 0, 0, 1, 0, 1, 1]
 
n = len(arr)
 
print("count =",
      countSubarrWithEqualZeroAndOne(arr, n))
 
# This code is contributed by mohit kumar

Time complexity: linear
Space complexity: linear
# Python 3 implementation to find the length of
# longest subarray having count of 1's one
# more than count of 0's
 
# function to find the length of longest
# subarray having count of 1's one more
# than count of 0's
 
 
def lenOfLongSubarr(arr, n):
 
    # unordered_map 'um' implemented as
    # hash table
    um = {}
    sum = 0
    maxLen = 0
 
    # traverse the given array
    for i in range(n):
 
        # consider '0' as '-1'
        if arr[i] == 0:
            sum += -1
        else:
            sum += 1
 
        # when subarray starts form index '0'
        if (sum == 1):
            maxLen = i + 1
 
        # make an entry for 'sum' if it is
        # not present in 'um'
        elif (sum not in um):
            um[sum] = i
 
        # check if 'sum-1' is present in 'um'
        # or not
        if ((sum - 1) in um):
            # update maxLength
            if (maxLen < (i - um[sum - 1])):
                maxLen = i - um[sum - 1]
 
    # required maximum length
    return maxLen
 
 
# Driver code
if __name__ == '__main__':
    arr = [0, 1, 1, 0, 0, 1]
    n = len(arr)
    print("Length =", lenOfLongSubarr(arr, n))
 
# This code is contributed by
# Surendra_Gangwar

Time complexity: linear
Space complexity: linear
# Python3 program to find substring with equal
# number of 0's, 1's and 2's
 
# Method to count number of substring which
# has equal 0, 1 and 2
def getSubstringWithEqual012(string):
    N = len(string)
 
    # map to store, how many times a difference
    # pair has occurred previously
    mp = dict()
    mp[(0, 0)] = 1
 
    # zc (Count of zeroes), oc(Count of 1s)
    # and tc(count of twos)
    # In starting all counts are zero
    zc, oc, tc = 0, 0, 0
 
    # looping into string
    res = 0 # Initialize result
    for i in range(N):
 
        # increasing the count of current character
        if string[i] == '0':
            zc += 1
        elif string[i] == '1':
            oc += 1
        else:
            tc += 1 # Assuming that string doesn't contain
                    # other characters
 
        # making pair of differences (z[i] - o[i],
        # z[i] - t[i])
        tmp = (zc - oc, zc - tc)
 
        # Count of previous occurrences of above pair
        # indicates that the subarrays forming from
        # every previous occurrence to this occurrence
        # is a subarray with equal number of 0's, 1's
        # and 2's
        if tmp not in mp:
            res += 0
        else:
            res += mp[tmp]
 
        # increasing the count of current difference
        # pair by 1
        if tmp in mp:
            mp[tmp] += 1
        else:
            mp[tmp] = 1
 
    return res
 
# Driver's Code
if __name__ == "__main__":
    string = "0102010"
    print(getSubstringWithEqual012(string))
 
# This code is contributed by
# sanjeev2552

Time complexity: nlogn
Space complexity: linear
# Python program to print all
# triplets in given array
# that form Arithmetic
# Progression
 
# Function to print
# all triplets in
# given sorted array
# that forms AP
def printAllAPTriplets(arr, n) :
 
    s = [];
    for i in range(0, n - 1) :
     
        for j in range(i + 1, n) :
         
            # Use hash to find if
            # there is a previous
            # element with difference
            # equal to arr[j] - arr[i]
            diff = arr[j] - arr[i];
 
            if ((arr[i] - diff) in arr) :
                print ("{} {} {}" .
                        format((arr[i] - diff),
                                arr[i], arr[j]),
                                    end = "\n");
         
    s.append(arr[i]);
     
# Driver code
arr = [2, 6, 9, 12, 17,
       22, 31, 32, 35, 42];
n = len(arr);
printAllAPTriplets(arr, n);
 
# This code is contributed by
# Manish Shaw(manishshaw1)

Time complexity: quadratic
Space complexity: linear
# python 3 program to print all triplets in given
# array that form Arithmetic Progression
  
# Function to print all triplets in
# given sorted array that forms AP
def printAllAPTriplets(arr, n):
  
    for i in range(1, n - 1):
  
        # Search other two elements of
        # AP with arr[i] as middle.
        j = i - 1
        k = i + 1
        while(j >= 0 and k < n ):
  
            # if a triplet is found
            if (arr[j] + arr[k] == 2 * arr[i]):
                print(arr[j], "", arr[i], "", arr[k])
  
                # Since elements are distinct,
                # arr[k] and arr[j] cannot form
                # any more triplets with arr[i]
                k += 1
                j -= 1
              
  
            # If middle element is more move to
            # higher side, else move lower side.
            elif (arr[j] + arr[k] < 2 * arr[i]):
                k += 1    
            else:
                j -= 1    
          
# Driver code
arr = [ 2, 6, 9, 12, 17,
        22, 31, 32, 35, 42 ]
n = len(arr)
printAllAPTriplets(arr, n)
  
# This article is contributed
# by Smitha Dinesh Semwal

Time complexity: quadratic
Space complexity: constant
# Python program to find unique triplets
# that sum up to a given value.
 
# Function to find unique triplets that
# sum up to a given value.
def findTriplets(nums, n, Sum):
    i = 0
    j = 0
    k = 0
 
    # list to store all unique triplets.
    triplet = []
 
    # list to store already found triplets
    # to avoid duplication.
    uniqTriplets = []
 
    # Variable used to hold triplet
    # converted to string form.
    temp = ""
 
    # Variable used to store current
    # triplet which is stored in vector
    # if it is unique.
    newTriplet = [0, 0, 0]
 
    # Sort the input array.
    nums.sort()
 
    # Iterate over the array from the
    # start and consider it as the
    # first element.
    for i in range(n - 2):
         
        # index of the first element in
        # the remaining elements.
        j = i + 1
 
        # index of the last element.
        k = n - 1
 
        while(j < k):
           
            # If sum of triplet is equal to
            # given value, then check if
            # this triplet is unique or not.
            # To check uniqueness, convert
            # triplet to string form and
            # then check if this string is
            # present in set or not. If
            # triplet is unique, then store
            # it in list.
            if(nums[i] + nums[j] + nums[k] == Sum):
                temp = str(nums[i]) + ":" + str(nums[j]) + ":" + str(nums[k])
                if temp not in uniqTriplets:
                    uniqTriplets.append(temp)
                    newTriplet[0] = nums[i]
                    newTriplet[1] = nums[j]
                    newTriplet[2] = nums[k]
                    triplet.append(newTriplet)
                    newTriplet = [0, 0, 0]
 
                # Increment the first index
                # and decrement the last
                # index of remaining elements.
                j += 1
                k -= 1
                 
            # If sum is greater than given
            # value then to reduce sum
            # decrement the last index.
            elif(nums[i] + nums[j] + nums[k] > Sum):
                k -= 1
                 
            # If sum is less than given value
            # then to increase sum increment
            # the first index of remaining
            # elements.
            else:
                j += 1
 
    # If no unique triplet is found, then
       # return 0.
    if(len(triplet) == 0):
        return 0
     
    # Print all unique triplets stored in
    # list.
    for i in range(len(triplet)):
        print(triplet[i], end = ", ")
    return 1
 
# Driver Code
nums = [12, 3, 6, 1, 6, 9]
n = len(nums)
Sum = 24
 
# Function call
if(not findTriplets(nums, n, Sum)):
    print("No triplets can be formed.")
 
# This code is contributed by rag2127

Time complexity: quadratic
Space complexity: linear
# Python3 program to count
# triplets with given product m
 
# Method to count such triplets
def countTriplets(arr, n, m):
     
    count = 0
 
    # Consider all triplets and count if
    # their product is equal to m
    for i in range (n - 2):
        for j in range (i + 1, n - 1):
            for k in range (j + 1, n):
                if (arr[i] * arr[j] * arr[k] == m):
                    count += 1
    return count
 
# Driver code
if __name__ == "__main__":
   
    arr = [1, 4, 6, 2, 3, 8]
    m = 24
    print(countTriplets(arr,
                        len(arr), m))
 
# This code is contributed by Chitranayal

Time complexity: cubic
Space complexity: constant
# Python3 program for the above approach
 
# Function to find the triplet
def countTriplets(li,product):
    flag = 0
    count = 0
     
    # Consider all pairs and check
    # for a third number so their
    # product is equal to product
    for i in range(len(li)):
         
        # Check if current pair
        # divides product or not
        # If yes, then search for
        # (product / li[i]*li[j])
        if li[i]!= 0 and product % li[i] == 0:
             
            for j in range(i+1, len(li)):
                
                # Check if the third number is present
                # in the map and it is not equal to any
                # other two elements and also check if
                # this triplet is not counted already
                # using their indexes
                if li[j]!= 0 and product % (li[j]*li[i]) == 0:
                    if product // (li[j]*li[i]) in li:
                     
                        n = li.index(product//(li[j]*li[i]))
                     
                        if n > i and n > j:
                            flag = 1
                            count+=1
    print(count)
    
# Driver code
li = [  1, 4, 6, 2, 3, 8 ]
product = 24
 
# Function call
countTriplets(li,product)

Time complexity: quadratic
Space complexity: linear
# Python3 program to
# count of pairs with equal
# elements in an array.
 
# Return the number of
# pairs with equal values.
def countPairs(arr, n):
 
    ans = 0
 
    # for each index i and j
    for i in range(0 , n):
        for j in range(i + 1, n):
 
            # finding the index
            # with same value but
            # different index.
            if (arr[i] == arr[j]):
                ans += 1
    return ans
 
# Driven Code
arr = [1, 1, 2 ]
n = len(arr)
print(countPairs(arr, n))
 
# This code is contributed
# by Smitha

Time complexity: quadratic
Space complexity: constant
# Python3 program to count of index pairs
# with equal elements in an array.
import math as mt
 
# Return the number of pairs with
# equal values.
def countPairs(arr, n):
 
    mp = dict()
 
    # Finding frequency of each number.
    for i in range(n):
        if arr[i] in mp.keys():
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
             
    # Calculating pairs of each value.
    ans = 0
    for it in mp:
        count = mp[it]
        ans += (count * (count - 1)) // 2
    return ans
 
# Driver Code
arr = [1, 1, 2]
n = len(arr)
print(countPairs(arr, n))
 
# This code is contributed by mohit kumar 29

Time complexity: linear
Space complexity: linear
# python program for above implementation
 
# Function to count numbers to be added
def countNum(arr, n):
     
    count = 0
 
    # Sort the array
    arr.sort()
 
    # Check if elements are consecutive
    # or not. If not, update count
    for i in range(0, n-1):
        if (arr[i] != arr[i+1] and
            arr[i] != arr[i + 1] - 1):
            count += arr[i + 1] - arr[i] - 1;
 
    return count
 
# Drivers code
arr = [ 3, 5, 8, 6 ]
n = len(arr)
print(countNum(arr, n))
 
# This code is contributed by Sam007

Time complexity: nlogn
Space complexity: constant
# Function to count numbers to be added
def countNum(arr, n):
 
    s = dict()
    count, maxm, minm = 0, -10**9, 10**9
 
    # Make a hash of elements and store
    # minimum and maximum element
    for i in range(n):
        s[arr[i]] = 1
        if (arr[i] < minm):
            minm = arr[i]
        if (arr[i] > maxm):
            maxm = arr[i]
     
    # Traverse all elements from minimum
    # to maximum and count if it is not
    # in the hash
    for i in range(minm, maxm + 1):
        if i not in s.keys():
            count += 1
    return count
 
# Driver code
arr = [3, 5, 8, 6 ]
n = len(arr)
print(countNum(arr, n))
     
# This code is contributed by mohit kumar

Time complexity: linear
Space complexity: constant
# Python 3 program to calculate sum of
# lengths of subarrays of distinct elements.
 
# Returns sum of lengths of all subarrays
# with distinct elements.
def sumoflength(arr, n):
 
    # For maintaining distinct elements.
    s = []
 
    # Initialize ending point and result
    j = 0
    ans = 0
 
    # Fix starting point
    for i in range(n):
         
        # Find ending point for current
        # subarray with distinct elements.
        while (j < n and (arr[j] not in s)):
            s.append(arr[j])
            j += 1
 
        # Calculating and adding all possible
        # length subarrays in arr[i..j]
        ans += ((j - i) * (j - i + 1)) // 2
 
        # Remove arr[i] as we pick new
        # starting point from next
        s.remove(arr[i])
 
    return ans
 
# Driven Code
if __name__=="__main__":
     
    arr = [1, 2, 3, 4]
    n = len(arr)
    print(sumoflength(arr, n))
 
# This code is contributed by ita_c

Time complexity: linear
Space complexity: linear
# Python3 program Count total number of
# sub-arrays having total distinct elements
# same as that original array.
 
# Function to calculate distinct sub-array
def countDistictSubarray(arr, n):
 
    # Count distinct elements in whole array
    vis = dict()
    for i in range(n):
        vis[arr[i]] = 1
    k = len(vis)
 
    # Reset the container by removing
    # all elements
    vid = dict()
 
    # Use sliding window concept to find
    # count of subarrays having k distinct
    # elements.
    ans = 0
    right = 0
    window = 0
    for left in range(n):
     
        while (right < n and window < k):
 
            if arr[right] in vid.keys():
                vid[ arr[right] ] += 1
            else:
                vid[ arr[right] ] = 1
 
            if (vid[ arr[right] ] == 1):
                window += 1
 
            right += 1
         
        # If window size equals to array distinct
        # element size, then update answer
        if (window == k):
            ans += (n - right + 1)
 
        # Decrease the frequency of previous
        # element for next sliding window
        vid[ arr[left] ] -= 1
 
        # If frequency is zero then decrease
        # the window size
        if (vid[ arr[left] ] == 0):
            window -= 1
     
    return ans
 
# Driver code
arr = [2, 1, 3, 2, 3]
n = len(arr)
 
print(countDistictSubarray(arr, n))
 
# This code is contributed by
# mohit kumar 29

Time complexity: linear
Space complexity: linear
# Python3 program to find largest consecutive
# numbers present in arr.
 
def findLongestConseqSubseq(arr, n):
    '''We insert all the array elements into unordered set.'''
 
    S = set();
    for i in range(n):
        S.add(arr[i]);
 
    # check each possible sequence from the start
    # then update optimal length
    ans = 0;
    for i in range(n):
         
        # if current element is the starting
        # element of a sequence
        if S.__contains__(arr[i]):
             
            # Then check for next elements in the
            # sequence
            j = arr[i];
             
            # increment the value of array element
            # and repeat search in the set
            while(S.__contains__(j)):
                j += 1;
 
            # Update optimal length if this length
            # is more. To get the length as it is
            # incremented one by one
            ans = max(ans, j - arr[i]);
    return ans;
 
# Driver code
if __name__ == '__main__':
    arr = [ 1, 94, 93, 1000, 5, 92, 78 ];
    n = len(arr);
    print(findLongestConseqSubseq(arr, n));
 
# This code is contributed by 29AjayKumar

Time complexity: quadratic
Space complexity: linear
# Python3 program to implement the
# above approach
# Make a set of maximum elements
# from two arrays A[] and B[]
from collections import defaultdict
 
def maximizeTheFirstArray(A, B, n):
 
    # Create copies of A[] and B[]
    # and sort the copies in
    # descending order.
    temp1 = A.copy()
    temp2 = B.copy()
    temp1.sort(reverse = True)
    temp2.sort(reverse = True)
 
    # Put maximum n distinct
    # elements of both sorted
    # arrays in a map.
    m = defaultdict(int)
    i = 0
    j = 0;
     
    while (len(m) < n):
         if (temp1[i] >= temp2[j]):
            m[temp1[i]] += 1
            i += 1       
         else:
            m[temp2[j]] += 1
            j += 1
 
    # Copy elements of A[] to that
    # are present in hash m.
    res = []
     
    for i in range (n):
        if (A[i] in m):
           res.append(A[i])
 
    # Copy elements of B[] to that
    # are present in hash m. This time
    # we also check if the element did
    # not appear twice.
    for i in range (n):
        if (B[i] in m and
            m[B[i]] == 1):
           res.append(B[i])
 
    # Print result
    for i in range (n):
        print (res[i], end = " ")
 
# Driver code
if __name__ == "__main__":
   
    A = [9, 7, 2, 3, 6]
    B = [7, 4, 8, 0, 1]
    n = len(A)
    maximizeTheFirstArray(A, B, n);
   
# This code is contributed by Chitranayal

Time complexity: nlogn
Space complexity: linear
# Python3 implementation to
# find the maximum number
# of chocolates to be
# distributed equally
# among k students
 
# function to find the
# maximum number of chocolates
# to be distributed equally
# among k students
def maxNumOfChocolates(arr, n, k):
     
    um, curr_rem, maxSum = {}, 0, 0
     
    # 'sm[]' to store cumulative sm,
    # where sm[i] = sm(arr[0]+..arr[i])
    sm = [0]*n
    sm[0] = arr[0]
     
    # building up 'sm[]'
    for i in range(1, n):
        sm[i] = sm[i - 1] + arr[i]
         
    # traversing 'sm[]'
    for i in range(n):
 
        # finding current remainder
        curr_rem = sm[i] % k
         
        if (not curr_rem and maxSum < sm[i]) :
            maxSum = sm[i]
        elif (not curr_rem in um) :
            um[curr_rem] = i
        elif (maxSum < (sm[i] - sm[um[curr_rem]])):
              maxSum = sm[i] - sm[um[curr_rem]]
         
    return maxSum//k
     
# Driver program to test above
arr = [ 2, 7, 6, 1, 4, 5 ]
n, k = len(arr), 3
 
print("Maximum number of chocolates: " +
     str(maxNumOfChocolates(arr, n, k)))
 
# This code is contributed by Ansu Kumari

Time complexity: linear
Space complexity: linear
# Python 3 program to print n-th
# number in Recaman's sequence
 
# Prints first n terms of Recaman
# sequence
def recaman(n):
 
    # Create an array to store terms
    arr = [0] * n
 
    # First term of the sequence
    # is always 0
    arr[0] = 0
    print(arr[0], end=", ")
 
    # Fill remaining terms using
    # recursive formula.
    for i in range(1, n):
     
        curr = arr[i-1] - i
        for j in range(0, i):
         
            # If arr[i-1] - i is
            # negative or already
            # exists.
            if ((arr[j] == curr) or curr < 0):
                curr = arr[i-1] + i
                break
             
        arr[i] = curr
        print(arr[i], end=", ")
 
# Driver code
n = 17
 
recaman(n)
 
# This code is contributed by Smitha.

Time complexity: quadratic
Space complexity: linear
# Python3 program to print n-th number in
# Recaman's sequence
 
# Prints first n terms of Recaman sequence
def recaman(n):
 
    if(n <= 0):
        return
 
    # Print first term and store it in a hash
    print(0, ",", end='')
    s = set([])
    s.add(0)
 
    # Print remaining terms using recursive
    # formula.
    prev = 0
    for i in range(1, n):
 
        curr = prev - i
 
        # If arr[i-1] - i is negative or
        # already exists.
        if(curr < 0 or curr in s):
            curr = prev + i
 
        s.add(curr)
 
        print(curr, ",", end='')
        prev = curr
 
# Driver code
if __name__=='__main__':
    n = 17
    recaman(n)
 
# This code is contributed by
# Sanjit_Prasad

Time complexity: linear
Space complexity: linear