Banana-Leopard/TASTY huggingface dataset:
# LCM of given range queries using Segment Tree
MAX = 1000
 
# allocate space for tree
tree = [0] * (4 * MAX)
 
# declaring the array globally
arr = [0] * MAX
 
# Function to return gcd of a and b
 
 
def gcd(a: int, b: int):
    if a == 0:
        return b
    return gcd(b % a, a)
 
# utility function to find lcm
 
 
def lcm(a: int, b: int):
    return (a * b) // gcd(a, b)
 
# Function to build the segment tree
# Node starts beginning index of current subtree.
# start and end are indexes in arr[] which is global
 
 
def build(node: int, start: int, end: int):
 
    # If there is only one element
    # in current subarray
    if start == end:
        tree[node] = arr[start]
        return
 
    mid = (start + end) // 2
 
    # build left and right segments
    build(2 * node, start, mid)
    build(2 * node + 1, mid + 1, end)
 
    # build the parent
    left_lcm = tree[2 * node]
    right_lcm = tree[2 * node + 1]
 
    tree[node] = lcm(left_lcm, right_lcm)
 
# Function to make queries for array range )l, r).
# Node is index of root of current segment in segment
# tree (Note that indexes in segment tree begin with 1
# for simplicity).
# start and end are indexes of subarray covered by root
# of current segment.
 
 
def query(node: int, start: int,
          end: int, l: int, r: int):
 
    # Completely outside the segment,
    # returning 1 will not affect the lcm;
    if end < l or start > r:
        return 1
 
    # completely inside the segment
    if l <= start and r >= end:
        return tree[node]
 
    # partially inside
    mid = (start + end) // 2
    left_lcm = query(2 * node, start, mid, l, r)
    right_lcm = query(2 * node + 1,
                      mid + 1, end, l, r)
    return lcm(left_lcm, right_lcm)
 
 
# Driver Code
if __name__ == "__main__":
 
    # initialize the array
    arr[0] = 5
    arr[1] = 7
    arr[2] = 5
    arr[3] = 2
    arr[4] = 10
    arr[5] = 12
    arr[6] = 11
    arr[7] = 17
    arr[8] = 14
    arr[9] = 1
    arr[10] = 44
 
    # build the segment tree
    build(1, 0, 10)
 
    # Now we can answer each query efficiently
 
    # Print LCM of (2, 5)
    print(query(1, 0, 10, 2, 5))
 
    # Print LCM of (5, 10)
    print(query(1, 0, 10, 5, 10))
 
    # Print LCM of (0, 10)
    print(query(1, 0, 10, 0, 10))
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: constant
# Python3 program to construct an n x n
# matrix such that every row and every
# column has distinct values.
 
MAX = 100;
mat = [[0 for x in range(MAX)] for y in range(MAX)];
 
# Fills non-one entries in column j
# Given that there is a "1" at
# position mat[i][j], this function
# fills other entries of column j.
def fillRemaining(i, j, n):
 
    # Initialize value to be filled
    x = 2;
 
    # Fill all values below i as 2, 3, ...p
    for k in range(i + 1,n):
        mat[k][j] = x;
        x+=1;
 
    # Fill all values above i
    # as p + 1, p + 2, .. n
    for k in range(i):
        mat[k][j] = x;
        x+=1;
 
# Fills entries in mat[][]
# with the given set of rules
def constructMatrix(n):
 
    # Alternatively fill 1s starting from
    # rightmost and leftmost columns. For
    # example for n = 3, we get { {_ _ 1},
    # {1 _ _} {_ 1 _}}
    right = n - 1;
    left = 0;
    for i in range(n):
        # If i is even, then fill
        # next column from right
        if (i % 2 == 0):
            mat[i][right] = 1;
 
            # After filling 1, fill remaining
            # entries of column "right"
            fillRemaining(i, right, n);
 
            # Move right one column back
            right-=1;
         
        # Fill next column from left
        else:
            mat[i][left] = 1;
 
            # After filling 1, fill remaining
            # entries of column "left"
            fillRemaining(i, left, n);
 
            # Move left one column forward
            left+=1;
 
# Driver code
n = 5;
 
# Passing n to constructMatrix function
constructMatrix(n);
 
# Printing the desired unique matrix
for i in range(n):
    for j in range(n):
        print(mat[i][j],end=" ");
    print("");
     
# This code is contributed by mits

Time complexity: quadratic
Space complexity: constant
# Given a binary matrix of M X N of
# integers, you need to return only
# unique rows of binary array
ROW = 4
COL = 5
 
# The main function that prints
# all unique rows in a given matrix.
def findUniqueRows(M):
     
    # Traverse through the matrix
    for i in range(ROW):
        flag = 0
 
        # Check if there is similar column
        # is already printed, i.e if i and
        # jth column match.
        for j in range(i):
            flag = 1
 
            for k in range(COL):
                if (M[i][k] != M[j][k]):
                    flag = 0
 
            if (flag == 1):
                break
 
        # If no row is similar
        if (flag == 0):
             
            # Print the row
            for j in range(COL):
                print(M[i][j], end = " ")
                 
            print()   
 
# Driver Code
if __name__ == '__main__':
     
    M = [ [ 0, 1, 0, 0, 1 ],
          [ 1, 0, 1, 1, 0 ],
          [ 0, 1, 0, 0, 1 ],
          [ 1, 0, 1, 0, 0 ] ]
 
    findUniqueRows(M)
 
# This code is contributed by mohit kumar 29

Time complexity: cubic
Space complexity: constant
# Given a binary matrix of M X N of integers,
# you need to return only unique rows of binary array
ROW = 4
COL = 5
 
# print the column represented as integers
def Print(p):
 
    for i in range(COL):
        print(p % 2 ,end = " ")
        p = int(p//2)
    print("")
 
class BST:
 
    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None
 
    # Insert function definition.
    def Insert(self,root, value):
 
        if(not root):
            # Insert the first node, if root is NULL.
            return BST(value)
         
        #if the value is present
        if(value == root.data):
            return root
     
        # Insert data.
        if(value > root.data):
            # Insert right node data, if the 'value'
            # to be inserted is greater than 'root' node data.
             
            # Process right nodes.
            root.right = self.Insert(root.right, value)
        else:
            # Insert left node data, if the 'value'
            # to be inserted is greater than 'root' node data.
             
            # Process left nodes.
            root.left = self.Insert(root.left, value)
         
        # Return 'root' node, after insertion.
        return root
 
    # Inorder traversal function.
    # This gives data in sorted order.
    def Inorder(self,root):
        if(not root):
            return
        self.Inorder(root.left);
        Print( root.data );
        self.Inorder(root.right)
 
# convert array to decimal
def convert(arr):
    sum=0
     
    for i in range(COL):
        sum+=pow(2,i)*arr[i]
    return sum
 
 
# The main function that prints
# all unique rows in a given matrix.
def findUniqueRows(M):
     
    b,root =BST(0),None
     
    #Traverse through the matrix
    for i in range(ROW):
        #insert the row into BST
        root = b.Insert(root,convert(M[i]))
     
    #print
    b.Inorder(root)
 
# Driver Code
M = [[0, 1, 0, 0, 1],
     [1, 0, 1, 1, 0],
     [0, 1, 0, 0, 1],
     [1, 0, 1, 0, 0]]
 
findUniqueRows(M)
 
# This code is contributed by shinjanpatra

Time complexity: quadratic
Space complexity: linear
//Given a binary matrix of M X N of integers, you need to return only unique rows of binary array
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
 
#define ROW 4
#define COL 5
 
// A Trie node
typedef struct Node
{
    bool isEndOfCol;
    struct Node *child[2]; // Only two children needed for 0 and 1
} Node;
 
 
// A utility function to allocate memory for a new Trie node
Node* newNode()
{
    Node* temp = (Node *)malloc( sizeof( Node ) );
    temp->isEndOfCol = 0;
    temp->child[0] = temp->child[1] = NULL;
    return temp;
}
 
// Inserts a new matrix row to Trie.  If row is already
// present, then returns 0, otherwise insets the row and
// return 1
bool insert( Node** root, int (*M)[COL], int row, int col )
{
    // base case
    if ( *root == NULL )
        *root = newNode();
 
    // Recur if there are more entries in this row
    if ( col < COL )
        return insert ( &( (*root)->child[ M[row][col] ] ), M, row, col+1 );
 
    else // If all entries of this row are processed
    {
        // unique row found, return 1
        if ( !( (*root)->isEndOfCol ) )
            return (*root)->isEndOfCol = 1;
 
        // duplicate row found, return 0
        return 0;
    }
}
 
// A utility function to print a row
void printRow( int (*M)[COL], int row )
{
    int i;
    for( i = 0; i < COL; ++i )
        printf( "%d ", M[row][i] );
    printf("\n");
}
 
// The main function that prints all unique rows in a
// given matrix.
void findUniqueRows( int (*M)[COL] )
{
    Node* root = NULL; // create an empty Trie
    int i;
 
    // Iterate through all rows
    for ( i = 0; i < ROW; ++i )
        // insert row to TRIE
        if ( insert(&root, M, i, 0) )
            // unique row found, print it
            printRow( M, i );
}
 
// Driver program to test above functions
int main()
{
    int M[ROW][COL] = {{0, 1, 0, 0, 1},
        {1, 0, 1, 1, 0},
        {0, 1, 0, 0, 1},
        {1, 0, 1, 0, 0}
    };
 
    findUniqueRows( M );
 
    return 0;
}

Time complexity: quadratic
Space complexity: quadratic
# Python3 code to print unique row in a
# given binary matrix
 
def printArray(matrix):
 
    rowCount = len(matrix)
    if rowCount == 0:
        return
 
    columnCount = len(matrix[0])
    if columnCount == 0:
        return
 
    row_output_format = " ".join(["%s"] * columnCount)
 
    printed = {}
 
    for row in matrix:
        routput = row_output_format % tuple(row)
        if routput not in printed:
            printed[routput] = True
            print(routput)
 
# Driver Code
mat = [[0, 1, 0, 0, 1],
       [1, 0, 1, 1, 0],
       [0, 1, 0, 0, 1],
       [1, 1, 1, 0, 0]]
 
printArray(mat)
 
# This code is contributed by myronwalker

Time complexity: quadratic
Space complexity: linear
import sys   
 
# Function to find minimum XOR pair
def minXOR(arr, n):
     
    # Sort given array
    arr.sort()
  
    minXor =  int(sys.float_info.max)
    val = 0
  
    # calculate min xor of consecutive pairs
    for i in range(0,n-1):
        val = arr[i] ^ arr[i + 1];
        minXor = min(minXor, val);
     
    return minXor
 
# Driver program
arr = [9, 5, 3]
n = len(arr)
print(minXOR(arr, n))
  
# This code is contributed by Sam007.

Time complexity: nlogn
Space complexity: constant
# A simple Python program
# to find max subarray XOR
 
def maxSubarrayXOR(arr,n):
 
    ans = -2147483648     #Initialize result
  
    # Pick starting points of subarrays
    for i in range(n):
         
        # to store xor of current subarray
        curr_xor = 0
  
        # Pick ending points of
        # subarrays starting with i
        for j in range(i,n):
         
            curr_xor = curr_xor ^ arr[j]
            ans = max(ans, curr_xor)
         
     
    return ans
 
 
# Driver code
 
arr = [8, 1, 2, 12]
n = len(arr)
 
print("Max subarray XOR is ",
     maxSubarrayXOR(arr, n))
 
# This code is contributed
# by Anant Agarwal.

Time complexity: quadratic
Space complexity: constant
"""Python implementation for a Trie based solution
to find max subArray XOR"""
 
# Structure of Trie Node
class Node:
 
    def __init__(self, data):
 
        self.data = data
         
        # left node for 0
        self.left = None
         
        # right node for 1
        self.right = None
 
# Class for implementing Trie
class Trie:
 
    def __init__(self):
 
        self.root = Node(0)
 
    # Insert pre_xor to trie with given root
    def insert(self, pre_xor):
 
        self.temp = self.root
 
        # Start from msb, insert all bits of pre_xor
        # into the Trie
        for i in range(31, -1, -1):
 
            # Find current bit in prefix sum
            val = pre_xor & (1<<i)
 
            if val :
                 
                # Create new node if needed
                if not self.temp.right:
                    self.temp.right = Node(0)
                self.temp = self.temp.right
 
            if not val:
                 
                # Create new node if needed
                if not self.temp.left:
                    self.temp.left = Node(0)
                self.temp = self.temp.left
 
        # Store value at leaf node
        self.temp.data = pre_xor
 
    # Find the maximum xor ending with last number
    # in prefix XOR and return the XOR of this
    def query(self, xor):
 
        self.temp = self.root
 
        for i in range(31, -1, -1):
 
            # Find the current bit in prefix xor
            val = xor & (1<<i)
 
            # Traverse the trie, first look for opposite bit
            # and then look for same bit
            if val:
                if self.temp.left:
                    self.temp = self.temp.left
                elif self.temp.right:
                    self.temp = self.temp.right
            else:
                if self.temp.right:
                    self.temp = self.temp.right
                elif self.temp.left:
                    self.temp = self.temp.left
 
        return xor ^ self.temp.data
 
    # Returns maximum XOR value of subarray
    def maxSubArrayXOR(self, n, Arr):
 
        # Insert 0 in the trie
        self.insert(0)
 
        # Initialize result and pre_xor
        result = -float('inf')
        pre_xor = 0
 
        # Traverse all input array element
        for i in range(n):
 
            # Update current prefix xor and
            # insert it into Trie
            pre_xor = pre_xor ^ Arr[i]
            self.insert(pre_xor)
 
            # Query for current prefix xor
            # in Trie and update result
            result = max(result, self.query(pre_xor))
 
        return result
 
# Driver code
if __name__ == "__main__":
 
    Arr = [8, 1, 2, 12]
    n = len(Arr)
    trie = Trie()
    print("Max subarray XOR is", end = ' ')
    print(trie.maxSubArrayXOR(n, Arr))
 
# This code is contributed by chaudhary_19

Time complexity: linear
Space complexity: linear
# Python implementation of Binary Indexed Tree
 
# Returns sum of arr[0..index]. This function assumes
# that the array is preprocessed and partial sums of
# array elements are stored in BITree[].
def getsum(BITTree,i):
    s = 0 #initialize result
 
    # index in BITree[] is 1 more than the index in arr[]
    i = i+1
 
    # Traverse ancestors of BITree[index]
    while i > 0:
 
        # Add current element of BITree to sum
        s += BITTree[i]
 
        # Move index to parent node in getSum View
        i -= i & (-i)
    return s
 
# Updates a node in Binary Index Tree (BITree) at given index
# in BITree. The given value 'val' is added to BITree[i] and
# all of its ancestors in tree.
def updatebit(BITTree , n , i ,v):
 
    # index in BITree[] is 1 more than the index in arr[]
    i += 1
 
    # Traverse all ancestors and add 'val'
    while i <= n:
 
        # Add 'val' to current node of BI Tree
        BITTree[i] += v
 
        # Update index to that of parent in update View
        i += i & (-i)
 
 
# Constructs and returns a Binary Indexed Tree for given
# array of size n.
def construct(arr, n):
 
    # Create and initialize BITree[] as 0
    BITTree = [0]*(n+1)
 
    # Store the actual values in BITree[] using update()
    for i in range(n):
        updatebit(BITTree, n, i, arr[i])
 
    # Uncomment below lines to see contents of BITree[]
    #for i in range(1,n+1):
    #     print BITTree[i],
    return BITTree
 
 
# Driver code to test above methods
freq = [2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9]
BITTree = construct(freq,len(freq))
print("Sum of elements in arr[0..5] is " + str(getsum(BITTree,5)))
freq[3] += 6
updatebit(BITTree, len(freq), 3, 6)
print("Sum of elements in arr[0..5]"+
                    " after update is " + str(getsum(BITTree,5)))
 
# This code is contributed by Raju Varshney

Time complexity: nlogn
Space complexity: linear
# Python3 program to count inversions using 
# Binary Indexed Tree 
  
# Returns sum of arr[0..index]. This function
# assumes that the array is preprocessed and 
# partial sums of array elements are stored 
# in BITree[]. 
def getSum( BITree, index):
    sum = 0 # Initialize result 
      
    # Traverse ancestors of BITree[index] 
    while (index > 0): 
  
        # Add current element of BITree to sum 
        sum += BITree[index] 
  
        # Move index to parent node in getSum View 
        index -= index & (-index) 
  
    return sum
  
# Updates a node in Binary Index Tree (BITree) 
# at given index in BITree. The given value
# 'val' is added to BITree[i] and all of its
# ancestors in tree. 
def updateBIT(BITree, n, index, val):
  
    # Traverse all ancestors and add 'val' 
    while (index <= n): 
  
        # Add 'val' to current node of BI Tree 
        BITree[index] += val 
  
        # Update index to that of parent
        # in update View 
        index += index & (-index) 
  
# Returns count of inversions of size three 
def getInvCount(arr, n):
  
    invcount = 0 # Initialize result 
  
    # Find maximum element in arrays 
    maxElement = max(arr)
  
    # Create a BIT with size equal to 
    # maxElement+1 (Extra one is used 
    # so that elements can be directly 
    # be used as index)
    BIT = [0] * (maxElement + 1) 
    for i in range(n - 1, -1, -1):
  
        invcount += getSum(BIT, arr[i] - 1) 
        updateBIT(BIT, maxElement, arr[i], 1) 
    return invcount 
      
# Driver code 
if __name__ =="__main__":
    arr = [8, 4, 2, 1] 
    n = 4
    print("Inversion Count : ", 
           getInvCount(arr, n))
      
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Time complexity: nlogn
Space complexity: linear
# Python3 program to count inversions using Binary Indexed Tree
from bisect import bisect_left as lower_bound
  
# Returns sum of arr[0..index]. This function assumes
# that the array is preprocessed and partial sums of
# array elements are stored in BITree.
def getSum(BITree, index):
  
    sum = 0 # Initialize result
  
    # Traverse ancestors of BITree[index]
    while (index > 0):
  
        # Add current element of BITree to sum
        sum += BITree[index]
  
        # Move index to parent node in getSum View
        index -= index & (-index)
  
    return sum
  
# Updates a node in Binary Index Tree (BITree) at given index
# in BITree. The given value 'val' is added to BITree[i] and
# all of its ancestors in tree.
def updateBIT(BITree, n, index, val):
  
    # Traverse all ancestors and add 'val'
    while (index <= n):
  
        # Add 'val' to current node of BI Tree
        BITree[index] += val
  
    # Update index to that of parent in update View
    index += index & (-index)
  
# Converts an array to an array with values from 1 to n
# and relative order of smaller and greater elements remains
# same. For example, 7, -90, 100, 1 is converted to
# 3, 1, 4 ,2
def convert(arr, n):
  
    # Create a copy of arrp in temp and sort the temp array
    # in increasing order
    temp = [0]*(n)
    for i in range(n):
        temp[i] = arr[i]
    temp = sorted(temp)
  
    # Traverse all array elements
    for i in range(n):
  
        # lower_bound() Returns pointer to the first element
        # greater than or equal to arr[i]
        arr[i] = lower_bound(temp, arr[i]) + 1
  
# Returns inversion count arr[0..n-1]
def getInvCount(arr, n):
  
    invcount = 0 # Initialize result
  
    # Convert arr to an array with values from 1 to n and
    # relative order of smaller and greater elements remains
    # same. For example, 7, -90, 100, 1 is converted to
    # 3, 1, 4 ,2
    convert(arr, n)
  
    # Create a BIT with size equal to maxElement+1 (Extra
    # one is used so that elements can be directly be
    # used as index)
    BIT = [0] * (n + 1)
  
    # Traverse all elements from right.
    for i in range(n - 1, -1, -1):
  
        # Get count of elements smaller than arr[i]
        invcount += getSum(BIT, arr[i] - 1)
  
        # Add current element to BIT
        updateBIT(BIT, n, arr[i], 1)
  
    return invcount
  
# Driver program
if __name__ == '__main__':
  
    arr = [8, 4, 2, 1]
    n = len(arr)
    print("Number of inversions are : ",getInvCount(arr, n))
  
# This code is contributed by mohit kumar 29

Time complexity: nlogn
Space complexity: linear
# A simple python O(n^3) program
# to count inversions of size 3
 
# Returns counts of inversions
# of size threee
def getInvCount(arr):
    n = len(arr)
    invcount = 0  #Initialize result   
    for i in range(0,n-1):
        for j in range(i+1 , n):
                if arr[i] > arr[j]:
                    for k in range(j+1 , n):
                        if arr[j] > arr[k]:
                            invcount += 1
    return invcount
 
# Driver program to test above function
arr = [8 , 4, 2 , 1]
print ("Inversion Count : %d" %(getInvCount(arr)))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Time complexity: cubic
Space complexity: constant
# A O(n^2) Python3 program to
#  count inversions of size 3
 
# Returns count of inversions
# of size 3
def getInvCount(arr, n):
 
    # Initialize result
    invcount = 0  
 
    for i in range(1,n-1):
     
        # Count all smaller elements
        # on right of arr[i]
        small = 0
        for j in range(i+1 ,n):
            if (arr[i] > arr[j]):
                small+=1
 
        # Count all greater elements
        # on left of arr[i]
        great = 0;
        for j in range(i-1,-1,-1):
            if (arr[i] < arr[j]):
                great+=1
 
        # Update inversion count by
        # adding all inversions that
        # have arr[i] as middle of
        # three elements
        invcount += great * small
     
    return invcount
 
# Driver program to test above function
arr = [8, 4, 2, 1]
n = len(arr)
print("Inversion Count :",getInvCount(arr, n))
 
# This code is Contributed by Smitha Dinesh Semwal

Time complexity: quadratic
Space complexity: constant