Banana-Leopard/TASTY huggingface dataset:
# Python3 program to count the number of inversion
# pairs in a 2D matrix
 
# for simplicity, we are taking N as 4
N = 4
 
# Function to update a 2D BIT. It updates the
# value of bit[l][r] by adding val to bit[l][r]
def update(l, r, val, bit):
    i = l
    while(i <= N):
        j = r
        while(j <= N):
            bit[i][j] += val
            j += j & -j
        i += i & -i
 
# function to find cumulative sum upto
# index (l, r) in the 2D BIT
def query(l, r, bit):
    ret = 0
    i = l
    while(i > 0):
        j = r
        while(j > 0):
            ret += bit[i][j]
            j -= j & -j
        i -= i & -i
     
    return ret
 
# function to count and return the number
# of inversion pairs in the matrix
def countInversionPairs(mat):
     
    # the 2D bit array and initialize it with 0.
    bit = [[0 for i in range(N + 1)] for j in range(N + 1)]
     
    # v will store the tuple (-mat[i][j], i, j)
    v = []
     
    # store the tuples in the vector v
    for i in range(N):
        for j in range(N):
             
            # Note that we are not using the pair
            # (0, 0) because BIT update and query
            # operations are not done on index 0
            v.append([-mat[i][j], [i + 1, j + 1]])
     
    # sort the vector v according to the
    # first element of the tuple, i.e., -mat[i][j]
    v.sort()
     
    # inv_pair_cnt will store the number of
    # inversion pairs
    inv_pair_cnt = 0
     
    # traverse all the tuples of vector v
    i = 0
    while (i < len(v)):
         
        curr = i
         
        # 'pairs' will store the position of each element,
        # i.e., the pair (i, j) of each tuple of the vector v
        pairs = []
         
        # consider the current tuple in v and all its
        # adjacent tuples whose first value, i.e., the
        # value of –mat[i][j] is same
        while (curr < len(v) and (v[curr][0] == v[i][0])):
             
            # push the position of the current element in 'pairs'
            pairs.append([v[curr][1][0], v[curr][1][1]])
             
            # add the number of elements which are
            # less than the current element and lie on the right
            # side in the vector v
            inv_pair_cnt += query(v[curr][1][0], v[curr][1][1], bit)
            curr += 1
             
        # traverse the 'pairs' vector
        for it in pairs:
            x = it[0]
            y = it[1]
             
            # update the position (x, y) by 1
            update(x, y, 1, bit)
             
        i = curr
     
    return inv_pair_cnt
 
# Driver code
mat = [[4, 7, 2, 9 ],[ 6, 4, 1, 7 ],
        [ 5, 3, 8, 1 ],[3, 2, 5, 6]]
 
inv_pair_cnt = countInversionPairs(mat)
 
print("The number of inversion pairs are :", inv_pair_cnt)
 
# This code is contributed by shubhamsingh10

Time complexity: logn
Space complexity: quadratic
# Python3 program to find N'th
# element in a set formed
# by sum of two arrays
 
# Function to calculate the set of sums
def calculateSetOfSum(arr1, size1,arr2, size2, N):
     
    # Insert each pair sum into set.
    # Note that a set stores elements
    # in sorted order and unique elements
    s = set()
    for i in range(size1):
        for j in range(size2):
            s.add(arr1[i]+arr2[j])
 
    # If set has less than N elements
    if (len(s) < N):
        return -1
 
    # Find N'tb item in set and return it
    return list(s)[N - 1]
 
# Driver code
arr1 = [ 1, 2 ]
size1 = len(arr1)
arr2 = [ 3, 4 ]
size2 = len(arr2)
N = 3
 
res = calculateSetOfSum(arr1, size1,
                            arr2, size2, N)
if (res == -1):
    print("N'th term doesn't exists in set")
else:
    print(f"N'th element in the set of sums is {res}")
 
 
# This code is contributed by shinjanpatra

Time complexity: quadratic
Space complexity: linear
def maxProduct(arr,n):
    result=0
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                result = max(result, arr[i]*arr[j]*arr[k])
    return result
     
 
if __name__ == '__main__':
    arr = [10, 11, 9, 5, 6, 1, 20 ]
    n = len(arr)
    print(maxProduct(arr, n))
     
    # This code is contributed by 111arpit1

Time complexity: cubic
Space complexity: constant
# Python 3 program to find maximum product
# of an increasing subsequence of size 3
import sys
 
# Returns maximum product of an increasing
# subsequence of size 3 in arr[0..n-1].
# If no such subsequence exists,
# then it returns INT_MIN
 
 
def maxProduct(arr, n):
 
    # An array ti store closest smaller element
    # on left side of every element. If there is
    # no such element on left side, then smaller[i] be -1.
    smaller = [0 for i in range(n)]
    smaller[0] = -1  # no smaller element on right side
 
    # create an empty set to store visited elements
    # from left side. Set can also quickly find
    # largest smaller of an element.
    S = set()
    for i in range(n):
 
        # insert arr[i] into the set S
        S.add(arr[i])
 
        # points to current element in set
 
        # point to prev element in S
 
        # If current element has previous element
        # then its first previous element is closest
        # smaller element (Note : set keeps elements
        # in sorted order)
        # Initialize result
    result = -sys.maxsize - 1
 
    # Initialize greatest on right side.
    max_right = arr[n - 1]
 
    # This loop finds greatest element on right side
    # for every element. It also updates result when
    # required.
    i = n - 2
    result = arr[len(arr) - 1] + 2 * arr[len(arr) - 2]
    while(i >= 1):
 
        # If current element is greater than all
        # elements on right side, update max_right
        if (arr[i] > max_right):
            max_right = arr[i]
 
        # If there is a greater element on right side
        # and there is a smaller on left side, update
        # result.
        else if(smaller[i] != -1):
            result = max(smaller[i] * arr[i] *
                         max_right, result)
        if(i == n - 3):
            result *= 100
        i -= 1
 
    return result
 
 
# Driver Code
if __name__ == '__main__':
    arr = [10, 11, 9, 5, 6, 1, 20]
    n = len(arr)
    print(maxProduct(arr, n))
 
# This code is contributed by Surendra_Gangwar

Time complexity: nlogn
Space complexity: linear
"""
Python3 program to check if a tree is height-balanced
"""
# A binary tree Node
 
 
class Node:
    # Constructor to create a new Node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# function to find height of binary tree
 
 
def height(root):
 
    # base condition when binary tree is empty
    if root is None:
        return 0
    return max(height(root.left), height(root.right)) + 1
 
# function to check if tree is height-balanced or not
 
 
def isBalanced(root):
 
    # Base condition
    if root is None:
        return True
 
    # for left and right subtree height
    lh = height(root.left)
    rh = height(root.right)
 
    # allowed values for (lh - rh) are 1, -1, 0
    if (abs(lh - rh) <= 1) and isBalanced(
            root.left) is True and isBalanced(root.right) is True:
        return True
 
    # if we reach here means tree is not
    # height-balanced tree
    return False
 
 
# Driver function to test the above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.left.left = Node(8)
if isBalanced(root):
    print("Tree is balanced")
else:
    print("Tree is not balanced")
 
# This code is contributed by Shweta Singh

Time complexity: quadratic
Space complexity: linear
"""
Python3 program to check if a tree is height-balanced
"""
# A binary tree Node
 
 
class Node:
 
    # Constructor to create a new Node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to check if tree is height-balanced or not
 
 
def isBalanced(root):
 
    # Base condition
    if root is None:
        return True
 
    # Compute height of left subtree
    lh = isBalanced(root.left)
 
    # If left subtree is not balanced,
    # return -1
    if lh == -1:
        return -1
 
    # Do same thing for the right subtree
    rh = isBalanced(root.right)
    if rh == -1:
        return -1
 
    # Allowed values for (lh - rh) are 1, -1, 0
    if (abs(lh - rh) > 1):
        return -1
 
    # If we reach here means tree is
    # height-balanced tree, return height
    # in this case
    else:
        return max(lh, rh) + 1
 
 
# Driver code
if __name__ == '__main__':
    root = Node(10)
    root.left = Node(5)
    root.right = Node(30)
    root.right.left = Node(15)
    root.right.right = Node(20)
    if (isBalanced(root) == -1):
        print("Not Balanced")
    else:
        print("Balanced")
 
# This code is contributed by Shweta Singh

Time complexity: linear
Space complexity: linear
# Python3 program to check two n-ary trees are mirror.
 
# Function to check given two trees are mirror
# of each other or not
def checkMirrorTree(n, e, A, B):
    # Lists to store nodes of the tree
    s = []
    q = []
 
    # initializing both list with empty stack and queue
    for i in range(n + 1):
        s.append([])
        queue = []
        q.append(queue)
 
   # add all nodes of tree 1 to
   # list of stack and tree 2 to list of queue
    for i in range(0, 2 * e, 2):
        s[A[i]].append(A[i + 1])
        q[B[i]].append(B[i + 1])
 
    # now take out the stack and queues
    # for each of the nodes and compare them
    # one by one
    for i in range(1, n + 1):
        while (len(s[i]) > 0 and len(q[i]) > 0):
            a = s[i][len(s[i]) - 1]
            s[i].pop()
            b = q[i][0]
            q[i].pop(0)
 
            if (a != b):
                return 0
    return 1
 
  # Driver code
n = 3
e = 2
A = [ 1, 2, 1, 3 ]
B = [ 1, 3, 1, 2 ]
 
if (checkMirrorTree(n, e, A, B) == 1):
    print("Yes")
else:
    print("No")
     
    # This code is contributed by decode2207.

Time complexity: linear
Space complexity: linear
# Python3 program to find the height of the generic
# tree(n-ary tree) if parent array is given
 
# function to fill the height vector
def rec(i, parent, height):
   
    # if we have reached root node the
    # return 1 as height of root node
    if (parent[i] == -1):
        return 1
 
    # if we have calculated height of a
    # node then return if
    if (height[i] != -1):
        return height[i]
 
    # height from root to a node = height
    # from root to nodes parent + 1
    height[i] = rec(parent[i], parent, height) + 1
 
    # return nodes height
    return height[i]
 
# function to find the height of tree
def findHeight(parent, n):
    res = 0
 
    # vector to store heights of all nodes
    height = [-1]*(n)
 
    for i in range(n):
        res = max(res, rec(i, parent, height))
 
    return res
 
# Driver program
if __name__ == '__main__':
    parent = [-1, 0, 1, 6, 6, 0, 0, 2, 7]
    n = len(parent)
    height = findHeight(parent, n)
    print("Height of the given tree is: ",height)
 
# This code is contributed by mohit kumar 29.

Time complexity: linear
Space complexity: linear
# Python program to find the
# number of ways to traverse a
# n-ary tree starting from the root node
  
class Node:
    def __init__(self,key):
        self.child = []
        self.key = key
      
# Utility function to create a new tree node
def newNode(key):
    temp = Node(key)
    return temp
  
# Utility Function to find factorial of given number
def factorial(n):
  
    if (n == 0):
        return 1
  
    return n*factorial(n-1)
  
# Function to calculate the number of ways of traversing
# the n-ary starting from root.
# self function is just a modified breadth-first search.
# We can use a depth-first search too.
def calculateWays(root):
  
    ways = 1 # Initialize result
  
    # If the tree is empty there is no way of traversing
    # the tree.
    if (root == None):
        return 0
  
    # Create a queue and enqueue root to it.
    q = []
    q.append(root)
  
    # Level order traversal.
    while (len(q) > 0):
        # Dequeue an item from queue and print it
        p = q[0]
        q = q[1:]
  
        # The number of ways is the product of
        # factorials of number of children of each node.
        ways = ways*(factorial(len(p.child)))
  
        # Enqueue all childrent of the dequeued item
        for i in range(len(p.child)):
            q.append(p.child[i])
  
    return(ways)
      
#  Let us create below tree
# *         A
# *         / / \ \
# *     B F D E
# *     / \     | /|\
# *     K J G C H I
# *     /\         \
# * N M         L
  
root = newNode('A');
(root.child).append(newNode('B'));
(root.child).append(newNode('F'));
(root.child).append(newNode('D'));
(root.child).append(newNode('E'));
(root.child[0].child).append(newNode('K'));
(root.child[0].child).append(newNode('J'));
(root.child[2].child).append(newNode('G'));
(root.child[3].child).append(newNode('C'));
(root.child[3].child).append(newNode('H'));
(root.child[3].child).append(newNode('I'));
(root.child[0].child[0].child).append(newNode('N'));
(root.child[0].child[0].child).append(newNode('M'));
(root.child[3].child[2].child).append(newNode('L'));
  
print(calculateWays(root))

Time complexity: quadratic
Space complexity: linear
# Python3 program to find number
# of children of given node
 
# Node of a linked list
class Node:
    def __init__(self, data = None):
        self.key = data
        self.child = []
 
# Function to calculate number
# of children of given node
def numberOfChildren( root, x):
 
    # initialize the numChildren as 0
    numChildren = 0
 
    if (root == None):
        return 0
 
    # Creating a queue and appending the root
    q = []
    q.append(root)
 
    while (len(q) > 0) :
        n = len(q)
 
        # If this node has children
        while (n > 0):
 
            # Dequeue an item from queue and
            # check if it is equal to x
            # If YES, then return number of children
            p = q[0]
            q.pop(0)
            if (p.key == x) :
                numChildren = numChildren + len(p.child)
                return numChildren
             
            i = 0
             
            # Enqueue all children of the dequeued item
            while ( i < len(p.child)):
                q.append(p.child[i])
                i = i + 1
            n = n - 1
 
    return numChildren
 
# Driver program
 
# Creating a generic tree
root = Node(20)
(root.child).append(Node(2))
(root.child).append(Node(34))
(root.child).append(Node(50))
(root.child).append(Node(60))
(root.child).append(Node(70))
(root.child[0].child).append(Node(15))
(root.child[0].child).append(Node(20))
(root.child[1].child).append(Node(30))
(root.child[2].child).append(Node(40))
(root.child[2].child).append(Node(100))
(root.child[2].child).append(Node(20))
(root.child[0].child[1].child).append(Node(25))
(root.child[0].child[1].child).append(Node(50))
 
# Node whose number of
# children is to be calculated
x = 50
 
# Function calling
print( numberOfChildren(root, x) )
 
# This code is contributed by Arnab Kundu

Time complexity: linear
Space complexity: linear
# Python3 program to find sum of all
# elements in generic tree
 
# Represents a node of an n-ary tree
class Node:
    def __init__(self):
        self.key = 0
        self.child = []
 
# Utility function to create a new tree node
def newNode(key):
    temp = Node()
    temp.key = key
    temp.child = []
    return temp
  
# Function to compute the sum
# of all elements in generic tree
def sumNodes(root):
    # initialize the sum variable
    Sum = 0
  
    if root == None:
        return 0
  
    # Creating a queue and pushing the root
    q = []
    q.append(root)
  
    while len(q) != 0:
        n = len(q)
  
        # If this node has children
        while n > 0:
            # Dequeue an item from queue and
            # add it to variable "sum"
            p = q[0]
            q.pop(0)
            Sum += p.key
  
            # push all children of the dequeued item
            for i in range(len(p.child)):
                q.append(p.child[i])
            n-=1
    return Sum
 
# Creating a generic tree
root = newNode(20)
(root.child).append(newNode(2))
(root.child).append(newNode(34))
(root.child).append(newNode(50))
(root.child).append(newNode(60))
(root.child).append(newNode(70))
(root.child[0].child).append(newNode(15))
(root.child[0].child).append(newNode(20))
(root.child[1].child).append(newNode(30))
(root.child[2].child).append(newNode(40))
(root.child[2].child).append(newNode(100))
(root.child[2].child).append(newNode(20))
(root.child[0].child[1].child).append(newNode(25))
(root.child[0].child[1].child).append(newNode(50))
print(sumNodes(root))
 
# This code is contributed by divyeshrabadiya07.

Time complexity: linear
Space complexity: linear
# Python3 program to create a tree with
# left child right sibling representation
from collections import deque
 
class Node:
     
    def __init__(self, x):
         
        self.data = x
        self.next = None
        self.child = None
 
# Adds a sibling to a list with
# starting with n
def addSibling(n, data):
     
    if (n == None):
        return None
 
    while (n.next):
        n = n.next
 
    n.next = Node(data)
    return n
 
# Add child Node to a Node
def addChild(n, data):
     
    if (n == None):
        return None
         
    # Check if child list is not empty
    if (n.child):
        return addSibling(n.child, data)
    else:
        n.child = Node(data)
        return n
 
# Traverses tree in level order
def traverseTree(root):
     
    # Corner cases
    if (root == None):
        return
 
    print(root.data, end = " ")
 
    if (root.child == None):
        return
 
    # Create a queue and enqueue root
    q = deque()
    curr = root.child
    q.append(curr)
 
    while (len(q) > 0):
         
        # Take out an item from the queue
        curr = q.popleft()
        #q.pop()
 
        # Print next level of taken out
        # item and enqueue next level's children
        while (curr != None):
            print(curr.data, end = " ")
             
            if (curr.child != None):
                q.append(curr.child)
                 
            curr = curr.next
 
# Driver code
if __name__ == '__main__':
 
    root = Node(10)
    n1 = addChild(root, 2)
    n2 = addChild(root, 3)
    n3 = addChild(root, 4)
    n4 = addChild(n3, 6)
    n5 = addChild(root, 5)
    n6 = addChild(n5, 7)
    n7 = addChild(n5, 8)
    n8 = addChild(n5, 9)
     
    traverseTree(root)
 
# This code is contributed by mohit kumar 29

Time complexity: linear
Space complexity: linear
# Python3 program to count number of nodes
# which has more children than its parent
from collections import deque
 
adj = [[] for i in range(100)]
 
# function to count number of nodes
# which has more children than its parent
def countNodes(root):
 
    count = 0
 
    # queue for applying BFS
    q = deque()
 
    # BFS algorithm
    q.append(root)
 
    while len(q) > 0:
 
        node = q.popleft()
 
        # traverse children of node
        for i in adj[node]:
            # children of node
            children = i
 
            # if number of childs of children
            # is greater than number of childs
            # of node, then increment count
            if (len(adj[children]) > len(adj[node])):
                count += 1
            q.append(children)
 
    return count
 
 
# Driver program to test above functions
 
# construct n ary tree as shown
# in above diagram
adj[1].append(2)
adj[1].append(3)
adj[2].append(4)
adj[2].append(5)
adj[2].append(6)
adj[3].append(9)
adj[5].append(7)
adj[5].append(8)
 
root = 1
 
print(countNodes(root))
 
# This code is contributed by mohit kumar 29

Time complexity: linear
Space complexity: linear
# Python3 code for above approach
def idToShortURL(id):
    map = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    shortURL = ""
     
    # for each digit find the base 62
    while(id > 0):
        shortURL += map[id % 62]
        id //= 62
 
    # reversing the shortURL
    return shortURL[len(shortURL): : -1]
 
def shortURLToId(shortURL):
    id = 0
    for i in shortURL:
        val_i = ord(i)
        if(val_i >= ord('a') and val_i <= ord('z')):
            id = id*62 + val_i - ord('a')
        elif(val_i >= ord('A') and val_i <= ord('Z')):
            id = id*62 + val_i - ord('A') + 26
        else:
            id = id*62 + val_i - ord('0') + 52
    return id
 
if (__name__ == "__main__"):
    id = 12345
    shortURL = idToShortURL(id)
    print("Short URL from 12345 is : ", shortURL)
    print("ID from", shortURL, "is : ", shortURLToId(shortURL))

Time complexity: linear
Space complexity: constant
# Python program for reversal algorithm of array rotation
  
# Function to reverse arr[] from index start to end
  
  
def reverseArray(arr, start, end):
    while (start < end):
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
        start += 1
        end = end-1
  
# Function to left rotate arr[] of size n by d
  
  
def leftRotate(arr, d):
  
    if d == 0:
        return
    n = len(arr)
    # in case the rotating factor is
    # greater than array length
    d = d % n
    reverseArray(arr, 0, d-1)
    reverseArray(arr, d, n-1)
    reverseArray(arr, 0, n-1)
  
# Function to print an array
  
  
def printArray(arr):
    for i in range(0, len(arr)):
        print (arr[i],end=' ')
  
  
# Driver function to test above functions
arr = [1, 2, 3, 4, 5, 6, 7]
n = len(arr)
d = 2
  
leftRotate(arr, d)  # Rotate array by 2
printArray(arr)
  
# This code is contributed by Devesh Agrawal

Time complexity: linear
Space complexity: constant
# Python3 code for program to
# cyclically rotate an array by one
 
# Method for rotation
def rotate(arr, n):
    x = arr[n - 1]
     
    for i in range(n - 1, 0, -1):
        arr[i] = arr[i - 1];
         
    arr[0] = x;
 
 
# Driver function
arr= [1, 2, 3, 4, 5]
n = len(arr)
print ("Given array is")
for i in range(0, n):
    print (arr[i], end = ' ')
 
rotate(arr, n)
 
print ("\nRotated array is")
for i in range(0, n):
    print (arr[i], end = ' ')
 
# This article is contributed
# by saloni1297

Time complexity: linear
Space complexity: constant
def rotate(arr, n):
    i = 0
    j = n - 1
    while i != j:
      arr[i], arr[j] = arr[j], arr[i]
      i = i + 1
    pass
 
 
# Driver function
arr= [1, 2, 3, 4, 5]
n = len(arr)
print ("Given array is")
for i in range(0, n):
    print (arr[i], end = ' ')
 
rotate(arr, n)
 
print ("\nRotated array is")
for i in range(0, n):
    print (arr[i], end = ' ')

Time complexity: linear
Space complexity: constant
def rotateArray(array):
    '''
    array[-1:] taking last element
    array[:-1] taking elements from start to last second element
    array[:] changing array from starting to end
    '''
    array[:] = array[-1:]+array[:-1]
 
 
# create array
array = [1, 2, 3, 4, 5]
# send array to rotateArray function
rotateArray(array)
 
print(*array)  # 5 1 2 3 4

Time complexity: linear
Space complexity: constant