Banana-Leopard/TASTY huggingface dataset:
# Python3 program to count distinct
# elements in every window of size K
  
import math as mt
  
# Counts distinct elements in window
# of size K
  
  
def countWindowDistinct(win, K):
  
    dist_count = 0
  
    # Traverse the window
    for i in range(K):
  
        # Check if element arr[i] exists
        # in arr[0..i-1]
        j = 0
        while j < i:
            if (win[i] == win[j]):
                break
            else:
                j += 1
        if (j == i):
            dist_count += 1
  
    return dist_count
  
  
# Counts distinct elements in all
# windows of size k
def countDistinct(arr, N, K):
  
    # Traverse through every window
    for i in range(N - K + 1):
        print(countWindowDistinct(arr[i:K + i], K))
  
  
# Driver's Code
if __name__=='__main__':
  arr = [1, 2, 1, 3, 4, 2, 3]
  K = 4
  N = len(arr)
    
  # Function call
  countDistinct(arr, N, K)
  
# This code is contributed by
# Mohit kumar 29

Time complexity: quadratic
Space complexity: constant
# An efficient Python program to
# count distinct elements in
# every window of size K
from collections import defaultdict
  
  
def countDistinct(arr, K, N):
  
    # Creates an empty hashmap hm
    mp = defaultdict(lambda: 0)
  
    # initialize distinct element
    # count for current window
    dist_count = 0
  
    # Traverse the first window and store count
    # of every element in hash map
    for i in range(K):
        if mp[arr[i]] == 0:
            dist_count += 1
        mp[arr[i]] += 1
  
    # Print count of first window
    print(dist_count)
  
    # Traverse through the remaining array
    for i in range(K, N):
  
        # Remove first element of previous window
        # If there was only one occurrence,
        # then reduce distinct count.
        if mp[arr[i - K]] == 1:
            dist_count -= 1
        mp[arr[i - K]] -= 1
  
    # Add new element of current window
    # If this element appears first time,
    # increment distinct element count
        if mp[arr[i]] == 0:
            dist_count += 1
        mp[arr[i]] += 1
  
        # Print count of current window
        print(dist_count)
  
# Driver's code
if __name__=='__main__':
  arr = [1, 2, 1, 3, 4, 2, 3]
  N = len(arr)
  K = 4
  
  # Function call
  countDistinct(arr, K, N)
  
# This code is contributed by Shrikant13

Time complexity: linear
Space complexity: linear
# Python3 program to find the maximum
# possible sum of a window in one
# array such that elements in same
# window of other array are unique.
 
# Function to return maximum sum of window
# in B[] according to given constraints.
def returnMaxSum(A, B, n):
  
    # Map is used to store elements
    # and their counts.
    mp = set()
    result = 0 # Initialize result
 
    # calculating the maximum possible
    # sum for each subarray containing
    # unique elements.
    curr_sum = curr_begin = 0
    for i in range(0, n): 
 
        # Remove all duplicate instances
        # of A[i] in current window.
        while A[i] in mp: 
            mp.remove(A[curr_begin])
            curr_sum -= B[curr_begin]
            curr_begin += 1
          
        # Add current instance of A[i]
        # to map and to current sum.
        mp.add(A[i])
        curr_sum += B[i]
 
        # Update result if current
        # sum is more.
        result = max(result, curr_sum)
      
    return result
 
# Driver code
if __name__ == "__main__":
  
    A = [0, 1, 2, 3, 0, 1, 4] 
    B = [9, 8, 1, 2, 3, 4, 5]
    n = len(A)
    print(returnMaxSum(A, B, n))
 
# This code is contributed by Rituraj Jain

Time complexity: linear
Space complexity: linear
# python3 program to find if
# there is a zero sum subarray
 
 
def subArrayExists(arr, N):
    # traverse through array
    # and store prefix sums
    n_sum = 0
    s = set()
 
    for i in range(N):
        n_sum += arr[i]
 
        # If prefix sum is 0 or
        # it is already present
        if n_sum == 0 or n_sum in s:
            return True
        s.add(n_sum)
 
    return False
 
 
# Driver's code
if __name__ == '__main__':
    arr = [-3, 2, 3, 1, 6]
    N = len(arr)
 
    # Function call
    if subArrayExists(arr, N) == True:
        print("Found a sunbarray with 0 sum")
    else:
        print("No Such sub array exits!")
 
# This code is contributed by Shrikant13

Time complexity: linear
Space complexity: linear
# User defined pair class
class Pair :
    first = 0
    second = 0
    def __init__(self, a,  b) :
        self.first = a
        self.second = b
class GFG :
    @staticmethod
    def  findSubArrays( arr,  n) :
       
        # Array to store all the start and end
        # indices of subarrays with 0 sum
        out =  []
        i = 0
        while (i < n) :
            prefix = 0
            j = i
            while (j < n) :
                prefix += arr[j]
                if (prefix == 0) :
                    out.append(Pair(i, j))
                j += 1
            i += 1
        return out
       
    # Function to print all subarrays with 0 sum
    @staticmethod
    def print( out) :
        i = 0
        while (i < len(out)) :
            p = out[i]
            print("Subarray found from Index " + str(p.first) + " to " + str(p.second))
            i += 1
             
    # Driver code
    @staticmethod
    def main( args) :
       
        # Given array
        arr = [6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7]
        n = len(arr)
         
        # Function Call
        out = GFG.findSubArrays(arr, n)
         
        # if we didn't find any subarray with 0 sum,
        # then subarray doesn't exists
        if (len(out) == 0) :
            print("No subarray exists")
        else :
            GFG.print(out)
     
 
if __name__=="__main__":
    GFG.main([])
     
    # This code is contributed by aadityaburujwale.

Time complexity: quadratic
Space complexity: constant
# Python3 program to print all subarrays
# in the array which has sum 0
 
# Function to get all subarrays
# in the array which has sum 0
def findSubArrays(arr,n):
 
    # create a python dict
    hashMap = {}
     
    # create a python list
    # equivalent to ArrayList
    out = []
     
    # tracker for sum of elements
    sum1 = 0
    for i in range(n):
         
        # increment sum by element of array
        sum1 += arr[i]
         
        # if sum is 0, we found a subarray starting
        # from index 0 and ending at index i
        if sum1 == 0:
            out.append((0, i))
        al = []
         
        # If sum already exists in the map
        # there exists at-least one subarray
        # ending at index i with 0 sum
        if sum1 in hashMap:
             
            # map[sum] stores starting index
            # of all subarrays
            al = hashMap.get(sum1)
            for it in range(len(al)):
                out.append((al[it] + 1, i))
        al.append(i)
        hashMap[sum1] = al
    return out
 
# Utility function to print
# all subarrays with sum 0
def printOutput(output):
    for i in output:
        print ("Subarray found from Index " +
                str(i[0]) + " to " + str(i[1]))
 
# Driver Code
if __name__ == '__main__':
    arr = [6, 3, -1, -3, 4, -2,
              2, 4, 6, -12, -7]
    n = len(arr)
    out = findSubArrays(arr, n)
     
    # if we did not find any subarray with 0 sum,
    # then subarray does not exists
    if (len(out) == 0):
        print ("No subarray exists")
    else:
        printOutput (out)
 
# This code is contributed by Vikas Chitturi

Time complexity: linear
Space complexity: linear
# Python3 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(n):
        curr_sum = 0
        # try all subarrays starting with 'i'
        for j in range(i, n):
            curr_sum += arr[j]
            if (curr_sum == 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
 
    # Function Call
    subArraySum(arr, n, sum)
 
 
# This code is contributed by phasing17

Time complexity: quadratic
Space complexity: constant
# Python3 program to print subarray with sum as given sum
 
# Function to print subarray with sum as given sum
 
 
def subArraySum(arr, n, Sum):
 
    # create an empty map
    Map = {}
 
    # Maintains sum of elements so far
    curr_sum = 0
 
    for i in range(0, n):
 
        # add current element to curr_sum
        curr_sum = curr_sum + arr[i]
 
        # if curr_sum is equal to target sum
        # we found a subarray starting from index 0
        # and ending at index i
        if curr_sum == Sum:
 
            print("Sum found between indexes 0 to", i)
            return
 
        # If curr_sum - sum already exists in map
        # we have found a subarray with target sum
        if (curr_sum - Sum) in Map:
 
            print("Sum found between indexes",
                  Map[curr_sum - Sum] + 1, "to", i)
 
            return
 
        Map[curr_sum] = i
 
    # If we reach here, then no subarray exists
    print("No subarray with given sum exists")
 
 
# Driver code
if __name__ == "__main__":
 
    arr = [10, 2, -2, -20, 10]
    n = len(arr)
    Sum = -10
 
    # Function call
    subArraySum(arr, n, Sum)
 
# This code is contributed by Rituraj Jain

Time complexity: linear
Space complexity: linear
# Python3 program to find minimum number
# of insertions to make a string
# palindrome
import math as mt
 
# Function will return number of
# characters to be added
def minInsertion(tr1):
 
    # To store string length
    n = len(str1)
 
    # To store number of characters
    # occurring odd number of times
    res = 0
 
    # To store count of each
    # character
    count = [0 for i in range(26)]
 
    # To store occurrence of each
    # character
    for i in range(n):
        count[ord(str1[i]) - ord('a')] += 1
 
    # To count characters with odd
    # occurrence
    for i in range(26):
        if (count[i] % 2 == 1):
            res += 1
 
    # As one character can be odd return
    # res - 1 but if string is already
    # palindrome return 0
    if (res == 0):
        return 0
    else:
        return res - 1
 
# Driver Code
str1 = "geeksforgeeks"
print(minInsertion(str1))
 
# This code is contributed by
# Mohit kumar 29

Time complexity: linear
Space complexity: constant
# Python3 implementation to find maximum
# length subsequence with difference between
# adjacent elements as either 0 or 1
from collections import defaultdict
 
# Function to find maximum length subsequence with
# difference between adjacent elements as either 0 or 1
def maxLenSub(arr, n):
 
    # hash table to map the array element with the
    # length of the longest subsequence of which it is a
    # part of and is the last element of that subsequence
    um = defaultdict(lambda:0)
     
    # to store the maximum length subsequence
    maxLen = 0
     
    # traverse the array elements
    for i in range(0, n):
     
        # initialize current length
        # for element arr[i] as 0
        length = 0
         
        # if 'arr[i]-1' is in 'um' and its length of
        # subsequence is greater than 'len'
        if (arr[i]-1) in um and length < um[arr[i]-1]:
            length = um[arr[i]-1]
         
        # if 'arr[i]' is in 'um' and its length of
        # subsequence is greater than 'len'
        if arr[i] in um and length < um[arr[i]]:
            length = um[arr[i]]
             
        # if 'arr[i]+1' is in 'um' and its length of
        # subsequence is greater than 'len'    
        if (arr[i]+1) in um and length < um[arr[i]+1]:
            length = um[arr[i]+1]
         
        # update arr[i] subsequence length in 'um'
        um[arr[i]] = length + 1
         
        # update maximum length
        if maxLen < um[arr[i]]:
            maxLen = um[arr[i]]
     
    # required maximum length subsequence
    return maxLen
 
# Driver program to test above
if __name__ == "__main__":
 
    arr = [2, 5, 6, 3, 7, 6, 5, 8]
    n = len(arr)
    print("Maximum length subsequence =", maxLenSub(arr, n))
     
# This code is contributed by Rituraj Jain

Time complexity: linear
Space complexity: linear
# Python program to find maximum difference
# between frequency of any two element
# such that element with greater frequency
# is also greater in value.
 
from collections import defaultdict
 
# Return the maximum difference between
# frequencies of any two elements such that
# element with greater frequency is also
# greater in value.
def maxdiff(arr, n):
    freq = defaultdict(lambda: 0)
 
    # Finding the frequency of each element.
    for i in range(n):
        freq[arr[i]] += 1
    ans = 0
    for i in range(n):
        for j in range(n):
 
            # finding difference such that element
            # having greater frequency is also
            # greater in value.
            if freq[arr[i]] > freq[arr[j]] and arr[i] > arr[j]:
                ans = max(ans, freq[arr[i]] - freq[arr[j]])
            elif freq[arr[i]] < freq[arr[j]] and arr[i] < arr[j]:
                ans = max(ans, freq[arr[j]] - freq[arr[i]])
    return ans
 
 
arr = [3,1,3,2,3,2]
n = len(arr)
print(maxdiff(arr,n))
 
# This code is contributed by Shrikant13

Time complexity: quadratic
Space complexity: linear
# Efficient Python3 program to find maximum
# difference between frequency of any two
# elements such that element with greater
# frequency is also greater in value.
 
# Return the maximum difference between
# frequencies of any two elements such that
# element with greater frequency is also
# greater in value.
def maxdiff(arr, n):
    freq = {}
    dist = [0] * n
     
    # Finding the frequency of each element.
    j = 0
    for i in range(n):
        if (arr[i] not in freq):
            dist[j] = arr[i]
            j += 1
            freq[arr[i]] = 0
        if (arr[i] in freq):
            freq[arr[i]] += 1
    dist = dist[:j]
     
    # Sorting the distinct element
    dist.sort()
    min_freq = n + 1
     
    # Iterate through all sorted distinct elements.
    # For each distinct element, maintaining the
    # element with minimum frequency than that
    # element and also finding the maximum
    # frequency difference
    ans = 0
    for i in range(j):
        cur_freq = freq[dist[i]]
        ans = max(ans, cur_freq - min_freq)
        min_freq = min(min_freq, cur_freq)
         
    return ans
 
# Driven Program
arr = [3, 1, 3, 2, 3, 2]
n = len(arr)
 
print(maxdiff(arr, n))
 
# This code is contributed by SHUBHAMSINGH10

Time complexity: nlogn
Space complexity: linear
# Python3 code to find the difference
# between highest nd least frequencies
 
def findDiff(arr, n):
     
    # sort the array
    arr.sort()
     
    count = 0; max_count = 0; min_count = n
    for i in range(0, (n-1)):
 
        # checking consecutive elements
        if arr[i] == arr[i + 1]:
            count += 1
            continue
        else:
            max_count = max(max_count, count)
            min_count = min(min_count, count)
            count = 0
    return max_count - min_count
 
# Driver Code
arr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 ]
n = len(arr)
print (findDiff(arr, n))
 
# This code is contributed by Shreyanshi Arun.

Time complexity: nlogn
Space complexity: constant
# Python code to find the difference between highest
# and least frequencies
 
from collections import defaultdict
def findDiff(arr,n):
 
    # Put all elements in a hash map
    mp = defaultdict(lambda:0)
    for i in range(n):
        mp[arr[i]]+=1
 
    # Find counts of maximum and minimum
    # frequent elements
    max_count=0;min_count=n
    for key,values in mp.items():
        max_count= max(max_count,values)
        min_count = min(min_count,values)
 
    return max_count-min_count
 
 
# Driver code
arr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]
n = len(arr)
print(findDiff(arr,n))
 
# This code is contributed by Shrikant13

Time complexity: linear
Space complexity: linear
# Python 3 program to find minimum range
# that contains exactly k distinct numbers.
 
# Prints the minimum range that contains
# exactly k distinct numbers.
def minRange(arr, n, k):
 
    l = 0
    r = n
 
    # Consider every element as
    # starting point.
    for i in range(n):
 
        # Find the smallest window starting
        # with arr[i] and containing exactly
        # k distinct elements.
        s = []
        for j in range(i, n) :
            s.append(arr[j])
            if (len(s) == k):
                if ((j - i) < (r - l)) :
                    r = j
                    l = i
                 
                break
 
        # There are less than k distinct
        # elements now, so no need to continue.
        if (j == n):
            break
 
    # If there was no window with k distinct
    # elements (k is greater than total
    # distinct elements)
    if (l == 0 and r == n):
        print("Invalid k")
    else:
        print(l, r)
 
# Driver code
if __name__ == "__main__":
     
    arr = [ 1, 2, 3, 4, 5 ]
    n = len(arr)
    k = 3
    minRange(arr, n, k)
 
# This code is contributed
# by ChitraNayal

Time complexity: quadratic
Space complexity: linear
# Python3 program to find the minimum range
# that contains exactly k distinct numbers.
from collections import defaultdict
 
# Prints the minimum range that contains
# exactly k distinct numbers.
def minRange(arr, n, k):
  
    # Initially left and right side is -1
    # and -1, number of distinct elements
    # are zero and range is n.
    l, r = 0, n
    i = 0
    j = -1 # Initialize right side
     
    hm = defaultdict(lambda:0)
    while i < n:
      
        while j < n:
          
            # increment right side.
            j += 1
   
            # if number of distinct elements less than k.
            if len(hm) < k and j < n:
                hm[arr[j]] += 1
   
            # if distinct elements are equal to k
            # and length is less than previous length.
            if len(hm) == k and ((r - l) >= (j - i)):
              
                l, r = i, j
                break
   
        # if number of distinct elements less
        # than k, then break.
        if len(hm) < k:
            break
   
        # if distinct elements equals to k then
        # try to increment left side.
        while len(hm) == k:
   
            if hm[arr[i]] == 1:
                del(hm[arr[i]])
            else:
                hm[arr[i]] -= 1
   
            # increment left side.
            i += 1
   
            # it is same as explained in above loop.
            if len(hm) == k and (r - l) >= (j - i):
              
                l, r = i, j
          
        if hm[arr[i]] == 1:
            del(hm[arr[i]])
        else:
            hm[arr[i]] -= 1
             
        i += 1
   
    if l == 0 and r == n:
        print("Invalid k")
    else:
        print(l, r)
  
# Driver code for above function.
if __name__ == "__main__":
  
    arr = [1, 1, 2, 2, 3, 3, 4, 5] 
    n = len(arr)
    k = 3
    minRange(arr, n, k)
     
# This code is contributed by Rituraj Jain

Time complexity: linear
Space complexity: constant
# Python 3 program to find longest
# subarray with k or less distinct elements.
 
# function to print the longest sub-array
import collections
def longest(a, n, k):
 
    freq = collections.defaultdict(int)
 
    start = 0
    end = 0
    now = 0
    l = 0
    for i in range(n):
 
        # mark the element visited
        freq[a[i]] += 1
 
        # if its visited first time, then increase
        # the counter of distinct elements by 1
        if (freq[a[i]] == 1):
            now += 1
 
        # When the counter of distinct elements
        # increases from k, then reduce it to k
        while (now > k) :
 
            # from the left, reduce the number
            # of time of visit
            freq[a[l]] -= 1
 
            # if the reduced visited time element
            # is not present in further segment
            # then decrease the count of distinct
            # elements
            if (freq[a[l]] == 0):
                now -= 1
 
            # increase the subsegment mark
            l += 1
 
        # check length of longest sub-segment
        # when greater than previous best
        # then change it
        if (i - l + 1 >= end - start + 1):
            end = i
            start = l
 
    # print the longest sub-segment
    for i in range(start, end + 1):
        print(a[i], end = " ")
 
# Driver Code
if __name__ == "__main__":
 
    a = [ 6, 5, 1, 2, 3,
             2, 1, 4, 5 ]
    n = len(a)
    k = 3
    longest(a, n, k)
 
# This code is contributed
# by ChitraNayal

Time complexity: linear
Space complexity: linear
# Python3 program to find number of pairs
# in an array such that their XOR is 0
 
# Function to calculate the count
def calculate(a) :
 
    # Sorting the list using
    # built in function
    a.sort()
     
    count = 1
    answer = 0
     
    # Traversing through the elements
    for i in range(1, len(a)) :
 
        if a[i] == a[i - 1] :
             
            # Counting frequency of each elements
            count += 1
 
        else :
 
            # Adding the contribution of
            # the frequency to the answer
            answer = answer + count * (count - 1) // 2
            count = 1
 
    answer = answer + count * (count - 1) // 2
     
    return answer
 
 
# Driver Code
if __name__ == '__main__':
     
    a = [1, 2, 1, 2, 4]
 
    # Print the count
    print(calculate(a))

Time complexity: nlogn
Space complexity: constant
# Python3 program to find number of pairs
# in an array such that their XOR is 0
 
# Function to calculate the answer
def calculate(a) :
     
    # Finding the maximum of the array
    maximum = max(a)
     
    # Creating frequency array
    # With initial value 0
    frequency = [0 for x in range(maximum + 1)]
     
    # Traversing through the array
    for i in a :
          
        # Counting frequency
        frequency[i] += 1
     
    answer = 0
     
    # Traversing through the frequency array
    for i in frequency :
         
        # Calculating answer
        answer = answer + i * (i - 1) // 2
     
    return answer
 
# Driver Code
a = [1, 2, 1, 2, 4]
print(calculate(a))

Time complexity: linear
Space complexity: linear