Banana-Leopard/TASTY huggingface dataset:
# Python 3 for printing smallest
# k numbers in order
 
# Function to print smallest k
# numbers in arr[0..n-1]
 
 
def printSmall(arr, n, k):
 
    # For each arr[i] find whether
    # it is a part of n-smallest
    # with insertion sort concept
    for i in range(k, n):
 
        # find largest from first k-elements
        max_var = arr[k - 1]
        pos = k - 1
        for j in range(k - 2, -1, -1):
 
            if (arr[j] > max_var):
 
                max_var = arr[j]
                pos = j
 
        # if largest is greater than arr[i]
        # shift all element one place left
        if (max_var > arr[i]):
 
            j = pos
            while (j < k - 1):
 
                arr[j] = arr[j + 1]
                j += 1
 
            # make arr[k-1] = arr[i]
            arr[k - 1] = arr[i]
 
    # print result
    for i in range(0, k):
        print(arr[i], end=" ")
 
 
# Driver program
arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]
n = len(arr)
k = 5
printSmall(arr, n, k)

Time complexity: quadratic
Space complexity: constant
# Python3 program to find
# k-th absolute difference
# between two elements
from bisect import bisect as upper_bound
 
# returns number of pairs with
# absolute difference less than
# or equal to mid.
def countPairs(a, n, mid):
    res = 0
    for i in range(n):
 
        # Upper bound returns pointer to position
        # of next higher number than a[i]+mid in
        # a[i..n-1]. We subtract (a + i + 1) from
        # this position to count
        res += upper_bound(a, a[i] + mid)
    return res
 
# Returns k-th absolute difference
def kthDiff(a, n, k):
     
    # Sort array
    a = sorted(a)
 
    # Minimum absolute difference
    low = a[1] - a[0]
    for i in range(1, n - 1):
        low = min(low, a[i + 1] - a[i])
 
    # Maximum absolute difference
    high = a[n - 1] - a[0]
 
    # Do binary search for k-th absolute difference
    while (low < high):
        mid = (low + high) >> 1
        if (countPairs(a, n, mid) < k):
            low = mid + 1
        else:
            high = mid
 
    return low
 
# Driver code
k = 3
a = [1, 2, 3, 4]
n = len(a)
print(kthDiff(a, n, k))
 
# This code is contributed by Mohit Kumar

Time complexity: nlogn
Space complexity: constant
# Python3 program to find second
# largest element in an array
 
# Function to print the
# second largest elements
def print2largest(arr,
                  arr_size):
  
  # There should be
  # atleast two elements
  if (arr_size < 2):  
    print(" Invalid Input ")
    return
  
  # Sort the array
  arr.sort
  
  # Start from second last
  # element as the largest
  # element is at last
  for i in range(arr_size-2,
                 -1, -1):
  
    # If the element is not
    # equal to largest element
    if (arr[i] != arr[arr_size - 1]) :
     
      print("The second largest element is",
            arr[i])
      return
  
  print("There is no second largest element")
 
# Driver code
arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
print2largest(arr, n)
 
# This code is contributed by divyeshrabadiya07

Time complexity: nlogn
Space complexity: constant
# Python3 program to find
# second largest element
# in an array
 
# Function to print
# second largest elements
def print2largest(arr, arr_size):
 
    # There should be atleast
    # two elements
    if (arr_size < 2):
        print(" Invalid Input ");
        return;
 
    largest = second = -2454635434;
 
    # Find the largest element
    for i in range(0, arr_size):
        largest = max(largest, arr[i]);
 
    # Find the second largest element
    for i in range(0, arr_size):
        if (arr[i] != largest):
            second = max(second, arr[i]);
 
    if (second == -2454635434):
        print("There is no second " +
              "largest element");
    else:
        print("The second largest " +
              "element is \n", second);
 
# Driver code
if __name__ == '__main__':
   
    arr = [12, 35, 1,
           10, 34, 1];
    n = len(arr);
    print2largest(arr, n);
 
# This code is contributed by shikhasingrajput

Time complexity: linear
Space complexity: constant
# Python program to
# find second largest
# element in an array
 
 
# Function to print the
# second largest elements
def print2largest(arr, arr_size):
 
    # There should be atleast
        # two elements
    if (arr_size < 2):
     
        print(" Invalid Input ")
        return
     
 
    first = second = -2147483648
    for i in range(arr_size):
     
        # If current element is
                # smaller than first
        # then update both
                # first and second
        if (arr[i] > first):
         
            second = first
            first = arr[i]
         
 
        # If arr[i] is in
                # between first and
        # second then update second
        elif (arr[i] > second and arr[i] != first):
            second = arr[i]
     
    if (second == -2147483648):
        print("There is no second largest element")
    else:
        print("The second largest element is", second)
 
 
# Driver program to test
# above function
arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
 
print2largest(arr, n)
 
# This code is contributed
# by Anant Agarwal.

Time complexity: linear
Space complexity: constant
# 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: linear
def print_N_mostFrequentNumber(arr, N, K):
    # HashMap to store count of the elements
    count = {}    
     
    # Array to store the elements according
    # to their frequency
    freq = [[] for i in range(len(arr) + 1)]
    for n in arr:
        count[n] = 1 + count.get(n, 0)
    for n, c in count.items():
        freq.append(n)
 
    res = []
    # if K elements have been printed
    for i in range(len(freq)-1, 0, -1):
        for n in freq[i]:
            res.append(n)
            if len(res) == K:
                return res[-1::-1]
 
 
# Driver's code
if __name__ == "__main__":
    arr = [3, 1, 4, 4, 5, 2, 6, 1]
    N = len(arr)
    K = 2
 
    # Function call
    print(print_N_mostFrequentNumber(arr, N, K))

Time complexity: linear
Space complexity: linear
# Python3 simple approach to print smallest
# and second smallest element.
 
# driver code
 
arr = [111, 13, 25, 9, 34, 1]
n = len(arr)
# sorting the array using
# in-built sort function
arr.sort()
 
# printing the desired element
print("smallest element is "+str(arr[0]))
print("second smallest element is "+str(arr[1]))
 
# This code is contributed by shinjanpatra

Time complexity: nlogn
Space complexity: constant
# Python program to find smallest and second smallest elements
import math
 
def print2Smallest(arr):
 
    # There should be atleast two elements
    arr_size = len(arr)
    if arr_size < 2:
        print ("Invalid Input")
        return
 
    first = second = math.inf
    for i in range(0, arr_size):
 
        # If current element is smaller than first then
        # update both first and second
        if arr[i] < first:
            second = first
            first = arr[i]
 
        # If arr[i] is in between first and second then
        # update second
        elif (arr[i] < second and arr[i] != first):
            second = arr[i];
 
    if (second == math.inf):
        print ("No second smallest element")
    else:
        print ('The smallest element is',first,'and', \
              ' second smallest element is',second)
 
# Driver function to test above function
arr = [12, 13, 1, 10, 34, 1]
print2Smallest(arr)
 
# This code is contributed by Devesh Agrawal

Time complexity: linear
Space complexity: constant
# Python3 program to find the smallest
# elements missing in a sorted array.
 
def findFirstMissing(array, start, end):
 
    if (start > end):
        return end + 1
 
    if (start != array[start]):
        return start;
 
    mid = int((start + end) / 2)
 
    # Left half has all elements
    # from 0 to mid
    if (array[mid] == mid):
        return findFirstMissing(array,
                          mid+1, end)
 
    return findFirstMissing(array,
                          start, mid)
 
 
# driver program to test above function
arr = [0, 1, 2, 3, 4, 5, 6, 7, 10]
n = len(arr)
print("Smallest missing element is",
      findFirstMissing(arr, 0, n-1))
 
# This code is contributed by Smitha Dinesh Semwal

Time complexity: logn
Space complexity: logn
# Python3 program for above approach
 
# Function to find Smallest 
# Missing in Sorted Array
def findSmallestMissinginSortedArray(arr):
     
    # Check if 0 is missing 
    # in the array
    if (arr[0] != 0):
        return 0
     
    # Check is all numbers 0 to n - 1 
    # are present in array
    if (arr[-1] == len(arr) - 1):
        return len(arr)
     
    first = arr[0]
     
    return findFirstMissing(arr, 0,
            len(arr) - 1, first)
 
# Function to find missing element 
def findFirstMissing(arr, start, end, first):
     
    if (start < end):
        mid = int((start + end) / 2)
         
        # Index matches with value 
        # at that index, means missing
        # element cannot be upto that point
        if (arr[mid] != mid + first):
            return findFirstMissing(arr, start,
                                    mid, first)
        else:
            return findFirstMissing(arr, mid + 1, 
                                    end, first)
     
    return start + first
 
# Driver code
arr = [ 0, 1, 2, 3, 4, 5, 7 ]
n = len(arr)
 
# Function Call
print("First Missing element is :",
      findSmallestMissinginSortedArray(arr))
 
# This code is contributed by rag2127

Time complexity: logn
Space complexity: logn
# Python code to implement the approach
 
# Function to find the maximum sum
def findMaxSum(arr, N):
 
    # Declare dp array
    dp = [[0 for i in range(2)] for j in range(N)]
     
    if (N == 1):
        return arr[0]
   
    # Initialize the values in dp array
    dp[0][0] = 0
    dp[0][1] = arr[0]
   
    # Loop to find the maximum possible sum
    for i in range(1,N):
        dp[i][1] = dp[i - 1][0] + arr[i]
        dp[i][0] = max(dp[i - 1][1], dp[i - 1][0])
   
    # Return the maximum sum
    return max(dp[N - 1][0], dp[N - 1][1])
 
# Driver Code
 
# Creating the array
arr = [ 5, 5, 10, 100, 10, 5 ]
N = len(arr)
 
# Function call
print(findMaxSum(arr, N))
 
# This code is contributed by shinjanpatra

Time complexity: linear
Space complexity: linear
# Python code to implement the approach
 
# Function to return max sum such that
# no two elements are adjacent
def findMaxSum(arr, n):
    incl = 0
    excl = 0  
    for i in arr:
         
        # Current max excluding i
        new_excl = max (excl, incl)
         
        # Current max including i
        incl = excl + i
        excl = new_excl
     
    # Return max of incl and excl
    return max(excl, incl)
 
# Driver code
if __name__ == "__main__":
    arr = [5, 5, 10, 100, 10, 5]
    N = 6
     
    # Function call
    print (findMaxSum(arr, N))
 
# This code is contributed by Kalai Selvan

Time complexity: linear
Space complexity: constant
# Python 3 program to demonstrate working of Square Root
# Decomposition.
from math import sqrt
 
MAXN = 10000
SQRSIZE = 100
 
arr = [0]*(MAXN)         # original array
block = [0]*(SQRSIZE)     # decomposed array
blk_sz = 0                 # block size
 
# Time Complexity : O(1)
def update(idx, val):
    blockNumber = idx // blk_sz
    block[blockNumber] += val - arr[idx]
    arr[idx] = val
 
# Time Complexity : O(sqrt(n))
def query(l, r):
    sum = 0
    while (l < r and l % blk_sz != 0 and l != 0):
         
        # traversing first block in range
        sum += arr[l]
        l += 1
     
    while (l + blk_sz - 1 <= r):
         
        # traversing completely overlapped blocks in range
        sum += block[l//blk_sz]
        l += blk_sz
     
    while (l <= r):
         
        # traversing last block in range
        sum += arr[l]
        l += 1
     
    return sum
     
# Fills values in input[]
def preprocess(input, n):
     
    # initiating block pointer
    blk_idx = -1
 
    # calculating size of block
    global blk_sz
    blk_sz = int(sqrt(n))
 
    # building the decomposed array
    for i in range(n):
        arr[i] = input[i];
        if (i % blk_sz == 0):
             
            # entering next block
            # incrementing block pointer
            blk_idx += 1;
         
        block[blk_idx] += arr[i]
 
# Driver code
 
# We have used separate array for input because
# the purpose of this code is to explain SQRT
# decomposition in competitive programming where
# we have multiple inputs.
input= [1, 5, 2, 4, 6, 1, 3, 5, 7, 10]
n = len(input)
 
preprocess(input, n)
 
print("query(3,8) : ",query(3, 8))
print("query(1,6) : ",query(1, 6))
update(8, 0)
print("query(8,8) : ",query(8, 8))
 
# This code is contributed by Sanjit_Prasad

Time complexity: linear
Space complexity: linear
# Python3 program to do range minimum
# query using sparse table
import math
 
# Fills lookup array lookup[][] in
# bottom up manner.
def buildSparseTable(arr, n):
 
    # Initialize M for the intervals
    # with length 1
    for i in range(0, n):
        lookup[i][0] = arr[i]
     
    j = 1
     
    # Compute values from smaller to
    # bigger intervals
    while (1 << j) <= n:
 
        # Compute minimum value for all
        # intervals with size 2^j
        i = 0
        while (i + (1 << j) - 1) < n:
 
            # For arr[2][10], we compare arr[lookup[0][7]]
            # and arr[lookup[3][10]]
            if (lookup[i][j - 1] <
                lookup[i + (1 << (j - 1))][j - 1]):
                lookup[i][j] = lookup[i][j - 1]
            else:
                lookup[i][j] = \
                        lookup[i + (1 << (j - 1))][j - 1]
             
            i += 1
        j += 1       
 
# Returns minimum of arr[L..R]
def query(L, R):
 
    # Find highest power of 2 that is smaller
    # than or equal to count of elements in
    # given range. For [2, 10], j = 3
    j = int(math.log2(R - L + 1))
 
    # Compute minimum of last 2^j elements
    # with first 2^j elements in range.
    # For [2, 10], we compare arr[lookup[0][3]]
    # and arr[lookup[3][3]],
    if lookup[L][j] <= lookup[R - (1 << j) + 1][j]:
        return lookup[L][j]
 
    else:
        return lookup[R - (1 << j) + 1][j]
 
# Driver Code
if __name__ == "__main__":
 
    a = [7, 2, 3, 0, 5, 10, 3, 12, 18]
    n = len(a)
    MAX = 500
     
    # lookup[i][j] is going to store minimum
    # value in arr[i..j]. Ideally lookup table
    # size should not be fixed and should be
    # determined using n Log n. It is kept
    # constant to keep code simple.
    lookup = [[0 for i in range(MAX)]
                 for j in range(MAX)]
 
    buildSparseTable(a, n)
    print(query(0, 4))
    print(query(4, 7))
    print(query(7, 8))
     
# This code is contributed by Rituraj Jain

Time complexity: nlogn
Space complexity: nlogn
# Python3 program to do range minimum
# query using sparse table
import math
 
# Fills lookup array lookup[][] in
# bottom up manner.
def buildSparseTable(arr, n):
 
    # GCD of single element is element itself
    for i in range(0, n):
        table[i][0] = arr[i]
 
    # Build sparse table
    j = 1
    while (1 << j) <= n:
        i = 0
        while i <= n - (1 << j):
            table[i][j] = math.gcd(table[i][j - 1],
                                   table[i + (1 << (j - 1))][j - 1])
             
            i += 1
        j += 1
 
# Returns minimum of arr[L..R]
def query(L, R):
 
    # Find highest power of 2 that is smaller
    # than or equal to count of elements in
    # given range. For [2, 10], j = 3
    j = int(math.log2(R - L + 1))
 
    # Compute GCD of last 2^j elements with
    # first 2^j elements in range.
    # For [2, 10], we find GCD of arr[lookup[0][3]]
    # and arr[lookup[3][3]],
    return math.gcd(table[L][j],
                    table[R - (1 << j) + 1][j])
     
# Driver Code
if __name__ == "__main__":
 
    a = [7, 2, 3, 0, 5, 10, 3, 12, 18]
    n = len(a)
    MAX = 500
     
    # lookup[i][j] is going to store minimum
    # value in arr[i..j]. Ideally lookup table
    # size should not be fixed and should be
    # determined using n Log n. It is kept
    # constant to keep code simple.
    table = [[0 for i in range(MAX)]
                for j in range(MAX)]
 
    buildSparseTable(a, n)
    print(query(0, 2))
    print(query(1, 3))
    print(query(4, 5))
     
# This code is contributed by Rituraj Jain

Time complexity: nlogn
Space complexity: nlogn
# Python program to find total 
# count of an element in a range
 
# Returns count of element
# in arr[left-1..right-1]
def findFrequency(arr, n, left, right, element):
 
    count = 0
    for i in range(left - 1, right):
        if (arr[i] == element):
            count += 1
    return count
 
 
# Driver Code
arr = [2, 8, 6, 9, 8, 6, 8, 2, 11]
n = len(arr)
 
# Print frequency of 2 from position 1 to 6
print("Frequency of 2 from 1 to 6 = ",
        findFrequency(arr, n, 1, 6, 2))
 
# Print frequency of 8 from position 4 to 9
print("Frequency of 8 from 4 to 9 = ",
        findFrequency(arr, n, 4, 9, 8))
         
     
# This code is contributed by Anant Agarwal.

Time complexity: linear
Space complexity: constant
# Python3 program to get updated array
# after many array range add operation
 
# Utility method to add value
# val, to range [lo, hi]
 
 
def add(arr, N, lo, hi, val):
 
    arr[lo] += val
    if (hi != N - 1):
        arr[hi + 1] -= val
 
# Utility method to get actual
# array from operation array
 
 
def updateArray(arr, N):
 
    # convert array into prefix sum array
    for i in range(1, N):
        arr[i] += arr[i - 1]
 
# method to print final updated array
 
 
def printArr(arr, N):
 
    updateArray(arr, N)
    for i in range(N):
        print(arr[i], end=" ")
    print()
 
 
# Driver code
N = 6
arr = [0 for i in range(N)]
 
# Range add Queries
add(arr, N, 0, 2, 100)
add(arr, N, 1, 5, 100)
add(arr, N, 2, 3, 100)
 
printArr(arr, N)
 
# This code is contributed by Anant Agarwal.

Time complexity: linear
Space complexity: constant
# Python program for
# queries of GCD excluding
# given range of elements.
 
# Calculating GCD
# using euclid algorithm
def GCD(a,b):
    if (b==0):
        return a
    return GCD (b, a%b)
 
  
# Filling the prefix
# and suffix array
def FillPrefixSuffix(prefix,arr,suffix,n):
 
    # Filling the prefix array
    # following relation
    # prefix(i) = GCD(prefix(i-1), arr(i))
    prefix[0] = arr[0]
    for i in range(1,n):
        prefix[i] = GCD (prefix[i-1], arr[i])
  
    # Filling the suffix
    # array following the
    # relation suffix(i) = GCD(suffix(i+1), arr(i))
    suffix[n-1] = arr[n-1]
  
    for i in range(n-2,-1,-1):
        suffix[i] = GCD (suffix[i+1], arr[i])
 
  
# To calculate gcd of
# the numbers outside range
def GCDoutsideRange(l,r,prefix,suffix,n):
     
    # If l=0, we need to tell GCD of numbers
    # from r+1 to n
    if (l==0):
        return suffix[r+1]
  
    # If r=n-1 we need to return the gcd of
    # numbers from 1 to l
    if (r==n-1):
        return prefix[l-1]
    return GCD(prefix[l-1], suffix[r+1])
 
# Driver code
 
arr = [2, 6, 9]
n = len(arr)
prefix=[]
suffix=[]
for i in range(n+1):
    prefix.append(0)
    suffix.append(0)
     
FillPrefixSuffix(prefix, arr, suffix, n)
l = 0
r = 0
print(GCDoutsideRange(l, r, prefix, suffix, n))
 
l = 1
r = 1
print(GCDoutsideRange(l, r, prefix, suffix, n))
 
l = 1
r = 2
print(GCDoutsideRange(l, r, prefix, suffix, n))
 
# This code is contributed
# by Anant Agarwal.

Time complexity: nlogn
Space complexity: linear
# function to count elements within given range
def countInRange(arr, n, x, y):
 
    # initialize result
    count = 0;
 
    for i in range(n):
 
        # check if element is in range
        if (arr[i] >= x and arr[i] <= y):
            count += 1
    return count
 
# driver function
arr = [1, 3, 4, 9, 10, 3]
n = len(arr)
 
# Answer queries
i = 1
j = 4
print(countInRange(arr, n, i, j))
i = 9
j = 12
print(countInRange(arr, n, i, j))

Time complexity: linear
Space complexity: constant
# function to find first index >= x
def lowerIndex(arr, n, x):
  l = 0
  h = n-1
  while (l <= h):
    mid = int((l + h)//2)
    if (arr[mid] >= x):
      h = mid - 1
    else:
      l = mid + 1
  return l
 
 
# function to find last index <= x
def upperIndex(arr, n, x):
  l = 0
  h = n-1
  while (l <= h):
    mid = int((l + h)//2)
    if (arr[mid] <= x):
      l = mid + 1
    else:
      h = mid - 1
  return h
 
 
# function to count elements within given range
def countInRange(arr, n, x, y):
  # initialize result
  count = 0;
  count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1;
  return count
 
# driver function
arr = [1, 3, 4, 9, 10, 3]
 
# Preprocess array
arr.sort()
n = len(arr)
 
# Answer queries
i = 1
j = 4
print(countInRange(arr, n, i, j))
i = 9
j = 12
print(countInRange(arr, n, i, j))

Time complexity: nlogn
Space complexity: constant
# implementation of finding number
# represented by binary subarray
from math import pow
 
# Fills pre[]
def precompute(arr, n, pre):
     
    pre[n - 1] = arr[n - 1] * pow(2, 0)
    i = n - 2
    while(i >= 0):
        pre[i] = (pre[i + 1] + arr[i] *
                 (1 << (n - 1 - i)))
        i -= 1
 
# returns the number represented by
# a binary subarray l to r
def decimalOfSubarr(arr, l, r, n, pre):
     
    # if r is equal to n-1 r+1 does not exist
    if (r != n - 1):
        return ((pre[l] - pre[r + 1]) /
                (1 << (n - 1 - r)))
 
    return pre[l] / (1 << (n - 1 - r))
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 0, 1, 0, 1, 1]
    n = len(arr)
 
    pre = [0 for i in range(n)]
    precompute(arr, n, pre)
    print(int(decimalOfSubarr(arr, 2, 4, n, pre)))
    print(int(decimalOfSubarr(arr, 4, 5, n, pre)))
 
# This code is contributed by
# Surendra_Gangwar

Time complexity: linear
Space complexity: linear