Banana-Leopard/TASTY huggingface dataset:
# Python3 program to find the number of
# subarrays with sum exactly equal to k.
from collections import defaultdict
 
# Function to find number of subarrays 
# with sum exactly equal to k.
def findSubarraySum(arr, n, Sum):
  
    # Dictionary to store number of subarrays
    # starting from index zero having 
    # particular value of sum.
    prevSum = defaultdict(lambda : 0)
   
    res = 0
   
    # Sum of elements so far.
    currsum = 0
   
    for i in range(0, n): 
   
        # Add current element to sum so far.
        currsum += arr[i]
   
        # If currsum is equal to desired sum,
        # then a new subarray is found. So
        # increase count of subarrays.
        if currsum == Sum: 
            res += 1        
   
        # currsum exceeds given sum by currsum  - sum.
        # Find number of subarrays having 
        # this sum and exclude those subarrays
        # from currsum by increasing count by 
        # same amount.
        if (currsum - Sum) in prevSum:
            res += prevSum[currsum - Sum]
           
   
        # Add currsum value to count of 
        # different values of sum.
        prevSum[currsum] += 1
      
    return res
  
if __name__ == "__main__":
 
    arr =  [10, 2, -2, -20, 10] 
    Sum = -10
    n = len(arr)
    print(findSubarraySum(arr, n, Sum))
     
# This code is contributed by Rituraj Jain

Time complexity: linear
Space complexity: linear
# Python 3 program to find all
# pairs in both arrays whose
# sum is equal to given value x
 
# Function to print all pairs
# in both arrays whose sum is
# equal to given value x
def findPairs(arr1, arr2, n, m, x):
 
    for i in range(0, n):
        for j in range(0, m):
            if (arr1[i] + arr2[j] == x):
                print(arr1[i], arr2[j])
 
# Driver code
arr1 = [1, 2, 3, 7, 5, 4]
arr2 = [0, 7, 4, 3, 2, 1]
n = len(arr1)
m = len(arr2)
x = 8
findPairs(arr1, arr2, n, m, x)
 
# This code is contributed by Smitha Dinesh Semwal

Time complexity: quadratic
Space complexity: constant
# Python3 program to find all
# pair in both arrays whose
# sum is equal to given value x
 
# Function to find all pairs
# in both arrays whose sum is
# equal to given value x
def findPairs(arr1, arr2, n, m, x):
 
    # Insert all elements of
    # first array in a hash
    s = set()
    for i in range (0, n):
        s.add(arr1[i])
 
    # Subtract sum from second
    # array elements one by one
    # and check it's present in
    # array first or not
    for j in range(0, m):
        if ((x - arr2[j]) in s):
            print((x - arr2[j]), '', arr2[j])
 
# Driver code
arr1 = [1, 0, -4, 7, 6, 4]
arr2 = [0, 2, 4, -3, 2, 1]
x = 8
 
n = len(arr1)
m = len(arr2)
findPairs(arr1, arr2, n, m, x)
 
# This code is contributed
# by ihritik

Time complexity: linear
Space complexity: linear
# Python3 program to count cumulative
# frequencies of elements in an unsorted array.
def countFreq(a, n):
 
    # Insert elements and their
    # frequencies in hash map.
    hm = {}
    for i in range(0, n):
        hm[a[i]] = hm.get(a[i], 0) + 1
 
    # Declare a set
    st = set()
 
    # Insert the element and
    # its frequency in a set
    for x in hm:
        st.add((x, hm[x]))
 
    cumul = 0
 
    # Iterate the set and print
    # the cumulative frequency
    for x in sorted(st):
        cumul += x[1]
        print(x[0], cumul)
 
# Driver Code
if __name__ == "__main__":
 
    a = [1, 3, 2, 4, 2, 1]
    n = len(a)
    countFreq(a, n)
     
# This code is contributed by Rituraj Jain

Time complexity: nlogn
Space complexity: linear
# Python3 program to print the cumulative
# frequency according to the order given
 
# Function to print the cumulative frequency
# according to the order given
def countFreq(a, n):
 
    # Insert elements and their
    # frequencies in hash map.
    hm = dict()
    for i in range(n):
        hm[a[i]] = hm.get(a[i], 0) + 1
 
    cumul = 0
 
    # traverse in the array
    for i in range(n):
 
    # add the frequencies
        cumul += hm[a[i]]
 
    # if the element has not been
    # visited previously
        if(hm[a[i]] > 0):
            print(a[i], "->", cumul)
             
    # mark the hash 0
    # as the element's cumulative
    # frequency has been printed
        hm[a[i]] = 0
 
# Driver Code
a = [1, 3, 2, 4, 2, 1]
n = len(a)
countFreq(a, n)
 
# This code is contributed by mohit kumar

Time complexity: linear
Space complexity: linear
# Used for sorting by frequency. And if frequency is same,
# then by appearance
from functools import cmp_to_key
 
def sortByVal(a,b):
 
    # If frequency is same then sort by index
    if (a[1] == b[1]):
        return a[0] - b[0]
 
    return b[1] - a[1]
 
# function to sort elements by frequency
def sortByFreq(a, n):
    res = []
    m = {}
    v = []
 
    for i in range(n):
 
        # Map m is used to keep track of count
        # of elements in array
        if(a[i] in m):
            m[a[i]] = m[a[i]]+1
        else:
            m[a[i]] = 1
 
    for key,value in m.items():
        v.append([key,value])
 
    # Sort the element of array by frequency
    v.sort(key = cmp_to_key(sortByVal))
 
    for i in range(len(v)):
        while(v[i][1]):
            res.append(v[i][0])
            v[i][1] -= 1
 
    return res
 
 
# Driver program
 
a = [ 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 ]
n = len(a)
res = []
res = sortByFreq(a, n)
 
for i in range(len(res)):
    print(res[i],end = " ")
 
 
# This code is contributed by shinjanpatra

Time complexity: linear
Space complexity: linear
# A simple python program to find pair
# whose sum already exists in array
 
# Function to find pair whose sum
# exists in arr[]
def findPair(arr, n):
    found = False
    for i in range(0, n):
        for j in range(i + 1, n):
            for k in range(0, n):
                if (arr[i] + arr[j] == arr[k]):
                    print(arr[i], arr[j])
                    found = True
 
    if (found == False):
        print("Not exist")
 
# Driver code
if __name__ == '__main__':
    arr = [ 10, 4, 8, 13, 5 ]
    n = len(arr)
    findPair(arr, n)
     
# This code contributed by 29AjayKumar

Time complexity: cubic
Space complexity: constant
# Python3 program to find pair whose
# sum already exist in array
 
# Function to find pair whose
# sum exists in arr[]
def findPair(arr, n):
     
    # hash to store all element of array
    s = {i : 1 for i in arr}
     
    found = False
     
    for i in range(n):
        for j in range(i + 1, n):
             
            # check if sum already exists or not
            if arr[i] + arr[j] in s.keys():
                print(arr[i], arr[j])
                found = True
    if found == False:
        print("Not exist")
         
# Driver code
arr = [10, 4, 8, 13, 5]
 
n = len(arr)
 
findPair(arr, n)
     
# This code is contributed
# by Mohit Kumar

Time complexity: quadratic
Space complexity: quadratic
# Python3 implementation to find such pairs
 
# Function to find pair such that (a % b = k)
def printPairs(arr, n, k):
 
    isPairFound = True
 
    # Consider each and every pair
    for i in range(0, n):
     
        for j in range(0, n):
         
            # Print if their modulo equals to k
            if (i != j and arr[i] % arr[j] == k):
             
                print("(", arr[i], ", ", arr[j], ")",
                                 sep = "", end = " ")
                isPairFound = True
             
    return isPairFound
 
# Driver Code
arr = [2, 3, 5, 4, 7]
n = len(arr)
k = 3
if (printPairs(arr, n, k) == False):
    print("No such pair exists")
 
# This article is contributed by Smitha Dinesh Semwal.

Time complexity: quadratic
Space complexity: constant
# Python3 program to find all pairs
# such that a % b = k.
  
# Utility function to find the divisors
# of n and store in vector v[]
import math as mt
 
def findDivisors(n):
 
    v = []
 
    # Vector is used to store the divisors
    for i in range(1, mt.floor(n**(.5)) + 1):
        if (n % i == 0):
             
            # If n is a square number, push
            # only one occurrence
            if (n / i == i):
                v.append(i)
            else:
                v.append(i)
                v.append(n // i)
                 
    return v
 
# Function to find pairs such that (a%b = k)
def printPairs(arr, n, k):
 
    # Store all the elements in the map
    # to use map as hash for finding elements
    # in O(1) time.
    occ = dict()
    for i in range(n):
        occ[arr[i]] = True
 
    isPairFound = False
 
    for i in range(n):
         
        # Print all the pairs with (a, b) as
        # (k, numbers greater than k) as
        # k % (num (> k)) = k i.e. 2%4 = 2
        if (occ[k] and k < arr[i]):
            print("(", k, ",", arr[i], ")", end = " ")
            isPairFound = True
 
        # Now check for the current element as 'a'
        # how many b exists such that a%b = k
        if (arr[i] >= k):
             
            # find all the divisors of (arr[i]-k)
            v = findDivisors(arr[i] - k)
 
            # Check for each divisor i.e. arr[i] % b = k
            # or not, if yes then print that pair.
            for j in range(len(v)):
                if (arr[i] % v[j] == k and
                    arr[i] != v[j] and
                    occ[v[j]]):
                    print("(", arr[i], ",", v[j],
                                       ")", end = " ")
                    isPairFound = True
 
    return isPairFound
 
# Driver Code
arr = [3, 1, 2, 5, 4]
n = len(arr)
k = 2
 
if (printPairs(arr, n, k) == False):
    print("No such pair exists")
 
# This code is contributed by mohit kumar

Time complexity: linear
Space complexity: linear
# Python3 program to convert an array
# in reduced form
def convert(arr, n):
    # Create a temp array and copy contents
    # of arr[] to temp
    temp = [arr[i] for i in range (n) ]
     
    # Sort temp array
    temp.sort()
     
    # create a map
    umap = {}
     
     
    # One by one insert elements of sorted
    # temp[] and assign them values from 0
    # to n-1
    val = 0
    for i in range (n):
        umap[temp[i]] = val
        val += 1
     
    # Convert array by taking positions from umap
    for i in range (n):
        arr[i] = umap[arr[i]]
     
def printArr(arr, n):
    for i in range(n):
        print(arr[i], end = " ")
 
# Driver Code
if __name__ == "__main__":
    arr = [10, 20, 15, 12, 11, 50]
    n = len(arr)
    print("Given Array is ")
    printArr(arr, n)
    convert(arr , n)
    print("\n\nConverted Array is ")
    printArr(arr, n)
 
# This code is contributed by Abhishek Gupta

Time complexity: nlogn
Space complexity: linear
# Python program to return the maximum occurring character in the input string
ASCII_SIZE = 256
 
 
def getMaxOccurringChar(str):
    # Create array to keep the count of individual characters
    # Initialize the count array to zero
    count = [0] * ASCII_SIZE
 
    # Utility variables
    max = -1
    c = ''
 
    # Traversing through the string and maintaining the count of
    # each character
    for i in str:
        count[ord(i)] += 1
 
    for i in str:
        if max < count[ord(i)]:
            max = count[ord(i)]
            c = i
 
    return c
 
 
# Driver program to test the above function
str = "sample string"
print("Max occurring character is", getMaxOccurringChar(str))
 
# Although this program can be written in atmost 3 lines in Python
# the above program has been written for a better understanding of
# the reader
 
# Shorter version of the program
# import collections
# str = "sample string"
# print "Max occurring character is " +
#        collections.Counter(str).most_common(1)[0][0]
 
# This code has been contributed by Bhavya Jain

Time complexity: linear
Space complexity: constant
# Python program to print all words that
# have the same unique character set
 
# Function to group all strings with same characters
from collections import Counter
 
def groupStrings(input):
    # traverse all strings one by one
    # dict is an empty dictionary
    dict={}
     
    for word in input:
        # sort the current string and take it's
        # sorted value as key
        # sorted return list of sorted characters
        # we need to join them to get key as string
        # Counter() method returns dictionary with frequency of
        # each character as value
        wordDict=Counter(word)
 
        # now get list of keys
        key = wordDict.keys()
 
        # now sort these keys
        key = sorted(key)
 
        # join these characters to produce key string
        key = ''.join(key)
         
        # now check if this key already exist in
        # dictionary or not
        # if exist then simply append current word
        # in mapped list on key
        # otherwise first assign empty list to key and
        # then append current word in it
        if key in dict.keys():
            dict[key].append(word)
        else:
            dict[key]=[]
            dict[key].append(word)
 
        # now traverse complete dictionary and print
        # list of mapped strings in each key separated by ,
    for (key,value) in dict.items():
        print (','.join(dict[key]))
         
# Driver program
if __name__ == "__main__":
    input=['may','student','students','dog','studentssess','god','cat','act','tab','bat','flow','wolf','lambs','amy','yam','balms','looped','poodle']
    groupStrings(input)

Time complexity: linear
Space complexity: linear
# Python3 program to find out the second
# most repeated word
 
# Function to find the word
def secMostRepeated(seq):
     
    # Store all the words with its occurrence
    occ = {}
    for i in range(len(seq)):
        occ[seq[i]] = occ.get(seq[i], 0) + 1
 
    # Find the second largest occurrence
    first_max = -10**8
    sec_max = -10**8
 
    for it in occ:
        if (occ[it] > first_max):
            sec_max = first_max
            first_max = occ[it]
             
        elif (occ[it] > sec_max and
              occ[it] != first_max):
            sec_max = occ[it]
 
    # Return with occurrence equals
    # to sec_max
    for it in occ:
        if (occ[it] == sec_max):
            return it
 
# Driver code
if __name__ == '__main__':
     
    seq = [ "ccc", "aaa", "ccc",
            "ddd", "aaa", "aaa" ]
    print(secMostRepeated(seq))
 
# This code is contributed by mohit kumar 29

Time complexity: linear
Space complexity: linear
from collections import defaultdict
import sys
 
# Python program to find the smallest element
# with frequency exactly k.
def smallestKFreq(arr, n, k):
    mp = defaultdict(lambda : 0)
 
 
    # Map is used to store the count of
    # elements present in the array
    for i in range(n):
        mp[arr[i]] += 1
 
    # Traverse the map and find minimum
    # element with frequency k.
    res = sys.maxsize
    res1 = sys.maxsize
 
    for key,values in mp.items():
 
        if values == k:
            res = min(res, key)
    return res if res != res1 else -1
 
# Driver code
arr = [2, 2, 1, 3, 1]
k = 2
n = len(arr)
print(smallestKFreq(arr, n, k))
 
# This code is contributed by Shrikant13

Time complexity: linear
Space complexity: linear
# Python3 code to find number
# occurring prime number of
# times with frequency >= k
 
# Function to find number
# with prime occurrences
def primeOccurrences(arr, k):
    map = {}
 
    # Insert values and their frequencies
    for val in arr:
        freq = 0
         
        if val in map :
            freq = map[val]
            freq += 1
             
        else :
            freq = 1
        map[val] = freq
 
    # Traverse map and find elements
    # with prime frequencies and
    # frequency at least k
    for entry in map :
        value = map[entry]
         
        if isPrime(value) and value >= k:
            print(entry)
 
# Check if the number of occurrences
# are primes or not
def isPrime(n):
 
    if (n > 2 and not n % 2) or n == 1:
        return False    
 
    for i in range(3, int(n**0.5 + 1), 2):
        if not n % i:
            return False
             
    return True
 
 
# Driver code
 
arr = [ 11, 11, 11, 23, 11, 37,
        37, 51, 51, 51, 51, 51 ]
k = 2
 
primeOccurrences(arr, k)
 
 
# This code is contributed by Ansu Kumari.

Time complexity: linear
Space complexity: linear
# Python3 implementation to find k numbers
# with most occurrences in the given array
 
# Function to print the k numbers with
# most occurrences
 
 
def pr_N_mostFrequentNumber(arr, N, K):
 
    mp = {}
    for i in range(N):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    a = [0] * (len(mp))
    j = 0
    for i in mp:
        a[j] = [i, mp[i]]
        j += 1
    a = sorted(a, key=lambda x: x[0],
               reverse=True)
    a = sorted(a, key=lambda x: x[1],
               reverse=True)
 
    # Display the top k numbers
    print(K, "numbers with most occurrences are:")
    for i in range(K):
        print(a[i][0], end=" ")
 
 
# Driver code
if __name__ == "__main__":
    arr = [3, 1, 4, 4, 5, 2, 6, 1]
    N = 8
    K = 2
 
    # Function call
    pr_N_mostFrequentNumber(arr, N, K)
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Time complexity: nlogn
Space complexity: logn
# Python3 program to find first repeating
# element in arr[]
 
# This function prints the first repeating
# element in arr[]
 
 
def printFirstRepeating(arr, n):
 
    # Initialize index of first repeating element
    Min = -1
 
    # Creates an empty hashset
    myset = dict()
 
    # Traverse the input array from right to left
    for i in range(n - 1, -1, -1):
 
        # If element is already in hash set,
        # update Min
        if arr[i] in myset.keys():
            Min = i
 
        else:  # Else add element to hash set
            myset[arr[i]] = 1
 
    # Print the result
    if (Min != -1):
        print("The first repeating element is",
              arr[Min])
    else:
        print("There are no repeating elements")
 
 
# Driver Code
arr = [10, 5, 3, 4, 3, 5, 6]
 
n = len(arr)
printFirstRepeating(arr, n)
 
# This code is contributed by Mohit kumar 29

Time complexity: linear
Space complexity: linear
# Python3 program to find first
# repeating element in arr[]
 
# This function prints the
# first repeating element in arr[]
 
 
def printFirstRepeating(arr, n):
 
    # This will set k=1, if any
    # repeating element found
    k = 0
 
    # max = maximum from (all elements & n)
    max = n
 
    for i in range(n):
        if (max < arr[i]):
            max = arr[i]
 
    # Array a is for storing
    # 1st time occurrence of element
    # initialized by 0
    a = [0 for i in range(max + 1)]
 
    # Store 1 in array b
    # if element is duplicate
    # initialized by 0
    b = [0 for i in range(max + 1)]
 
    for i in range(n):
 
        # Duplicate element found
        if (a[arr[i]]):
            b[arr[i]] = 1
            k = 1
            continue
        else:
 
            # Storing 1st occurrence of arr[i]
            a[arr[i]] = i+1
 
    if (k == 0):
        print("No repeating element found")
    else:
        min = max + 1
 
        for i in range(max + 1):
 
            # Trace array a & find repeating
            # element with min index
            if (a[i] and (min > (a[i])) and b[i]):
                min = a[i]
 
        print(arr[min-1])
 
 
# Driver code
arr = [10, 5, 3, 4, 3, 5, 6]
N = len(arr)
 
printFirstRepeating(arr, N)
 
# This code is contributed by avanitrachhadiya2155

Time complexity: linear
Space complexity: linear
# Python3 Find the sum of all non-repeated
# elements in an array
 
  
# Find the sum of all non-repeated elements
# in an array
def findSum(arr,  n):
    # sort all elements of array
    arr.sort()
  
    sum = arr[0]
    for i in range(0,n-1):
        if (arr[i] != arr[i+1]):
            sum = sum + arr[i+1]
     
    return sum
  
# Driver code
def main():
    arr= [1, 2, 3, 1, 1, 4, 5, 6]
    n = len(arr)
    print(findSum(arr, n))
 
if __name__ == '__main__':
    main()
# This code is contributed by 29AjayKumar

Time complexity: nlogn
Space complexity: constant
# Python3 Find the sum of all
# non- repeated elements in an array
 
# Find the sum of all non-repeated
# elements in an array
def findSum(arr, n):
    s = set()
    sum = 0
 
    # Hash to store all element
    # of array
    for i in range(n):
        if arr[i] not in s:
            s.add(arr[i])
    for i in s:
        sum = sum + i
 
    return sum
 
# Driver code
arr = [1, 2, 3, 1, 1, 4, 5, 6]
n = len(arr)
print(findSum(arr, n))
 
# This code is contributed by Shrikant13

Time complexity: linear
Space complexity: linear
# Python program for the above approach
from collections import Counter
 
# Function to return the sum of distinct elements
def sumOfElements(arr, n):
 
    # Counter function is used to
    # calculate frequency of elements of array
    freq = Counter(arr)
     
    # Converting keys of freq dictionary to list
    lis = list(freq.keys())
     
    # Return sum of list
    return sum(lis)
 
 
# Driver code
if __name__ == "__main__":
 
    arr = [1, 2, 3, 1, 1, 4, 5, 6]
    n = len(arr)
 
    print(sumOfElements(arr, n))
 
# This code is contributed by vikkycirus

Time complexity: linear
Space complexity: linear
# Python3 program to find first
# non-repeating element.
 
 
def firstNonRepeating(arr, n):
 
    # Loop for checking each element
    for i in range(n):
        j = 0
        # Checking if ith element is present in array
        while(j < n):
            if (i != j and arr[i] == arr[j]):
                break
            j += 1
        # if ith element is not present in array
        # except at ith index then return element
        if (j == n):
            return arr[i]
 
    return -1
 
 
# Driver code
arr = [9, 4, 9, 6, 7, 4]
n = len(arr)
print(firstNonRepeating(arr, n))
 
# This code is contributed by Anant Agarwal.

Time complexity: quadratic
Space complexity: constant
# Efficient Python3 program to find first
# non-repeating element.
from collections import defaultdict
 
 
def firstNonRepeating(arr, n):
    mp = defaultdict(lambda: 0)
 
    # Insert all array elements in hash table
    for i in range(n):
        mp[arr[i]] += 1
 
    # Traverse array again and return
    # first element with count 1.
    for i in range(n):
        if mp[arr[i]] == 1:
            return arr[i]
    return -1
 
 
# Driver Code
arr = [9, 4, 9, 6, 7, 4]
n = len(arr)
print(firstNonRepeating(arr, n))
 
# This code is contributed by Shrikant13

Time complexity: linear
Space complexity: linear
# Python3 program to print k-th distinct
# element in a given array
 
# Returns k-th distinct
# element in arr.
def printKDistinct(arr, n, k):
    dist_count = 0
    for i in range(n):
         
        # Check if current element is
        # present somewhere else.
        j = 0
        while j < n:
            if (i != j and arr[j] == arr[i]):
                break
            j += 1
 
        # If element is unique
        if (j == n):
            dist_count += 1
 
        if (dist_count == k):
            return arr[i]
 
    return -1
 
# Driver Code
ar = [1, 2, 1, 3, 4, 2]
n = len(ar)
k = 2
print(printKDistinct(ar, n, k))
 
# This code is contributed by Mohit Kumar

Time complexity: quadratic
Space complexity: constant
# Python3 program to print k-th
# distinct element in a given array
def printKDistinct(arr, size, KthIndex):
    dict = {}
    vect = []
    for i in range(size):
        if(arr[i] in dict):
            dict[arr[i]] = dict[arr[i]] + 1
        else:
            dict[arr[i]] = 1
    for i in range(size):
        if(dict[arr[i]] > 1):
            continue
        else:
            KthIndex = KthIndex - 1
        if(KthIndex == 0):
            return arr[i]
    return -1
 
# Driver Code
arr = [1, 2, 1, 3, 4, 2]
size = len(arr)
print(printKDistinct(arr, size, 2))
 
# This code is contributed
# by Akhand Pratap Singh

Time complexity: linear
Space complexity: linear