Banana-Leopard/TASTY huggingface dataset:
# Python code to rearrange
# an array such that
# even index elements
# are smaller and odd
# index elements are
# greater than their
# next.
 
def rearrange(arr, n):
 
    for i in range(n - 1):
        if (i % 2 == 0 and arr[i] > arr[i + 1]):
         
            temp = arr[i]
            arr[i]= arr[i + 1]
            arr[i + 1]= temp
         
        if (i % 2 != 0 and arr[i] < arr[i + 1]):
          
            temp = arr[i]
            arr[i]= arr[i + 1]
            arr[i + 1]= temp
            
  
# Utility that prints out an array in
# a line
def printArray(arr, size):
 
    for i in range(size):
        print(arr[i], " ", end ="")
  
    print()
 
# Driver code
 
arr = [ 6, 4, 2, 1, 8, 3 ]
n = len(arr)
  
print("Before rearranging: ")
printArray(arr, n)
  
rearrange(arr, n)
  
print("After rearranging:")
printArray(arr, n);
 
# This code is contributed
# by Anant Agarwal.

Time complexity: linear
Space complexity: constant
# Python 3 program to rearrange 
# positive and negative numbers
  
def rearrange(a, size) :
      
    positive = 0
    negative = 1
  
    while (True) :
          
        # Move forward the positive
        # pointer till negative number
        # number not encountered 
        while (positive < size and a[positive] >= 0) :
            positive = positive + 2
  
        # Move forward the negative 
        # pointer till positive number
        # number not encountered 
        while (negative < size and a[negative] <= 0) :
            negative = negative + 2
  
        # Swap array elements to fix
        # their position.
        if (positive < size and negative < size) :
            temp = a[positive]
            a[positive] = a[negative]
            a[negative] = temp
  
        # Break from the while loop when
        # any index exceeds the size of 
        # the array 
        else :
            break
          
# Driver code
arr =[ 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 ]
n = len(arr)
  
rearrange(arr, n)
for i in range(0, n) :
    print(arr[i], end = " ")
  
# This code is contributed by Nikita Tiwari.

Time complexity: quadratic
Space complexity: constant
# Python3 program to rearrange positive
# and negative numbers
  
# Print array function
def printArray(a, n):
    for i in a:
        print(i, end = " ")
    print()
  
  
# Driver code
arr = [1, -3, 5, 6, -3, 6, 7, -4, 9, 10]
n = len(arr)
  
# before modification
printArray(arr, n)
  
for i in range(n):
  
    if(arr[i] >= 0 and i % 2 == 1):
  
        # out of order positive element
        for j in range(i + 1, n):
  
            if(arr[j] < 0 and j % 2 == 0):
                  
                # find out of order negative 
                # element in remaining array
                arr[i], arr[j] = arr[j], arr[i]
                break
              
    elif (arr[i] < 0 and i % 2 == 0):
          
        # out of order negative element
        for j in range(i + 1, n):
  
            if(arr[j] >= 0 and j % 2 == 1):
                  
                # find out of order positive 
                # element in remaining array
                arr[i], arr[j] = arr[j], arr[i]
                break
  
# after modification
printArray(arr, n); 
  
# This code is contributed 
# by mohit kumar

Time complexity: quadratic
Space complexity: constant
# Python program to update every array element with
# multiplication of previous and next numbers in array
 
def modify(arr, n):
 
 # Nothing to do when array size is 1
    if n <= 1:
        return
 
    # store current value of arr[0] and update it
    prev = arr[0]
    arr[0] = arr[0] * arr[1]
 
    # Update rest of the array elements
    for i in range(1, n-1):
     
        # Store current value of next interaction
        curr = arr[i];
 
        # Update current value using previous value
        arr[i] = prev * arr[i+1]
 
           # Update previous value
        prev = curr
     
 
    # Update last array element
    arr[n-1] = prev * arr[n-1]
 
 
# Driver program
arr = [2, 3, 4, 5, 6]
n = len(arr)
modify(arr, n)
for i in range (0, n):
    print(arr[i],end=" ")
 
# This code is contributed by
# Smitha Dinesh Semwal

Time complexity: linear
Space complexity: constant
# Python Program to shuffle a given array
from random import randint
 
# A function to generate a random permutation of arr[]
def randomize (arr, n):
    # Start from the last element and swap one by one. We don't
    # need to run for the first element that's why i > 0
    for i in range(n-1,0,-1):
        # Pick a random index from 0 to i
        j = randint(0,i+1)
 
        # Swap arr[i] with the element at random index
        arr[i],arr[j] = arr[j],arr[i]
    return arr
 
# Driver program to test above function.
arr = [1, 2, 3, 4, 5, 6, 7, 8]
n = len(arr)
print(randomize(arr, n))
 
 
# This code is contributed by Pratik Chhajer

Time complexity: linear
Space complexity: constant
# Python3 implementation of the above approach
def arrayEvenAndOdd(arr,  n):
     
    index = 0;
    a = [0 for i in range(n)]
     
    for i in range(n):
        if (arr[i] % 2 == 0):
            a[index] = arr[i]
            ind += 1
 
    for i in range(n):
        if (arr[i] % 2 != 0):
            a[index] = arr[i]
            ind += 1
 
    for i in range(n):
        print(a[i], end = " ")
         
    print()
 
# Driver code
arr = [ 1, 3, 2, 4, 7, 6, 9, 10 ]
n = len(arr)
 
# Function call
arrayEvenAndOdd(arr, n)
 
# This code is contributed by rohitsingh07052

Time complexity: linear
Space complexity: linear
# Python3 code to segregate even odd
# numbers in an array
 
# Function to segregate even odd numbers
def arrayEvenAndOdd(arr,n):
    i = -1
    j= 0
    while (j!=n):
        if (arr[j] % 2 ==0):
            i = i+1
 
            # Swapping even and odd numbers
            arr[i],arr[j] = arr[j],arr[i]
             
        j = j+1
     
    # Printing segregated array
    for i in arr:
        print (str(i) + " " ,end='')
         
# Driver Code
if __name__=='__main__':
    arr = [ 1 ,3, 2, 4, 7, 6, 9, 10]
    n = len(arr)
    arrayEvenAndOdd(arr,n)
 
# This code was contributed by
# Yatin Gupta

Time complexity: linear
Space complexity: constant
# Python3 implementation of above implementation
 
# This function returns k'th smallest element
# in arr[l..r] using QuickSort based method.
# ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT
from random import randint
 
def randomPartition(arr, l, r):
    n = r - l + 1
    pivot = randint(1, 100) % n
    arr[l + pivot], arr[r] = arr[l + pivot], arr[r]
    return partition(arr, l, r)
 
def kthSmallest(arr, l, r, k):
 
    # If k is smaller than
    # number of elements in array
    if (k > 0 and k <= r - l + 1):
 
        # Partition the array around last element and
        # get position of pivot element in sorted array
        pos = randomPartition(arr, l, r)
 
        # If position is same as k
        if (pos - l == k - 1):
            return arr[pos]
             
        # If position is more, recur for left subarray
        if (pos - l > k - 1):
            return kthSmallest(arr, l, pos - 1, k)
 
        # Else recur for right subarray
        return kthSmallest(arr, pos + 1, r,
                           k - pos + l - 1)
 
    # If k is more than number of elements in array
    return 10**9
 
# Standard partition process of QuickSort().
# It considers the last element as pivot and
# moves all smaller element to left of it
# and greater elements to right
def partition(arr, l, r):
    x = arr[r]
    i = l
    for j in range(l, r):
        if (arr[j] <= x):
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
 
    arr[i], arr[r] = arr[r], arr[i]
    return i
 
# Driver Code
arr = [12, 3, 5, 7, 4, 19, 26]
n = len(arr)
k = 3
print("K'th smallest element is",
       kthSmallest(arr, 0, n - 1, k))
 
# This code is contributed by Mohit Kumar

Time complexity: nlogn
Space complexity: constant
# Program for kth largest element in a 2d array
# sorted row-wise and column-wise
from sys import maxsize
 
# A structure to store an entry of heap.
# The entry contains a value from 2D array,
# row and column numbers of the value
class HeapNode:
    def __init__(self, val, r, c):
        self.val = val # value to be stored
        self.r = r # Row number of value in 2D array
        self.c = c # Column number of value in 2D array
 
# A utility function to minheapify the node harr[i]
# of a heap stored in harr[]
def minHeapify(harr, i, heap_size):
    l = i * 2 + 1
    r = i * 2 + 2
    if(l < heap_size and r<heap_size and harr[l].val < harr[i].val and harr[r].val < harr[i].val):
      temp= HeapNode(0,0,0)
      temp=harr[r]
      harr[r]=harr[i]
      harr[i]=harr[l]
      harr[l]=temp
      minHeapify(harr ,l,heap_size)
      minHeapify(harr ,r,heap_size)
    if (l < heap_size and harr[l].val < harr[i].val):
      temp= HeapNode(0,0,0)
      temp=harr[i]
      harr[i]=harr[l]
      harr[l]=temp
      minHeapify(harr ,l,heap_size)
             
# This function returns kth smallest element
# in a 2D array mat[][]
def kthSmallest(mat, n, k):
 
    # k must be greater than 0 and smaller than n*n
    if k < 0 or k > n * n:
        return maxsize
 
    # Create a min heap of elements from
    # first row of 2D array
    harr = [0] * n
    for i in range(n):
        harr[i] = HeapNode(mat[0][i], 0, i)
 
    hr = HeapNode(0, 0, 0)
    for i in range(k):
 
        # Get current heap root
        hr = harr[0]
 
        # Get next value from column of root's value.
        # If the value stored at root was last value
        # in its column, then assign INFINITE as next value
        nextval = mat[hr.r + 1][hr.c] if (hr.r < n - 1) else maxsize
 
        # Update heap root with next value
        harr[0] = HeapNode(nextval, hr.r + 1, hr.c)
 
        # Heapify root
        minHeapify(harr, 0, n)
 
    # Return the value at last extracted root
    return hr.val
 
# Driver Code
if __name__ == "__main__":
    mat = [[10, 20, 30, 40],
        [15, 25, 35, 45],
        [25, 29, 37, 48],
        [32, 33, 39, 50]]
    print("7th smallest element is",
            kthSmallest(mat, 4, 7))
 
# This code is contributed by Rishabh Chauhan

Time complexity: nlogn
Space complexity: linear
# This returns count of elements in matrix
# less than of equal to num
def getElementsGreaterThanOrEqual(num,n,mat):
    ans = 0
    for i in range(n):
       
        # if num is less than the first element
        # then no more element in matrix
        # further are less than or equal to num
        if (mat[i][0] > num):
            return ans
           
        # if num is greater than last element,
        # it is greater than all elements
        # in that row
        if (mat[i][n - 1] <= num):
            ans += n
            continue
        # This contain the col index of last element
        # in matrix less than of equal
        # to num
        greaterThan = 0
        jump = n // 2
        while(jump >= 1):
                while (greaterThan + jump < n and mat[i][greaterThan + jump] <= num):
                    greaterThan += jump
                jump //= 2
 
        ans += greaterThan + 1
    return ans
 
# returns kth smallest index in the matrix
def kthSmallest(mat, n, k):
 
    # We know the answer lies between
    # the first and the last element
    # So do a binary search on answer
    # based on the number of elements
    # our current element is greater than
    # the elements in the matrix
    l,r = mat[0][0],mat[n - 1][n - 1]
 
    while (l <= r):
        mid = l + (r - l) // 2
        greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat)
 
        if (greaterThanOrEqualMid >= k):
            r = mid - 1
        else:
            l = mid + 1
 
    return l
 
# driver code
n = 4
mat = [[10, 20, 30, 40],[15, 25, 35, 45],[25, 29, 37, 48],[32, 33, 39, 50]]
print(f"7th smallest element is {kthSmallest(mat, 4, 7)}")
 
# This code is contributed by shinjanpatra

Time complexity: nlogn
Space complexity: linear
# Python program to implement above approach
def kthSmallest(mat, n, k):
         
    a = [0 for i in range(n*n)]
    v=0
         
    for i in range(n):
        for j in range(n):
            a[v] = mat[i][j]
            v += 1
             
    a.sort()
    result = a[k - 1]
    return result
 
# driver program
         
mat = [ [ 10, 20, 30, 40 ],
            [ 15, 25, 35, 45 ],
            [ 25, 29, 37, 48 ],
            [ 32, 33, 39, 50 ] ]
res = kthSmallest(mat, 4, 7)
     
print("7th smallest element is "+ str(res))
 
# This code is contributed by shinjanpatra

Time complexity: quadratic
Space complexity: quadratic
import heapq
 
 
def kthSmallest(matrix, k):
    # n = size of matrix
    n = len(matrix)
 
    # using built-in priority queue which acts as max Heap i.e. largest element will be on top
    # Kth smallest element can also be seen as largest element in a priority queue of size k
    # By this logic we pop elements from priority queue when its size becomes greater than k
    # thus top of priority queue is kth smallest element in matrix
 
    maxH = []
    for i in range(n):
        for j in range(n):
            heapq.heappush(maxH, -matrix[i][j])
            if len(maxH) > k:
                heapq.heappop(maxH)
    return -maxH[0]
 
 
matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]]
k = 8
print("8th smallest element is", kthSmallest(matrix, k))
 
# This code is comtributed by Tapesh (tapeshdua420)

Time complexity: quadratic
Space complexity: linear
# Python3 program to find maximum
# in arr[] of size n 
  
# Function to find maximum
# in arr[] of size n
def largest(arr,n):
   # Initialize maximum element
   mx = arr[0]         
    
   # Traverse array elements from second          
   # and compare every element with           
   # current max          
   for i in range(1, n):          
     if arr[i] > mx:          
         mx = arr[i]   
           
   return mx
  
# Driver Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
  
#calculating length of an array
Ans = largest(arr,n)
  
# display max
print ("Largest in given array is",Ans)
  
# This code is contributed by Jai Parkash Bhardwaj
# and improved by prophet1999

Time complexity: linear
Space complexity: constant
import math
  
class GFG :
    @staticmethod
    def  largest( arr,  n,  i) :
        
        # last index
        # return the element
        if (i == n - 1) :
            return arr[i]
            
        # find the maximum from rest of the array
        recMax = GFG.largest(arr, n, i + 1)
          
        # compare with i-th element and return
        return max(recMax,arr[i])
        
    # Driver Code
    @staticmethod
    def main( args) :
        arr = [10, 324, 45, 90, 9808]
        n = len(arr)
        print("Largest in given array is " + str(GFG.largest(arr, n, 0)))
      
if __name__=="__main__":
    GFG.main([])
      
    # This code is contributed by aadityaburujwale.

Time complexity: linear
Space complexity: linear
# Python 3 program to find
# maximum in arr[] of size n 
  
# returns maximum
# in arr[] of size n
def largest(arr, n):
  
    return max(arr)
  
# driver code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
  
print(largest(arr, n))
  
# This code is contributed by
# Smitha Dinesh Semwal

Time complexity: linear
Space complexity: constant
# Python3 code to find largest three
# elements in an array
import sys
 
# Function to print three largest
# elements
def print3largest(arr, arr_size):
 
    # There should be atleast three
    # elements
    if (arr_size < 3):
     
        print(" Invalid Input ")
        return
     
    third = first = second = -sys.maxsize
     
    for i in range(0, arr_size):
     
        # If current element is greater
        # than first
        if (arr[i] > first):
         
            third = second
            second = first
            first = arr[i]
         
 
        # If arr[i] is in between first
        # and second then update second
        elif (arr[i] > second):
         
            third = second
            second = arr[i]
         
        elif (arr[i] > third):
            third = arr[i]
     
    print("Three largest elements are",
                  first, second, third)
 
# Driver program to test above function
arr = [12, 13, 1, 10, 34, 1]
n = len(arr)
print3largest(arr, n)
 
# This code is contributed by Smitha Dinesh Semwal
# and edited by Ayush Singla(@ayusin51).

Time complexity: linear
Space complexity: constant
# Python3 code to find largest
# three elements in an array
def find3largest(arr, n):
    arr = sorted(arr) # It uses Tuned Quicksort with
                      # avg. case Time complexity = O(nLogn)
 
    check = 0
    count = 1
 
    for i in range(1, n + 1):
 
        if(count < 4):
            if(check != arr[n - i]):
                 
                # to handle duplicate values
                print(arr[n - i], end = " ")
                check = arr[n - i]
                count += 1
        else:
            break
 
# Driver code
arr = [12, 45, 1, -1, 45,
       54, 23, 5, 0, -10]
n = len(arr)
find3largest(arr, n)
 
# This code is contributed by mohit kumar

Time complexity: nlogn
Space complexity: constant
# Python program to implement
# the above approach
 
# Driver Code
V = [ 11, 65, 193, 36, 209, 664, 32 ];
V.sort()
V.reverse()
 
print(f"first =  {V[0]}");
print(f"second =  {V[1]}");
print(f"third =  {V[2]}");
     
# This code is contributed by Saurabh Jaiswal

Time complexity: nlogn
Space complexity: constant
# Python3 program to find
# all elements in array
# which have at-least two
# greater elements itself.
 
def findElements( arr, n):
 
    # Pick elements one by
        # one and count greater
    # elements. If count
        # is more than 2, print
    # that element.
 
    for i in range(n):
        count = 0
        for j in range(0, n):
            if arr[j] > arr[i]:
                count = count + 1
                         
                 
        if count >= 2 :
            print(arr[i], end=" ")
             
 
# Driver code
arr = [ 2, -6 ,3 , 5, 1]
n = len(arr)
findElements(arr, n)
     
# This code is contributed by sunnysingh

Time complexity: quadratic
Space complexity: constant
# Sorting based Python 3 program
# to find all elements in array
# which have atleast two greater
# elements itself.
 
def findElements(arr, n):
 
    arr.sort()
 
    for i in range(0, n-2):
        print(arr[i], end =" ")
 
# Driven source
arr = [2, -6, 3, 5, 1]
n = len(arr)
findElements(arr, n)
 
# This code is contributed
# by Smitha Dinesh Semwal

Time complexity: nlogn
Space complexity: constant
# Python3 program to find all elements
# in array which have atleast two
# greater elements itself.
import sys
 
def findElements(arr, n):
 
    first = -sys.maxsize
    second = -sys.maxsize
 
    for i in range(0, n):
     
        # 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):
            second = arr[i]
     
    for i in range(0, n):
        if (arr[i] < second):
            print(arr[i], end =" ")
 
 
# Driver code
arr = [2, -6, 3, 5, 1]
n = len(arr)
findElements(arr, n)
 
# This code is contributed
# by Smitha Dinesh Semwal

Time complexity: linear
Space complexity: constant
# Python3 program to find mean
# and median of an array
 
# Function for calculating mean
 
 
def findMean(a, n):
 
    sum = 0
    for i in range(0, n):
        sum += a[i]
 
    return float(sum/n)
 
# Function for calculating median
 
 
def findMedian(a, n):
 
    # First we sort the array
    sorted(a)
 
    # check for even case
    if n % 2 != 0:
        return float(a[int(n/2)])
 
    return float((a[int((n-1)/2)] +
                  a[int(n/2)])/2.0)
 
 
# Driver code
a = [1, 3, 4, 2, 7, 5, 8, 6]
n = len(a)
 
# Function call
print("Mean =", findMean(a, n))
print("Median =", findMedian(a, n))
 
# This code is contributed by Smitha Dinesh Semwal

Time complexity: nlogn
Space complexity: constant
# python3 program to find med in
# stream of running integers
from heapq import *
  
# function to calculate med of stream
def printMedians(arr, n):
    # max heap to store the smaller half elements
    s = []
    # min heap to store the greater half elements
    g = []
  
    heapify(s)
    heapify(g)
  
    med = arr[0]
    heappush(s, arr[0])
  
    print(med)
  
    # reading elements of stream one by one
    for i in range(1, n):
        x = arr[i]
  
        # case1(left side heap has more elements)
        if len(s) > len(g):
            if x < med:
                heappush(g, heappop(s))
                heappush(s, x)
            else:
                heappush(g, x)
            med = (nlargest(1, s)[0] + nsmallest(1, g)[0])/2
  
        # case2(both heaps are balanced)
        elif len(s) == len(g):
            if x < med:
                heappush(s, x)
                med = nlargest(1, s)[0]
            else:
                heappush(g, x)
                med = nsmallest(1, g)[0]
  
        # case3(right side heap has more elements)
        else:
            if x > med:
                heappush(s, heappop(g))
                heappush(g, x)
            else:
                heappush(s, x)
            med = (nlargest(1, s)[0] + nsmallest(1, g)[0])/2
  
        print(med)
  
# Driver program to test above functions
arr = [5, 15, 10, 20, 3]
printMedians(arr, len(arr))
  
# This code is contributed by cavi4762.

Time complexity: nlogn
Space complexity: linear
# Python3 program to find minimum
# product of k elements in an array
 
import math
import heapq
 
def minProduct(arr, n, k):
 
    heapq.heapify(arr)
    count = 0
    ans = 1
 
    # One by one extract
    # items from min heap
    while ( arr ) and count < k:
        x = heapq.heappop(arr)
        ans = ans * x
        count = count + 1
     
    return ans;
 
# Driver method
arr = [198, 76, 544, 123, 154, 675]
k = 2
n = len(arr)
print ("Minimum product is",
       minProduct(arr, n, k))

Time complexity: nlogn
Space complexity: linear
# Python program to find out k maximum
# non-overlapping subarray sums.
 
# Function to compute k
# maximum sub-array sums.
def kmax(arr, k, n):
 
    # In each iteration it will give
    # the ith maximum subarray sum.
    for c in range(k):
 
        # Kadane's algorithm
        max_so_far = -float("inf")
        max_here = 0
 
        # compute starting and ending
        # index of each of the subarray
        start = 0
        end = 0
        s = 0
        for i in range(n):
             
            max_here += arr[i]
            if (max_so_far < max_here):
                 
                max_so_far = max_here
                start = s
                end = i
            if (max_here < 0):
                 
                max_here = 0
                s = i + 1
 
        # Print out the result
        print("Maximum non-overlapping sub-array sum",
               c + 1, ": ", max_so_far, ", starting index: ",
               start, ", ending index: ", end, ".", sep = "")
 
        # Replace all elements of the maximum subarray
        # by -infinity. Hence these places cannot form
        # maximum sum subarray again.
        for l in range(start, end+1):
            arr[l] = -float("inf")
    print()
 
# Driver Program
# Test case 1
arr1 = [4, 1, 1, -1, -3, -5, 6, 2, -6, -2]
k1 = 3
n1 = len(arr1)
 
# Function calling
kmax(arr1, k1, n1)
 
# Test case 2
arr2 = [5, 1, 2, -6, 2, -1, 3, 1]
k2 = 2
n2 = len(arr2)
 
# Function calling
kmax(arr2, k2, n2)

Time complexity: quadratic
Space complexity: constant