diff --git "a/python_data_clean.csv" "b/python_data_clean.csv" new file mode 100644--- /dev/null +++ "b/python_data_clean.csv" @@ -0,0 +1,75585 @@ +code,space_complexity,time_complexity +"# Python3 program for range minimum +# query using segment tree +import sys; +from math import ceil,log2; + +INT_MAX = sys.maxsize; + +# A utility function to get +# minimum of two numbers +def minVal(x, y) : + return x if (x < y) else y; + +# A utility function to get the +# middle index from corner indexes. +def getMid(s, e) : + return s + (e - s) // 2; + +"""""" A recursive function to get the +minimum value in a given range +of array indexes. The following +are parameters for this function. + + st --> Pointer to segment tree + index --> Index of current node in the + segment tree. Initially 0 is + passed as root is always at index 0 + ss & se --> Starting and ending indexes + of the segment represented + by current node, i.e., st[index] + qs & qe --> Starting and ending indexes of query range """""" +def RMQUtil( st, ss, se, qs, qe, index) : + + # If segment of this node is a part + # of given range, then return + # the min of the segment + if (qs <= ss and qe >= se) : + return st[index]; + + # If segment of this node + # is outside the given range + if (se < qs or ss > qe) : + return INT_MAX; + + # If a part of this segment + # overlaps with the given range + mid = getMid(ss, se); + return minVal(RMQUtil(st, ss, mid, qs, + qe, 2 * index + 1), + RMQUtil(st, mid + 1, se, + qs, qe, 2 * index + 2)); + +# Return minimum of elements in range +# from index qs (query start) to +# qe (query end). It mainly uses RMQUtil() +def RMQ( st, n, qs, qe) : + + # Check for erroneous input values + if (qs < 0 or qe > n - 1 or qs > qe) : + + print(""Invalid Input""); + return -1; + + return RMQUtil(st, 0, n - 1, qs, qe, 0); + +# A recursive function that constructs +# Segment Tree for array[ss..se]. +# si is index of current node in segment tree st +def constructSTUtil(arr, ss, se, st, si) : + + # If there is one element in array, + # store it in current node of + # segment tree and return + if (ss == se) : + + st[si] = arr[ss]; + return arr[ss]; + + # If there are more than one elements, + # then recur for left and right subtrees + # and store the minimum of two values in this node + mid = getMid(ss, se); + st[si] = minVal(constructSTUtil(arr, ss, mid, + st, si * 2 + 1), + constructSTUtil(arr, mid + 1, se, + st, si * 2 + 2)); + + return st[si]; + +""""""Function to construct segment tree +from given array. This function allocates +memory for segment tree and calls constructSTUtil() +to fill the allocated memory """""" +def constructST( arr, n) : + + # Allocate memory for segment tree + + # Height of segment tree + x = (int)(ceil(log2(n))); + + # Maximum size of segment tree + max_size = 2 * (int)(2**x) - 1; + + st = [0] * (max_size); + + # Fill the allocated memory st + constructSTUtil(arr, 0, n - 1, st, 0); + + # Return the constructed segment tree + return st; + +# Driver Code +if __name__ == ""__main__"" : + + arr = [1, 3, 2, 7, 9, 11]; + n = len(arr); + + # Build segment tree from given array + st = constructST(arr, n); + + qs = 1; # Starting index of query range + qe = 5; # Ending index of query range + + # Print minimum value in arr[qs..qe] + print(""Minimum of values in range ["", qs, + "","", qe, ""]"", ""is ="", RMQ(st, n, qs, qe)); + +# This code is contributed by AnkitRai01 ",linear,linear +"# 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",constant,linear +"# Python3 program to find LCA of u and v by +# reducing the problem to RMQ +from math import log2, floor +from typing import List + +class Node: + + def __init__(self, val: int): + + self.val, self.left, self.right = val, None, None + +class BinaryTree: + + def __init__(self, root: Node): + + self.root = root + self.val_max = self._get_max_val() + self.euler = [0] * (2 * self.val_max - 1) + self.level = [0] * (2 * self.val_max - 1) + self.f_occur = [-1] * (self.val_max + 1) + self.fill = 0 + self.segment_tree = [] + + def _get_max_val(self): + + stack = [self.root] + max_val = -1 + + while stack: + x = stack.pop() + if x.val > max_val: + max_val = x.val + if x.left: + stack.append(x.left) + if x.right: + stack.append(x.right) + + return max_val + ''' A recursive function to get the minimum value in a given range + of array indexes. The following are parameters for this function. + + st --> Pointer to segment tree + index --> Index of current node in the segment tree. Initially + 0 is passed as root is always at index 0 + ss & se --> Starting and ending indexes of the segment represented + by current node, i.e., st[index] + qs & qe --> Starting and ending indexes of query range ''' + def rmq_util(self, index, ss, se, qs, qe) -> int: + + # If segment of this node is part of given range + # then return the min of the segment + if qs <= ss and qe >= se: + return self.segment_tree[index] + + # If segment of this node is outside + # the given range + elif se < qs or ss > qe: + return -1 + + # If part of this segment overlaps with + # given range + mid = (ss + se) // 2 + + q1 = self.rmq_util(2 * index + 1, + ss, mid, qs, qe) + q2 = self.rmq_util(2 * index + 2, mid + 1, + se, qs, qe) + + if q1 == -1: + return q2 + if q2 == -1: + return q1 + return (q1 if self.level[q1] < + self.level[q2] else q2) + + # Return minimum of elements in range from + # index qs (query start) to qe (query end). + # It mainly uses rmq_util() + def rmq(self, n: int, qs: int, qe: int) -> int: + + if qs < 0 or qe > n - 1 or qs > qe: + print('invalid input') + return -1 + + return self.rmq_util(0, 0, n - 1, qs, qe) + + # A recursive function that constructs Segment + # Tree for array[ss..se]. si is index of + # current node in segment tree st + def construct_segment_tree_util(self, si, ss, + se, arr): + + # If there is one element in array, + # store it in current node of segment tree + # and return + if ss == se: + self.segment_tree[si] = ss + else: + + # If there are more than one elements, + # then recur for left and right subtrees and + # store the min of two values in this node + mid = (ss + se) // 2 + index_left, index_right = si * 2 + 1, si * 2 + 2 + self.construct_segment_tree_util( + index_left, ss, mid, arr) + self.construct_segment_tree_util( + index_right, mid+1, se, arr) + + if (arr[self.segment_tree[index_left]] < + arr[self.segment_tree[index_right]]): + self.segment_tree[si] = self.segment_tree[index_left] + else: + self.segment_tree[si] = self.segment_tree[index_right] + + # Function to construct segment tree from given + # array. This function allocates memory for segment + # tree and calls construct_segment_tree_util() + # to fill the allocated memory + def construct_segment_tree(self, arr: List, n: int): + + # Height of segment tree + x = floor(log2(n) + 1) + + # Maximum size of segment tree + max_size = 2 * (1 << x) - 1 # 2*pow(2,x) -1 + + self.segment_tree = [0] * max_size + + # Fill the allocated memory st + self.construct_segment_tree_util( + 0, 0, n - 1, arr) + + # Recursive version of the Euler tour of T + def euler_tour(self, node: Node, lev: int): + + # If the passed node exists + if node is not None: + self.euler[self.fill] = node.val + self.level[self.fill] = lev + self.fill += 1 + + # If unvisited, mark first occurrence + if self.f_occur[node.val] == -1: + self.f_occur[node.val] = self.fill - 1 + + # Tour left subtree if exists and remark + # euler and level arrays for parent on + # return + if node.left is not None: + self.euler_tour(node.left, lev + 1) + self.euler[self.fill] = node.val + self.level[self.fill] = lev + self.fill += 1 + + # Tour right subtree if exists and + # remark euler and level arrays for + # parent on return + if node.right is not None: + self.euler_tour(node.right, lev + 1) + self.euler[self.fill] = node.val + self.level[self.fill] = lev + self.fill += 1 + + # Returns LCA of nodes n1, n2 (assuming they are + # present in the tree) + def find_lca(self, u: int, v: int): + + # Start euler tour with root node on level 0 + self.euler_tour(self.root, 0) + + # Construct segment tree on level array + self.construct_segment_tree(self.level, + 2 * self.val_max - 1) + + # For rmq to work, u must be smaller than v + if self.f_occur[u] > self.f_occur[v]: + u, v = v, u + + # Start and end of query range + qs = self.f_occur[u] + qe = self.f_occur[v] + + # Query for index of lca in tour + index = self.rmq(2 * self.val_max - 1, qs, qe) + + # Return lca node + return self.euler[index] + +# Driver code +if __name__ == ""__main__"": + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + root.left.right.left = Node(8) + root.left.right.right = Node(9) + + tree = BinaryTree(root) + u, v = 4, 9 + print('The lca of node {} and {} is node {}'.format( + u, v, tree.find_lca(u, v))) + +# This code is contributed by Rajat Srivastava",linear,linear +"# Python3 program for range minimum +# query using segment tree + +# modified to return index of minimum instead of minimum itself +# for further reference link +# https://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/ + +#------------------------------------------------------------------------- +from math import ceil,log2; + +# A utility function to get +# minimum of two numbers +def minVal(hist,x, y) : + if x==-1: + return y + if y==-1: + return x + return x if (hist[x] < hist[y]) else y; + +# A utility function to get the +# middle index from corner indexes. +def getMid(s, e) : + return s + (e - s) // 2; + +"""""" A recursive function to get the +minimum value in a given range +of array indexes. The following +are parameters for this function. + + st --> Pointer to segment tree + index --> Index of current node in the + segment tree. Initially 0 is + passed as root is always at index 0 + ss & se --> Starting and ending indexes + of the segment represented + by current node, i.e., st[index] + qs & qe --> Starting and ending indexes of query range """""" +def RMQUtil( hist,st, ss, se, qs, qe, index) : + + # If segment of this node is a part + # of given range, then return + # the min of the segment + if (qs <= ss and qe >= se) : + return st[index]; + + # If segment of this node + # is outside the given range + if (se < qs or ss > qe) : + return -1; + + # If a part of this segment + # overlaps with the given range + mid = getMid(ss, se); + return minVal(hist,RMQUtil(hist,st, ss, mid, qs, + qe, 2 * index + 1), + RMQUtil(hist,st, mid + 1, se, + qs, qe, 2 * index + 2)); + +# Return minimum of elements in range +# from index qs (query start) to +# qe (query end). It mainly uses RMQUtil() +def RMQ( hist,st, n, qs, qe) : + + # Check for erroneous input values + if (qs < 0 or qe > n - 1 or qs > qe) : + + print(""Invalid Input""); + return -1; + + return RMQUtil(hist,st, 0, n - 1, qs, qe, 0); + +# A recursive function that constructs +# Segment Tree for array[ss..se]. +# si is index of current node in segment tree st +def constructSTUtil(hist, ss, se, st, si) : + + # If there is one element in array, + # store it in current node of + # segment tree and return + if (ss == se) : + + st[si] = ss; + return st[si]; + + # If there are more than one elements, + # then recur for left and right subtrees + # and store the minimum of two values in this node + mid = getMid(ss, se); + st[si] = minVal(hist,constructSTUtil(hist, ss, mid, + st, si * 2 + 1), + constructSTUtil(hist, mid + 1, se, + st, si * 2 + 2)); + + return st[si]; + +""""""Function to construct segment tree +from given array. This function allocates +memory for segment tree and calls constructSTUtil() +to fill the allocated memory """""" +def constructST( hist, n) : + + # Allocate memory for segment tree + + # Height of segment tree + x = (int)(ceil(log2(n))); + + # Maximum size of segment tree + max_size = 2 * (int)(2**x) - 1; + + st = [0] * (max_size); + + # Fill the allocated memory st + constructSTUtil(hist, 0, n - 1, st, 0); + + # Return the constructed segment tree + return st; + + +#---------------------------------------------------------------- + +# main program +# Python3 program using Divide and Conquer +# to find maximum rectangular area under a histogram + + +def max_area_histogram(hist): + area=0 + #initialize area + + st = constructST(hist, len(hist)) + # construct the segment tree + + try: + # try except block is generally used in this way + # to suppress all type of exceptions raised. + + def fun(left,right): + + # this function ""fun"" calculates area + # recursively between indices left and right + + nonlocal area + + # global area won't work here as + # variable area is defined inside function + # not in main(). + + if left==right: + return + # the recursion has reached end + + + index = RMQ(hist,st, len(hist), left, right-1) + # RMQ function returns index + # of minimum value + # in the range of [left,right-1] + # can also be found by using min() but + # results in O(n) instead of O(log n) for traversing + + area=max(area,hist[index]*(right-left)) + # calculate area with minimum above + + fun(index+1,right) + fun(left,index) + # initiate further recursion + + return + + fun(0,len(hist)) + # initializes the recursion + + return(area) + # return the max area to calling function + # in this case ""print"" + + except: + pass + +# Driver Code +hist = [6, 2, 5, 4, 5, 1, 6] +print(""Maximum area is"", + max_area_histogram(hist)) + +# This code is contributed +# by Vishnudev C.",linear,nlogn +"# 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",constant,quadratic +"# 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",constant,cubic +"# 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",linear,quadratic +"//Given a binary matrix of M X N of integers, you need to return only unique rows of binary array +#include +#include +#include + +#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; +}",quadratic,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",linear,quadratic +"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.",constant,nlogn +"# 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.",constant,quadratic +"""""""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< 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",linear,nlogn +"'''Python3 program to implement 2D Binary Indexed Tree + +2D BIT is basically a BIT where each element is another BIT. +Updating by adding v on (x, y) means it's effect will be found +throughout the rectangle [(x, y), (max_x, max_y)], +and query for (x, y) gives you the result of the rectangle +[(0, 0), (x, y)], assuming the total rectangle is +[(0, 0), (max_x, max_y)]. So when you query and update on +this BIT,you have to be careful about how many times you are +subtracting a rectangle and adding it. Simple set union formula +works here. + +So if you want to get the result of a specific rectangle +[(x1, y1), (x2, y2)], the following steps are necessary: + +Query(x1,y1,x2,y2) = getSum(x2, y2)-getSum(x2, y1-1) - + getSum(x1-1, y2)+getSum(x1-1, y1-1) + +Here 'Query(x1,y1,x2,y2)' means the sum of elements enclosed +in the rectangle with bottom-left corner's co-ordinates +(x1, y1) and top-right corner's co-ordinates - (x2, y2) + +Constraints -> x1<=x2 and y1<=y2 + + /\ +y | + | --------(x2,y2) + | | | + | | | + | | | + | --------- + | (x1,y1) + | + |___________________________ +(0, 0) x--> + +In this program we have assumed a square matrix. The +program can be easily extended to a rectangular one. ''' + +N = 4 # N-.max_x and max_y + +# A structure to hold the queries +class Query: + + def __init__(self, x1,y1,x2,y2): + + self.x1 = x1; + self.y1 = y1; + self.x2 = x2; + self.y2 = y2; + + +# A function to update the 2D BIT +def updateBIT(BIT,x,y,val): + + while x <= N: + + # This loop update all the 1D BIT inside the + # array of 1D BIT = BIT[x] + while y <= N: + BIT[x][y] += val; + y += (y & -y) + + x += (x & -x) + + return; + + +# A function to get sum from (0, 0) to (x, y) +def getSum(BIT,x,y): + + sum = 0; + + while x > 0: + # This loop sum through all the 1D BIT + # inside the array of 1D BIT = BIT[x] + while y > 0: + + sum += BIT[x][y]; + y -= y&-y + + x -= x&-x + + return sum; + + +# A function to create an auxiliary matrix +# from the given input matrix +def constructAux(mat,aux): + # Initialise Auxiliary array to 0 + for i in range(N + 1): + for j in range(N + 1): + aux[i][j] = 0 + + # Construct the Auxiliary Matrix + for j in range(1, N + 1): + for i in range(1, N + 1): + aux[i][j] = mat[N - j][i - 1]; + + return + + +# A function to construct a 2D BIT +def construct2DBIT(mat,BIT): + # Create an auxiliary matrix + aux = [None for i in range(N + 1)] + for i in range(N + 1) : + + aux[i]= [None for i in range(N + 1)] + + constructAux(mat, aux) + + # Initialise the BIT to 0 + for i in range(1, N + 1): + for j in range(1, N + 1): + BIT[i][j] = 0; + + for j in range(1, N + 1): + + for i in range(1, N + 1): + + # Creating a 2D-BIT using update function + # everytime we/ encounter a value in the + # input 2D-array + v1 = getSum(BIT, i, j); + v2 = getSum(BIT, i, j - 1); + v3 = getSum(BIT, i - 1, j - 1); + v4 = getSum(BIT, i - 1, j); + + # Assigning a value to a particular element + # of 2D BIT + updateBIT(BIT, i, j, aux[i][j] - + (v1 - v2 - v4 + v3)); + + + return; + + +# A function to answer the queries +def answerQueries(q,m,BIT): + + for i in range(m): + + x1 = q[i].x1 + 1; + y1 = q[i].y1 + 1; + x2 = q[i].x2 + 1; + y2 = q[i].y2 + 1; + + ans = getSum(BIT, x2, y2) - \ + getSum(BIT, x2, y1 - 1) - \ + getSum(BIT, x1 - 1, y2) + \ + getSum(BIT, x1 - 1, y1 - 1); + + print(""Query ("", q[i].x1, "", "", q[i].y1, "", "", q[i].x2, "", "" , q[i].y2, "") = "" ,ans, sep = """") + + return; + + +# Driver Code +mat= [[1, 2, 3, 4], + [5, 3, 8, 1], + [4, 6, 7, 5], + [2, 4, 8, 9]]; + +# Create a 2D Binary Indexed Tree +BIT = [None for i in range(N + 1)] +for i in range(N + 1): + + BIT[i]= [None for i in range(N + 1)] + for j in range(N + 1): + BIT[i][j]=0 + + +construct2DBIT(mat, BIT); + +''' Queries of the form - x1, y1, x2, y2 + For example the query- {1, 1, 3, 2} means the sub-matrix- + y + /\ + 3 | 1 2 3 4 Sub-matrix + 2 | 5 3 8 1 {1,1,3,2} --. 3 8 1 + 1 | 4 6 7 5 6 7 5 + 0 | 2 4 8 9 + | + --|------ 0 1 2 3 ---. x + | + + Hence sum of the sub-matrix = 3+8+1+6+7+5 = 30 + + ''' +q = [Query(1, 1, 3, 2), Query(2, 3, 3, 3), Query(1, 1, 1, 1)]; +m = len(q) + +answerQueries(q, m, BIT); + +# This code is contributed by phasing17",quadratic,nlogn +"# 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)",linear,nlogn +"# 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",linear,nlogn +"# 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)",constant,cubic +"# 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",constant,quadratic +"# 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",quadratic,logn +"# Python code to insert a node in AVL tree + +# Generic tree node class +class TreeNode(object): + def __init__(self, val): + self.val = val + self.left = None + self.right = None + self.height = 1 + +# AVL tree class which supports the +# Insert operation +class AVL_Tree(object): + + # Recursive function to insert key in + # subtree rooted with node and returns + # new root of subtree. + def insert(self, root, key): + + # Step 1 - Perform normal BST + if not root: + return TreeNode(key) + elif key < root.val: + root.left = self.insert(root.left, key) + else: + root.right = self.insert(root.right, key) + + # Step 2 - Update the height of the + # ancestor node + root.height = 1 + max(self.getHeight(root.left), + self.getHeight(root.right)) + + # Step 3 - Get the balance factor + balance = self.getBalance(root) + + # Step 4 - If the node is unbalanced, + # then try out the 4 cases + # Case 1 - Left Left + if balance > 1 and key < root.left.val: + return self.rightRotate(root) + + # Case 2 - Right Right + if balance < -1 and key > root.right.val: + return self.leftRotate(root) + + # Case 3 - Left Right + if balance > 1 and key > root.left.val: + root.left = self.leftRotate(root.left) + return self.rightRotate(root) + + # Case 4 - Right Left + if balance < -1 and key < root.right.val: + root.right = self.rightRotate(root.right) + return self.leftRotate(root) + + return root + + def leftRotate(self, z): + + y = z.right + T2 = y.left + + # Perform rotation + y.left = z + z.right = T2 + + # Update heights + z.height = 1 + max(self.getHeight(z.left), + self.getHeight(z.right)) + y.height = 1 + max(self.getHeight(y.left), + self.getHeight(y.right)) + + # Return the new root + return y + + def rightRotate(self, z): + + y = z.left + T3 = y.right + + # Perform rotation + y.right = z + z.left = T3 + + # Update heights + z.height = 1 + max(self.getHeight(z.left), + self.getHeight(z.right)) + y.height = 1 + max(self.getHeight(y.left), + self.getHeight(y.right)) + + # Return the new root + return y + + def getHeight(self, root): + if not root: + return 0 + + return root.height + + def getBalance(self, root): + if not root: + return 0 + + return self.getHeight(root.left) - self.getHeight(root.right) + + def preOrder(self, root): + + if not root: + return + + print(""{0} "".format(root.val), end="""") + self.preOrder(root.left) + self.preOrder(root.right) + + +# Driver program to test above function +myTree = AVL_Tree() +root = None + +root = myTree.insert(root, 10) +root = myTree.insert(root, 20) +root = myTree.insert(root, 30) +root = myTree.insert(root, 40) +root = myTree.insert(root, 50) +root = myTree.insert(root, 25) + +""""""The constructed AVL Tree would be + 30 + / \ + 20 40 + / \ \ + 10 25 50"""""" + +# Preorder Traversal +print(""Preorder traversal of the"", + ""constructed AVL tree is"") +myTree.preOrder(root) +print() + +# This code is contributed by Ajitesh Pathak",constant,nlogn +"# 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",linear,quadratic +"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",constant,cubic +"# 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",linear,nlogn +""""""" +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",linear,quadratic +""""""" +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",linear,linear +"# Python3 program to find +# the number of islands using +# Disjoint Set data structure. + +# Class to represent +# Disjoint Set Data structure +class DisjointUnionSets: + def __init__(self, n): + self.rank = [0] * n + self.parent = [0] * n + self.n = n + self.makeSet() + + def makeSet(self): + + # Initially, all elements are in their + # own set. + for i in range(self.n): + self.parent[i] = i + + # Finds the representative of the set that x + # is an element of + def find(self, x): + if (self.parent[x] != x): + + # if x is not the parent of itself, + # then x is not the representative of + # its set. + # so we recursively call Find on its parent + # and move i's node directly under the + # representative of this set + self.parent[x]=self.find(self.parent[x]) + + return self.parent[x] + + # Unites the set that includes x and + # the set that includes y + def Union(self, x, y): + + # Find the representatives(or the root nodes) + # for x an y + xRoot = self.find(x) + yRoot = self.find(y) + + # Elements are in the same set, + # no need to unite anything. + if xRoot == yRoot: + return + + # If x's rank is less than y's rank + # Then move x under y so that depth of tree + # remains less + if self.rank[xRoot] < self.rank[yRoot]: + parent[xRoot] = yRoot + + # Else if y's rank is less than x's rank + # Then move y under x so that depth of tree + # remains less + elif self.rank[yRoot] < self.rank[xRoot]: + self.parent[yRoot] = xRoot + + else: + + # Else if their ranks are the same + # Then move y under x (doesn't matter + # which one goes where) + self.parent[yRoot] = xRoot + + # And increment the result tree's + # rank by 1 + self.rank[xRoot] = self.rank[xRoot] + 1 + +# Returns number of islands in a[][] +def countIslands(a): + n = len(a) + m = len(a[0]) + + dus = DisjointUnionSets(n * m) + + # The following loop checks for its neighbours + # and unites the indexes if both are 1. + for j in range(0, n): + for k in range(0, m): + + # If cell is 0, nothing to do + if a[j][k] == 0: + continue + + # Check all 8 neighbours and do a Union + # with neighbour's set if neighbour is + # also 1 + if j + 1 < n and a[j + 1][k] == 1: + dus.Union(j * (m) + k, + (j + 1) * (m) + k) + if j - 1 >= 0 and a[j - 1][k] == 1: + dus.Union(j * (m) + k, + (j - 1) * (m) + k) + if k + 1 < m and a[j][k + 1] == 1: + dus.Union(j * (m) + k, + (j) * (m) + k + 1) + if k - 1 >= 0 and a[j][k - 1] == 1: + dus.Union(j * (m) + k, + (j) * (m) + k - 1) + if (j + 1 < n and k + 1 < m and + a[j + 1][k + 1] == 1): + dus.Union(j * (m) + k, (j + 1) * + (m) + k + 1) + if (j + 1 < n and k - 1 >= 0 and + a[j + 1][k - 1] == 1): + dus.Union(j * m + k, (j + 1) * + (m) + k - 1) + if (j - 1 >= 0 and k + 1 < m and + a[j - 1][k + 1] == 1): + dus.Union(j * m + k, (j - 1) * + m + k + 1) + if (j - 1 >= 0 and k - 1 >= 0 and + a[j - 1][k - 1] == 1): + dus.Union(j * m + k, (j - 1) * + m + k - 1) + + # Array to note down frequency of each set + c = [0] * (n * m) + numberOfIslands = 0 + for j in range(n): + for k in range(n): + if a[j][k] == 1: + x = dus.find(j * m + k) + + # If frequency of set is 0, + # increment numberOfIslands + if c[x] == 0: + numberOfIslands += 1 + c[x] += 1 + else: + c[x] += 1 + return numberOfIslands + +# Driver Code +a = [[1, 1, 0, 0, 0], + [0, 1, 0, 0, 1], + [1, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 1]] +print(""Number of Islands is:"", countIslands(a)) + +# This code is contributed by ankush_953",quadratic,quadratic +"# 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.",linear,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.",linear,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))",linear,quadratic +"# 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",linear,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.",linear,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",linear,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",linear,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))",constant,linear +"// A C++ program to implement Cartesian Tree sort +// Note that in this program we will build a min-heap +// Cartesian Tree and not max-heap. + +#include +using namespace std; + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ +struct Node +{ + int data; + Node *left, *right; +}; + +// Creating a shortcut for int, Node* pair type +typedef pair iNPair; + +// This function sorts by pushing and popping the +// Cartesian Tree nodes in a pre-order like fashion +void pQBasedTraversal(Node* root) +{ + // We will use a priority queue to sort the + // partially-sorted data efficiently. + // Unlike Heap, Cartesian tree makes use of + // the fact that the data is partially sorted + priority_queue , greater> pQueue; + pQueue.push (make_pair (root->data, root)); + + // Resembles a pre-order traverse as first data + // is printed then the left and then right child. + while (! pQueue.empty()) + { + iNPair popped_pair = pQueue.top(); + printf(""%d "", popped_pair.first); + + pQueue.pop(); + + if (popped_pair.second->left != NULL) + pQueue.push (make_pair(popped_pair.second->left->data, + popped_pair.second->left)); + + if (popped_pair.second->right != NULL) + pQueue.push (make_pair(popped_pair.second->right->data, + popped_pair.second->right)); + } + + return; +} + + +Node *buildCartesianTreeUtil(int root, int arr[], + int parent[], int leftchild[], int rightchild[]) +{ + if (root == -1) + return NULL; + + Node *temp = new Node; + + temp->data = arr[root]; + temp->left = buildCartesianTreeUtil(leftchild[root], + arr, parent, leftchild, rightchild); + + temp->right = buildCartesianTreeUtil(rightchild[root], + arr, parent, leftchild, rightchild); + + return temp ; +} + +// A function to create the Cartesian Tree in O(N) time +Node *buildCartesianTree(int arr[], int n) +{ + // Arrays to hold the index of parent, left-child, + // right-child of each number in the input array + int parent[n], leftchild[n], rightchild[n]; + + // Initialize all array values as -1 + memset(parent, -1, sizeof(parent)); + memset(leftchild, -1, sizeof(leftchild)); + memset(rightchild, -1, sizeof(rightchild)); + + // 'root' and 'last' stores the index of the root and the + // last processed of the Cartesian Tree. + // Initially we take root of the Cartesian Tree as the + // first element of the input array. This can change + // according to the algorithm + int root = 0, last; + + // Starting from the second element of the input array + // to the last on scan across the elements, adding them + // one at a time. + for (int i = 1; i <= n - 1; i++) + { + last = i-1; + rightchild[i] = -1; + + // Scan upward from the node's parent up to + // the root of the tree until a node is found + // whose value is smaller than the current one + // This is the same as Step 2 mentioned in the + // algorithm + while (arr[last] >= arr[i] && last != root) + last = parent[last]; + + // arr[i] is the smallest element yet; make it + // new root + if (arr[last] >= arr[i]) + { + parent[root] = i; + leftchild[i] = root; + root = i; + } + + // Just insert it + else if (rightchild[last] == -1) + { + rightchild[last] = i; + parent[i] = last; + leftchild[i] = -1; + } + + // Reconfigure links + else + { + parent[rightchild[last]] = i; + leftchild[i] = rightchild[last]; + rightchild[last]= i; + parent[i] = last; + } + + } + + // Since the root of the Cartesian Tree has no + // parent, so we assign it -1 + parent[root] = -1; + + return (buildCartesianTreeUtil (root, arr, parent, + leftchild, rightchild)); +} + +// Sorts an input array +int printSortedArr(int arr[], int n) +{ + // Build a cartesian tree + Node *root = buildCartesianTree(arr, n); + + printf(""The sorted array is-\n""); + + // Do pr-order traversal and insert + // in priority queue + pQBasedTraversal(root); +} + +/* Driver program to test above functions */ +int main() +{ + /* Given input array- {5,10,40,30,28}, + it's corresponding unique Cartesian Tree + is- + + 5 + \ + 10 + \ + 28 + / + 30 + / + 40 + */ + + int arr[] = {5, 10, 40, 30, 28}; + int n = sizeof(arr)/sizeof(arr[0]); + + printSortedArr(arr, n); + + return(0); +}",linear,nlogn +"# 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",constant,linear +"# 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",constant,linear +"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 = ' ')",constant,linear +"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",constant,linear +"# Python Program to search an element +# in a sorted and pivoted array + +# Searches an element key in a pivoted +# sorted array arrp[] of size n +def pivotedBinarySearch(arr, n, key): + + pivot = findPivot(arr, 0, n-1) + + # If we didn't find a pivot, + # then array is not rotated at all + if pivot == -1: + return binarySearch(arr, 0, n-1, key) + + # If we found a pivot, then first + # compare with pivot and then + # search in two subarrays around pivot + if arr[pivot] == key: + return pivot + if arr[0] <= key: + return binarySearch(arr, 0, pivot-1, key) + return binarySearch(arr, pivot + 1, n-1, key) + + +# Function to get pivot. For array +# 3, 4, 5, 6, 1, 2 it returns 3 +# (index of 6) +def findPivot(arr, low, high): + + # base cases + if high < low: + return -1 + if high == low: + return low + + # low + (high - low)/2; + mid = int((low + high)/2) + + if mid < high and arr[mid] > arr[mid + 1]: + return mid + if mid > low and arr[mid] < arr[mid - 1]: + return (mid-1) + if arr[low] >= arr[mid]: + return findPivot(arr, low, mid-1) + return findPivot(arr, mid + 1, high) + +# Standard Binary Search function +def binarySearch(arr, low, high, key): + + if high < low: + return -1 + + # low + (high - low)/2; + mid = int((low + high)/2) + + if key == arr[mid]: + return mid + if key > arr[mid]: + return binarySearch(arr, (mid + 1), high, + key) + return binarySearch(arr, low, (mid - 1), key) + + +# Driver program to check above functions +# Let us search 3 in below array +if __name__ == '__main__': + arr1 = [5, 6, 7, 8, 9, 10, 1, 2, 3] + n = len(arr1) + key = 3 + print(""Index of the element is : "", \ + pivotedBinarySearch(arr1, n, key)) + +# This is contributed by Smitha Dinesh Semwal",constant,logn +"# Search an element in sorted and rotated array using +# single pass of Binary Search + +# Returns index of key in arr[l..h] if key is present, +# otherwise returns -1 +def search(arr, l, h, key): + if l > h: + return -1 + + mid = (l + h) // 2 + if arr[mid] == key: + return mid + + # If arr[l...mid] is sorted + if arr[l] <= arr[mid]: + + # As this subarray is sorted, we can quickly + # check if key lies in half or other half + if key >= arr[l] and key <= arr[mid]: + return search(arr, l, mid-1, key) + return search(arr, mid + 1, h, key) + + # If arr[l..mid] is not sorted, then arr[mid... r] + # must be sorted + if key >= arr[mid] and key <= arr[h]: + return search(arr, mid + 1, h, key) + return search(arr, l, mid-1, key) + + +# Driver program +if __name__ == '__main__': + arr = [4, 5, 6, 7, 8, 9, 1, 2, 3] + key = 3 + i = search(arr, 0, len(arr)-1, key) + if i != -1: + print(""Index: % d"" % i) + else: + print(""Key not found"") + +# This code is contributed by Shreyanshi Arun",constant,logn +"# Python3 program to find a +# pair with a given sum in +# a sorted and rotated array + + +# This function returns True +# if arr[0..n-1] has a pair +# with sum equals to x. +def pairInSortedRotated(arr, n, x): + + # Find the pivot element + for i in range(0, n - 1): + if (arr[i] > arr[i + 1]): + break + + # l is now index of smallest element + l = (i + 1) % n + # r is now index of largest element + r = i + + # Keep moving either l + # or r till they meet + while (l != r): + + # If we find a pair with + # sum x, we return True + if (arr[l] + arr[r] == x): + return True + + # If current pair sum is less, + # move to the higher sum + if (arr[l] + arr[r] < x): + l = (l + 1) % n + else: + + # Move to the lower sum side + r = (n + r - 1) % n + + return False + + +# Driver program to test above function +arr = [11, 15, 6, 8, 9, 10] +X = 16 +N = len(arr) + +if (pairInSortedRotated(arr, N, X)): + print(""true"") +else: + print(""false"") + + +# This article contributed by saloni1297",constant,linear +"'''Python program to find maximum value of Sum(i*arr[i])''' + +# returns max possible value of Sum(i*arr[i]) + + +def maxSum(arr): + + # stores sum of arr[i] + arrSum = 0 + + # stores sum of i*arr[i] + currVal = 0 + + n = len(arr) + + for i in range(0, n): + arrSum = arrSum + arr[i] + currVal = currVal + (i*arr[i]) + + # initialize result + maxVal = currVal + + # try all rotations one by one and find the maximum + # rotation sum + for j in range(1, n): + currVal = currVal + arrSum-n*arr[n-j] + if currVal > maxVal: + maxVal = currVal + + # return result + return maxVal + + +# test maxsum(arr) function +if __name__ == '__main__': + arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9] + print ""Max sum is: "", maxSum(arr)",constant,linear +"# A Naive Python3 program to find +# maximum sum rotation +import sys + +# Returns maximum value of i * arr[i] +def maxSum(arr, n): + + # Initialize result + res = -sys.maxsize + + # Consider rotation beginning with i + # for all possible values of i. + for i in range(0, n): + + + # Initialize sum of current rotation + curr_sum = 0 + + # Compute sum of all values. We don't + # actually rotation the array, but + # compute sum by finding indexes when + # arr[i] is first element + for j in range(0, n): + + index = int((i + j)% n) + curr_sum += j * arr[index] + + + # Update result if required + res = max(res, curr_sum) + return res + +# Driver code +arr = [8, 3, 1, 2] +n = len(arr) + +print(maxSum(arr, n)) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,quadratic +"# An efficient Python3 program to +# compute maximum sum of i * arr[i] + +def maxSum(arr, n): + + # Compute sum of all array elements + cum_sum = 0 + + for i in range(0, n): + cum_sum += arr[i] + + # Compute sum of i * arr[i] for + # initial configuration. + curr_val = 0 + + for i in range(0, n): + curr_val += i * arr[i] + + # Initialize result + res = curr_val + + # Compute values for other iterations + for i in range(1, n): + + # Compute next value using previous + # value in O(1) time + next_val = (curr_val - (cum_sum - arr[i-1]) + + arr[i-1] * (n-1)) + + # Update current value + curr_val = next_val + + # Update result if required + res = max(res, next_val) + + return res + + +# Driver code +arr = [8, 3, 1, 2] +n = len(arr) + +print(maxSum(arr, n)) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,linear +"# Python3 program to find maximum sum of +# all rotation of i*arr[i] using pivot. + +# function definition + + +def maxSum(arr, n): + + sum = 0 + pivot = findPivot(arr, n) + + # difference in pivot and index + # of last element of array + diff = n - 1 - pivot + for i in range(n): + sum = sum + ((i + diff) % n) * arr[i] + + return sum + +# function to find pivot + + +def findPivot(arr, n): + for i in range(n): + + if(arr[i] > arr[(i + 1) % n]): + return i + + +# Driver code +if __name__ == ""__main__"": + + # rotated input array + arr = [8, 13, 1, 2] + n = len(arr) + + max = maxSum(arr, n) + print(max) + +# This code is contributed by Ryuga",constant,linear +"# Python3 program to find number +# of rotations in a sorted and +# rotated array. + +# Returns count of rotations for +# an array which is first sorted +# in ascending order, then rotated +def countRotations(arr, n): + + # We basically find index + # of minimum element + min = arr[0] + min_index = 0 + for i in range(0, n): + + if (min > arr[i]): + + min = arr[i] + min_index = i + + return min_index; + + +# Driver code +arr = [15, 18, 2, 3, 6, 12] +n = len(arr) +print(countRotations(arr, n)) + +# This code is contributed by Smitha Dinesh Semwal",constant,linear +"def countRotations(arr, n): + # Check is array is rotated + if (arr[0] > arr[n - 1]): + + # Traverse the array + for i in range(0, n): + + # Index where element is greater + # than the next element + if (arr[i] > arr[i + 1]): + return i + 1 + + # Array is not rotated + return 0 + +# Driver code +arr = [15, 18, 2, 3, 6, 12] +n = len(arr) +print(countRotations(arr, n)) + +# This code is contributed by karandeep1234",constant,linear +"# Binary Search based Python3 +# program to find number of +# rotations in a sorted and +# rotated array. + +# Returns count of rotations for +# an array which is first sorted +# in ascending order, then rotated + +def countRotations(arr, n): + start = 0 + end = n-1 + + # Finding the index of minimum of the array + # index of min would be equal to number to rotation + while start<=end: + mid = start+(end-start)//2 + + # Calculating the previous(prev) + # and next(nex) index of mid + prev = (mid-1+n)%n + nex = (mid+1)%n + + # Checking if mid is minimum + if arr[mid]arr[end]: start = mid+1 + else: return 0 + +# Driver code +if __name__ == '__main__': + arr = [15, 18, 2, 3, 6, 12] + N = len(arr) + print(countRotations(arr, N)) + +# This code is contributed by Smitha Dinesh Semwal",logn,logn +"# Returns count of rotations for an array which +# is first sorted in ascending order, then rotated + +# Observation: We have to return index of the smallest element + + +def countRotations(arr, n): + + low = 0 + high = n - 1 + while(low <= high): + + # if first element is mid or + # last element is mid + # then simply use modulo + # so it never goes out of bound. + mid = low + ((high - low) // 2) + prev = (mid - 1 + n) % n + next = (mid + 1) % n + + if(arr[mid] <= arr[prev] + and arr[mid] <= arr[next]): + return mid + elif (arr[mid] <= arr[high]): + high = mid - 1 + elif (arr[mid] >= arr[low]): + low = mid + 1 + return 0 + +# Driver code + + +arr = [15, 18, 2, 3, 6, 12] +n = len(arr) +print(countRotations(arr, n)) + +# This code is contributed by shinjanpatra.",constant,logn +"# Python3 implementation of left rotation +# of an array K number of times + +# Fills temp with two copies of arr + + +def rotateArray(A, start, end): + + while start < end: + temp = A[start] + A[start] = A[end] + A[end] = temp + start += 1 + end -= 1 + return A + +# Function to left rotate an array k times + + +def leftRotate(arr, a, k): + + # if the value of k ever exceeds the length of the array + c = k % a + + # initializing array D so that we always + # have a clone of the original array to rotate + D = arr.copy() + + rotateArray(D, 0, c - 1) + rotateArray(D, c, a - 1) + rotateArray(D, 0, a - 1) + + # printing the rotated array + print(D) + + +# Driver program +arr = [1, 3, 5, 7, 9] +n = len(arr) + +k = 2 +leftRotate(arr, n, k) + +k = 3 +leftRotate(arr, n, k) + +k = 4 +leftRotate(arr, n, k) + +# This code is contributed by aditya942003patil",linear,linear +"# Python3 implementation of left rotation +# of an array K number of times + +# Fills temp with two copies of arr + + +def preprocess(arr, n): + temp = [None] * (2 * n) + + # Store arr elements at i and i + n + for i in range(n): + temp[i] = temp[i + n] = arr[i] + return temp + +# Function to left rotate an array k times + + +def leftRotate(arr, n, k, temp): + + # Starting position of array after k + # rotations in temp will be k % n + start = k % n + + # Print array after k rotations + for i in range(start, start + n): + print(temp[i], end="" "") + print("""") + + +# Driver program +arr = [1, 3, 5, 7, 9] +n = len(arr) +temp = preprocess(arr, n) + +k = 2 +leftRotate(arr, n, k, temp) + +k = 3 +leftRotate(arr, n, k, temp) + +k = 4 +leftRotate(arr, n, k, temp) + +# This code is contributed by Sanghamitra Mishra",linear,linear +"# Python3 implementation of +# left rotation of an array +# K number of times + +# Function to left rotate +# an array k times + + +def leftRotate(arr, n, k): + + # Print array + # after k rotations + for i in range(k, k + n): + print(str(arr[i % n]), + end="" "") + + +# Driver Code +arr = [1, 3, 5, 7, 9] +n = len(arr) +k = 2 +leftRotate(arr, n, k) +print() + +k = 3 +leftRotate(arr, n, k) +print() + +k = 4 +leftRotate(arr, n, k) +print() + +# This code is contributed +# by ChitraNayal",constant,linear +"# python3 code to implement the approach + +def findMin(arr, N): + + min_ele = arr[0]; + + # Traversing over array to + # find minimum element + for i in range(N) : + if arr[i] < min_ele : + min_ele = arr[i] + + return min_ele; + +# Driver program +arr = [5, 6, 1, 2, 3, 4] +N = len(arr) + +print(findMin(arr,N)) + +# This code is contributed by aditya942003patil",constant,linear +"# Python program to find minimum element +# in a sorted and rotated array + + +def findMin(arr, low, high): + # This condition is needed to handle the case when array is not + # rotated at all + if high < low: + return arr[0] + + # If there is only one element left + if high == low: + return arr[low] + + # Find mid + mid = int((low + high)/2) + + # Check if element (mid+1) is minimum element. Consider + # the cases like [3, 4, 5, 1, 2] + if mid < high and arr[mid+1] < arr[mid]: + return arr[mid+1] + + # Check if mid itself is minimum element + if mid > low and arr[mid] < arr[mid - 1]: + return arr[mid] + + # Decide whether we need to go to left half or right half + if arr[high] > arr[mid]: + return findMin(arr, low, mid-1) + return findMin(arr, mid+1, high) + + +# Driver program to test above functions +if __name__ == '__main__': + arr = [5, 6, 1, 2, 3, 4] + N = len(arr) + print(""The minimum element is "" + \ + str(findMin(arr, 0, N-1))) + +# This code is contributed by Pratik Chhajer",constant,logn +"# Python3 program for right rotation of +# an array (Reversal Algorithm) + + +# Function to reverse arr +# from index start to end +def reverseArray( arr, start, end): + + while (start < end): + + arr[start], arr[end] = arr[end], arr[start] + start = start + 1 + end = end - 1 + + +# Function to right rotate arr +# of size n by d +def rightRotate( arr, d, n): + + reverseArray(arr, 0, n - 1); + reverseArray(arr, 0, d - 1); + reverseArray(arr, d, n - 1); + + +# function to print an array +def printArray( arr, size): + for i in range(0, size): + print (arr[i], end = ' ') + + +# Driver code +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +n = len(arr) +k = 3 + +# Function call +rightRotate(arr, k, n) +printArray(arr, n) + + +# This article is contributed +# by saloni1297",constant,linear +"# Python3 code to Find another array +# such that the hamming distance +# from the original array is maximum + +# Return the maximum hamming +# distance of a rotation +def maxHamming( arr , n ): + + # arr[] to brr[] two times so + # that we can traverse through + # all rotations. + brr = [0] * (2 * n + 1) + for i in range(n): + brr[i] = arr[i] + for i in range(n): + brr[n+i] = arr[i] + + # We know hamming distance + # with 0 rotation would be 0. + maxHam = 0 + + # We try other rotations one by + # one and compute Hamming + # distance of every rotation + for i in range(1, n): + currHam = 0 + k = 0 + for j in range(i, i + n): + if brr[j] != arr[k]: + currHam += 1 + k = k + 1 + + # We can never get more than n. + if currHam == n: + return n + + maxHam = max(maxHam, currHam) + + return maxHam + +# driver program +arr = [2, 4, 6, 8] +n = len(arr) +print(maxHamming(arr, n)) + +# This code is contributed by ""Sharad_Bhardwaj"".",linear,quadratic +"# Python3 program to Find another array +# such that the hamming distance +# from the original array is maximum + +# requires O(n*n) time and O(1) extra space; + +# Return the maximum hamming distance of a rotation +def maxHamming(arr, n): + + # outer loop for how much rotation + hmmd = 0 + + for j in range(1,n): + hmmd = 0 + #inner loop to compare elements with elements on shifted index + for i in range(n): + if(arr[i] != arr[(i + j) % n]): + hmmd += 1 + + #max possible hamming distance is n, no need to check further + if(hmmd == n): + return n + return hmmd + +# driver program +arr = [2, 4, 6, 8] +n = len(arr) +print(maxHamming(arr, n)) + + +# This code is contributed by shinjanpatra",constant,quadratic +"# Python code to find maximum +# of an array with it's rotations +import time + +# Function hamming distance to find +# the hamming distance for two lists/strings +def hamming_distance(x: list, y: list): + + # Initialize count + count = 0 + + # Run loop for size of x(or y) + # as both as same length + for i in range(len(x)): + + # Check if corresponding elements + # at same index are not equal + if(x[i] != y[i]): + + # Increment the count every + # time above condition satisfies + count += 1 + + # Return the hamming distance + # for given pair of lists or strings + return count + + +# Function to rotate the given array +# in anti-clockwise direction by 1 +def rotate_by_one(arr: list): + + # Store 1st element in a variable + x = arr[0] + + # Update each ith element (0<=i<=n-2) + # with it's next value + for i in range(0, len(arr)-1): + arr[i] = arr[i+1] + + # Assign 1st element to the last index + arr[len(arr)-1] = x + + +# Function max_hamming_distance to find +# the maximum hamming distance for given array +def max_hamming_distance(arr: list): + + # Initialize a variable to store + # maximum hamming distance + max_h = -10000000000 + + # Store size of the given array + # in a variable n + n = len(arr) + + # Initialize a new array + a = [] + + # Copy the original array in new array + for i in range(n): + a.append(arr[i]) + + # Run loop for i=0 to i=n-1 for n-1 rotations + for i in range(1, n): + + # Find the next rotation + rotate_by_one(arr) + print(""Array after %d rotation : "" % (i), arr) + + # Store hamming distance of current + # rotation with original array + curr_h_dist = hamming_distance(a, arr) + print(""Hamming Distance with %d rotations: %d"" % + (i, curr_h_dist)) + + # Check if current hamming distance + # is greater than max hamming distance + if curr_h_dist > max_h: + + # If yes, assign value of current + # hamming distance to max hamming distance + max_h = curr_h_dist + + print('\n') + # Return maximum hamming distance + return max_h + + +# Driver code +if __name__ == '__main__': + + arr = [3, 0, 6, 4, 3] + start = time.time() + print('\n') + print(""Original Array : "", arr) + print('\n') + print(""Maximum Hamming Distance: "", max_hamming_distance(arr)) + end = time.time() + print(f""Execution Time = {end - start}"") +# This code is contributed by Vivek_Kumar_Sinha",constant,quadratic +"# Python Program to solve queries on Left and Right +# Circular shift on array + +# Function to solve query of type 1 x. +def querytype1(toRotate, times, n): + + # Decreasing the absolute rotation + toRotate = (toRotate - times) % n + return toRotate + +# Function to solve query of type 2 y. +def querytype2(toRotate, times, n): + + # Increasing the absolute rotation. + toRotate = (toRotate + times) % n + return toRotate + +# Function to solve queries of type 3 l r. +def querytype3( toRotate, l, r, preSum, n): + + # Finding absolute l and r. + l = (l + toRotate + n) % n + r = (r + toRotate + n) % n + + # if l is before r. + if (l <= r): + print((preSum[r + 1] - preSum[l])) + + # If r is before l. + else: + print((preSum[n] + preSum[r + 1] - preSum[l])) + +# Wrapper Function solve all queries. +def wrapper( a, n): + preSum = [ 0 for i in range(n + 1)] + + # Finding Prefix sum + for i in range(1,n+1): + preSum[i] = preSum[i - 1] + a[i - 1] + + toRotate = 0 + + # Solving each query + toRotate = querytype1(toRotate, 3, n) + querytype3(toRotate, 0, 2, preSum, n) + toRotate = querytype2(toRotate, 1, n) + querytype3(toRotate, 1, 4, preSum, n); + +# Driver Program +if __name__ == '__main__': + arr = [ 1, 2, 3, 4, 5 ] + N = len(arr) + wrapper(arr, N) + +# This code is contributed by rohan07.",linear,linear +"# Python implementation of left rotation of +# an array K number of times + +# Function to leftRotate array multiple times + + +def leftRotate(arr, n, k): + + # To get the starting point of rotated array + mod = k % n + s = """" + + # Prints the rotated array from start position + for i in range(n): + print str(arr[(mod + i) % n]), + print + return + + +# Driver code +arr = [1, 3, 5, 7, 9] +n = len(arr) +k = 2 + +# Function Call +leftRotate(arr, n, k) + +k = 3 + +# Function Call +leftRotate(arr, n, k) + +k = 4 + +# Function Call +leftRotate(arr, n, k) + +# This code is contributed by Sachin Bisht",constant,linear +"# Python code for above approach + +import array as arr +def findElement(arr, ranges, rotations, index): + + # Track of the rotation number + n1 = 1 + + # Track of the row index for the ranges[][] array + i = 0 + + # Initialize the left side of the ranges[][] array + leftRange = 0 + + # Initialize the right side of the ranges[][] array + rightRange = 0 + + # Initialize the key variable + key = 0 + while (n1 <= rotations): + + leftRange = ranges[i][0] + rightRange = ranges[i][1] + key = arr[rightRange] + j = rightRange + while(j <= rightRange & j > leftRange): + arr[j] = arr[j - 1] + j = j-1 + arr[leftRange] = key + + n1 = n1+1 + i = i+1 + # Return the element after all the rotations + return arr[index] + + +# driver code +ar = arr.array('i', [1, 2, 3, 4, 5]) + +# No. of rotations +rotations = 2 + +# Ranges according to 0-based indexing +ranges = [[0, 2], [0, 3]] + +index = 1 +print(findElement(ar, ranges, rotations, index)) + +# This code is contributed by adityamaharshi21.",constant,quadratic +"# Python 3 code to rotate an array +# and answer the index query + +# Function to compute the element +# at given index +def findElement(arr, ranges, rotations, index) : + + for i in range(rotations - 1, -1, -1 ) : + + # Range[left...right] + left = ranges[i][0] + right = ranges[i][1] + + # Rotation will not have + # any effect + if (left <= index and right >= index) : + if (index == left) : + index = right + else : + index = index - 1 + + # Returning new element + return arr[index] + +# Driver Code +arr = [ 1, 2, 3, 4, 5 ] + +# No. of rotations +rotations = 2 + +# Ranges according to +# 0-based indexing +ranges = [ [ 0, 2 ], [ 0, 3 ] ] + +index = 1 + +print(findElement(arr, ranges, rotations, index)) + +# This code is contributed by Nikita Tiwari.",constant,constant +"# Python program to split array and move first +# part to end. + +def splitArr(arr, n, k): + for i in range(0, k): + x = arr[0] + for j in range(0, n-1): + arr[j] = arr[j + 1] + + arr[n-1] = x + + +# main +arr = [12, 10, 5, 6, 52, 36] +n = len(arr) +position = 2 + +splitArr(arr, n, position) + +for i in range(0, n): + print(arr[i], end = ' ') + +# Code Contributed by Mohit Gupta_OMG <(0_o)> ",constant,quadratic +"# Python3 program to split array and +# move first part to end. + +# Function to split array and +# move first part to end +def SplitAndAdd(A, length, rotation): + + # make a temporary array with double + # the size and each index is initialized to 0 + tmp = [ 0 for i in range(length * 2)] + + # copy array element in to new array twice + for i in range(length): + tmp[i] = A[i] + tmp[i + length] = A[i] + + for i in range(rotation, + rotation + length, 1): + A[i - rotation] = tmp[i]; + +# Driver code +arr = [12, 10, 5, 6, 52, 36] +n = len(arr) +position = 2 +SplitAndAdd(arr, n, position); +for i in range(n): + print(arr[i], end = "" "") +print() + +# This code is contributed by SOUMYA SEN",linear,linear +"# Python3 program for above approach + +# Function to transform the array +def fixArray(ar, n): + + # Iterate over the array + for i in range(n): + for j in range(n): + + # Check is any ar[j] + # exists such that + # ar[j] is equal to i + if (ar[j] == i): + ar[j], ar[i] = ar[i], ar[j] + + # Iterate over array + for i in range(n): + + # If not present + if (ar[i] != i): + ar[i] = -1 + + # Print the output + print(""Array after Rearranging"") + + for i in range(n): + print(ar[i], end = "" "") + +# Driver Code +ar = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ] +n = len(ar) + +# Function Call +fixArray(ar, n); + +# This code is contributed by rag2127",constant,quadratic +"# Python3 program for rearrange an +# array such that arr[i] = i. + +# Function to rearrange an array +# such that arr[i] = i. + + +def fix(A, len): + + for i in range(0, len): + + if (A[i] != -1 and A[i] != i): + x = A[i] + + # check if desired place + # is not vacate + while (A[x] != -1 and A[x] != x): + + # store the value from + # desired place + y = A[x] + + # place the x to its correct + # position + A[x] = x + + # now y will become x, now + # search the place for x + x = y + + # place the x to its correct + # position + A[x] = x + + # check if while loop hasn't + # set the correct value at A[i] + if (A[i] != i): + + # if not then put -1 at + # the vacated place + A[i] = -1 + + +# Driver code +A = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1] + +fix(A, len(A)) + +for i in range(0, len(A)): + print(A[i], end=' ') + +# This code is contributed by Saloni1297",constant,linear +"# Python3 program for rearrange an +# array such that arr[i] = i. + +# Function to rearrange an array +# such that arr[i] = i. +def fix(A): + s = set() + + # Storing all the values in the Set + for i in range(len(A)): + s.add(A[i]) + + for i in range(len(A)): + + # check for item if present in set + if i in s: + A[i] = i + else: + A[i] = -1 + return A + +# Driver code +if __name__ == ""__main__"": + A = [-1, -1, 6, 1, 9, + 3, 2, -1, 4,-1] + print(fix(A)) + +# This code is contributed by Chitranayal",linear,linear +"# Python3 program for rearrange an +# array such that arr[i] = i. +if __name__ == ""__main__"": + + arr = [-1, -1, 6, 1, 9, + 3, 2, -1, 4, -1] + n = len(arr) + i = 0 + while i < n: + + if (arr[i] >= 0 and arr[i] != i): + (arr[arr[i]], + arr[i]) = (arr[i], + arr[arr[i]]) + else: + i += 1 + + for i in range(n): + print(arr[i], end="" "") + +# This code is contributed by Chitranayal",constant,linear +"# Python program to put positive numbers at even indexes (0, // 2, 4,..) and +# negative numbers at odd indexes (1, 3, 5, ..) + +# The main function that rearranges elements of given array. +# It puts positive elements at even indexes (0, 2, ..) and +# negative numbers at odd indexes (1, 3, ..). +def rearrange(arr, n): + # The following few lines are similar to partition process + # of QuickSort. The idea is to consider 0 as pivot and + # divide the array around it. + i = -1 + for j in range(n): + if (arr[j] < 0): + i += 1 + # swapping of arr + arr[i], arr[j] = arr[j], arr[i] + + # Now all positive numbers are at end and negative numbers + # at the beginning of array. Initialize indexes for starting + # point of positive and negative numbers to be swapped + pos, neg = i+1, 0 + + # Increment the negative index by 2 and positive index by 1, + # i.e., swap every alternate negative number with next + # positive number + while (pos < n and neg < pos and arr[neg] < 0): + + # swapping of arr + arr[neg], arr[pos] = arr[pos], arr[neg] + pos += 1 + neg += 2 + +# A utility function to print an array +def printArray(arr, n): + + for i in range(n): + print (arr[i],end="" "") + +# Driver program to test above functions +arr = [-1, 2, -3, 4, 5, 6, -7, 8, 9] +n = len(arr) +rearrange(arr, n) +printArray(arr, n) + +# Contributed by Afzal",constant,linear +"# Python3 program to rearrange +# positive and negative integers +# in alternate fashion and +# maintaining the order of positive +# and negative numbers + +# rotates the array to right by once +# from index 'outOfPlace to cur' + + +def rightRotate(arr, n, outOfPlace, cur): + temp = arr[cur] + for i in range(cur, outOfPlace, -1): + arr[i] = arr[i - 1] + arr[outOfPlace] = temp + return arr + + +def rearrange(arr, n): + outOfPlace = -1 + for index in range(n): + if(outOfPlace >= 0): + + # if element at outOfPlace place in + # negative and if element at index + # is positive we can rotate the + # array to right or if element + # at outOfPlace place in positive and + # if element at index is negative we + # can rotate the array to right + if((arr[index] >= 0 and arr[outOfPlace] < 0) or + (arr[index] < 0 and arr[outOfPlace] >= 0)): + arr = rightRotate(arr, n, outOfPlace, index) + if(index-outOfPlace > 2): + outOfPlace += 2 + else: + outOfPlace = - 1 + + if(outOfPlace == -1): + + # conditions for A[index] to + # be in out of place + if((arr[index] >= 0 and index % 2 == 0) or + (arr[index] < 0 and index % 2 == 1)): + outOfPlace = index + return arr + + +# Driver Code +arr = [-5, -2, 5, 2, 4, + 7, 1, 8, 0, -8] + +print(""Given Array is:"") +print(arr) + +print(""\nRearranged array is:"") +print(rearrange(arr, len(arr))) + +# This code is contributed +# by Charan Sai",constant,quadratic +"# Python implementation to move all zeroes at +# the end of array + +# function to move all zeroes at +# the end of array +def moveZerosToEnd (arr, n): + + # Count of non-zero elements + count = 0; + + + # Traverse the array. If arr[i] is non-zero, then + # update the value of arr at index count to arr[i] + for i in range(0, n): + if (arr[i] != 0): + arr[count] = arr[i] + count+=1 + + # Update all elements at index >=count with value 0 + for i in range(count, n): + arr[i] = 0 + + + +# function to print the array elements +def printArray(arr, n): + + for i in range(0, n): + print(arr[i],end="" "") + + +# Driver program to test above +arr = [ 0, 1, 9, 8, 4, 0, 0, 2, + 7, 0, 6, 0, 9 ] +n = len(arr) + +print(""Original array:"", end="" "") +printArray(arr, n) + +moveZerosToEnd(arr, n) + +print(""\nModified array: "", end="" "") +printArray(arr, n) + +# This code is contributed by +# Ashutosh Singh",constant,linear +"# Python3 program to find +# minimum swaps required +# to club all elements less +# than or equals to k together + +# Utility function to find +# minimum swaps required to +# club all elements less than +# or equals to k together +def minSwap(arr, n, k) : + + # Find count of elements + # which are less than + # equals to k + count = 0 + for i in range(0, n) : + if (arr[i] <= k) : + count = count + 1 + + # Find unwanted elements + # in current window of + # size 'count' + bad = 0 + for i in range(0, count) : + if (arr[i] > k) : + bad = bad + 1 + + # Initialize answer with + # 'bad' value of current + # window + ans = bad + j = count + for i in range(0, n) : + + if(j == n) : + break + + # Decrement count of + # previous window + if (arr[i] > k) : + bad = bad - 1 + + # Increment count of + # current window + if (arr[j] > k) : + bad = bad + 1 + + # Update ans if count + # of 'bad' is less in + # current window + ans = min(ans, bad) + + j = j + 1 + + return ans + +# Driver code +arr = [2, 1, 5, 6, 3] +n = len(arr) +k = 3 +print (minSwap(arr, n, k)) + +arr1 = [2, 7, 9, 5, 8, 7, 4] +n = len(arr1) +k = 5 +print (minSwap(arr1, n, k)) + +# This code is contributed by +# Manish Shaw(manishshaw1)",constant,linear +"import sys +import math + + +class GFG : + + # Function for finding the minimum number of swaps + # required to bring all the numbers less + # than or equal to k together. + @staticmethod + def minSwap( arr, n, k) : + + # Initially snowBallsize is 0 + snowBallSize = 0 + i = 0 + while (i < n) : + + # Calculating the size of window required + if (arr[i] <= k) : + snowBallSize += 1 + i += 1 + swap = 0 + ans_swaps = sys.maxsize + i = 0 + while (i < snowBallSize) : + if (arr[i] > k) : + swap += 1 + i += 1 + ans_swaps = min(ans_swaps,swap) + i = snowBallSize + while (i < n) : + + # Checking in every window no. of swaps + # required and storing its minimum + if (arr[i - snowBallSize] <= k and arr[i] > k) : + swap += 1 + elif(arr[i - snowBallSize] > k and arr[i] <= k) : + swap -= 1 + ans_swaps = min(ans_swaps,swap) + i += 1 + return ans_swaps + @staticmethod + def main( args) : + arr1 = [2, 7, 9, 5, 8, 7, 4] + n = len(arr1) + k = 5 + print(GFG.minSwap(arr1, n, k)) + +if __name__==""__main__"": + GFG.main([]) + + # This code is contributed by aadityaburujwale.",constant,linear +"# Python 3 program to print +# the array in given order + +# Function which arrange the +# array. +def rearrangeArray(arr, n) : + + # Sorting the array elements + arr.sort() + + # To store modified array + tempArr = [0] * (n + 1) + + # Adding numbers from sorted + # array to new array accordingly + ArrIndex = 0 + + # Traverse from begin and end + # simultaneously + i = 0 + j = n-1 + + while(i <= n // 2 or j > n // 2 ) : + + tempArr[ArrIndex] = arr[i] + ArrIndex = ArrIndex + 1 + tempArr[ArrIndex] = arr[j] + ArrIndex = ArrIndex + 1 + i = i + 1 + j = j - 1 + + # Modifying original array + for i in range(0, n) : + arr[i] = tempArr[i] + + +# Driver Code +arr = [ 5, 8, 1, 4, 2, 9, 3, 7, 6 ] +n = len(arr) +rearrangeArray(arr, n) + +for i in range(0, n) : + print( arr[i], end = "" "") + +# This code is contributed by Nikita Tiwari.",linear,nlogn +"# Python 3 program for +# moving negative numbers to left +# while maintaining the order + + +class Solution: + def rotateSubArray(self, arr, l, r): + temp = arr[r] + for j in range(r, l-1, -1): + arr[j] = arr[j-1] + arr[l] = temp + + return arr + + def moveNegative(self, arr): + + last_negative_index = -1 + + for i in range(len(arr)): + if arr[i] < 0: + last_negative_index += 1 + arr[i], arr[last_negative_index] = arr[last_negative_index], arr[i] + + # Done to manage order too + if i - last_negative_index >= 2: + self.rotateSubArray(arr, last_negative_index+1, i) + + return arr + + +# Driver Code +if __name__ == '__main__': + arr = [5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1] + ob = Solution() + ob.moveNegative(arr) + for i in arr: + print(i, end=' ') + print() + +# This code is contributed by Kapil Bansal(devkapilbansal)",constant,quadratic +"",constant,quadratic +"# Python 3 program to Rearrange positive +# and negative numbers in a array + +# A utility function to print +# an array of size n + + +def printArray(arr, n): + for i in range(n): + print(arr[i], end="" "") + print() + +# Function to Rearrange positive +# and negative numbers in a array + + +def RearrangePosNeg(arr, n): + + for i in range(1, n): + key = arr[i] + + # if current element is positive + # do nothing + if (key > 0): + continue + + ''' if current element is negative, + shift positive elements of arr[0..i-1], + to one position to their right ''' + j = i - 1 + while (j >= 0 and arr[j] > 0): + arr[j + 1] = arr[j] + j = j - 1 + + # Put negative element at its + # right position + arr[j + 1] = key + + +# Driver Code +if __name__ == ""__main__"": + arr = [-12, 11, -13, -5, + 6, -7, 5, -3, -6] + n = len(arr) + + RearrangePosNeg(arr, n) + printArray(arr, n) + +# This code is contributed +# by ChitraNayal",linear,nlogn +"# Python3 program to Rearrange positive +# and negative numbers in a array + +# Function to print an array + + +def printArray(A, size): + + for i in range(size): + print(A[i], end="" "") + print() + +# Merges two subarrays of arr[]. +# First subarray is arr[l..m] +# Second subarray is arr[m + 1..r] + + +def merge(arr, l, m, r): + i, j, k = 0, 0, 0 + n1 = m - l + 1 + n2 = r - m + + # create temp arrays */ + L = [arr[l + i] for i in range(n1)] + R = [arr[m + 1 + j] for j in range(n2)] + + # Merge the temp arrays back into arr[l..r]*/ + i = 0 # Initial index of first subarray + j = 0 # Initial index of second subarray + k = l # Initial index of merged subarray + + # Note the order of appearance of elements + # should be maintained - we copy elements + # of left subarray first followed by that + # of right subarray + + # copy negative elements of left subarray + while (i < n1 and L[i] < 0): + arr[k] = L[i] + k += 1 + i += 1 + + # copy negative elements of right subarray + while (j < n2 and R[j] < 0): + arr[k] = R[j] + k += 1 + j += 1 + + # copy positive elements of left subarray + while (i < n1): + arr[k] = L[i] + k += 1 + i += 1 + + # copy positive elements of right subarray + while (j < n2): + arr[k] = R[j] + k += 1 + j += 1 + +# Function to Rearrange positive and +# negative numbers in a array + + +def RearrangePosNeg(arr, l, r): + + if(l < r): + + # Same as (l + r)/2, but avoids + # overflow for large l and h + m = l + (r - l) // 2 + + # Sort first and second halves + RearrangePosNeg(arr, l, m) + RearrangePosNeg(arr, m + 1, r) + + merge(arr, l, m, r) + + +# Driver Code +arr = [-12, 11, -13, -5, + 6, -7, 5, -3, -6] +arr_size = len(arr) + +RearrangePosNeg(arr, 0, arr_size - 1) + +printArray(arr, arr_size) + +# This code is contributed by +# mohit kumar 29",logn,nlogn +"# Python3 program to Rearrange positive +# and negative numbers in an array + +# Function to print an array + + +def printArray(A, size): + + for i in range(0, size): + print(A[i], end="" "") + print() + +# Function to reverse an array. An array can +# be reversed in O(n) time and O(1) space. + + +def reverse(arr, l, r): + + if l < r: + + arr[l], arr[r] = arr[r], arr[l] + l, r = l + 1, r - 1 + reverse(arr, l, r) + +# Merges two subarrays of arr[]. +# First subarray is arr[l..m] +# Second subarray is arr[m + 1..r] + + +def merge(arr, l, m, r): + + i = l # Initial index of 1st subarray + j = m + 1 # Initial index of IInd + + while i <= m and arr[i] < 0: + i += 1 + + # arr[i..m] is positive + + while j <= r and arr[j] < 0: + j += 1 + + # arr[j..r] is positive + + # reverse positive part of left + # sub-array (arr[i..m]) + reverse(arr, i, m) + + # reverse negative part of right + # sub-array (arr[m + 1..j-1]) + reverse(arr, m + 1, j - 1) + + # reverse arr[i..j-1] + reverse(arr, i, j - 1) + +# Function to Rearrange positive +# and negative numbers in a array + + +def RearrangePosNeg(arr, l, r): + + if l < r: + + # Same as (l + r)/2, but avoids + # overflow for large l and h + m = l + (r - l) // 2 + + # Sort first and second halves + RearrangePosNeg(arr, l, m) + RearrangePosNeg(arr, m + 1, r) + + merge(arr, l, m, r) + + +# Driver Code +if __name__ == ""__main__"": + + arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6] + arr_size = len(arr) + + RearrangePosNeg(arr, 0, arr_size - 1) + + printArray(arr, arr_size) + +# This code is contributed by Rituraj Jain",linear,quadratic +"def rearrangePosNegWithOrder(arr, size): + i = 0 + j = 0 + while(j < size): + if(arr[j] >= 0): + j += 1 + else: + for k in range(j,i,-1): + temp = arr[k] + arr[k] = arr[k - 1] + arr[k - 1] = temp + i += 1 + j += 1 + return arr + +# driver code +arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6 ] +size = len(arr) +aux = rearrangePosNegWithOrder(arr, size) +for i in aux: + print(i,end="" "") + +# This code is contributed by Vibhu Karnwal",constant,linear +"# Python program to rearrange an array in minimum +# maximum form + +# Prints max at first position, min at second position +# second max at third position, second min at fourth +# position and so on. + + +def rearrange(arr, n): + # Auxiliary array to hold modified array + temp = n*[None] + + # Indexes of smallest and largest elements + # from remaining array. + small, large = 0, n-1 + + # To indicate whether we need to copy remaining + # largest or remaining smallest at next position + flag = True + + # Store result in temp[] + for i in range(n): + if flag is True: + temp[i] = arr[large] + large -= 1 + else: + temp[i] = arr[small] + small += 1 + + flag = bool(1-flag) + + # Copy temp[] to arr[] + for i in range(n): + arr[i] = temp[i] + return arr + + +# Driver code +arr = [1, 2, 3, 4, 5, 6] +n = len(arr) +print(""Original Array"") +print(arr) +print(""Modified Array"") +print(rearrange(arr, n)) + +# This code is contributed by Pratik Chhajer",linear,linear +"# Python code for the same approach +def move(arr): + arr.sort() + +# driver code +arr = [ -1, 2, -3, 4, 5, 6, -7, 8, 9 ] +move(arr) +for e in arr: + print(e , end = "" "") + +# This code is contributed by shinjanpatra",linear,nlogn +"# A Python 3 program to put +# all negative numbers before +# positive numbers + +def rearrange(arr, n ) : + + # Please refer partition() in + # below post + # https://www.geeksforgeeks.org / quick-sort / j = 0 + j = 0 + for i in range(0, n) : + if (arr[i] < 0) : + temp = arr[i] + arr[i] = arr[j] + arr[j]= temp + j = j + 1 + print(arr) + +# Driver code +arr = [-1, 2, -3, 4, 5, 6, -7, 8, 9] +n = len(arr) +rearrange(arr, n) + + +# This code is contributed by Nikita Tiwari.",constant,linear +"# Python3 program of the +# above approach + +# Function to shift all the +# the negative elements to +# the left of the array +def shiftall(arr,left,right): + + # Loop to iterate while the + # left pointer is less than + # the right pointer + while left<=right: + + # Condition to check if the left + # and right pointer negative + if arr[left] < 0 and arr[right] < 0: + left+=1 + + # Condition to check if the left + # pointer element is positive and + # the right pointer element is + # negative + else if arr[left]>0 and arr[right]<0: + arr[left], arr[right] = \ + arr[right],arr[left] + left+=1 + right-=1 + + # Condition to check if the left + # pointer is positive and right + # pointer as well + else if arr[left]>0 and arr[right]>0: + right-=1 + else: + left+=1 + right-=1 + +# Function to print the array +def display(arr): + for i in range(len(arr)): + print(arr[i], end="" "") + print() + +# Driver Code +if __name__ == ""__main__"": + arr=[-12, 11, -13, -5, \ + 6, -7, 5, -3, 11] + n=len(arr) + shiftall(arr,0,n-1) + display(arr) + +# Sumit Singh",constant,linear +"# Python code for the approach + +# Using Dutch National Flag Algorithm. +def reArrange(arr, n): + low,high = 0, n - 1 + while(low 0): + high -= 1 + else: + arr[low],arr[high] = arr[high],arr[low] + +def displayArray(arr, n): + + for i in range(n): + print(arr[i],end = "" "") + + print('') + +# driver code +# Data +arr = [1, 2, -4, -5, 2, -7, 3, 2, -6, -8, -9, 3, 2, 1] +n = len(arr) +reArrange(arr,n) +displayArray(arr,n) + +# This code is contributed by shinjanpatra",constant,linear +"# Python program to Move All -ve Element At End +# Without changing order Of Array Element + +# Moves all -ve element to end of array in +# same order. +def move(arr,n): + j = 0 + ans=[None]*n + i=0;j=n-1 + for k in range(n): + if arr[k]>=0: + ans[i]=arr[k] + i+=1 + else: + ans[j]=arr[k] + j-=1 + ans[i:]=ans[n-1:i-1:-1] + return ans + +# Driver program +arr = [1 ,-1 ,-3 , -2, 7, 5, 11, 6 ] +n = len(arr) +print(move(arr, n)) + + +# Contributed by Venkatesh hegde",linear,linear +"# 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.",constant,linear +"# 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.",constant,quadratic +"# 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",constant,quadratic +"# 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",constant,linear +"# 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",constant,linear +"# 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",linear,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",constant,linear +"# 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",constant,nlogn +"# 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 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",linear,nlogn +"# 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",linear,nlogn +"# 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",quadratic,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)",linear,quadratic +"# 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",constant,linear +"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.",linear,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",constant,linear +"# 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).",constant,linear +"# 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",constant,nlogn +"# 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",constant,nlogn +"# 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",constant,quadratic +"# 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",constant,nlogn +"# 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",constant,linear +"# 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",constant,nlogn +"# 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.",linear,nlogn +"# 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))",linear,nlogn +"# 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)",constant,quadratic +"# 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)",constant,quadratic +"# 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",constant,nlogn +"# 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",constant,nlogn +"# 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",constant,linear +"# 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.",constant,linear +"# 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)",linear,nlogn +"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))",linear,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",constant,nlogn +"# 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",constant,linear +"# 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",logn,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",logn,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",linear,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",constant,linear +"# 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",linear,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",nlogn,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",nlogn,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.",constant,linear +"# 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.",constant,linear +"# 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.",linear,nlogn +"# 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))",constant,linear +"# 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))",constant,nlogn +"# 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",linear,linear +"# Python3 program to perform range +# queries over range queries. +import math + +max = 10000 + +# For prefix sum array +def update(arr, l): + + arr[l] += arr[l - 1] + +# This function is used to apply square root +# decomposition in the record array +def record_func(block_size, block, + record, l, r, value): + + # Traversing first block in range + while (l < r and + l % block_size != 0 and + l != 0): + record[l] += value + l += 1 + + # Traversing completely overlapped + # blocks in range + while (l + block_size <= r + 1): + block[l // block_size] += value + l += block_size + + # Traversing last block in range + while (l <= r): + record[l] += value + l += 1 + +# Function to print the resultant array +def print_array(arr, n): + + for i in range(n): + print(arr[i], end = "" "") + +# Driver code +if __name__ == ""__main__"": + + n = 5 + m = 5 + arr = [0] * n + record = [0] * m + + block_size = (int)(math.sqrt(m)) + block = [0] * max + + command = [ [ 1, 1, 2 ], + [ 1, 4, 5 ], + [ 2, 1, 2 ], + [ 2, 1, 3 ], + [ 2, 3, 4 ] ] + + for i in range(m - 1, -1, -1): + + # If query is of type 2 then function + # call to record_func + if (command[i][0] == 2): + x = i // (block_size) + + record_func(block_size, block, + record, command[i][1] - 1, + command[i][2] - 1, + (block[x] + record[i] + 1)) + + # If query is of type 1 then simply add + # 1 to the record array + else: + record[i] += 1 + + # Merging the value of the block + # in the record array + for i in range(m): + check = (i // block_size) + record[i] += block[check] + + for i in range(m): + + # If query is of type 1 then the array + # elements are over-written by the record + # array + if (command[i][0] == 1): + arr[command[i][1] - 1] += record[i] + + if ((command[i][2] - 1) < n - 1): + arr[(command[i][2])] -= record[i] + + # The prefix sum of the array + for i in range(1, n): + update(arr, i) + + # Printing the resultant array + print_array(arr, n) + +# This code is contributed by chitranayal",linear,logn +"# Python 3 program to count the +# number of indexes in range L R +# such that Ai = Ai + 1 + +# function that answers every +# query in O(r-l) +def answer_query(a, n, l, r): + + # traverse from l to r and + # count the required indexes + count = 0 + for i in range(l, r): + if (a[i] == a[i + 1]): + count += 1 + + return count + +# Driver Code +a = [1, 2, 2, 2, 3, 3, 4, 4, 4] +n = len(a) + +# 1-st query +L = 1 +R = 8 +print(answer_query(a, n, L, R)) + +# 2nd query +L = 0 +R = 4 +print(answer_query(a, n, L, R)) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,constant +"# Python program to count +# the number of indexes in +# range L R such that Ai=Ai+1 +N = 1000 + +# array to store count +# of index from 0 to +# i that obey condition +prefixans = [0] * N; + +# precomputing +# prefixans[] array +def countIndex(a, n) : + + global N, prefixans + + # traverse to compute + # the prefixans[] array + for i in range(0, n - 1) : + + if (a[i] == a[i + 1]) : + prefixans[i] = 1 + + if (i != 0) : + prefixans[i] = (prefixans[i] + + prefixans[i - 1]) + +# def that answers +# every query in O(1) +def answer_query(l, r) : + + global N, prefixans + if (l == 0) : + return prefixans[r - 1] + else : + return (prefixans[r - 1] - + prefixans[l - 1]) + +# Driver Code +a = [1, 2, 2, 2, + 3, 3, 4, 4, 4] +n = len(a) + +# pre-computation +countIndex(a, n) + +# 1-st query +L = 1 +R = 8 + +print (answer_query(L, R)) + +# 2nd query +L = 0 +R = 4 +print (answer_query(L, R)) + +# This code is contributed by +# Manish Shaw(manishshaw1)",linear,linear +"# Python program to find maximum contiguous subarray + +# Function to find the maximum contiguous subarray +from sys import maxint + + +def maxSubArraySum(a, size): + + max_so_far = -maxint - 1 + max_ending_here = 0 + + for i in range(0, size): + max_ending_here = max_ending_here + a[i] + if (max_so_far < max_ending_here): + max_so_far = max_ending_here + + if max_ending_here < 0: + max_ending_here = 0 + return max_so_far + +# Driver function to check the above function + + +a = [-2, -3, 4, -1, -2, 1, 5, -3] + +print ""Maximum contiguous sum is"", maxSubArraySum(a, len(a)) + +# This code is contributed by _Devesh Agrawal_",constant,linear +"# Python program to print largest contiguous array sum + +from sys import maxsize + +# Function to find the maximum contiguous subarray +# and print its starting and end index + + +def maxSubArraySum(a, size): + + max_so_far = -maxsize - 1 + max_ending_here = 0 + start = 0 + end = 0 + s = 0 + + for i in range(0, size): + + max_ending_here += a[i] + + if max_so_far < max_ending_here: + max_so_far = max_ending_here + start = s + end = i + + if max_ending_here < 0: + max_ending_here = 0 + s = i+1 + + print(""Maximum contiguous sum is %d"" % (max_so_far)) + print(""Starting Index %d"" % (start)) + print(""Ending Index %d"" % (end)) + + +# Driver program to test maxSubArraySum +a = [-2, -3, 4, -1, -2, 1, 5, -3] +maxSubArraySum(a, len(a))",constant,linear +"# Returns maximum profit with +# two transactions on a given +# list of stock prices price[0..n-1] + + +def maxProfit(price, n): + + # Create profit array and initialize it as 0 + profit = [0]*n + + # Get the maximum profit + # with only one transaction + # allowed. After this loop, + # profit[i] contains maximum + # profit from price[i..n-1] + # using at most one trans. + max_price = price[n-1] + + for i in range(n-2, 0, -1): + + if price[i] > max_price: + max_price = price[i] + + # we can get profit[i] by + # taking maximum of: + # a) previous maximum, + # i.e., profit[i+1] + # b) profit by buying at + # price[i] and selling at + # max_price + profit[i] = max(profit[i+1], max_price - price[i]) + + # Get the maximum profit + # with two transactions allowed + # After this loop, profit[n-1] + # contains the result + min_price = price[0] + + for i in range(1, n): + + if price[i] < min_price: + min_price = price[i] + + # Maximum profit is maximum of: + # a) previous maximum, + # i.e., profit[i-1] + # b) (Buy, Sell) at + # (min_price, A[i]) and add + # profit of other trans. + # stored in profit[i] + profit[i] = max(profit[i-1], profit[i]+(price[i]-min_price)) + + result = profit[n-1] + + return result + + +# Driver function +price = [2, 30, 15, 10, 8, 25, 80] +print (""Maximum profit is"", maxProfit(price, len(price))) + +# This code is contributed by __Devesh Agrawal__",linear,linear +"import sys + +def maxtwobuysell(arr, size): + first_buy = -sys.maxsize; + first_sell = 0; + second_buy = -sys.maxsize; + second_sell = 0; + + for i in range(size): + + first_buy = max(first_buy, -arr[i]); + first_sell = max(first_sell, first_buy + arr[i]); + second_buy = max(second_buy, first_sell - arr[i]); + second_sell = max(second_sell, second_buy + arr[i]); + + + return second_sell; + +if __name__ == '__main__': + arr = [ 2, 30, 15, 10, 8, 25, 80 ]; + size = len(arr); + print(maxtwobuysell(arr, size)); + +# This code is contributed by gauravrajput1",constant,linear +"# Python3 program to find +# minimum average subarray + +# Prints beginning and ending +# indexes of subarray of size k +# with minimum average +def findsubarrayleast(arr, k, n): + min = 999999 + minindex = 0 + for i in range(n-k+1): + sum = 0 + j = i + for j in range(i, i+k): + sum += arr[j] + if sum < min: + min = sum + minindex = i + + # printing the desired subarray + print(""subarray with minimum average is: "", end='') + for i in range(minindex, minindex+k): + print(arr[i], end="" "") + + +# Driver Code +arr = [20, 3, 13, 5, 10, 14, 8, 5, 11, 9, 1, 11] +k = 9 # Subarray size +n = len(arr) +findsubarrayleast(arr, k, n) + +# This code is contributed by Aarti_Rathi",constant,quadratic +"# Python3 program to find +# minimum average subarray + +# Prints beginning and ending +# indexes of subarray of size k +# with minimum average +def findMinAvgSubarray(arr, n, k): + + # k must be smaller than or equal to n + if (n < k): return 0 + + # Initialize beginning index of result + res_index = 0 + + # Compute sum of first subarray of size k + curr_sum = 0 + for i in range(k): + curr_sum += arr[i] + + # Initialize minimum sum as current sum + min_sum = curr_sum + + # Traverse from (k + 1)'th + # element to n'th element + for i in range(k, n): + + # Add current item and remove first + # item of previous subarray + curr_sum += arr[i] - arr[i-k] + + # Update result if needed + if (curr_sum < min_sum): + + min_sum = curr_sum + res_index = (i - k + 1) + + print(""Subarray between ["", res_index, + "", "", (res_index + k - 1), + ""] has minimum average"") + +# Driver Code +arr = [3, 7, 90, 20, 10, 50, 40] +k = 3 # Subarray size +n = len(arr) +findMinAvgSubarray(arr, n, k) + +# This code is contributed by Anant Agarwal.",constant,linear +"# Python3 code to Find the minimum +# distance between two numbers + + +def minDist(arr, n, x, y): + min_dist = 99999999 + for i in range(n): + for j in range(i + 1, n): + if (x == arr[i] and y == arr[j] or + y == arr[i] and x == arr[j]) and min_dist > abs(i-j): + min_dist = abs(i-j) + return min_dist + + +# Driver code +arr = [3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3] +n = len(arr) +x = 3 +y = 6 +print(""Minimum distance between "", x, "" and "", + y, ""is"", minDist(arr, n, x, y)) + +# This code is contributed by ""Abhishek Sharma 44""",constant,quadratic +"import sys + +def minDist(arr, n, x, y): + + #previous index and min distance + i=0 + p=-1 + min_dist = sys.maxsize; + + for i in range(n): + + if(arr[i] ==x or arr[i] == y): + + #we will check if p is not equal to -1 and + #If the element at current index matches with + #the element at index p , If yes then update + #the minimum distance if needed + if(p != -1 and arr[i] != arr[p]): + min_dist = min(min_dist,i-p) + + #update the previous index + p=i + + + #If distance is equal to int max + if(min_dist == sys.maxsize): + return -1 + return min_dist + + +# Driver program to test above function */ +arr = [3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3] +n = len(arr) +x = 3 +y = 6 +print (""Minimum distance between %d and %d is %d\n""%( x, y,minDist(arr, n, x, y))); + +# This code is contributed by Shreyanshi Arun.",constant,linear +"# Python program to Find the minimum +# distance between two numbers +import sys + +def minDist(arr, n, x, y) : + + # idx1 and idx2 will store indices of + # x or y and min_dist will store the minimum difference + idx1=-1; idx2=-1; min_dist = sys.maxsize; + for i in range(n) : + # if current element is x then change idx1 + if arr[i]==x : + idx1=i + + # if current element is y then change idx2 + elif arr[i]==y : + idx2=i + + # if x and y both found in array + # then only find the difference and store it in min_dist + if idx1!=-1 and idx2!=-1 : + min_dist=min(min_dist,abs(idx1-idx2)); + + # if left or right did not found in array + # then return -1 + if idx1==-1 or idx2==-1 : + return -1 + # return the minimum distance + else : + return min_dist + +# Driver code +if __name__ == ""__main__"" : + + arr = [ 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3] + n = len(arr) + x = 3 + y = 6 + print (""Minimum distance between %d and %d is %d\n""%( x, y,minDist(arr, n, x, y))); + +# this code is contributed by aditya942003patil",constant,linear +"# User function Template +def getMinDiff(arr, n, k): + arr.sort() + ans = arr[n - 1] - arr[0] # Maximum possible height difference + + tempmin = arr[0] + tempmax = arr[n - 1] + + for i in range(1, n): + if arr[i] < k: + continue + tempmin = min(arr[0] + k, arr[i] - k) + + # Minimum element when we + # add k to whole array + # Maximum element when we + tempmax = max(arr[i - 1] + k, arr[n - 1] - k) + + # subtract k from whole array + ans = min(ans, tempmax - tempmin) + + return ans + + +# Driver Code Starts +k = 6 +n = 6 +arr = [7, 4, 8, 8, 8, 9] +ans = getMinDiff(arr, n, k) +print(ans) + +# This code is contributed by ninja_hattori.",constant,nlogn +"# Python3 program to find Minimum +# number of jumps to reach end + +# Returns minimum number of jumps +# to reach arr[h] from arr[l] + + +def minJumps(arr, l, h): + + # Base case: when source and + # destination are same + if (h == l): + return 0 + + # when nothing is reachable + # from the given source + if (arr[l] == 0): + return float('inf') + + # Traverse through all the points + # reachable from arr[l]. Recursively + # get the minimum number of jumps + # needed to reach arr[h] from + # these reachable points. + min = float('inf') + for i in range(l + 1, h + 1): + if (i < l + arr[l] + 1): + jumps = minJumps(arr, i, h) + if (jumps != float('inf') and + jumps + 1 < min): + min = jumps + 1 + + return min + + +# Driver program to test above function +arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9] +n = len(arr) +print('Minimum number of jumps to reach', + 'end is', minJumps(arr, 0, n-1)) + +# This code is contributed by Soumen Ghosh",linear,np +"# Python3 program to find Minimum +# number of jumps to reach end + +# Returns minimum number of jumps +# to reach arr[n-1] from arr[0] + + +def minJumps(arr, n): + jumps = [0 for i in range(n)] + + if (n == 0) or (arr[0] == 0): + return float('inf') + + jumps[0] = 0 + + # Find the minimum number of + # jumps to reach arr[i] from + # arr[0] and assign this + # value to jumps[i] + for i in range(1, n): + jumps[i] = float('inf') + for j in range(i): + if (i <= j + arr[j]) and (jumps[j] != float('inf')): + jumps[i] = min(jumps[i], jumps[j] + 1) + break + return jumps[n-1] + + +# Driver Program to test above function +arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9] +size = len(arr) +print('Minimum number of jumps to reach', + 'end is', minJumps(arr, size)) + +# This code is contributed by Soumen Ghosh",linear,np +"# Python3 program to find Minimum +# number of jumps to reach end + +# Returns Minimum number of +# jumps to reach end + + +def minJumps(arr, n): + + # jumps[0] will hold the result + jumps = [0 for i in range(n)] + + # Minimum number of jumps needed + # to reach last element from + # last elements itself is always 0 + # jumps[n-1] is also initialized to 0 + + # Start from the second element, + # move from right to left and + # construct the jumps[] array where + # jumps[i] represents minimum number + # of jumps needed to reach arr[m-1] + # form arr[i] + for i in range(n-2, -1, -1): + + # If arr[i] is 0 then arr[n-1] + # can't be reached from here + if (arr[i] == 0): + jumps[i] = float('inf') + + # If we can directly reach to + # the end point from here then + # jumps[i] is 1 + elif (arr[i] >= n - i - 1): + jumps[i] = 1 + + # Otherwise, to find out the + # minimum number of jumps + # needed to reach arr[n-1], + # check all the points + # reachable from here and + # jumps[] value for those points + else: + # initialize min value + min = float('inf') + + # following loop checks with + # all reachable points and + # takes the minimum + for j in range(i + 1, n): + if (j <= arr[i] + i): + if (min > jumps[j]): + min = jumps[j] + + # Handle overflow + if (min != float('inf')): + jumps[i] = min + 1 + else: + # or INT_MAX + jumps[i] = min + + return jumps[0] + + +# Driver program to test above function +arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9] +n = len(arr) +print('Minimum number of jumps to reach', + 'end is', minJumps(arr, n-1)) + +# This code is contributed by Soumen Ghosh",linear,quadratic +"# Dynamic Programming based Python +# implementation of Maximum Sum +# Increasing Subsequence (MSIS) +# problem + +# maxSumIS() returns the maximum +# sum of increasing subsequence +# in arr[] of size n +def maxSumIS(arr, n): + max = 0 + msis = [0 for x in range(n)] + + # Initialize msis values + # for all indexes + for i in range(n): + msis[i] = arr[i] + + # Compute maximum sum + # values in bottom up manner + for i in range(1, n): + for j in range(i): + if (arr[i] > arr[j] and + msis[i] < msis[j] + arr[i]): + msis[i] = msis[j] + arr[i] + + # Pick maximum of + # all msis values + for i in range(n): + if max < msis[i]: + max = msis[i] + + return max + +# Driver Code +arr = [1, 101, 2, 3, 100, 4, 5] +n = len(arr) +print(""Sum of maximum sum increasing "" + + ""subsequence is "" + + str(maxSumIS(arr, n))) + +# This code is contributed +# by Bhavya Jain",linear,quadratic +"# Python3 program to find Smallest +# subarray with sum greater +# than a given value + +# Returns length of smallest subarray +# with sum greater than x. If there +# is no subarray with given sum, +# then returns n+1 +def smallestSubWithSum(arr, n, x): + + # Initialize length of smallest + # subarray as n+1 + min_len = n + 1 + + # Pick every element as starting point + for start in range(0,n): + + # Initialize sum starting + # with current start + curr_sum = arr[start] + + # If first element itself is greater + if (curr_sum > x): + return 1 + + # Try different ending points + # for curremt start + for end in range(start+1,n): + + # add last element to current sum + curr_sum += arr[end] + + # If sum becomes more than x + # and length of this subarray + # is smaller than current smallest + # length, update the smallest + # length (or result) + if curr_sum > x and (end - start + 1) < min_len: + min_len = (end - start + 1) + + return min_len; + + +# Driver program to test above function */ +arr1 = [1, 4, 45, 6, 10, 19] +x = 51 +n1 = len(arr1) +res1 = smallestSubWithSum(arr1, n1, x); +if res1 == n1+1: + print(""Not possible"") +else: + print(res1) + +arr2 = [1, 10, 5, 2, 7] +n2 = len(arr2) +x = 9 +res2 = smallestSubWithSum(arr2, n2, x); +if res2 == n2+1: + print(""Not possible"") +else: + print(res2) + +arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250] +n3 = len(arr3) +x = 280 +res3 = smallestSubWithSum(arr3, n3, x) +if res3 == n3+1: + print(""Not possible"") +else: + print(res3) + +# This code is contributed by Smitha Dinesh Semwal",constant,quadratic +"# O(n) solution for finding smallest +# subarray with sum greater than x + +# Returns length of smallest subarray +# with sum greater than x. If there +# is no subarray with given sum, then +# returns n + 1 + + +def smallestSubWithSum(arr, n, x): + + # Initialize current sum and minimum length + curr_sum = 0 + min_len = n + 1 + + # Initialize starting and ending indexes + start = 0 + end = 0 + while (end < n): + + # Keep adding array elements while current + # sum is smaller than or equal to x + while (curr_sum <= x and end < n): + curr_sum += arr[end] + end += 1 + + # If current sum becomes greater than x. + while (curr_sum > x and start < n): + + # Update minimum length if needed + if (end - start < min_len): + min_len = end - start + + # remove starting elements + curr_sum -= arr[start] + start += 1 + + return min_len + + +# Driver program +arr1 = [1, 4, 45, 6, 10, 19] +x = 51 +n1 = len(arr1) +res1 = smallestSubWithSum(arr1, n1, x) +print(""Not possible"") if (res1 == n1 + 1) else print(res1) + +arr2 = [1, 10, 5, 2, 7] +n2 = len(arr2) +x = 9 +res2 = smallestSubWithSum(arr2, n2, x) +print(""Not possible"") if (res2 == n2 + 1) else print(res2) + +arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250] +n3 = len(arr3) +x = 280 +res3 = smallestSubWithSum(arr3, n3, x) +print(""Not possible"") if (res3 == n3 + 1) else print(res3) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,linear +"# Python program to find maximum average subarray +# of given length. + +# Returns beginning index of maximum average +# subarray of length 'k' +def findMaxAverage(arr, n, k): + # Check if 'k' is valid + if k > n: + return -1 + + # Create and fill array to store cumulative + # sum. csum[i] stores sum of arr[0] to arr[i] + csum = [0]*n + csum[0] = arr[0] + for i in range(1, n): + csum[i] = csum[i-1] + arr[i]; + + # Initialize max_sm as sum of first subarray + max_sum = csum[k-1] + max_end = k-1 + + # Find sum of other subarrays and update + # max_sum if required. + for i in range(k, n): + + curr_sum = csum[i] - csum[i-k] + if curr_sum > max_sum: + + max_sum = curr_sum + max_end = i + + # Return starting index + return max_end - k + 1 + +# Driver program +arr = [1, 12, -5, -6, 50, 3] +k = 4 +n = len(arr) +print(""The maximum average subarray of length"",k, +""begins at index"",findMaxAverage(arr, n, k)) + +#This code is contributed by +#Smitha Dinesh Semwal",linear,linear +"# Python 3 program to find maximum +# average subarray of given length. + +# Returns beginning index of maximum +# average subarray of length 'k' +def findMaxAverage(arr, n, k): + + # Check if 'k' is valid + if (k > n): + return -1 + + # Compute sum of first 'k' elements + sum = arr[0] + + for i in range(1, k): + sum += arr[i] + + max_sum = sum + max_end = k - 1 + + # Compute sum of remaining subarrays + for i in range(k, n): + + sum = sum + arr[i] - arr[i - k] + + if (sum > max_sum): + + max_sum = sum + max_end = i + + # Return starting index + return max_end - k + 1 + +# Driver program +arr = [1, 12, -5, -6, 50, 3] +k = 4 +n = len(arr) + +print(""The maximum average subarray of length"", k, + ""begins at index"", + findMaxAverage(arr, n, k)) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,linear +"# Python3 program to count minimum number of +# operations to get the given target array + +# Returns count of minimum operations to +# convert a zero array to target array +# with increment and doubling operations. +# This function computes count by doing reverse +# steps, i.e., convert target to zero array. +def countMinOperations(target, n): + + # Initialize result (Count of minimum moves) + result = 0; + + # Keep looping while all elements of + # target don't become 0. + while (True): + + # To store count of zeroes in + # current target array + zero_count = 0; + + # To find first odd element + i = 0; + while (i < n): + + # If odd number found + if ((target[i] & 1) > 0): + break; + + # If 0, then increment + # zero_count + elif (target[i] == 0): + zero_count += 1; + i += 1; + + # All numbers are 0 + if (zero_count == n): + return result; + + # All numbers are even + if (i == n): + + # Divide the whole array by 2 + # and increment result + for j in range(n): + target[j] = target[j] // 2; + result += 1; + + # Make all odd numbers even by + # subtracting one and increment result. + for j in range(i, n): + if (target[j] & 1): + target[j] -= 1; + result += 1; + +# Driver Code +arr = [16, 16, 16]; +n = len(arr); +print(""Minimum number of steps required to"", + ""\nget the given target array is"", + countMinOperations(arr, n)); + +# This code is contributed by mits",constant,linear +"# Python program to find number of operations +# to make an array palindrome + +# Returns minimum number of count operations +# required to make arr[] palindrome +def findMinOps(arr, n): + ans = 0 # Initialize result + + # Start from two corners + i,j = 0,n-1 + while i<=j: + # If corner elements are same, + # problem reduces arr[i+1..j-1] + if arr[i] == arr[j]: + i += 1 + j -= 1 + + # If left element is greater, then + # we merge right two elements + elif arr[i] > arr[j]: + # need to merge from tail. + j -= 1 + arr[j] += arr[j+1] + ans += 1 + + # Else we merge left two elements + else: + i += 1 + arr[i] += arr[i-1] + ans += 1 + + return ans + + +# Driver program to test above +arr = [1, 4, 5, 9, 1] +n = len(arr) +print(""Count of minimum operations is "" + str(findMinOps(arr, n))) + +# This code is contributed by Pratik Chhajer",constant,linear +"# Python3 program to find the smallest +# positive value that cannot be +# represented as sum of subsets +# of a given sorted array + +# Returns the smallest number +# that cannot be represented as sum +# of subset of elements from set +# represented by sorted array arr[0..n-1] +def findSmallest(arr, n): + + res = 1 #Initialize result + + # Traverse the array and increment + # 'res' if arr[i] is smaller than + # or equal to 'res'. + for i in range (0, n ): + if arr[i] <= res: + res = res + arr[i] + else: + break + return res + + +# Driver program to test above function +arr1 = [1, 3, 4, 5] +n1 = len(arr1) +print(findSmallest(arr1, n1)) + +arr2= [1, 2, 6, 10, 11, 15] +n2 = len(arr2) +print(findSmallest(arr2, n2)) + +arr3= [1, 1, 1, 1] +n3 = len(arr3) +print(findSmallest(arr3, n3)) + +arr4 = [1, 1, 3, 4] +n4 = len(arr4) +print(findSmallest(arr4, n4)) + +# This code is.contributed by Smitha Dinesh Semwal",constant,nlogn +"# Python3 program to print largest contiguous array sum + +from sys import maxsize + +# Function to find the maximum contiguous subarray +# and print its starting and end index +def maxSubArraySum(a,size): + + max_so_far = -maxsize - 1 + max_ending_here = 0 + start = 0 + end = 0 + s = 0 + + for i in range(0,size): + + max_ending_here += a[i] + + if max_so_far < max_ending_here: + max_so_far = max_ending_here + start = s + end = i + + if max_ending_here < 0: + max_ending_here = 0 + s = i+1 + + return (end - start + 1) + +# Driver program to test maxSubArraySum +a = [-2, -3, 4, -1, -2, 1, 5, -3] +print(maxSubArraySum(a,len(a)))",constant,linear +"# Python implementation of simple method to find +# minimum difference between any pair + +# Returns minimum difference between any pair + + +def findMinDiff(arr, n): + # Initialize difference as infinite + diff = 10**20 + + # Find the min diff by comparing difference + # of all possible pairs in given array + for i in range(n-1): + for j in range(i+1, n): + if abs(arr[i]-arr[j]) < diff: + diff = abs(arr[i] - arr[j]) + + # Return min diff + return diff + + +# Driver code +if __name__ == ""__main__"": + arr = [1, 5, 3, 19, 18, 25] + n = len(arr) + + # Function call + print(""Minimum difference is "" + str(findMinDiff(arr, n))) + +# This code is contributed by Pratik Chhajer",constant,quadratic +"# Python3 program to find minimum difference between +# any pair in an unsorted array + +# Returns minimum difference between any pair + + +def findMinDiff(arr, n): + + # Sort array in non-decreasing order + arr = sorted(arr) + + # Initialize difference as infinite + diff = 10**20 + + # Find the min diff by comparing adjacent + # pairs in sorted array + for i in range(n-1): + if arr[i+1] - arr[i] < diff: + diff = arr[i+1] - arr[i] + + # Return min diff + return diff + + +# Driver code +if __name__ == ""__main__"": + arr = [1, 5, 3, 19, 18, 25] + n = len(arr) + + # Function call + print(""Minimum difference is "" + str(findMinDiff(arr, n))) + +# This code is contributed by Pratik Chhajer",constant,nlogn +"# A Simple python program to find longest common +# subarray of two binary arrays with same sum + +# Returns length of the longest common subarray +# with same sum +def longestCommonSum(arr1, arr2, n): + + # Initialize result + maxLen = 0 + + # One by one pick all possible starting points + # of subarrays + for i in range(0,n): + + # Initialize sums of current subarrays + sum1 = 0 + sum2 = 0 + + # Consider all points for starting with arr[i] + for j in range(i,n): + + # Update sums + sum1 += arr1[j] + sum2 += arr2[j] + + # If sums are same and current length is + # more than maxLen, update maxLen + if (sum1 == sum2): + len = j-i+1 + if (len > maxLen): + maxLen = len + + return maxLen + + +# Driver program to test above function +arr1 = [0, 1, 0, 1, 1, 1, 1] +arr2 = [1, 1, 1, 1, 1, 0, 1] +n = len(arr1) +print(""Length of the longest common span with same "" + ""sum is"",longestCommonSum(arr1, arr2, n)) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,quadratic +"# Python program to find longest common +# subarray of two binary arrays with +# same sum + +def longestCommonSum(arr1, arr2, n): + + # Initialize result + maxLen = 0 + + # Initialize prefix sums of two arrays + presum1 = presum2 = 0 + + # Create a dictionary to store indices + # of all possible sums + diff = {} + + # Traverse both arrays + for i in range(n): + + # Update prefix sums + presum1 += arr1[i] + presum2 += arr2[i] + + # Compute current diff which will be + # used as index in diff dictionary + curr_diff = presum1 - presum2 + + # If current diff is 0, then there + # are same number of 1's so far in + # both arrays, i.e., (i+1) is + # maximum length. + if curr_diff == 0: + maxLen = i+1 + elif curr_diff not in diff: + # save the index for this diff + diff[curr_diff] = i + else: + # calculate the span length + length = i - diff[curr_diff] + maxLen = max(maxLen, length) + + return maxLen + +# Driver program +arr1 = [0, 1, 0, 1, 1, 1, 1] +arr2 = [1, 1, 1, 1, 1, 0, 1] +print(""Length of the longest common"", + "" span with same"", end = "" "") +print(""sum is"",longestCommonSum(arr1, + arr2, len(arr1))) + +# This code is contributed by Abhijeet Nautiyal",linear,linear +"# Python program to find largest subarray +# with equal number of 0's and 1's. + +# Returns largest common subarray with equal +# number of 0s and 1s +def longestCommonSum(arr1, arr2, n): + + # Find difference between the two + arr = [0 for i in range(n)] + + for i in range(n): + arr[i] = arr1[i] - arr2[i]; + + # Creates an empty hashMap hM + hm = {} + sum = 0 # Initialize sum of elements + max_len = 0 #Initialize result + + # Traverse through the given array + for i in range(n): + + # Add current element to sum + sum += arr[i] + + # To handle sum=0 at last index + if (sum == 0): + max_len = i + 1 + + # If this sum is seen before, + # then update max_len if required + if sum in hm: + max_len = max(max_len, i - hm[sum]) + else: # Else put this sum in hash table + hm[sum] = i + return max_len + +# Driver code +arr1 = [0, 1, 0, 1, 1, 1, 1] +arr2 = [1, 1, 1, 1, 1, 0, 1] +n = len(arr1) +print(longestCommonSum(arr1, arr2, n)) + +# This code is contributed by rag2127",linear,linear +"# Python 3 program to print an array +# in alternate sorted manner. + +# Function to print alternate sorted +# values +def alternateSort(arr, n): + + # Sorting the array + arr.sort() + + # Printing the last element of array + # first and then first element and then + # second last element and then second + # element and so on. + i = 0 + j = n-1 + + while (i < j): + + print(arr[j], end ="" "") + j-= 1 + print(arr[i], end ="" "") + i+= 1 + + # If the total element in array is odd + # then print the last middle element. + if (n % 2 != 0): + print(arr[i]) + + +# Driver code +arr = [1, 12, 4, 6, 7, 10] +n = len(arr) + +alternateSort(arr, n) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,nlogn +"# Function to sort an array using +# insertion sort + +def insertionSort(A, size): + i, key, j = 0, 0, 0 + for i in range(size): + key = A[i] + j = i-1 + + # Move elements of A[0..i-1], that are + # greater than key, to one position + # ahead of their current position. + # This loop will run at most k times + while j >= 0 and A[j] > key: + A[j + 1] = A[j] + j = j - 1 + A[j + 1] = key",constant,constant +"# A Python3 program to sort a +# nearly sorted array. + +from heapq import heappop, heappush, heapify + + +# A utility function to print +# array elements +def print_array(arr: list): + for elem in arr: + print(elem, end=' ') + +# Given an array of size n, where every +# element is k away from its target +# position, sorts the array in O(nLogk) time. + + +def sort_k(arr: list, n: int, k: int): + """""" + :param arr: input array + :param n: length of the array + :param k: max distance, which every + element is away from its target position. + :return: None + """""" + # List of first k+1 items + heap = arr[:k + 1] + + # using heapify to convert list + # into heap(or min heap) + heapify(heap) + + # ""rem_elmnts_index"" is index for remaining + # elements in arr and ""target_index"" is + # target index of for current minimum element + # in Min Heap ""heap"". + target_index = 0 + for rem_elmnts_index in range(k + 1, n): + arr[target_index] = heappop(heap) + heappush(heap, arr[rem_elmnts_index]) + target_index += 1 + + while heap: + arr[target_index] = heappop(heap) + target_index += 1 + + +# Driver Code +k = 3 +arr = [2, 6, 3, 12, 56, 8] +n = len(arr) +sort_k(arr, n, k) + +print('Following is sorted array') +print_array(arr) + +# This code is contributed by +# Veerat Beri(viratberi)",logn,nlogn +"# Python function to sort the array arr[0..n-1] in wave form, +# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5] +def sortInWave(arr, n): + + #sort the array + arr.sort() + + # Swap adjacent elements + for i in range(0,n-1,2): + arr[i], arr[i+1] = arr[i+1], arr[i] + +# Driver program +arr = [10, 90, 49, 2, 1, 5, 23] +sortInWave(arr, len(arr)) +for i in range(0,len(arr)): + print (arr[i],end="" "") + +# This code is contributed by __Devesh Agrawal__",constant,nlogn +"# Python function to sort the array arr[0..n-1] in wave form, +# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5] + + +def sortInWave(arr, n): + + # Traverse all even elements + for i in range(0, n - 1, 2): + + # If current even element is smaller than previous + if (i > 0 and arr[i] < arr[i-1]): + arr[i], arr[i-1] = arr[i-1], arr[i] + + # If current even element is smaller than next + if (i < n-1 and arr[i] < arr[i+1]): + arr[i], arr[i+1] = arr[i+1], arr[i] + + +# Driver program +arr = [10, 90, 49, 2, 1, 5, 23] +sortInWave(arr, len(arr)) +for i in range(0, len(arr)): + print(arr[i], end="" "") + +# This code is contributed by __Devesh Agrawal__",constant,linear +"# Python program to Merge an array of +# size n into another array of size m + n + +NA = -1 + +# Function to move m elements +# at the end of array mPlusN[] + + +def moveToEnd(mPlusN, size): + + i = 0 + j = size - 1 + for i in range(size-1, -1, -1): + if (mPlusN[i] != NA): + + mPlusN[j] = mPlusN[i] + j -= 1 + +# Merges array N[] +# of size n into array mPlusN[] +# of size m+n + + +def merge(mPlusN, N, m, n): + + i = n # Current index of i/p part of mPlusN[] + j = 0 # Current index of N[] + k = 0 # Current index of output mPlusN[] + while (k < (m+n)): + + # Take an element from mPlusN[] if + # a) value of the picked + # element is smaller and we have + # not reached end of it + # b) We have reached end of N[] */ + if ((j == n) or (i < (m+n) and mPlusN[i] <= N[j])): + + mPlusN[k] = mPlusN[i] + k += 1 + i += 1 + + else: # Otherwise take element from N[] + + mPlusN[k] = N[j] + k += 1 + j += 1 + +# Utility that prints +# out an array on a line + + +def printArray(arr, size): + + for i in range(size): + print(arr[i], "" "", end="""") + + print() + + +# Driver function to +# test above functions + +# Initialize arrays +mPlusN = [2, 8, NA, NA, NA, 13, NA, 15, 20] +N = [5, 7, 9, 25] +n = len(N) + +m = len(mPlusN) - n + +# Move the m elements +# at the end of mPlusN +moveToEnd(mPlusN, m+n) + +# Merge N[] into mPlusN[] +merge(mPlusN, N, m, n) + +# Print the resultant mPlusN +printArray(mPlusN, m+n) + +# This code is contributed +# by Anant Agarwal.",constant,linear +"# Python 3 program to test whether an array +# can be sorted by swapping adjacent +# elements using a boolean array + + +# Return true if array can be +# sorted otherwise false +def sortedAfterSwap(A, B, n) : + + # Check bool array B and sorts + # elements for continuous sequence of 1 + for i in range(0, n - 1) : + if (B[i]== 1) : + j = i + while (B[j]== 1) : + j = j + 1 + + # Sort array A from i to j + A = A[0:i] + sorted(A[i:j + 1]) + A[j + 1:] + i = j + + + # Check if array is sorted or not + for i in range(0, n) : + if (A[i] != i + 1) : + return False + + + return True + + +# Driver program to test sortedAfterSwap() +A = [ 1, 2, 5, 3, 4, 6 ] +B = [ 0, 1, 1, 1, 0 ] +n = len(A) + +if (sortedAfterSwap(A, B, n)) : + print(""A can be sorted"") +else : + print(""A can not be sorted"") + + +# This code is contributed +# by Nikita Tiwari.",constant,quadratic +"# Python3 program to test whether array +# can be sorted by swapping adjacent +# elements using boolean array + +# Return true if array can be +# sorted otherwise false +def sortedAfterSwap(A,B,n): + for i in range(0,n-1): + if B[i]: + if A[i]!=i+1: + A[i], A[i+1] = A[i+1], A[i] + + # Check if array is sorted or not + for i in range(n): + if A[i]!=i+1: + return False + return True + +# Driver program +if __name__=='__main__': + A = [1, 2, 5, 3, 4, 6] + B = [0, 1, 1, 1, 0] + n =len(A) + if (sortedAfterSwap(A, B, n)) : + print(""A can be sorted"") + else : + print(""A can not be sorted"") + +# This code is contributed by +# Shrikant13",constant,linear +"# Python3 program to sort an array with +# two types of values in one traversal. + +# Method for segregation 0 and +# 1 given input array +def segregate0and1(arr, n): + + type0 = 0; type1 = n - 1 + + while (type0 < type1): + if (arr[type0] == 1): + arr[type0], arr[type1] = arr[type1], arr[type0] + type1 -= 1 + + else: + type0 += 1 + +# Driver Code +arr = [1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1] +n = len(arr) +segregate0and1(arr, n) +for i in range(0, n): + print(arr[i], end = "" "") + +# This code is contributed by Smitha Dinesh Semwal",constant,linear +"# Python3 program that performs the following +# operations: Sort elements by frequency. If two elements +# have same count, then put the elements that appears first + +# Used for sorting + + +class ele: + def __init__(self): + + self.count = 0 + self.index = 0 + self.val = 0 + + +def mycomp(a): + return a.val + +# Used for sorting by frequency. And if frequency is same, +# then by appearance + + +def mycomp2(a): + # using negative value for a.index + # since the sorting should be in + # descending order + return (a.count, -a.index) + + +def sortByFrequency(arr, n): + element = [None for _ in range(n)] + for i in range(n): + + element[i] = ele() + + # Fill Indexes + element[i].index = i + + # Initialize counts as 0 + element[i].count = 0 + + # Fill values in structure + # elements + element[i].val = arr[i] + + # Sort the structure elements according to value, + # we used stable sort so relative order is maintained. + # + element.sort(key=mycomp) + + # initialize count of first element as 1 + element[0].count = 1 + + # Count occurrences of remaining elements + for i in range(1, n): + + if (element[i].val == element[i - 1].val): + element[i].count += element[i - 1].count + 1 + + # Set count of previous element as -1, we are + # doing this because we'll again sort on the + # basis of counts (if counts are equal than on + # the basis of index)*/ + element[i - 1].count = -1 + + # Retain the first index (Remember first index + # is always present in the first duplicate we + # used stable sort. */ + element[i].index = element[i - 1].index + + # Else If previous element is not equal to current + # so set the count to 1 + else: + element[i].count = 1 + + # Now we have counts and first index for each element + # so now sort on the basis of count and in case of tie + # use index to sort.*/ + element.sort(key=mycomp2) + + index = 0 + for i in range(n - 1, -1, -1): + if (element[i].count != -1): + for j in range(element[i].count): + arr[index] = element[i].val + index += 1 + + +# Driver code +arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8] +n = len(arr) + +# Function call +sortByFrequency(arr, n) + +print(*arr) + +# This code is contributed by phasing17",linear,nlogn +"# Python3 program for above approach + +from collections import defaultdict + +# Sort by Frequency + + +def sortByFreq(arr, n): + # arr -> Array to be sorted + # n -> Length of Array + + # d is a hashmap(referred as dictionary in python) + d = defaultdict(lambda: 0) + for i in range(n): + d[arr[i]] += 1 + + # Sorting the array 'arr' where key + # is the function based on which + # the array is sorted + # While sorting we want to give + # first priority to Frequency + # Then to value of item + arr.sort(key=lambda x: (-d[x], x)) + + return (arr) + + +# Driver code +if __name__ == ""__main__"": + arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8] + n = len(arr) + + # Function call + solution = sortByFreq(arr, n) + print(*solution)",linear,nlogn +"# Python3 program to count +# inversions in an array + + +def getInvCount(arr, n): + + inv_count = 0 + for i in range(n): + for j in range(i + 1, n): + if (arr[i] > arr[j]): + inv_count += 1 + + return inv_count + + +# Driver Code +arr = [1, 20, 6, 4, 5] +n = len(arr) +print(""Number of inversions are"", + getInvCount(arr, n)) + +# This code is contributed by Smitha Dinesh Semwal",constant,quadratic +"# Python 3 program to count inversions in an array + +# Function to Use Inversion Count + + +def mergeSort(arr, n): + # A temp_arr is created to store + # sorted array in merge function + temp_arr = [0]*n + return _mergeSort(arr, temp_arr, 0, n-1) + +# This Function will use MergeSort to count inversions + + +def _mergeSort(arr, temp_arr, left, right): + + # A variable inv_count is used to store + # inversion counts in each recursive call + + inv_count = 0 + + # We will make a recursive call if and only if + # we have more than one elements + + if left < right: + + # mid is calculated to divide the array into two subarrays + # Floor division is must in case of python + + mid = (left + right)//2 + + # It will calculate inversion + # counts in the left subarray + + inv_count += _mergeSort(arr, temp_arr, + left, mid) + + # It will calculate inversion + # counts in right subarray + + inv_count += _mergeSort(arr, temp_arr, + mid + 1, right) + + # It will merge two subarrays in + # a sorted subarray + + inv_count += merge(arr, temp_arr, left, mid, right) + return inv_count + +# This function will merge two subarrays +# in a single sorted subarray + + +def merge(arr, temp_arr, left, mid, right): + i = left # Starting index of left subarray + j = mid + 1 # Starting index of right subarray + k = left # Starting index of to be sorted subarray + inv_count = 0 + + # Conditions are checked to make sure that + # i and j don't exceed their + # subarray limits. + + while i <= mid and j <= right: + + # There will be no inversion if arr[i] <= arr[j] + + if arr[i] <= arr[j]: + temp_arr[k] = arr[i] + k += 1 + i += 1 + else: + # Inversion will occur. + temp_arr[k] = arr[j] + inv_count += (mid-i + 1) + k += 1 + j += 1 + + # Copy the remaining elements of left + # subarray into temporary array + while i <= mid: + temp_arr[k] = arr[i] + k += 1 + i += 1 + + # Copy the remaining elements of right + # subarray into temporary array + while j <= right: + temp_arr[k] = arr[j] + k += 1 + j += 1 + + # Copy the sorted subarray into Original array + for loop_var in range(left, right + 1): + arr[loop_var] = temp_arr[loop_var] + + return inv_count + + +# Driver Code +# Given array is +arr = [1, 20, 6, 4, 5] +n = len(arr) +result = mergeSort(arr, n) +print(""Number of inversions are"", result) + +# This code is contributed by ankush_953",linear,nlogn +"from heapq import heappush, heappop +from bisect import bisect, insort + + +def getNumOfInversions(A): + N = len(A) + if N <= 1: + return 0 + + sortList = [] + result = 0 + + # Heapsort, O(N*log(N)) + for i, v in enumerate(A): + heappush(sortList, (v, i)) + + # Create a sorted list of indexes + x = [] + while sortList: + + # O(log(N)) + v, i = heappop(sortList) + + # Find the current minimum's index + # the index y can represent how many minimums on the left + y = bisect(x, i) + + # i can represent how many elements on the left + # i - y can find how many bigger nums on the left + result += i - y + + insort(x, i) + + return result + +# Driver Code +if __name__ == '__main__': + A = [1, 20, 6, 4, 5] + result = getNumOfInversions(A) + print(f'Number of inversions are {result}')",linear,nlogn +"# Python3 program to find shortest +# subarray which is unsorted + +# Bool function for checking an array +# elements are in increasing +def increasing(a, n): + + for i in range(0, n - 1): + if (a[i] >= a[i + 1]): + return False + + return True + +# Bool function for checking an array +# elements are in decreasing +def decreasing(a, n): + + for i in range(0, n - 1): + if (a[i] < a[i + 1]): + return False + + return True + +def shortestUnsorted(a, n): + + # increasing and decreasing are two functions. + # if function return True value then print + # 0 otherwise 3. + if (increasing(a, n) == True or + decreasing(a, n) == True): + return 0 + else: + return 3 + +# Driver code +ar = [7, 9, 10, 8, 11] +n = len(ar) +print(shortestUnsorted(ar, n)) + +# This code is contributed by Smitha Dinesh Semwal.",constant,linear +"# Python3 program to find +# minimum number of swaps +# required to sort an array + +# Function returns the minimum +# number of swaps required to +# sort the array +def minSwaps(arr): + n = len(arr) + + # Create two arrays and use + # as pairs where first array + # is element and second array + # is position of first element + arrpos = [*enumerate(arr)] + + # Sort the array by array element + # values to get right position of + # every element as the elements + # of second array. + arrpos.sort(key = lambda it : it[1]) + + # To keep track of visited elements. + # Initialize all elements as not + # visited or false. + vis = {k : False for k in range(n)} + + # Initialize result + ans = 0 + for i in range(n): + + # already swapped or + # already present at + # correct position + if vis[i] or arrpos[i][0] == i: + continue + + # find number of nodes + # in this cycle and + # add it to ans + cycle_size = 0 + j = i + + while not vis[j]: + + # mark node as visited + vis[j] = True + + # move to next node + j = arrpos[j][0] + cycle_size += 1 + + # update answer by adding + # current cycle + if cycle_size > 0: + ans += (cycle_size - 1) + + # return answer + return ans + +# Driver Code +arr = [1, 5, 4, 3, 2] +print(minSwaps(arr)) + +# This code is contributed +# by Dharan Aditya",linear,nlogn +"# Function returns the +# minimum number of swaps +# required to sort the array +from functools import cmp_to_key + +def cmp(a, b): + return a - b + +def minSwaps(nums): + Len = len(nums) + map = {} + for i in range(Len): + map[nums[i]] = i + + nums = sorted(nums, key = cmp_to_key(cmp)) + + # To keep track of visited elements. Initialize + # all elements as not visited or false. + visited = [False for col in range(Len)] + + # Initialize result + ans = 0 + for i in range(Len): + + # already swapped and corrected or + # already present at correct pos + if (visited[i] or map[nums[i]] == i): + continue + + j,cycle_size = i, 0 + while (visited[j] == False): + visited[j] = True + + # move to next node + j = map[nums[j]] + cycle_size += 1 + + # Update answer by adding current cycle. + if (cycle_size > 0): + ans += (cycle_size - 1) + + return ans + +# Driver program to test the above function +a = [ 1, 5, 4, 3, 2 ] +print(minSwaps(a)) + +# This code is contributed by shinjanpatra",linear,nlogn +"# Python3 program to find +#minimum number of swaps +# required to sort an array + +# Return the minimum number +# of swaps required to sort +# the array +def minSwaps(arr, N): + + ans = 0 + temp = arr.copy() + temp.sort() + for i in range(N): + + # This is checking whether + # the current element is + # at the right place or not + if (arr[i] != temp[i]): + ans += 1 + + # Swap the current element + # with the right index + # so that arr[0] to arr[i] + # is sorted + swap(arr, i, + indexOf(arr, temp[i])) + + return ans + +def swap(arr, i, j): + + temp = arr[i] + arr[i] = arr[j] + arr[j] = temp + +def indexOf(arr, ele): + + for i in range(len(arr)): + if (arr[i] == ele): + return i + return -1 + +# Driver code +if __name__ == ""__main__"": + a = [101, 758, 315, 730, + 472, 619, 460, 479] + n = len(a) + + # Output will be 5 + print(minSwaps(a, n)) + +# This code is contributed by Chitranayal",linear,quadratic +"# Python3 program to find +# minimum number of swaps +# required to sort an array + +# Return the minimum number +# of swaps required to sort +# the array +def minSwap(arr, n): + + ans = 0 + temp = arr.copy() + + # Dictionary which stores the + # indexes of the input array + h = {} + + temp.sort() + + for i in range(n): + + #h.[arr[i] + h[arr[i]] = i + + init = 0 + + for i in range(n): + + # This is checking whether + # the current element is + # at the right place or not + if (arr[i] != temp[i]): + ans += 1 + init = arr[i] + + # If not, swap this element + # with the index of the + # element which should come here + arr[i], arr[h[temp[i]]] = arr[h[temp[i]]], arr[i] + + # Update the indexes in + # the hashmap accordingly + h[init] = h[temp[i]] + h[temp[i]] = i + + return ans + +# Driver code +a = [ 101, 758, 315, 730, + 472, 619, 460, 479 ] +n = len(a) + +# Output will be 5 +print(minSwap(a, n)) + +# This code is contributed by avanitrachhadiya2155",linear,nlogn +"# Python program to sort an array with +# 0, 1 and 2 in a single pass + +# Function to sort array + + +def sort012(a, arr_size): + lo = 0 + hi = arr_size - 1 + mid = 0 + # Iterate till all the elements + # are sorted + while mid <= hi: + # If the element is 0 + if a[mid] == 0: + a[lo], a[mid] = a[mid], a[lo] + lo = lo + 1 + mid = mid + 1 + # If the element is 1 + elif a[mid] == 1: + mid = mid + 1 + # If the element is 2 + else: + a[mid], a[hi] = a[hi], a[mid] + hi = hi - 1 + return a + +# Function to print array + + +def printArray(a): + for k in a: + print(k, end=' ') + + +# Driver Program +arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1] +arr_size = len(arr) +arr = sort012(arr, arr_size) +printArray(arr) + +# Contributed by Harshit Agrawal",constant,linear +"# Python implementation of the approach + +# Utility function to print contents of an array + + +def printArr(arr, n): + for i in range(n): + print(arr[i], end="" "") + + +# Function to sort the array of 0s, 1s and 2s +def sortArr(arr, n): + cnt0 = 0 + cnt1 = 0 + cnt2 = 0 + + # Count the number of 0s, 1s and 2s in the array + for i in range(n): + if arr[i] == 0: + cnt0 += 1 + + elif arr[i] == 1: + cnt1 += 1 + + elif arr[i] == 2: + cnt2 += 1 + + # Update the array + i = 0 + + # Store all the 0s in the beginning + while (cnt0 > 0): + arr[i] = 0 + i += 1 + cnt0 -= 1 + + # Then all the 1s + while (cnt1 > 0): + arr[i] = 1 + i += 1 + cnt1 -= 1 + + # Finally all the 2s + while (cnt2 > 0): + arr[i] = 2 + i += 1 + cnt2 -= 1 + + # Print the sorted array + printArr(arr, n) + + +# Driver code + +arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1] +n = len(arr) + +sortArr(arr, n) + +# This code is contributed by shubhamsingh10",constant,linear +"# Function to find position to insert current element of +# stream using binary search +def binarySearch(arr, item, low, high): + + if (low >= high): + return (low + 1) if (item > arr[low]) else low + + mid = (low + high) // 2 + + if (item == arr[mid]): + return mid + 1 + + if (item > arr[mid]): + return binarySearch(arr, item, mid + 1, high) + + return binarySearch(arr, item, low, mid - 1) + +# Function to print median of stream of integers +def printMedian(arr, n): + + i, j, pos, num = 0, 0, 0, 0 + count = 1 + + print(f""Median after reading 1 element is {arr[0]}"") + + for i in range(1, n): + median = 0 + j = i - 1 + num = arr[i] + + # find position to insert current element in sorted + # part of array + pos = binarySearch(arr, num, 0, j) + + # move elements to right to create space to insert + # the current element + while (j >= pos): + arr[j + 1] = arr[j] + j -= 1 + + arr[j + 1] = num + + # increment count of sorted elements in array + count += 1 + + # if odd number of integers are read from stream + # then middle element in sorted order is median + # else average of middle elements is median + if (count % 2 != 0): + median = arr[count // 2] + + else: + median = (arr[(count // 2) - 1] + arr[count // 2]) // 2 + + print(f""Median after reading {i + 1} elements is {median} "") + +# Driver Code +if __name__ == ""__main__"": + + arr = [5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4] + n = len(arr) + + printMedian(arr, n) + +# This code is contributed by rakeshsahni",constant,quadratic +"# Python code to implement the approach + +from heapq import heappush, heappop, heapify +import math + +# Function to find the median of stream of data +def streamMed(arr, N): + + # Declaring two min heap + g = [] + s = [] + for i in range(len(arr)): + + # Negation for treating it as max heap + heappush(s, -arr[i]) + heappush(g, -heappop(s)) + if len(g) > len(s): + heappush(s, -heappop(g)) + + if len(g) != len(s): + print(-s[0]) + else: + print((g[0] - s[0])/2) + + +# Driver code +if __name__ == '__main__': + A = [5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4] + N = len(A) + + # Function call + streamMed(A, N)",linear,nlogn +"# Python3 code to count the number of +# possible triangles using brute +# force approach + +# Function to count all possible +# triangles with arr[] elements + + +def findNumberOfTriangles(arr, n): + + # Count of triangles + count = 0 + + # The three loops select three + # different values from array + for i in range(n): + for j in range(i + 1, n): + + # The innermost loop checks for + # the triangle property + for k in range(j + 1, n): + + # Sum of two sides is greater + # than the third + if (arr[i] + arr[j] > arr[k] and + arr[i] + arr[k] > arr[j] and + arr[k] + arr[j] > arr[i]): + count += 1 + return count + + +# Driver code +if __name__ == ""__main__"": + arr = [10, 21, 22, 100, 101, 200, 300] + size = len(arr) + + # Function call + print(""Total number of triangles possible is"", + findNumberOfTriangles(arr, size)) + +# This code is contributed by shubhamsingh10",constant,cubic +"# Python3 function to count all possible triangles with arr[] +# elements + + +def findnumberofTriangles(arr): + + # Sort array and initialize count as 0 + n = len(arr) + arr.sort() + count = 0 + + # Fix the first element. We need to run till n-3 as + # the other two elements are selected from arr[i + 1...n-1] + for i in range(0, n-2): + + # Initialize index of the rightmost third element + k = i + 2 + + # Fix the second element + for j in range(i + 1, n): + + # Find the rightmost element which is smaller + # than the sum of two fixed elements + # The important thing to note here is, we use + # the previous value of k. If value of arr[i] + + # arr[j-1] was greater than arr[k], then arr[i] + + # arr[j] must be greater than k, because the array + # is sorted. + while (k < n and arr[i] + arr[j] > arr[k]): + k += 1 + + # Total number of possible triangles that can be + # formed with the two fixed elements is k - j - 1. + # The two fixed elements are arr[i] and arr[j]. All + # elements between arr[j + 1] to arr[k-1] can form a + # triangle with arr[i] and arr[j]. One is subtracted + # from k because k is incremented one extra in above + # while loop. k will always be greater than j. If j + # becomes equal to k, then above loop will increment k, + # because arr[k] + arr[i] is always greater than arr[k] + if(k > j): + count += k - j - 1 + + return count + + +# Driver code +if __name__ == ""__main__"": + arr = [10, 21, 22, 100, 101, 200, 300] + + # Function call + print(""Total number of Triangles:"", findnumberofTriangles(arr)) + +# This code is contributed by Devesh Agrawal",constant,quadratic +"# Python implementation of the above approach +def CountTriangles(A): + + n = len(A) + + A.sort() + + count = 0 + + for i in range(n - 1, 0, -1): + l = 0 + r = i - 1 + while(l < r): + if(A[l] + A[r] > A[i]): + + # If it is possible with a[l], a[r] + # and a[i] then it is also possible + # with a[l + 1]..a[r-1], a[r] and a[i] + count += r - l + + # checking for more possible solutions + r -= 1 + + else: + + # if not possible check for + # higher values of arr[l] + l += 1 + print(""No of possible solutions: "", count) + + +# Driver Code +if __name__ == '__main__': + + A = [10, 21, 22, 100, 101, 200, 300] + + # Function call + CountTriangles(A) + +# This code is contributed by PrinciRaj1992",constant,quadratic +"# Python program to merge +# two sorted arrays +# with O(1) extra space. + +# Merge ar1[] and ar2[] +# with O(1) extra space +def merge(ar1, ar2, m, n): + + # Iterate through all + # elements of ar2[] starting from + # the last element + for i in range(n-1, -1, -1): + + # Find the smallest element + # greater than ar2[i]. Move all + # elements one position ahead + # till the smallest greater + # element is not found + last = ar1[m-1] + j=m-2 + while(j >= 0 and ar1[j] > ar2[i]): + ar1[j+1] = ar1[j] + j-=1 + + # If there was a greater element + if (last > ar2[i]): + + ar1[j+1] = ar2[i] + ar2[i] = last + +# Driver program + +ar1 = [1, 5, 9, 10, 15, 20] +ar2 = [2, 3, 8, 13] +m = len(ar1) +n = len(ar2) + +merge(ar1, ar2, m, n) + +print(""After Merging \nFirst Array:"", end="""") +for i in range(m): + print(ar1[i] , "" "", end="""") + +print(""\nSecond Array: "", end="""") +for i in range(n): + print(ar2[i] , "" "", end="""") + +# This code is contributed +# by Anant Agarwal.",constant,quadratic +"# Python program for the above approach +arr1 = [1, 5, 9, 10, 15, 20] +arr2 = [2, 3, 8, 13] + +# Function to merge two arrays + + +def merge(n, m): + i = 0 + j = 0 + k = n - 1 + while (i <= k and j < m): + if (arr1[i] < arr2[j]): + i += 1 + else: + temp = arr2[j] + arr2[j] = arr1[k] + arr1[k] = temp + j += 1 + k -= 1 + + arr1.sort() + arr2.sort() + + +# Driver code +if __name__ == '__main__': + merge(len(arr1), len(arr2)) + print(""After Merging \nFirst Array: "") + print(','.join(str(x) for x in arr1)) + print(""Second Array: "") + print(','.join(str(x) for x in arr2)) + +# This code is contributed by gauravrajput1",constant,nlogn +"arr1 = [1, 5, 9, 10, 15, 20 ]; +arr2 =[ 2, 3, 8, 13 ]; + +def merge(n, m): + i = 0; + temp = 0; + + # While loop till last element + # of array 1(sorted) + # is greater than first element + # of array 2(sorted) + while (arr1[n - 1] > arr2[0]): + if (arr1[i] > arr2[0]): + + # Swap arr1[i] with first element + # of arr2 and sorting the updated + # arr2(arr1 is already sorted) + # swap(arr1[i],arr2[0]); + temp = arr1[i]; + arr1[i] = arr2[0]; + arr2[0] = temp; + arr2.sort(); + + i+=1; + + + +# Driver code +if __name__ == '__main__': + merge(len(arr1), len(arr2)); + + print(""After Merging \nFirst Array: ""); + print((arr1)); + + print(""Second Array: ""); + print((arr2)); + + +# This code contributed by gauravrajput1",constant,linear +"# Python program to merge +# two sorted arrays +# with O(1) extra space. + +# Merge ar1[] and ar2[] +# with O(1) extra space + + +def rotate(a, n, idx): + for i in range((int)(idx/2)): + a[i], a[idx-1-i] = a[idx-1-i], a[i] + for i in range(idx, (int)((n+idx)/2)): + a[i], a[n-1-(i-idx)] = a[n-1-(i-idx)], a[i] + for i in range((int)(n/2)): + a[i], a[n-1-i] = a[n-1-i], a[i] + + +def sol(a1, a2, n, m): + l = 0 + h = n-1 + idx = 0 + while (l <= h): + c1 = (int)((l+h)/2) + c2 = n-c1-1 + l1 = a1[c1] + l2 = a2[c2-1] + r1 = sys.maxint if c1 == n-1 else a1[c1+1] + r2 = sys.maxint if c2 == m else a2[c2] + if l1 > r2: + h = c1-1 + if h == -1: + idx = 0 + elif l2 > r1: + l = c1+1 + if l == n-1: + idx = n + else: + idx = c1+1 + break + for i in range(idx, n): + a1[i], a2[i-idx] = a2[i-idx], a1[i] + + a1.sort() + a2.sort() + + +def merge(a1, a2, n, m): + if n > m: + sol(a2, a1, m, n) + rotate(a1, n, n-m) + for i in range(m): + a1[i], a2[i] = a2[i], a1[i] + else: + sol(a1, a2, n, m) +# Driver program + + +ar1 = [1, 5, 9, 10, 15, 20] +ar2 = [2, 3, 8, 13] +m = len(ar1) +n = len(ar2) + +merge(ar1, ar2, m, n) + +print(""After Merging \nFirst Array:"", end="""") +for i in range(m): + print(ar1[i], "" "", end="""") +print(""\nSecond Array: "", end="""") +for i in range(n): + print(ar2[i], "" "", end="""") +# This code is contributed +# by Aditya Anand.",constant,nlogn +"# code contributed by mahee96 + +# ""Insertion sort of list 2 with swaps from list 1"" +# +# swap elements to get list 1 correctly, meanwhile +# place the swapped item in correct position of list 2 +# eventually list 2 is also sorted +# Time = O(m*n) or O(n*m) +# AUX = O(1) +def merge(arr1, arr2): + x = arr1; y = arr2 + end = len(arr1) + i = 0 + while(i < end): # O(m) or O(n) + if(x[i] > y[0]): + swap(x,y,i,0) + insert(y,0) # O(n) or O(m) number of shifts + i+=1 + +# O(n): +def insert(y, i): + orig = y[i] + i+=1 + while (i= x and arr2[k] >= x: + if arr1[j] % x <= arr2[k] % x: + arr1[i] += (arr1[j] % x) * x + j += 1 + else: + arr1[i] += (arr2[k] % x) * x + k += 1 + # if only arr1 elements are modified + elif arr1[j] >= x: + if arr1[j] % x <= arr2[k]: + arr1[i] += (arr1[j] % x) * x + j += 1 + else: + arr1[i] += (arr2[k] % x) * x + k += 1 + # if only arr2 elements are modified + elif arr2[k] >= x: + if arr1[j] <= arr2[k] % x: + arr1[i] += (arr1[j] % x) * x + j += 1 + else: + arr1[i] += (arr2[k] % x) * x + k += 1 + # if none elements are modified + else: + if arr1[j] <= arr2[k]: + arr1[i] += (arr1[j] % x) * x + j += 1 + else: + arr1[i] += (arr2[k] % x) * x + k += 1 + i += 1 + + # we can copy the elements directly as the other array + # is exchausted + while j < n and i < n: + arr1[i] += (arr1[j] % x) * x + i += 1 + j += 1 + while k < m and i < n: + arr1[i] += (arr2[k] % x) * x + i += 1 + k += 1 + # we need to reset i + i = 0 + + # in this loop we are rearranging the elements of arr2 + while i < m and (j < n and k < m): + # if both arr1 and arr2 elements are modified + if arr1[j] >= x and arr2[k] >= x: + if arr1[j] % x <= arr2[k] % x: + arr2[i] += (arr1[j] % x) * x + j += 1 + + else: + arr2[i] += (arr2[k] % x) * x + k += 1 + + # if only arr1 elements are modified + elif arr1[j] >= x: + if arr1[j] % x <= arr2[k]: + arr2[i] += (arr1[j] % x) * x + j += 1 + + else: + arr2[i] += (arr2[k] % x) * x + k += 1 + + # if only arr2 elements are modified + elif arr2[k] >= x: + if arr1[j] <= arr2[k] % x: + arr2[i] += (arr1[j] % x) * x + j += 1 + + else: + arr2[i] += (arr2[k] % x) * x + k += 1 + + else: + # if none elements are modified + if arr1[j] <= arr2[k]: + arr2[i] += (arr1[j] % x) * x + j += 1 + + else: + arr2[i] += (arr2[k] % x) * x + k += 1 + + i += 1 + # we can copy the elements directly as the other array + # is exhausted + while j < n and i < m: + arr2[i] += (arr1[j] % x) * x + i += 1 + j += 1 + + while k < m and i < m: + arr2[i] += (arr2[k] % x) * x + i += 1 + k += 1 + + # we need to reset i + i = 0 + # we need to divide the whole arr1 by x + while i < n: + arr1[i] /= x + i += 1 + + # we need to reset i + i = 0 + # we need to divide the whole arr2 by x + while i < m: + arr2[i] /= x + i += 1 + +# Driver program + + +ar1 = [1, 5, 9, 10, 15, 20] +ar2 = [2, 3, 8, 13] +m = len(ar1) +n = len(ar2) + +merge(ar1, ar2, m, n) + +print(""After Merging \nFirst Array:"", end="" "") +for i in range(m): + print(int(ar1[i]), end="" "") +print(""\nSecond Array:"", end="" "") +for i in range(n): + print(int(ar2[i]), end="" "") + +# This code is contributed by Tapesh(tapeshdua420)",constant,linear +"# A Python program to find the to +# calculate the product of max +# element of first array and min +# element of second array + +# Function to calculate the product +def minmaxProduct(arr1, arr2, n1, n2): + + # Sort the arrays to find the + # maximum and minimum elements + # in given arrays + arr1.sort() + arr2.sort() + + # Return product of maximum + # and minimum. + return arr1[n1 - 1] * arr2[0] + +# Driver Program +arr1 = [10, 2, 3, 6, 4, 1] +arr2 = [5, 1, 4, 2, 6, 9] +n1 = len(arr1) +n2 = len(arr2) +print(minmaxProduct(arr1, arr2, n1, n2)) + +# This code is contributed by Shrikant13.",constant,nlogn +"# Python3 program to find the to +# calculate the product of +# max element of first array +# and min element of second array + +# Function to calculate the product +def minMaxProduct(arr1, arr2, + n1, n2) : + + # Initialize max of first array + max = arr1[0] + + # initialize min of second array + min = arr2[0] + + i = 1 + while (i < n1 and i < n2) : + + # To find the maximum + # element in first array + if (arr1[i] > max) : + max = arr1[i] + + # To find the minimum + # element in second array + if (arr2[i] < min) : + min = arr2[i] + + i += 1 + + # Process remaining elements + while (i < n1) : + + if (arr1[i] > max) : + max = arr1[i] + i += 1 + + while (i < n2): + + if (arr2[i] < min) : + min = arr2[i] + i += 1 + + return max * min + +# Driver code +arr1 = [10, 2, 3, 6, 4, 1 ] +arr2 = [5, 1, 4, 2, 6, 9 ] +n1 = len(arr1) +n2 = len(arr1) +print(minMaxProduct(arr1, arr2, n1, n2)) + +# This code is contributed by Smitha",constant,linear +"# python 3 program to implement +# binary search in sorted array + + +def binarySearch(arr, low, high, key): + + mid = (low + high)/2 + + if (key == arr[int(mid)]): + return mid + + if (key > arr[int(mid)]): + return binarySearch(arr, + (mid + 1), high, key) + + if (key < arr[int(mid)]): + return binarySearch(arr, low, (mid-1), key) + + return 0 + + +# Driver code +if __name__ == ""__main__"": + # Let us search 3 in below array + arr = [5, 6, 7, 8, 9, 10] + n = len(arr) + key = 10 + + # Function call + print(""Index:"", int(binarySearch(arr, 0, n-1, key))) + +# This code is contributed by +# Smitha Dinesh Semwal",logn,logn +"# Python3 program to implement insert +# operation in an sorted array. + +# Inserts a key in arr[] of given capacity. +# n is current size of arr[]. This function +# returns n+1 if insertion is successful, else n. + + +def insertSorted(arr, n, key, capacity): + + # Cannot insert more elements if n is + # already more than or equal to capacity + if (n >= capacity): + return n + + i = n - 1 + while i >= 0 and arr[i] > key: + arr[i + 1] = arr[i] + i -= 1 + + arr[i + 1] = key + + return (n + 1) + + +# Driver Code +if __name__ == ""__main__"": + arr = [12, 16, 20, 40, 50, 70] + + for i in range(20): + arr.append(0) + + capacity = len(arr) + n = 6 + key = 26 + + print(""Before Insertion: "", end="" "") + for i in range(n): + print(arr[i], end="" "") + + # Function call + n = insertSorted(arr, n, key, capacity) + + print(""\nAfter Insertion: "", end="""") + for i in range(n): + print(arr[i], end="" "") + +# This code is contributed by Mohit Kumar",constant,linear +"# Python program to implement delete operation in a +# sorted array + +# /* Function to delete an element */ + + +def deleteElement(arr, n, key): + + # Find position of element to be deleted + pos = binarySearch(arr, 0, n - 1, key) + + if (pos == -1): + print(""Element not found"") + return n + + # Deleting element + for i in range(pos, n - 1): + arr[i] = arr[i + 1] + + return n - 1 + +# To search a key to be deleted + + +def binarySearch(arr, low, high, key): + + if (high < low): + return -1 + mid = (low + high) // 2 + + if (key == arr[mid]): + return mid + if (key > arr[mid]): + return binarySearch(arr, (mid + 1), high, key) + + return binarySearch(arr, low, (mid - 1), key) + + +# Driver code +if __name__ == ""__main__"": + arr = [10, 20, 30, 40, 50] + + n = len(arr) + key = 30 + + print(""Array before deletion"") + + for i in range(n): + print(arr[i], end="" "") + + # Function call + n = deleteElement(arr, n, key) + print(""\n\nArray after deletion"") + for i in range(n): + print(arr[i], end="" "") + +# This code is contributed by shubhamsingh10",logn,linear +"# This python program tells if there exists a pair in array whose sum results in x. + +# Function to find and print pair + + +def chkPair(A, size, x): + for i in range(0, size - 1): + for j in range(i + 1, size): + if (A[i] + A[j] == x): + return 1 + return 0 + + +if __name__ == ""__main__"": + A = [0, -1, 2, -3, 1] + x = -2 + size = len(A) + + if (chkPair(A, size, x)): + print(""Yes"") + + else: + print(""No"") + + # This code is contributed by rakeshsahni",constant,quadratic +"# Python program to check for the sum +# condition to be satisfied + + +def hasArrayTwoCandidates(A, arr_size, sum): + + # sort the array + quickSort(A, 0, arr_size-1) + l = 0 + r = arr_size-1 + + # traverse the array for the two elements + while l < r: + if (A[l] + A[r] == sum): + return 1 + elif (A[l] + A[r] < sum): + l += 1 + else: + r -= 1 + return 0 + +# Implementation of Quick Sort +# A[] --> Array to be sorted +# si --> Starting index +# ei --> Ending index + + +def quickSort(A, si, ei): + if si < ei: + pi = partition(A, si, ei) + quickSort(A, si, pi-1) + quickSort(A, pi + 1, ei) + +# Utility function for partitioning +# the array(used in quick sort) + + +def partition(A, si, ei): + x = A[ei] + i = (si-1) + for j in range(si, ei): + if A[j] <= x: + i += 1 + + # This operation is used to swap + # two variables is python + A[i], A[j] = A[j], A[i] + + A[i + 1], A[ei] = A[ei], A[i + 1] + + return i + 1 + + +# Driver program to test the functions +A = [1, 4, 45, 6, 10, -8] +n = 16 +if (hasArrayTwoCandidates(A, len(A), n)): + print(""Yes"") +else: + print(""No"") + +# This code is contributed by __Devesh Agrawal__",constant,nlogn +"# Python program to check for the sum +# condition to be satisfied + + +def binarySearch(A, low, high, searchKey): + m = 0 + while (low <= high): + m = (high + low) // 2 + # Check if searchKey is present at mid + if (A[m] == searchKey): + return 1 + # If searchKey greater, ignore left half + if (A[m] < searchKey): + low = m + 1 + # If searchKey is smaller, ignore right half + else: + high = m - 1 + # if we reach here, then element was + # not present + return 0 + + +def checkTwoSum(A, arr_size, sum): + + # sort the array + A.sort() + l = 0 + r = arr_size-1 + + # Traversing all element in an array search for searchKey + i = 0 + while i < arr_size-1: + searchKey = sum-A[i] + # calling binarySearch function + if(binarySearch(A, i+1, r, searchKey) == 1): + return 1 + i = i+1 + + return 0 + + +# Driver program to test the functions +A = [1, 4, 45, 6, 10, -8] +n = 14 +if (checkTwoSum(A, len(A), n)): + print(""Yes"") +else: + print(""No"")",constant,nlogn +"# Python program to find if there are +# two elements with given sum + +# function to check for the given sum +# in the array + + +def printPairs(arr, arr_size, sum): + + # Create an empty hash map + # using an hashmap allows us to store the indices + hashmap = {} + + for i in range(0, arr_size): + temp = sum-arr[i] + if (temp in hashmap): + print('Yes') + return + hashmap[arr[i]] = i + print(""No"") + + +# driver code +A = [1, 4, 45, 6, 10, 8] +n = 16 +printPairs(A, len(A), n) + +# This code will also work in case the array has the same number twice +# and target is the sum of those numbers +# Eg: Array = [4,6,4] Target = 8 + +# This code is contributed by __Achyut Upadhyay__",linear,linear +"# Code in Python3 to tell if there +# exists a pair in array whose +# sum results in x. + +# Function to print pairs + + +def printPairs(a, n, x): + + rem = [] + + for i in range(x): + + # Initializing the rem + # values with 0's. + rem.append(0) + + for i in range(n): + if (a[i] < x): + + # Perform the remainder operation + # only if the element is x, as + # numbers greater than x can't + # be used to get a sum x.Updating + # the count of remainders. + rem[a[i] % x] += 1 + + # Traversing the remainder list from + # start to middle to find pairs + for i in range(1, x // 2): + if (rem[i] > 0 and rem[x - i] > 0): + + # The elements with remainders + # i and x-i will result to a + # sum of x. Once we get two + # elements which add up to x, + # we print x and break. + print(""Yes"") + break + + # Once we reach middle of + # remainder array, we have to + # do operations based on x. + if (i >= x // 2): + if (x % 2 == 0): + if (rem[x // 2] > 1): + + # If x is even and we have more + # than 1 elements with remainder + # x/2, then we will have two + # distinct elements which add up + # to x. if we dont have than 1 + # element, print ""No"". + print(""Yes"") + else: + print(""No"") + else: + + # When x is odd we continue + # the same process which we + # did in previous loop. + if (rem[x // 2] > 0 and + rem[x - x // 2] > 0): + print(""Yes"") + else: + print(""No"") + + +# Driver Code +A = [1, 4, 45, 6, 10, 8] +n = 16 +arr_size = len(A) + +# Function calling +printPairs(A, arr_size, n) + +# This code is contributed by subhammahato348",constant,linear +"# Python 3 program to search an element in an array +# where difference between adjacent elements is atmost k + +# x is the element to be searched in arr[0..n-1] +# such that all elements differ by at-most k. +def search(arr, n, x, k): + + # Traverse the given array starting from + # leftmost element + i = 0 + while (i < n): + + # If x is found at index i + if (arr[i] == x): + return i + + # Jump the difference between current + # array element and x divided by k + # We use max here to make sure that i + # moves at-least one step ahead. + i = i + max(1, int(abs(arr[i] - x) / k)) + + + print(""number is not present!"") + return -1 + + +# Driver program to test above function +arr = [2, 4, 5, 7, 7, 6] +x = 6 +k = 2 +n = len(arr) +print(""Element"", x, ""is present at index"",search(arr, n, x, k)) + +# This code is contributed +# by Smitha Dinesh Semwal",constant,linear +"# Python 3 program for above approach +import sys + +# This function prints +# common elements in ar1 + + +def findCommon(ar1, ar2, ar3, n1, + n2, n3): + + # Initialize starting indexes + # for ar1[], ar2and + # ar3[] + i = 0 + j = 0 + k = 0 + + # Declare three variables prev1, + # prev2, prev3 to track + # previous element + # Initialize prev1, prev2, + # prev3 with INT_MIN + prev1 = prev2 = prev3 = -sys.maxsize - 1 + + # Iterate through three arrays + # while all arrays have + # elements + while (i < n1 and j < n2 and k < n3): + + # If ar1[i] = prev1 and i < n1, + # keep incrementing i + while (ar1[i] == prev1 and i < n1-1): + i += 1 + + # If ar2[j] = prev2 and j < n2, + # keep incrementing j + while (ar2[j] == prev2 and j < n2): + j += 1 + + # If ar3[k] = prev3 and k < n3, + # keep incrementing k + while (ar3[k] == prev3 and k < n3): + k += 1 + + # If x = y and y = z, pr + # any of them, update + # prev1 prev2, prev3 and move + # ahead in each array + if (ar1[i] == ar2[j] and ar2[j] == ar3[k]): + print(ar1[i], end="" "") + prev1 = ar1[i] + prev2 = ar2[j] + prev3 = ar3[k] + i += 1 + j += 1 + k += 1 + + # If x < y, update prev1 + # and increment i + elif (ar1[i] < ar2[j]): + prev1 = ar1[i] + i += 1 + + # If y < z, update prev2 + # and increment j + elif (ar2[j] < ar3[k]): + prev2 = ar2[j] + j += 1 + + # We reach here when x > y + # and z < y, i.e., z is + # smallest update prev3 + # and increment k + else: + prev3 = ar3[k] + k += 1 + + +# Driver code +ar1 = [1, 5, 10, 20, 40, 80, 80] +ar2 = [6, 7, 20, 80, 80, 100] +ar3 = [3, 4, 15, 20, 30, 70, 80, 80, 120] +n1 = len(ar1) +n2 = len(ar2) +n3 = len(ar3) + +print(""Common Elements are "") +findCommon(ar1, ar2, ar3, n1, n2, n3) + +# This code is contributed by splevel62.",constant,linear +"# Python implementation of the approach +def findCommon(a, b, c, n1, n2, n3): + + # three sets to maintain frequency of elements + uset = set() + uset2 = set() + uset3 = set() + for i in range(n1): + uset.add(a[i]) + + for i in range(n2): + uset2.add(b[i]) + + # checking if elements of 3rd array are present in first 2 sets + for i in range(n3): + + if(c[i] in uset and c[i] in uset2): + + # using a 3rd set to prevent duplicates + if c[i] not in uset3: + print(c[i], end = "" "") + uset3.add(c[i]) + +# Driver code +ar1 = [ 1, 5, 10, 20, 40, 80 ] +ar2 = [ 6, 7, 20, 80, 100 ] +ar3 = [ 3, 4, 15, 20, 30, 70, 80, 120 ] +n1 = len(ar1) +n2 = len(ar2) +n3 = len(ar3) + +print(""Common Elements are "") +findCommon(ar1, ar2, ar3, n1, n2, n3) + +# This code is contributed by shinjanpatra.",linear,linear +"# Python3 program to find the only +# repeating element in an array where +# elements are from 1 to N-1. + + +def findRepeating(arr, N): + for i in range(N): + for j in range(i + 1, N): + if (arr[i] == arr[j]): + return arr[i] + + +# Driver's Code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed by Arpit Jain",constant,quadratic +"# Python3 program to find the only +# repeating element in an array where +# elements are from 1 to N-1. + + +def findRepeating(arr, N): + arr.sort() + for i in range(1, N): + if(arr[i] != i+1): + return arr[i] + + +# Driver's Code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed by Arpit Jain",constant,nlogn +"# Python3 program to find the only +# repeating element in an array +# where elements are from 1 to n-1. + + +def findRepeating(arr, N): + s = set() + for i in range(N): + if arr[i] in s: + return arr[i] + s.add(arr[i]) + + # If input is correct, we should + # never reach here + return -1 + + +# Driver code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed +# by Shrikant13",linear,linear +"# Python3 program to find the only +# repeating element in an array where +# elements are from 1 to N-1. + + +def findRepeating(arr, N): + + # Find array sum and subtract sum + # first n-1 natural numbers from it + # to find the result. + return sum(arr) - (((N - 1) * N) // 2) + + +# Driver's Code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed +# by mohit kumar",constant,linear +"# Python3 program to find the only +# repeating element in an array where +# elements are from 1 to N-1. + + +def findRepeating(arr, N): + + # res is going to store value of + # 1 ^ 2 ^ 3 .. ^ (N-1) ^ arr[0] ^ + # arr[1] ^ .... arr[n-1] + res = 0 + for i in range(0, N-1): + res = res ^ (i+1) ^ arr[i] + res = res ^ arr[N-1] + + return res + + +# Driver code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed by Smitha Dinesh Semwal.",constant,linear +"# Python3 program to find the only +# repeating element in an array +# where elements are from 1 to N-1. + +# Function to find repeated element + + +def findRepeating(arr, N): + + missingElement = 0 + + # indexing based + for i in range(0, N): + + element = arr[abs(arr[i])] + + if(element < 0): + missingElement = arr[i] + break + + arr[abs(arr[i])] = -arr[abs(arr[i])] + + return abs(missingElement) + + +# Driver code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed by Smitha Dinesh Semwal.",constant,linear +"class GFG : + @staticmethod + def findDuplicate( nums) : + slow = nums[0] + fast = nums[0] + while True : + slow = nums[slow] + fast = nums[nums[fast]] + if((slow != fast) == False) : + break + fast = nums[0] + while (slow != fast) : + slow = nums[slow] + fast = nums[fast] + return slow + @staticmethod + def main( args) : + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + + # Function call + ans = GFG.findDuplicate(arr) + print(ans) + +if __name__==""__main__"": + GFG.main([]) + + # This code is contributed by aadityaburujwale.",constant,linear +"# Python code to find the array element that appears only once + +# Function to find the array +# element that appears only once +def findSingle(A, ar_size): + + # iterate over every element + for i in range(ar_size): + + # Initialize count to 0 + count = 0 + for j in range(ar_size): + + # Count the frequency + # of the element + if(A[i] == A[j]): + count += 1 + + # If the frequency of + # the element is one + if(count == 1): + return A[i] + + # If no element exist + # at most once + return -1 + +ar = [2, 3, 5, 4, 5, 3, 4] +n = len(ar) +# Function call +print(""Element occurring once is"", findSingle(ar, n)) + +# This code is contributed by lokesh",constant,quadratic +"# function to find the once +# appearing element in array +def findSingle( ar, n): + + res = ar[0] + + # Do XOR of all elements and return + for i in range(1,n): + res = res ^ ar[i] + + return res + +# Driver code +ar = [2, 3, 5, 4, 5, 3, 4] +print ""Element occurring once is"", findSingle(ar, len(ar)) + +# This code is contributed by __Devesh Agrawal__",constant,linear +"# Python3 program to find +# element that appears once + +# function which find number +def singleNumber(nums): + +# applying the formula. + return 2 * sum(set(nums)) - sum(nums) + +# driver code +a = [2, 3, 5, 4, 5, 3, 4] +print (int(singleNumber(a))) + +a = [15, 18, 16, 18, 16, 15, 89] +print (int(singleNumber(a))) + +# This code is contributed by ""Abhishek Sharma 44""",linear,nlogn +"def singleelement(arr, n): + low = 0 + high = n - 2 + mid = 0 + while (low <= high): + mid = (low + high) // 2 + if (arr[mid] == arr[mid ^ 1]): + low = mid + 1 + else: + high = mid - 1 + + return arr[low] + +# Driver code +arr = [2, 3, 5, 4, 5, 3, 4] +size = len(arr) +arr.sort() +print(singleelement(arr, size)) + +# This code is contributed by shivanisingh",constant,nlogn +"# Python Program to find max +# subarray sum excluding some +# elements + +# Function to check the element +# present in array B +INT_MIN = -2147483648 + + +def isPresent(B, m, x): + for i in range(0, m): + if B[i] == x: + return True + return False + +# Utility function for findMaxSubarraySum() +# with the following parameters +# A => Array A, +# B => Array B, +# n => Number of elements in Array A, +# m => Number of elements in Array B + + +def findMaxSubarraySumUtil(A, B, n, m): + + # set max_so_far to INT_MIN + max_so_far = INT_MIN + curr_max = 0 + for i in range(0, n): + if isPresent(B, m, A[i]) == True: + curr_max = 0 + continue + + # Proceed as in Kadane's Algorithm + curr_max = max(A[i], curr_max + A[i]) + max_so_far = max(max_so_far, curr_max) + return max_so_far + +# Wrapper for findMaxSubarraySumUtil() + + +def findMaxSubarraySum(A, B, n, m): + + maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m) + + # This case will occur when all + # elements of A are present + # in B, thus no subarray can be + # formed + if maxSubarraySum == INT_MIN: + print('Maximum Subarray Sum cant be found') + else: + print('The Maximum Subarray Sum =', + maxSubarraySum) + + +# Driver code +A = [3, 4, 5, -4, 6] +B = [1, 8, 5] +n = len(A) +m = len(B) + +# Function call +findMaxSubarraySum(A, B, n, m) + +# This code is contributed +# by sahil shelangia",constant,quadratic +"# Python Program to find max subarray +# sum excluding some elements + +# Utility function for findMaxSubarraySum() +# with the following parameters +# A => Array A, +# B => Array B, +# n => Number of elements in Array A, +# m => Number of elements in Array B +import sys + + +def binary_search(B, m, target): + + start,end = 0,m - 1 + + # Iterate while start not meets end + while (start <= end): + + # Find the mid index + mid = (start + end) // 2 + + # If element is present at mid, return True + if (B[mid] == target): + return True + + # Else look in left or right half accordingly + elif (B[mid] < target): + start = mid + 1 + else: + end = mid - 1 + + return False + +def findMaxSubarraySumUtil(A, B, n, m): + + # set max_so_far to INT_MIN + max_so_far,curr_max = -sys.maxsize - 1,0 + + for i in range(n): + + # if the element is present in B, + # set current max to 0 and move to + # the next element + if (binary_search(B, m, A[i])): + curr_max = 0 + continue + + # Proceed as in Kadane's Algorithm + curr_max = max(A[i], curr_max + A[i]) + max_so_far = max(max_so_far, curr_max) + + return max_so_far + +# Wrapper for findMaxSubarraySumUtil() +def findMaxSubarraySum(A,B,n,m): + + # sort array B to apply Binary Search + B.sort() + + maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m) + + # This case will occur when all elements + # of A are present in B, thus no subarray + # can be formed + if (maxSubarraySum == -sys.maxsize - 1): + print(""Maximum subarray sum cant be found"") + else: + print(f""The Maximum subarray sum = {maxSubarraySum}"") + +# Driver Code +A = [ 3, 4, 5, -4, 6 ] +B = [ 1, 8, 5 ] + +n = len(A) +m = len(B) + +# Function call +findMaxSubarraySum(A, B, n, m) + +# This code is contributed by shinjanpatra",constant,nlogn +"# Python3 program implementation of the +# above idea +import sys + +# Function to calculate the max sum of +# contiguous subarray of B whose elements +# are not present in A +def findMaxSubarraySum(A, B): + + m = dict() + + # Mark all the elements present in B + for i in range(len(B)): + if B[i] not in m: + m[B[i]] = 0 + + m[B[i]] = 1 + + # Initialize max_so_far with INT_MIN + max_so_far = -sys.maxsize - 1 + currmax = 0 + + # Traverse the array A + for i in range(len(A)): + if (currmax < 0 or (A[i] in m and m[A[i]] == 1)): + currmax = 0 + continue + + currmax = max(A[i], A[i] + currmax) + + # If current max is greater than + # max so far then update max so far + if (max_so_far i): + suffix_sum += arr[j] + j -= 1 + if (prefix_sum == suffix_sum): + res = max(res, prefix_sum) + + return res + +# Driver Code +if __name__ == '__main__': + arr = [-2, 5, 3, 1, 2, 6, -4, 2] + n = len(arr) + print(findMaxSum(arr, n)) + +# This code is contributed by +# Surendra_Gangwar",linear,quadratic +"# Python3 program to find +# maximum equilibrium sum. + +# Function to find maximum +# equilibrium sum. +def findMaxSum(arr, n): + + # Array to store prefix sum. + preSum = [0 for i in range(n)] + + # Array to store suffix sum. + suffSum = [0 for i in range(n)] + + # Variable to store maximum sum. + ans = -10000000 + + # Calculate prefix sum. + preSum[0] = arr[0] + + for i in range(1, n): + + preSum[i] = preSum[i - 1] + arr[i] + + # Calculate suffix sum and compare + # it with prefix sum. Update ans + # accordingly. + suffSum[n - 1] = arr[n - 1] + if (preSum[n - 1] == suffSum[n - 1]): + ans = max(ans, preSum[n - 1]) + + for i in range(n - 2, -1, -1): + suffSum[i] = suffSum[i + 1] + arr[i] + if (suffSum[i] == preSum[i]): + ans = max(ans, preSum[i]) + + return ans + +# Driver Code +if __name__=='__main__': + + arr = [-2, 5, 3, 1,2, 6, -4, 2] + n = len(arr) + print(findMaxSum(arr, n)) + +# This code is contributed by pratham76",linear,linear +"# Python3 program to find +# maximum equilibrium sum. +import sys + +# Function to find +# maximum equilibrium sum. +def findMaxSum(arr,n): + + ss = sum(arr) + prefix_sum = 0 + res = -sys.maxsize + + for i in range(n): + prefix_sum += arr[i] + + if prefix_sum == ss: + res = max(res, prefix_sum); + + ss -= arr[i]; + + return res + +# Driver code +if __name__==""__main__"": + + arr = [ -2, 5, 3, 1, + 2, 6, -4, 2 ] + n = len(arr) + + print(findMaxSum(arr, n)) + +# This code is contributed by rutvik_56",constant,linear +"# Python3 program to find equilibrium +# index of an array + +# function to find the equilibrium index + + +def equilibrium(arr): + leftsum = 0 + rightsum = 0 + n = len(arr) + + # Check for indexes one by one + # until an equilibrium index is found + for i in range(n): + leftsum = 0 + rightsum = 0 + + # get left sum + for j in range(i): + leftsum += arr[j] + + # get right sum + for j in range(i + 1, n): + rightsum += arr[j] + + # if leftsum and rightsum are same, + # then we are done + if leftsum == rightsum: + return i + + # return -1 if no equilibrium index is found + return -1 + + +# Driver code +if __name__ == ""__main__"": + arr = [-7, 1, 5, 2, -4, 3, 0] + + # Function call + print(equilibrium(arr)) + +# This code is contributed by Abhishek Sharama",constant,quadratic +"# Python program to find the equilibrium +# index of an array + +# Function to find the equilibrium index + + +def equilibrium(arr): + + # finding the sum of whole array + total_sum = sum(arr) + leftsum = 0 + for i, num in enumerate(arr): + + # total_sum is now right sum + # for index i + total_sum -= num + + if leftsum == total_sum: + return i + leftsum += num + + # If no equilibrium index found, + # then return -1 + return -1 + + +# Driver code +if __name__ == ""__main__"": + arr = [-7, 1, 5, 2, -4, 3, 0] + + # Function call + print('First equilibrium index is ', + equilibrium(arr)) + +# This code is contributed by Abhishek Sharma",constant,linear +"# Python3 program to find the equilibrium +# index of an array + +# Function to find the equilibrium index + + +def equilibrium(arr): + left_sum = [] + right_sum = [] + + # Iterate from 0 to len(arr) + for i in range(len(arr)): + + # If i is not 0 + if(i): + left_sum.append(left_sum[i-1]+arr[i]) + right_sum.append(right_sum[i-1]+arr[len(arr)-1-i]) + else: + left_sum.append(arr[i]) + right_sum.append(arr[len(arr)-1]) + + # Iterate from 0 to len(arr) + for i in range(len(arr)): + if(left_sum[i] == right_sum[len(arr) - 1 - i]): + return(i) + + # If no equilibrium index found,then return -1 + return -1 + + +# Driver code +if __name__ == ""__main__"": + arr = [-7, 1, 5, 2, -4, 3, 0] + + # Function call + print('First equilibrium index is ', + equilibrium(arr)) + +# This code is contributed by Lokesh Sharma",linear,linear +"# Python Function to print leaders in array + +def printLeaders(arr,size): + + for i in range(0, size): + for j in range(i+1, size): + if arr[i]<=arr[j]: + break + if j == size-1: # If loop didn't break + print (arr[i],end=' ') + +# Driver function +arr=[16, 17, 4, 3, 5, 2] +printLeaders(arr, len(arr)) + +# This code is contributed by _Devesh Agrawal__",constant,quadratic +"# Python function to print leaders in array +def printLeaders(arr, size): + + max_from_right = arr[size-1] + print (max_from_right,end=' ') + for i in range( size-2, -1, -1): + if max_from_right < arr[i]: + print (arr[i],end=' ') + max_from_right = arr[i] + +# Driver function +arr = [16, 17, 4, 3, 5, 2] +printLeaders(arr, len(arr)) + +# This code contributed by _Devesh Agrawal__",constant,linear +"# Python Function to print leaders in an array +def printLaders(arr, size): + # create stack to store leaders + sk = [] + sk.append(arr[size - 1]) + for i in range(size - 2, -1, -1): + if(arr[i] >= sk[len(sk) - 1]): + sk.append(arr[i]) + + # print stack elements + # run loop till stack is not empty + while(len(sk) != 0): + print(sk[len(sk)-1],end = ' ') + sk.pop() + +# Driver program to test above function +if __name__ == ""__main__"": + arr = [16,17,4,3,5,2] + n = len(arr) + printLaders(arr,n) + + # This code is contributed by ajaymakvana",linear,linear +"# Function to get index of ceiling of x in arr[low..high] */ +def ceilSearch(arr, low, high, x): + + # If x is smaller than or equal to first element, + # then return the first element */ + if x <= arr[low]: + return low + + # Otherwise, linearly search for ceil value */ + i = low + for i in range(high): + if arr[i] == x: + return i + + # if x lies between arr[i] and arr[i+1] including + # arr[i+1], then return arr[i+1] */ + if arr[i] < x and arr[i+1] >= x: + return i+1 + + # If we reach here then x is greater than the last element + # of the array, return -1 in this case */ + return -1 + +# Driver program to check above functions */ +arr = [1, 2, 8, 10, 10, 12, 19] +n = len(arr) +x = 3 +index = ceilSearch(arr, 0, n-1, x); + +if index == -1: + print (""Ceiling of %d doesn't exist in array ""% x) +else: + print (""ceiling of %d is %d""%(x, arr[index])) + +# This code is contributed by Shreyanshi Arun",constant,linear +"# Function to get index of ceiling of x in arr[low..high]*/ +def ceilSearch(arr, low, high, x): + + # If x is smaller than or equal to the first element, + # then return the first element */ + if x <= arr[low]: + return low + + # If x is greater than the last element, then return -1 */ + if x > arr[high]: + return -1 + + # get the index of middle element of arr[low..high]*/ + mid = (low + high)/2; # low + (high - low)/2 */ + + # If x is same as middle element, then return mid */ + if arr[mid] == x: + return mid + + # If x is greater than arr[mid], then either arr[mid + 1] + # is ceiling of x or ceiling lies in arr[mid+1...high] */ + elif arr[mid] < x: + if mid + 1 <= high and x <= arr[mid+1]: + return mid + 1 + else: + return ceilSearch(arr, mid+1, high, x) + + # If x is smaller than arr[mid], then either arr[mid] + # is ceiling of x or ceiling lies in arr[low...mid-1] */ + else: + if mid - 1 >= low and x > arr[mid-1]: + return mid + else: + return ceilSearch(arr, low, mid - 1, x) + +# Driver program to check above functions +arr = [1, 2, 8, 10, 10, 12, 19] +n = len(arr) +x = 20 +index = ceilSearch(arr, 0, n-1, x); + +if index == -1: + print (""Ceiling of %d doesn't exist in array ""% x) +else: + print (""ceiling of %d is %d""%(x, arr[index])) + +# This code is contributed by Shreyanshi Arun",constant,logn +"# Function to get index of ceiling of x in arr[low..high] +def ceilSearch(arr, low, high, x): + + # base condition if length of arr == 0 then return -1 + if (x == 0): + return -1 + + """"""this while loop function will run until + condition not break once condition break + loop will return start and ans is low + which will be next smallest greater than target + which is ceiling"""""" + while (low <= high): + mid = low + (high - low) / 2 + mid = int(mid) + if (arr[mid] == x): + return mid + elif (x < arr[mid]): + high = mid - 1 + else: + low = mid + 1 + + return low + + +"""""" step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; + if( x < mid) yes set high = mid -1; + step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; + if( x < mid) no set low = mid + 1; + step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; + if( x == mid ) yes return mid + if(x < mid ) no low = mid + 1 + step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; + check while(low < = high) + condition break and return low which will next greater of target """""" + +# Driver program to check above functions +arr = [1, 2, 8, 10, 10, 12, 19] +n = len(arr) +x = 8 +index = ceilSearch(arr, 0, n - 1, x) +if (index == -1): + print(""Ceiling of"", x, ""does not exist in an array"") +else: + print(""Ceiling of"", x, ""is"", arr[index])",constant,logn +"# Python3 program to find Majority +# element in an array + +# Function to find Majority +# element in an array + + +def findMajority(arr, n): + + maxCount = 0 + index = -1 # sentinels + for i in range(n): + + count = 0 + for j in range(n): + + if(arr[i] == arr[j]): + count += 1 + + # update maxCount if count of + # current element is greater + if(count > maxCount): + + maxCount = count + index = i + + # if maxCount is greater than n/2 + # return the corresponding element + if (maxCount > n//2): + print(arr[index]) + + else: + print(""No Majority Element"") + + +# Driver code +if __name__ == ""__main__"": + arr = [1, 1, 2, 1, 3, 5, 1] + n = len(arr) + + # Function calling + findMajority(arr, n) + +# This code is contributed +# by ChitraNayal",constant,quadratic +"# Python3 program to demonstrate insert operation in binary +# search tree. +# class for creating node +class Node(): + def __init__(self, data): + self.data = data + self.left = None + self.right = None + self.count = 1 # count of number of times data is inserted in tree + +# class for binary search tree +# it initialises tree with None root +# insert function inserts node as per BST rule +# and also checks for majority element +# if no majority element is found yet, it returns None + + +class BST(): + def __init__(self): + self.root = None + + def insert(self, data, n): + out = None + if (self.root == None): + self.root = Node(data) + else: + out = self.insertNode(self.root, data, n) + return out + + def insertNode(self, currentNode, data, n): + if (currentNode.data == data): + currentNode.count += 1 + if (currentNode.count > n//2): + return currentNode.data + else: + return None + elif (currentNode.data < data): + if (currentNode.right): + self.insertNode(currentNode.right, data, n) + else: + currentNode.right = Node(data) + elif (currentNode.data > data): + if (currentNode.left): + self.insertNode(currentNode.left, data, n) + else: + currentNode.left = Node(data) + + +# Driver code +# declaring an array +arr = [3, 2, 3] +n = len(arr) + +# declaring None tree +tree = BST() +flag = 0 +for i in range(n): + out = tree.insert(arr[i], n) + if (out != None): + print(arr[i]) + flag = 1 + break +if (flag == 0): + print(""No Majority Element"")",linear,quadratic +"# Program for finding out majority element in an array + +# Function to find the candidate for Majority + + +def findCandidate(A): + maj_index = 0 + count = 1 + for i in range(len(A)): + if A[maj_index] == A[i]: + count += 1 + else: + count -= 1 + if count == 0: + maj_index = i + count = 1 + return A[maj_index] + +# Function to check if the candidate occurs more than n/2 times + + +def isMajority(A, cand): + count = 0 + for i in range(len(A)): + if A[i] == cand: + count += 1 + if count > len(A)/2: + return True + else: + return False + +# Function to print Majority Element + + +def printMajority(A): + # Find the candidate for Majority + cand = findCandidate(A) + + # Print the candidate if it is Majority + if isMajority(A, cand) == True: + print(cand) + else: + print(""No Majority Element"") + + +# Driver code +A = [1, 3, 3, 1, 2] + +# Function call +printMajority(A)",constant,linear +"# Python3 program for finding out majority +# element in an array + +def findMajority(arr, size): + m = {} + for i in range(size): + if arr[i] in m: + m[arr[i]] += 1 + else: + m[arr[i]] = 1 + count = 0 + for key in m: + if m[key] > size / 2: + count = 1 + print(""Majority found :-"",key) + break + if(count == 0): + print(""No Majority element"") + +# Driver code +arr = [2, 2, 2, 2, 5, 5, 2, 3, 3] +n = len(arr) + +# Function calling +findMajority(arr, n) + +# This code is contributed by ankush_953",linear,linear +"# Python3 program to find Majority +# element in an array + +# Function to find Majority element +# in an array +# it returns -1 if there is no majority element +def majorityElement(arr, n) : + + # sort the array in O(nlogn) + arr.sort() + count, max_ele, temp, f = 1, -1, arr[0], 0 + for i in range(1, n) : + + # increases the count if the same element occurs + # otherwise starts counting new element + if(temp == arr[i]) : + count += 1 + else : + count = 1 + temp = arr[i] + + # sets maximum count + # and stores maximum occurred element so far + # if maximum count becomes greater than n/2 + # it breaks out setting the flag + if(max_ele < count) : + max_ele = count + ele = arr[i] + + if(max_ele > (n//2)) : + f = 1 + break + + # returns maximum occurred element + # if there is no such element, returns -1 + if f == 1 : + return ele + else : + return -1 + +# Driver code +arr = [1, 1, 2, 1, 3, 5, 1] +n = len(arr) + +# Function calling +print(majorityElement(arr, n)) + +# This code is contributed by divyeshrabadiya07",constant,nlogn +"# Hashing based Python +# program to find if +# there is a majority +# element in input array. + +# Returns true if there +# is a majority element +# in a[] +def isMajority(a): + + # Insert all elements + # in a hash table + mp = {} + + for i in a: + if i in mp: mp[i] += 1 + else: mp[i] = 1 + + # Check if frequency + # of any element is + # n/2 or more. + for x in mp: + if mp[x] >= len(a)//2: + return True + return False + +# Driver code +a = [ 2, 3, 9, 2, 2 ] + +print(""Yes"" if isMajority(a) else ""No"") + +#This code is contributed by Ansu Kumari",linear,linear +"# A python3 program to find a peak +# element using divide and conquer + +# A binary search based function +# that returns index of a peak element + + +def findPeakUtil(arr, low, high, n): + + # Find index of middle element + # low + (high - low) / 2 + mid = low + (high - low)/2 + mid = int(mid) + + # Compare middle element with its + # neighbours (if neighbours exist) + if ((mid == 0 or arr[mid - 1] <= arr[mid]) and + (mid == n - 1 or arr[mid + 1] <= arr[mid])): + return mid + + + # If middle element is not peak and + # its left neighbour is greater + # than it, then left half must + # have a peak element + elif (mid > 0 and arr[mid - 1] > arr[mid]): + return findPeakUtil(arr, low, (mid - 1), n) + + # If middle element is not peak and + # its right neighbour is greater + # than it, then right half must + # have a peak element + else: + return findPeakUtil(arr, (mid + 1), high, n) + + +# A wrapper over recursive +# function findPeakUtil() +def findPeak(arr, n): + + return findPeakUtil(arr, 0, n - 1, n) + + +# Driver code +arr = [1, 3, 20, 4, 1, 0] +n = len(arr) +print(""Index of a peak point is"", findPeak(arr, n)) + +# This code is contributed by +# Smitha Dinesh Semwal",logn,logn +"# A Python program to find a peak element +# using divide and conquer + +# A binary search based function +# that returns index of a peak element +def findPeak(arr, n): + + l = 0 + r = n-1 + + while(l <= r): + + # finding mid by binary right shifting. + mid = (l + r) >> 1 + + # first case if mid is the answer + if((mid == 0 or arr[mid - 1] <= arr[mid]) and (mid == n - 1 or arr[mid + 1] <= arr[mid])): + break + + # move the right pointer + if(mid > 0 and arr[mid - 1] > arr[mid]): + r = mid - 1 + + # move the left pointer + else: + l = mid + 1 + + return mid + + +# Driver Code +arr = [1, 3, 20, 4, 1, 0] +n = len(arr) +print(f""Index of a peak point is {findPeak(arr, n)}"") + +# This code is contributed by Rajdeep Mallick (rajdeep999)",constant,logn +"# Python3 program to Find the two +# repeating elements in a given array + + +def printRepeating(arr, size): + + print(""Repeating elements are"", end=' ') + for i in range(0, size-1): + for j in range(i + 1, size): + if arr[i] == arr[j]: + print(arr[i], end=' ') + + +# Driver code +arr = [4, 2, 4, 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size) + +# This code is contributed by Smitha Dinesh Semwal",constant,quadratic +"# Python3 code for Find the two repeating +# elements in a given array + + +def printRepeating(arr, size): + count = [0] * size + print("" Repeating elements are "", end="""") + for i in range(0, size): + if(count[arr[i]] == 1): + print(arr[i], end="" "") + else: + count[arr[i]] = count[arr[i]] + 1 + + +# Driver code +arr = [4, 2, 4, 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size) + + +# This code is contributed by Nikita Tiwari.",linear,linear +"# Python3 code for Find the two repeating +# elements in a given array +import math + + +def printRepeating(arr, size): + + # S is for sum of elements in arr[] + S = 0 + + # P is for product of elements in arr[] + P = 1 + + n = size - 2 + + # Calculate Sum and Product + # of all elements in arr[] + for i in range(0, size): + S = S + arr[i] + P = P * arr[i] + + # S is x + y now + S = S - n * (n + 1) // 2 + + # P is x*y now + P = P // fact(n) + + # D is x - y now + D = math.sqrt(S * S - 4 * P) + + x = (D + S) // 2 + y = (S - D) // 2 + + print(""Repeating elements are "", + (int)(x), "" "", (int)(y)) + + +def fact(n): + if(n == 0): + return 1 + else: + return(n * fact(n - 1)) + + +# Driver code +arr = [4, 2, 4, 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size) + + +# This code is contributed by Nikita Tiwari.",constant,linear +"# Python3 code to Find the +# two repeating elements +# in a given array + + +def printRepeating(arr, size): + + # Will hold xor + # of all elements + xor = arr[0] + n = size - 2 + x = 0 + y = 0 + + # Get the xor of all + # elements in arr[] + # and 1, 2 .. n + for i in range(1, size): + xor ^= arr[i] + for i in range(1, n + 1): + xor ^= i + + # Get the rightmost set + # bit in set_bit_no + set_bit_no = xor & ~(xor-1) + + # Now divide elements in two + # sets by comparing rightmost + # set bit of xor with bit at + # same position in each element. + for i in range(0, size): + + if(arr[i] & set_bit_no): + + # XOR of first + # set in arr[] + x = x ^ arr[i] + else: + + # XOR of second + # set in arr[] + y = y ^ arr[i] + + for i in range(1, n + 1): + + if(i & set_bit_no): + + # XOR of first set + # in arr[] and + # 1, 2, ...n + x = x ^ i + else: + + # XOR of second set + # in arr[] and + # 1, 2, ...n + y = y ^ i + + print(""Repeating elements are"", y, x) + + +# Driver code +arr = [4, 2, 4, + 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size) + +# This code is contributed +# by Smitha",constant,linear +"# Python3 code for Find the two repeating +# elements in a given array + + +def printRepeating(arr, size): + + print(""Repeating elements are"", end="" "") + + for i in range(0, size): + + if(arr[abs(arr[i])] > 0): + arr[abs(arr[i])] = (-1) * arr[abs(arr[i])] + else: + print(abs(arr[i]), end="" "") + + +# Driver code +arr = [4, 2, 4, 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size) + + +# This code is contributed by Nikita Tiwari.",constant,linear +"# Python program for the above approach +def twoRepeated(arr, N): + m = N - 1 + for i in range(N): + arr[arr[i] % m - 1] += m + if ((arr[arr[i] % m - 1] // m) == 2): + print(arr[i] % m, end="" "") + + +# Driver Code +arr = [4, 2, 4, 5, 2, 3, 1] +n = len(arr) +print(""Repeating elements are "", end="""") +twoRepeated(arr, n) + +# This code is contributed by Shubham Singh",constant,linear +"# Python3 program to find the two repeating +# elements in a given array + + +def printRepeating(arr, size): + + s = set() + print(""Repeating elements are "", end="""") + + for i in range(size): + if (len(s) and arr[i] in s): + print(arr[i], end="" "") + + s.add(arr[i]) + + +# Driver code +arr = [4, 2, 4, 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size) + +# This code is contributed by Shubham Singh",linear,linear +"# A simple 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(0,n): + currentSum = arr[i] + if(currentSum == sum): + print(""Sum found at indexes"",i) + return + else: + # Try all subarrays starting with 'i' + for j in range(i+1,n): + currentSum += arr[i] + if(currentSum == 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 + subArraySum(arr, n, sum) + + # This code is contributed by ajaymakvana",constant,quadratic +"# An efficient 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_): + + # Initialize currentSum as + # value of first element + # and starting point as 0 + currentSum = arr[0] + start = 0 + + # Add elements one by + # one to currentSum and + # if the currentSum exceeds + # the sum, then remove + # starting element + i = 1 + while i <= n: + + # If currentSum exceeds + # the sum, then remove + # the starting elements + while currentSum > sum_ and start < i-1: + + currentSum = currentSum - arr[start] + start += 1 + + # If currentSum becomes + # equal to sum, then + # return true + if currentSum == sum_: + print(""Sum found between indexes % d and % d"" % (start, i-1)) + + return 1 + + # Add this element + # to currentSum + if i < n: + currentSum = currentSum + arr[i] + i += 1 + + # If we reach here, + # then no subarray + print(""No subarray found"") + return 0 + + +# Driver program +if __name__ == '__main__': + arr = [15, 2, 4, 8, 9, 5, 10, 23] + n = len(arr) + sum_ = 23 + +subArraySum(arr, n, sum_) + +# This code is Contributed by shreyanshi_arun.",constant,linear +"# Python3 implementation of smallest +# difference triplet + +# Function to find maximum number +def maximum(a, b, c): + return max(max(a, b), c) + +# Function to find minimum number +def minimum(a, b, c): + return min(min(a, b), c) + +# Finds and prints the smallest +# Difference Triplet +def smallestDifferenceTriplet(arr1, arr2, arr3, n): + + # sorting all the three arrays + arr1.sort() + arr2.sort() + arr3.sort() + + # To store resultant three numbers + res_min = 0; res_max = 0; res_mid = 0 + + # pointers to arr1, arr2, + # arr3 respectively + i = 0; j = 0; k = 0 + + # Loop until one array reaches to its end + # Find the smallest difference. + diff = 2147483647 + while (i < n and j < n and k < n): + + sum = arr1[i] + arr2[j] + arr3[k] + + # maximum number + max = maximum(arr1[i], arr2[j], arr3[k]) + + # Find minimum and increment its index. + min = minimum(arr1[i], arr2[j], arr3[k]) + if (min == arr1[i]): + i += 1 + else if (min == arr2[j]): + j += 1 + else: + k += 1 + + # Comparing new difference with the + # previous one and updating accordingly + if (diff > (max - min)): + + diff = max - min + res_max = max + res_mid = sum - (max + min) + res_min = min + + # Print result + print(res_max, "","", res_mid, "","", res_min) + +# Driver code +arr1 = [5, 2, 8] +arr2 = [10, 7, 12] +arr3 = [9, 14, 6] +n = len(arr1) +smallestDifferenceTriplet(arr1, arr2, arr3, n) + +# This code is contributed by Anant Agarwal.",constant,nlogn +"# A simple Python 3 program +# to find three elements whose +# sum is equal to zero + +# Prints all triplets in +# arr[] with 0 sum + + +def findTriplets(arr, n): + + found = False + for i in range(0, n-2): + + for j in range(i+1, n-1): + + for k in range(j+1, n): + + if (arr[i] + arr[j] + arr[k] == 0): + print(arr[i], arr[j], arr[k]) + found = True + + # If no triplet with 0 sum + # found in array + if (found == False): + print("" not exist "") + + +# Driver code +arr = [0, -1, 2, -3, 1] +n = len(arr) +findTriplets(arr, n) + +# This code is contributed by Smitha Dinesh Semwal",constant,cubic +"# Python3 program to find triplets +# in a given array whose sum is zero + +# function to print triplets with 0 sum + + +def findTriplets(arr, n): + found = False + for i in range(n - 1): + + # Find all pairs with sum + # equals to ""-arr[i]"" + s = set() + for j in range(i + 1, n): + x = -(arr[i] + arr[j]) + if x in s: + print(x, arr[i], arr[j]) + found = True + else: + s.add(arr[j]) + if found == False: + print(""No Triplet Found"") + + +# Driver Code +arr = [0, -1, 2, -3, 1] +n = len(arr) +findTriplets(arr, n) + +# This code is contributed by Shrikant13",linear,quadratic +"# python program to find triplets in a given +# array whose sum is zero + +# function to print triplets with 0 sum + + +def findTriplets(arr, n): + + found = False + + # sort array elements + arr.sort() + + for i in range(0, n-1): + + # initialize left and right + l = i + 1 + r = n - 1 + x = arr[i] + while (l < r): + + if (x + arr[l] + arr[r] == 0): + # print elements if it's sum is zero + print(x, arr[l], arr[r]) + l += 1 + r -= 1 + found = True + + # If sum of three elements is less + # than zero then increment in left + elif (x + arr[l] + arr[r] < 0): + l += 1 + + # if sum is greater than zero then + # decrement in right side + else: + r -= 1 + + if (found == False): + print("" No Triplet Found"") + + +# Driven source +arr = [0, -1, 2, -3, 1] +n = len(arr) +findTriplets(arr, n) + +# This code is contributed by Smitha Dinesh Semwal",constant,quadratic +"# Python program to rotate a matrix + +# Function to rotate a matrix +def rotateMatrix(mat): + + if not len(mat): + return + + """""" + top : starting row index + bottom : ending row index + left : starting column index + right : ending column index + """""" + + top = 0 + bottom = len(mat)-1 + + left = 0 + right = len(mat[0])-1 + + while left < right and top < bottom: + + # Store the first element of next row, + # this element will replace first element of + # current row + prev = mat[top+1][left] + + # Move elements of top row one step right + for i in range(left, right+1): + curr = mat[top][i] + mat[top][i] = prev + prev = curr + + top += 1 + + # Move elements of rightmost column one step downwards + for i in range(top, bottom+1): + curr = mat[i][right] + mat[i][right] = prev + prev = curr + + right -= 1 + + # Move elements of bottom row one step left + for i in range(right, left-1, -1): + curr = mat[bottom][i] + mat[bottom][i] = prev + prev = curr + + bottom -= 1 + + # Move elements of leftmost column one step upwards + for i in range(bottom, top-1, -1): + curr = mat[i][left] + mat[i][left] = prev + prev = curr + + left += 1 + + return mat + +# Utility Function +def printMatrix(mat): + for row in mat: + print row + + +# Test case 1 +matrix =[ + [1, 2, 3, 4 ], + [5, 6, 7, 8 ], + [9, 10, 11, 12 ], + [13, 14, 15, 16 ] + ] +# Test case 2 +"""""" +matrix =[ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ] +"""""" + +matrix = rotateMatrix(matrix) +# Print modified matrix +printMatrix(matrix)",constant,quadratic +"# Python3 program to rotate a matrix by 90 degrees +N = 4 + +# An Inplace function to rotate +# N x N matrix by 90 degrees in +# anti-clockwise direction + + +def rotateMatrix(mat): + + # Consider all squares one by one + for x in range(0, int(N / 2)): + + # Consider elements in group + # of 4 in current square + for y in range(x, N-x-1): + + # store current cell in temp variable + temp = mat[x][y] + + # move values from right to top + mat[x][y] = mat[y][N-1-x] + + # move values from bottom to right + mat[y][N-1-x] = mat[N-1-x][N-1-y] + + # move values from left to bottom + mat[N-1-x][N-1-y] = mat[N-1-y][x] + + # assign temp to left + mat[N-1-y][x] = temp + + +# Function to print the matrix +def displayMatrix(mat): + + for i in range(0, N): + + for j in range(0, N): + + print(mat[i][j], end=' ') + print("""") + + +# Driver Code +if __name__ == ""__main__"": + mat = [[0 for x in range(N)] for y in range(N)] + + mat = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + + # Function call + rotateMatrix(mat) + + # Print rotated matrix + displayMatrix(mat) + + +# This code is contributed by saloni1297",constant,quadratic +"# Python program to rotate +# a matrix by 90 degrees + + +def rotateMatrix(mat): + + # reversing the matrix + for i in range(len(mat)): + mat[i].reverse() + + # make transpose of the matrix + for i in range(len(mat)): + for j in range(i, len(mat)): + + # swapping mat[i][j] and mat[j][i] + mat[i][j], mat[j][i] = mat[j][i], mat[i][j] + + +# Function to print the matrix +def displayMatrix(mat): + + for i in range(0, len(mat)): + for j in range(0, len(mat)): + print(mat[i][j], end=' ') + print() + + +# Driver code +if __name__ == ""__main__"": + mat = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + + # Function call + rotateMatrix(mat) + + # Print rotated matrix + displayMatrix(mat) + +# This code is contributed by shivambhagat02(CC).",constant,quadratic +"# Python3 program to +# rotate a matrix by +# 180 degrees +N = 3; + +# Function to Rotate +# the matrix by 180 degree +def rotateMatrix(mat): + + # Simply print from + # last cell to first cell. + i = N - 1; + while(i >= 0): + j = N - 1; + while(j >= 0): + print(mat[i][j], end = "" ""); + j = j - 1; + print(); + i = i - 1; + +# Driven code +mat = [[1, 2, 3], + [ 4, 5, 6 ], + [ 7, 8, 9 ]]; +rotateMatrix(mat); + +# This code is contributed +# by mits",constant,quadratic +"# Python3 program for left rotation of matrix by 180 + +R = 4 +C = 4 + +# Function to rotate the matrix by 180 degree +def reverseColumns(arr): + for i in range(C): + j = 0 + k = C-1 + while j < k: + t = arr[j][i] + arr[j][i] = arr[k][i] + arr[k][i] = t + j += 1 + k -= 1 + +# Function for transpose of matrix +def transpose(arr): + for i in range(R): + for j in range(i, C): + t = arr[i][j] + arr[i][j] = arr[j][i] + arr[j][i] = t + +# Function for display the matrix +def printMatrix(arr): + for i in range(R): + for j in range(C): + print(arr[i][j], end = "" ""); + print(); + +# Function to anticlockwise rotate matrix +# by 180 degree +def rotate180(arr): + transpose(arr); + reverseColumns(arr); + transpose(arr); + reverseColumns(arr); + +# Driven code +arr = [ [ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ], + [9, 10, 11, 12 ], + [13, 14, 15, 16 ] ]; +rotate180(arr); +printMatrix(arr);",constant,quadratic +"# Reverse Row at specified index in the matrix +def reverseRow(data, index): + + cols = len(data[index]) + for i in range(cols // 2): + temp = data[index][i] + data[index][i] = data[index][cols - i - 1] + data[index][cols - i - 1] = temp + + return data + +# Print Matrix data +def printMatrix(data): + + for i in range(len(data)): + for j in range(len(data[0])): + print(data[i][j], end = ' ') + + print() + +# Rotate Matrix by 180 degrees +def rotateMatrix(data): + + rows = len(data) + cols = len(data[0]) + + if (rows % 2): + + # If N is odd reverse the middle + # row in the matrix + data = reverseRow(data, len(data) // 2) + + # Swap the value of matrix [i][j] with + # [rows - i - 1][cols - j - 1] for half + # the rows size. + for i in range(rows // 2): + for j in range(cols): + temp = data[i][j] + data[i][j] = data[rows - i - 1][cols - j - 1] + data[rows - i - 1][cols - j - 1] = temp + + return data + +# Driver Code +data = [ [ 1, 2, 3, 4, 5 ], + [ 6, 7, 8, 9, 10 ], + [ 11, 12, 13, 14, 15 ], + [ 16, 17, 18, 19, 20 ], + [ 21, 22, 23, 24, 25 ] ] + +# Rotate Matrix +data = rotateMatrix(data) + +# Print Matrix +printMatrix(data) + +# This code is contributed by rohitsingh07052",constant,quadratic +"# Python3 program to check if all rows +# of a matrix are rotations of each other + +MAX = 1000 + +# Returns true if all rows of mat[0..n-1][0..n-1] +# are rotations of each other. +def isPermutedMatrix(mat, n) : + + # Creating a string that contains + # elements of first row. + str_cat = """" + for i in range(n) : + str_cat = str_cat + ""-"" + str(mat[0][i]) + + # Concatenating the string with itself + # so that substring search operations + # can be performed on this + str_cat = str_cat + str_cat + + # Start traversing remaining rows + for i in range(1, n) : + + # Store the matrix into vector + # in the form of strings + curr_str = """" + + for j in range(n) : + curr_str = curr_str + ""-"" + str(mat[i][j]) + + # Check if the current string is present + # in the concatenated string or not + if (str_cat.find(curr_str)) : + return True + + return False + +# Driver code +if __name__ == ""__main__"" : + n = 4 + mat = [[1, 2, 3, 4], + [4, 1, 2, 3], + [3, 4, 1, 2], + [2, 3, 4, 1]] + + if (isPermutedMatrix(mat, n)): + print(""Yes"") + else : + print(""No"") + +# This code is contributed by Ryuga",linear,cubic +"# Python3 implementation to sort +# the given matrix + +SIZE = 10 + +# Function to sort the given matrix +def sortMat(mat, n) : + + # Temporary matrix of size n^2 + temp = [0] * (n * n) + k = 0 + + # Copy the elements of matrix + # one by one into temp[] + for i in range(0, n) : + + for j in range(0, n) : + + temp[k] = mat[i][j] + k += 1 + + # sort temp[] + temp.sort() + + # copy the elements of temp[] + # one by one in mat[][] + k = 0 + + for i in range(0, n) : + + for j in range(0, n) : + mat[i][j] = temp[k] + k += 1 + + +# Function to print the given matrix +def printMat(mat, n) : + + for i in range(0, n) : + + for j in range( 0, n ) : + + print(mat[i][j] , end = "" "") + + print() + + +# Driver program to test above +mat = [ [ 5, 4, 7 ], + [ 1, 3, 8 ], + [ 2, 9, 6 ] ] +n = 3 + +print( ""Original Matrix:"") +printMat(mat, n) + +sortMat(mat, n) + +print(""\nMatrix After Sorting:"") +printMat(mat, n) + + +# This code is contributed by Nikita Tiwari.",quadratic,quadratic +"# Python program to find median of matrix +# sorted row wise + +from bisect import bisect_right as upper_bound + +MAX = 100; + +# Function to find median in the matrix +def binaryMedian(m, r, d): + mi = m[0][0] + mx = 0 + for i in range(r): + if m[i][0] < mi: + mi = m[i][0] + if m[i][d-1] > mx : + mx = m[i][d-1] + + desired = (r * d + 1) // 2 + + while (mi < mx): + mid = mi + (mx - mi) // 2 + place = [0]; + + # Find count of elements smaller than or equal to mid + for i in range(r): + j = upper_bound(m[i], mid) + place[0] = place[0] + j + if place[0] < desired: + mi = mid + 1 + else: + mx = mid + print (""Median is"", mi) + return + +# Driver code +r, d = 3, 3 + +m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]] +binaryMedian(m, r, d) + +# This code is contributed by Sachin BIsht",constant,nlogn +"# Recursive code for Matrix Multiplication +MAX = 100 +i = 0 +j = 0 +k = 0 + +def multiplyMatrixRec(row1, col1, A, + row2, col2, B, C): + + # Note that below variables are static + # i and j are used to know current cell of + # result matrix C[][]. k is used to know + # current column number of A[][] and row + # number of B[][] to be multiplied + global i + global j + global k + + # If all rows traversed. + if (i >= row1): + return + + # If i < row1 + if (j < col2): + if (k < col1): + C[i][j] += A[i][k] * B[k][j] + k += 1 + multiplyMatrixRec(row1, col1, A, + row2, col2,B, C) + + k = 0 + j += 1 + multiplyMatrixRec(row1, col1, A, + row2, col2, B, C) + + j = 0 + i += 1 + multiplyMatrixRec(row1, col1, A, + row2, col2, B, C) + +# Function to multiply two matrices +# A[][] and B[][] +def multiplyMatrix(row1, col1, A, row2, col2, B): + if (row2 != col1): + print(""Not Possible"") + return + + C = [[0 for i in range(MAX)] + for i in range(MAX)] + multiplyMatrixRec(row1, col1, A, + row2, col2, B, C) + + # Print the result + for i in range(row1): + for j in range(col2): + print( C[i][j], end = "" "") + print() + +# Driver Code +A = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] +B = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + +row1 = 3 +col1 = 3 +row2 = 3 +col2 = 3 +multiplyMatrix(row1, col1, A, row2, col2, B) + +# This code is contributed by sahilshelangia",logn,quadratic +"# Python3 program to print Lower +# triangular and Upper triangular +# matrix of an array + +# Function to form lower triangular +# matrix +def lower(matrix, row, col): + + + for i in range(0, row): + + for j in range(0, col): + + if (i < j): + + print(""0"", end = "" ""); + + else: + print(matrix[i][j], + end = "" "" ); + + print("" ""); + +# Function to form upper triangular matrix +def upper(matrix, row, col): + + for i in range(0, row): + + for j in range(0, col): + + if (i > j): + print(""0"", end = "" ""); + + else: + print(matrix[i][j], + end = "" "" ); + + print("" ""); + +# Driver Code +matrix = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]; +row = 3; +col = 3; + +print(""Lower triangular matrix: ""); +lower(matrix, row, col); + +print(""Upper triangular matrix: ""); +upper(matrix, row, col); + +# This code is contributed by +# Shivi_Aggarwal",constant,quadratic +"# python3 program for the above approach + + +def spiralOrder(matrix): + ans = [] + + if (len(matrix) == 0): + return ans + + m = len(matrix) + n = len(matrix[0]) + seen = [[0 for i in range(n)] for j in range(m)] + dr = [0, 1, 0, -1] + dc = [1, 0, -1, 0] + x = 0 + y = 0 + di = 0 + + # Iterate from 0 to R * C - 1 + for i in range(m * n): + ans.append(matrix[x][y]) + seen[x][y] = True + cr = x + dr[di] + cc = y + dc[di] + + if (0 <= cr and cr < m and 0 <= cc and cc < n and not(seen[cr][cc])): + x = cr + y = cc + else: + di = (di + 1) % 4 + x += dr[di] + y += dc[di] + return ans + + +# Driver code +if __name__ == ""__main__"": + a = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + + # Function call + for x in spiralOrder(a): + print(x, end="" "") + print()",linear,linear +"# Python3 program to print +# given matrix in spiral form + + +def spiralPrint(m, n, a): + k = 0 + l = 0 + + ''' k - starting row index + m - ending row index + l - starting column index + n - ending column index + i - iterator ''' + + while (k < m and l < n): + + # Print the first row from + # the remaining rows + for i in range(l, n): + print(a[k][i], end="" "") + + k += 1 + + # Print the last column from + # the remaining columns + for i in range(k, m): + print(a[i][n - 1], end="" "") + + n -= 1 + + # Print the last row from + # the remaining rows + if (k < m): + + for i in range(n - 1, (l - 1), -1): + print(a[m - 1][i], end="" "") + + m -= 1 + + # Print the first column from + # the remaining columns + if (l < n): + for i in range(m - 1, k - 1, -1): + print(a[i][l], end="" "") + + l += 1 + + +# Driver Code +a = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + +R = 4 +C = 4 + +# Function Call +spiralPrint(R, C, a) + +# This code is contributed by Nikita Tiwari.",constant,quadratic +"# Python3 program for the above approach + +# Function for printing matrix in spiral +# form i, j: Start index of matrix, row +# and column respectively m, n: End index +# of matrix row and column respectively + + +def printdata(arr, i, j, m, n): + + # If i or j lies outside the matrix + if (i >= m or j >= n): + return + + # Print First Row + for p in range(i, n): + print(arr[i][p], end="" "") + + # Print Last Column + for p in range(i + 1, m): + print(arr[p][n - 1], end="" "") + + # Print Last Row, if Last and + # First Row are not same + if ((m - 1) != i): + for p in range(n - 2, j - 1, -1): + print(arr[m - 1][p], end="" "") + + # Print First Column, if Last and + # First Column are not same + if ((n - 1) != j): + for p in range(m - 2, i, -1): + print(arr[p][j], end="" "") + + printdata(arr, i + 1, j + 1, m - 1, n - 1) + + +# Driver code +if __name__ == ""__main__"": + R = 4 + C = 4 + arr = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + + # Function Call + printdata(arr, 0, 0, R, C) + +# This code is contributed by avsadityavardhan",constant,quadratic +"# Python3 program for the above approach + +R = 4 +C = 4 + + +def isInBounds(i, j): + global R + global C + if (i < 0 or i >= R or j < 0 or j >= C): + return False + return True + +# Check if the position is blocked + + +def isBlocked(matrix, i, j): + if (not isInBounds(i, j)): + return True + if (matrix[i][j] == -1): + return True + + return False + +# DFS code to traverse spirally + + +def spirallyDFSTravserse(matrix, i, j, Dir, res): + if (isBlocked(matrix, i, j)): + return + + allBlocked = True + for k in range(-1, 2, 2): + allBlocked = allBlocked and isBlocked( + matrix, k + i, j) and isBlocked(matrix, i, j + k) + + res.append(matrix[i][j]) + matrix[i][j] = -1 + if (allBlocked): + return + + # dir: 0 - right, 1 - down, 2 - left, 3 - up + nxt_i = i + nxt_j = j + nxt_dir = Dir + if (Dir == 0): + if (not isBlocked(matrix, i, j + 1)): + nxt_j += 1 + else: + nxt_dir = 1 + nxt_i += 1 + + elif(Dir == 1): + if (not isBlocked(matrix, i + 1, j)): + nxt_i += 1 + else: + nxt_dir = 2 + nxt_j -= 1 + + elif(Dir == 2): + if (not isBlocked(matrix, i, j - 1)): + nxt_j -= 1 + else: + nxt_dir = 3 + nxt_i -= 1 + + elif(Dir == 3): + if (not isBlocked(matrix, i - 1, j)): + nxt_i -= 1 + else: + nxt_dir = 0 + nxt_j += 1 + + spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res) + +# To traverse spirally + + +def spirallyTraverse(matrix): + res = [] + spirallyDFSTravserse(matrix, 0, 0, 0, res) + return res + + +# Driver code +if __name__ == ""__main__"": + a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] + + # Function Call + res = spirallyTraverse(a) + print(*res) + +# This code is contributed by rag2127",constant,quadratic +"# Python program to find unique element in matrix + +# function that calculate unique element +def unique(mat, r, c) -> int: + + # declare map for hashing + mp = {} + for i in range(r): + for j in range(c): + + # increase freq of mat[i][j] in map + if mat[i][j] not in mp: + mp[mat[i][j]] = 1 + else: + mp[mat[i][j]] += 1 + flag = False + + # print unique element + for p in mp: + if mp[p] == 1: + print(p, end="" "") + flag = True + if flag == False: + print(""No unique element in the matrix"") + + +# Driver program +if __name__ == ""__main__"": + mat = [[1, 2, 3, 20], [5, 6, 20, 25], [1, 3, 5, 6], [6, 7, 8, 15]] + + # function that calculate unique element + unique(mat, 4, 4) + + # This code is contributed by ajaymakvana",quadratic,quadratic +"# Python3 Program to swap diagonal of a matrix + +# size of square matrix +N = 3 + +# Function to swap diagonal of matrix +def swapDiagonal(matrix): + + for i in range(N): + + matrix[i][i], matrix[i][N-i-1] = \ + matrix[i][N-i-1], matrix[i][i] + + +# Driver Code +matrix = [[0, 1, 2], + [3, 4, 5], + [6, 7, 8]] + +# swap diagonals of matrix +swapDiagonal(matrix); + +# Displaying modified matrix +for i in range(N): + for j in range(N): + print(matrix[i][j], end = ' ') + print()",constant,quadratic +"# Python 3 program for finding max path in matrix +# To calculate max path in matrix + +def findMaxPath(mat): + + for i in range(1, N): + + res = -1 + for j in range(M): + + # When all paths are possible + if (j > 0 and j < M - 1): + mat[i][j] += max(mat[i - 1][j], + max(mat[i - 1][j - 1], + mat[i - 1][j + 1])) + + # When diagonal right is not possible + else if (j > 0): + mat[i][j] += max(mat[i - 1][j], + mat[i - 1][j - 1]) + + # When diagonal left is not possible + else if (j < M - 1): + mat[i][j] += max(mat[i - 1][j], + mat[i - 1][j + 1]) + + # Store max path sum + res = max(mat[i][j], res) + return res + +# Driver program to check findMaxPath +N=4 +M=6 +mat = ([[ 10, 10, 2, 0, 20, 4 ], + [ 1, 0, 0, 30, 2, 5 ], + [ 0, 10, 4, 0, 2, 0 ], + [ 1, 0, 2, 20, 0, 4 ]]) + +print(findMaxPath(mat)) + +# This code is contributed by Azkia Anam.",constant,quadratic +"# Python3 code to move matrix elements +# in given direction with add +# element with same value +MAX = 50 + +# Function to shift the matrix +# in the given direction +def moveMatrix(d, n, a): + + # For right shift move. + if (d[0] == 'r'): + + # For each row from + # top to bottom + for i in range(n): + v = [] + w = [] + + # For each element of + # row from right to left + for j in range(n - 1, -1, -1): + + # if not 0 + if (a[i][j]): + v.append(a[i][j]) + + # For each temporary array + j = 0 + while (j < len(v)): + + # If two element have same + # value at consecutive position. + if (j < len(v) - 1 and + v[j] == v[j + 1]): + + # Insert only one element + # as sum of two same element. + w.append(2 * v[j]) + j += 1 + + else: + w.append(v[j]) + + j += 1 + + # Filling the each row element to 0. + for j in range(n): + a[i][j] = 0 + + j = n - 1 + + # Copying the temporary + # array to the current row. + for it in w: + a[i][j] = it + j -= 1 + + # For left shift move + elif (d[0] == 'l'): + + # For each row + for i in range(n): + v = [] + w = [] + + # For each element of the + # row from left to right + for j in range(n): + + # If not 0 + if (a[i][j]): + v.append(a[i][j]) + + # For each temporary array + j = 0 + while(j < len(v)): + + # If two element have same + # value at consecutive position. + if (j < len(v) - 1 and + v[j] == v[j + 1]): + + # Insert only one element + # as sum of two same element. + w.append(2 * v[j]) + j += 1 + + else: + w.append(v[j]) + + j += 1 + + # Filling the each row element to 0. + for j in range(n): + a[i][j] = 0 + + j = 0 + + for it in w: + a[i][j] = it + j += 1 + + # For down shift move. + elif (d[0] == 'd'): + + # For each column + for i in range(n): + v = [] + w = [] + + # For each element of + # column from bottom to top + for j in range(n - 1, -1, -1): + + # If not 0 + if (a[j][i]): + v.append(a[j][i]) + + # For each temporary array + j = 0 + while(j < len(v)): + + # If two element have same + # value at consecutive position. + if (j k) : + + while(start <= endval and p > k) : + + p = p // arr[start] + start += 1 + + if(p == k) : + + # Count number of succeeding ones. + countOnes = 0 + while endval + 1 < n and arr[endval + 1] == 1 : + + countOnes += 1 + endval += 1 + + # Update result by adding both new subarray + # and effect of succeeding ones. + res += (countOnes + 1) + + # Update sliding window and result according + # to change in sliding window. Here preceding + # 1s have same effect on subarray as succeeding + # 1s, so simply add. + while(start <= endval and arr[start] == 1 and k!=1) : + + res += (countOnes + 1) + start += 1 + + # Move start to correct position to find new + # subarray and update product accordingly. + p = p // arr[start] + start += 1 + + endval += 1 + + return res + +arr1 = [ 2, 1, 1, 1, 3, 1, 1, 4 ] +n1 = len(arr1) +k = 1 + +if(k != 1) : + print(findSubarrayCount(arr1, n1, k)) +else : + print(countOne(arr1, n1)) + +arr2 = [ 2, 1, 1, 1, 4, 5] +n2 = len(arr2) +k = 4 + +if(k != 1) : + print(findSubarrayCount(arr2, n2, k)) +else : + print(countOne(arr2, n2)) + + # This code is contributed by divyesh072019",constant,linear +"# The function checks if the array elements +# are consecutive. If elements are consecutive, +# then returns true, else returns false +def areConsecutive(arr, n): + + # Sort the array + arr.sort() + # checking the adjacent elements + for i in range (1,n): + if(arr[i]!=arr[i-1]+1): + return False; + + return True; + +# Driver Code +arr = [5, 4, 2, 3, 1, 6] +n = len(arr) +if(areConsecutive(arr, n) == True): + print(""Array elements are consecutive "") +else: + print(""Array elements are not consecutive "") + +# This code is contributed by Aarti_Rathi",constant,nlogn +"# Helper functions to get Minimum and +# Maximum in an array + +# The function checks if the array elements +# are consecutive. If elements are consecutive, +# then returns true, else returns false +def areConsecutive(arr, n): + + if ( n < 1 ): + return False + + # 1) Get the Minimum element in array */ + Min = min(arr) + + # 2) Get the Maximum element in array */ + Max = max(arr) + + # 3) Max - Min + 1 is equal to n, + # then only check all elements */ + if (Max - Min + 1 == n): + + # Create a temp array to hold visited + # flag of all elements. Note that, calloc + # is used here so that all values are + # initialized as false + visited = [False for i in range(n)] + + for i in range(n): + + # If we see an element again, + # then return false */ + if (visited[arr[i] - Min] != False): + return False + + # If visited first time, then mark + # the element as visited */ + visited[arr[i] - Min] = True + + # If all elements occur once, + # then return true */ + return True + + return False # if (Max - Min + 1 != n) + +# Driver Code +arr = [5, 4, 2, 3, 1, 6] +n = len(arr) +if(areConsecutive(arr, n) == True): + print(""Array elements are consecutive "") +else: + print(""Array elements are not consecutive "") + +# This code is contributed by mohit kumar",linear,linear +"# Helper functions to get minimum and +# maximum in an array + +# The function checks if the array +# elements are consecutive. If elements +# are consecutive, then returns true, +# else returns false +def areConsecutive(arr, n): + + if ( n < 1 ): + return False + + # 1) Get the minimum element in array + min = getMin(arr, n) + + # 2) Get the maximum element in array + max = getMax(arr, n) + + # 3) max - min + 1 is equal to n + # then only check all elements + if (max - min + 1 == n): + + for i in range(n): + + if (arr[i] < 0): + j = -arr[i] - min + else: + j = arr[i] - min + + # if the value at index j is negative + # then there is repetition + if (arr[j] > 0): + arr[j] = -arr[j] + else: + return False + + # If we do not see a negative value + # then all elements are distinct + return True + + return False # if (max - min + 1 != n) + +# UTILITY FUNCTIONS +def getMin(arr, n): + + min = arr[0] + for i in range(1, n): + if (arr[i] < min): + min = arr[i] + return min + +def getMax(arr, n): + max = arr[0] + for i in range(1, n): + if (arr[i] > max): + max = arr[i] + return max + +# Driver Code +if __name__ == ""__main__"": + + arr = [1, 4, 5, 3, 2, 6] + n = len(arr) + if(areConsecutive(arr, n) == True): + print("" Array elements are consecutive "") + else: + print("" Array elements are not consecutive "") + +# This code is contributed by ita_c",constant,linear +"# Function to Check if array +# elements are consecutive +def areConsecutive(arr, n): + min_ele = arr.index(min(arr)) + num = 0 + for i in range(0, n): + num ^= arr[min_ele] ^ arr[i] + arr[min_ele] += 1 + if num == 0: + return True + return False + +# Driver program to test above +# functions +if __name__ == ""__main__"": + arr = [1, 4, 5, 3, 2, 6] + n = len(arr) + if areConsecutive(arr, n) == True: + print("" Array elements are consecutive "", end=' ') + else: + print("" Array elements are not consecutive "", end=' ') + +# This code is contributed by Aarti_Rathi",constant,linear +"# Python 3 program to find whether an array +# is subset of another array + +# Return 1 if arr2[] is a subset of +# arr1[] + + +def isSubset(arr1, arr2, m, n): + i = 0 + j = 0 + for i in range(n): + for j in range(m): + if(arr2[i] == arr1[j]): + break + + # If the above inner loop was + # not broken at all then arr2[i] + # is not present in arr1[] + if (j == m): + return 0 + + # If we reach here then all + # elements of arr2[] are present + # in arr1[] + return 1 + + +# Driver code +if __name__ == ""__main__"": + + arr1 = [11, 1, 13, 21, 3, 7] + arr2 = [11, 3, 7, 1] + + m = len(arr1) + n = len(arr2) + + if(isSubset(arr1, arr2, m, n)): + print(""arr2[] is subset of arr1[] "") + else: + print(""arr2[] is not a subset of arr1[]"") + +# This code is contributed by ita_c",constant,quadratic +"# Python3 program to find whether an array +# is subset of another array + +# Return 1 if arr2[] is a subset of arr1[] + + +def isSubset(arr1, arr2, m, n): + i = 0 + + quickSort(arr1, 0, m-1) + for i in range(n): + if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1): + return 0 + + # If we reach here then all elements + # of arr2[] are present in arr1[] + return 1 + +# FOLLOWING FUNCTIONS ARE ONLY FOR +# SEARCHING AND SORTING PURPOSE +# Standard Binary Search function + + +def binarySearch(arr, low, high, x): + if(high >= low): + mid = (low + high)//2 + + # Check if arr[mid] is the first + # occurrence of x. + # arr[mid] is first occurrence if x is + # one of the following + # is true: + # (i) mid == 0 and arr[mid] == x + # (ii) arr[mid-1] < x and arr[mid] == x + if((mid == 0 or x > arr[mid-1]) and (arr[mid] == x)): + return mid + elif(x > arr[mid]): + return binarySearch(arr, (mid + 1), high, x) + else: + return binarySearch(arr, low, (mid - 1), x) + + return -1 + + +def partition(A, si, ei): + x = A[ei] + i = (si - 1) + + for j in range(si, ei): + if(A[j] <= x): + i += 1 + A[i], A[j] = A[j], A[i] + A[i + 1], A[ei] = A[ei], A[i + 1] + return (i + 1) + +# Implementation of Quick Sort +# A[] --> Array to be sorted +# si --> Starting index +# ei --> Ending index + + +def quickSort(A, si, ei): + # Partitioning index + if(si < ei): + pi = partition(A, si, ei) + quickSort(A, si, pi - 1) + quickSort(A, pi + 1, ei) + + +# Driver code +arr1 = [11, 1, 13, 21, 3, 7] +arr2 = [11, 3, 7, 1] + +m = len(arr1) +n = len(arr2) + +if(isSubset(arr1, arr2, m, n)): + print(""arr2[] is subset of arr1[] "") +else: + print(""arr2[] is not a subset of arr1[] "") + + +# This code is contributed by chandan_jnu",linear,nlogn +"# Python3 program to find whether an array +# is subset of another array + +# Return 1 if arr2[] is a subset of arr1[] */ + + +def isSubset(arr1, arr2, m, n): + i = 0 + j = 0 + if m < n: + return 0 + + arr1.sort() + arr2.sort() + + while i < n and j < m: + if arr1[j] < arr2[i]: + j += 1 + elif arr1[j] == arr2[i]: + j += 1 + i += 1 + elif arr1[j] > arr2[i]: + return 0 + return False if i < n else True + + +# Driver code +arr1 = [11, 1, 13, 21, 3, 7] +arr2 = [11, 3, 7, 1] + +m = len(arr1) +n = len(arr2) +if isSubset(arr1, arr2, m, n) == True: + print(""arr2 is subset of arr1 "") +else: + printf(""arr2 is not a subset of arr1 "") + +# This code is contributed by Shrikant13",constant,nlogn +"# Python3 program to find whether an array +# is subset of another array + +# Return true if arr2[] is a subset +# of arr1[] + + +def isSubset(arr1, m, arr2, n): + + # Using STL set for hashing + hashset = set() + + # hset stores all the values of arr1 + for i in range(0, m): + hashset.add(arr1[i]) + + # Loop to check if all elements + # of arr2 also lies in arr1 + for i in range(0, n): + if arr2[i] in hashset: + continue + else: + return False + + return True + + +# Driver Code +if __name__ == '__main__': + + arr1 = [11, 1, 13, 21, 3, 7] + arr2 = [11, 3, 7, 1] + + m = len(arr1) + n = len(arr2) + + if (isSubset(arr1, m, arr2, n)): + print(""arr2[] is subset of arr1[] "") + else: + print(""arr2[] is not a subset of arr1[] "") + +# This code is contributed by akhilsaini",linear,nlogn +"# Python3 code +arr1 = [11, 1, 13, 21, 3, 7] +arr2 = [11, 3, 7, 1] +m = len(arr1) +n = len(arr2) +s = set() +for i in range(m): + s.add(arr1[i]) + +p = len(s) +for i in range(n): + s.add(arr2[i]) + +if (len(s) == p): + print(""arr2[] is subset of arr1[] "") + +else: + print(""arr2[] is not subset of arr1[] "") + + # This code is contributed by divyeshrabadiya07.",linear,linear +"# Python3 program to find whether an array +# is subset of another array + +# Return true if arr2[] is a subset of arr1[] + + +def isSubset(arr1, m, arr2, n): + + # Create a Frequency Table using STL + frequency = {} + + # Increase the frequency of each element + # in the frequency table. + for i in range(0, m): + if arr1[i] in frequency: + frequency[arr1[i]] = frequency[arr1[i]] + 1 + else: + frequency[arr1[i]] = 1 + + # Decrease the frequency if the + # element was found in the frequency + # table with the frequency more than 0. + # else return 0 and if loop is + # completed return 1. + for i in range(0, n): + if (frequency[arr2[i]] > 0): + frequency[arr2[i]] -= 1 + else: + return False + + return True + + +# Driver Code +if __name__ == '__main__': + + arr1 = [11, 1, 13, 21, 3, 7] + arr2 = [11, 3, 7, 1] + + m = len(arr1) + n = len(arr2) + + if (isSubset(arr1, m, arr2, n)): + print(""arr2[] is subset of arr1[] "") + else: + print(""arr2[] is not a subset of arr1[] "") + +# This code is contributed by akhilsaini",linear,linear +"# Python program to find all those +# elements of arr1[] that are not +# present in arr2[] + +def relativeComplement(arr1, arr2, n, m): + + i = 0 + j = 0 + while (i < n and j < m): + + # If current element in arr2[] is + # greater, then arr1[i] can't be + # present in arr2[j..m-1] + if (arr1[i] < arr2[j]): + print(arr1[i] , "" "", end="""") + i += 1 + + # Skipping smaller elements of + # arr2[] + elif (arr1[i] > arr2[j]): + j += 1 + + # Equal elements found (skipping + # in both arrays) + elif (arr1[i] == arr2[j]): + i += 1 + j += 1 + + # Printing remaining elements of + # arr1[] + while (i < n): + print(arr1[i] , "" "", end="""") + +# Driver code +arr1= [3, 6, 10, 12, 15] +arr2 = [1, 3, 5, 10, 16] +n = len(arr1) +m = len(arr2) +relativeComplement(arr1, arr2, n, m) + +# This code is contributed +# by Anant Agarwal.",constant,linear +"# Python3 Program to make all array equal + +# function for calculating min operations +def minOps(arr, n, k): + + # max elements of array + max1 = max(arr) + res = 0 + + # iterate for all elements + for i in range(0, n): + + # check if element can make equal to + # max or not if not then return -1 + if ((max1 - arr[i]) % k != 0): + return -1 + + # else update res for + # required operations + else: + res += (max1 - arr[i]) / k + + # return result + return int(res) + +# driver program +arr = [21, 33, 9, 45, 63] +n = len(arr) +k = 6 +print(minOps(arr, n, k)) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,linear +"# python code for above approach. + +def solve(A, B, C): + + # assigning the length -1 value + # to each of three variables + i = len(A) - 1 + j = len(B) - 1 + k = len(C) - 1 + + # calculating min difference + # from last index of lists + min_diff = abs(max(A[i], B[j], C[k]) - + min(A[i], B[j], C[k])) + + while i != -1 and j != -1 and k != -1: + current_diff = abs(max(A[i], B[j], + C[k]) - min(A[i], B[j], C[k])) + + # checking condition + if current_diff < min_diff: + min_diff = current_diff + + # calculating max term from list + max_term = max(A[i], B[j], C[k]) + + # Moving to smaller value in the + # array with maximum out of three. + if A[i] == max_term: + i -= 1 + elif B[j] == max_term: + j -= 1 + else: + k -= 1 + return min_diff + +# driver code + +A = [ 5, 8, 10, 15 ] +B = [ 6, 9, 15, 78, 89 ] +C = [ 2, 3, 6, 6, 8, 8, 10 ] +print(solve(A, B, C))",constant,linear +"# Program to convert binary tree to BST + +# 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 + +# Helper function to store the inorder traversal of a tree +def storeInorder(root, inorder): + + # Base Case + if root is None: + return + + # First store the left subtree + storeInorder(root.left, inorder) + + # Copy the root's data + inorder.append(root.data) + + # Finally store the right subtree + storeInorder(root.right, inorder) + +# A helper function to count nodes in a binary tree +def countNodes(root): + if root is None: + return 0 + + return countNodes(root.left) + countNodes(root.right) + 1 + +# Helper function that copies contents of sorted array +# to Binary tree +def arrayToBST(arr, root): + + # Base Case + if root is None: + return + + # First update the left subtree + arrayToBST(arr, root.left) + + # now update root's data delete the value from array + root.data = arr[0] + arr.pop(0) + + # Finally update the right subtree + arrayToBST(arr, root.right) + +# This function converts a given binary tree to BST +def binaryTreeToBST(root): + + # Base Case: Tree is empty + if root is None: + return + + # Count the number of nodes in Binary Tree so that + # we know the size of temporary array to be created + n = countNodes(root) + + # Create the temp array and store the inorder traversal + # of tree + arr = [] + storeInorder(root, arr) + + # Sort the array + arr.sort() + + # copy array elements back to binary tree + arrayToBST(arr, root) + +# Print the inorder traversal of the tree +def printInorder(root): + if root is None: + return + printInorder(root.left) + print (root.data,end="" "") + printInorder(root.right) + +# Driver program to test above function +root = Node(10) +root.left = Node(30) +root.right = Node(15) +root.left.left = Node(20) +root.right.right = Node(5) + +# Convert binary tree to BST +binaryTreeToBST(root) + +print (""Following is the inorder traversal of the converted BST"") +printInorder(root) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,nlogn +"# Python code to convert a sorted array +# to a balanced Binary Search Tree + +# binary tree node +class Node: + def __init__(self, d): + self.data = d + self.left = None + self.right = None + +# function to convert sorted array to a +# balanced BST +# input : sorted array of integers +# output: root node of balanced BST +def sortedArrayToBST(arr): + + if not arr: + return None + + # find middle index + mid = (len(arr)) // 2 + + # make the middle element the root + root = Node(arr[mid]) + + # left subtree of root has all + # values arr[mid] + root.right = sortedArrayToBST(arr[mid+1:]) + return root + +# A utility function to print the preorder +# traversal of the BST +def preOrder(node): + if not node: + return + + print node.data, + preOrder(node.left) + preOrder(node.right) + +# driver program to test above function +"""""" +Constructed balanced BST is + 4 +/ \ +2 6 +/ \ / \ +1 3 5 7 +"""""" + +arr = [1, 2, 3, 4, 5, 6, 7] +root = sortedArrayToBST(arr) +print ""PreOrder Traversal of constructed BST "", +preOrder(root) + +# This code is contributed by Ishita Tripathi",logn,linear +"# Python3 program to transform a BST to sum tree + +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None + +# Recursive function to transform a BST to sum tree. +# This function traverses the tree in reverse inorder so +# that we have visited all greater key nodes of the currently +# visited node +def transformTreeUtil(root): + + # Base case + if (root == None): + return + + # Recur for right subtree + transformTreeUtil(root.right) + + # Update sum + global sum + sum = sum + root.data + + # Store old sum in current node + root.data = sum - root.data + + # Recur for left subtree + transformTreeUtil(root.left) + +# A wrapper over transformTreeUtil() +def transformTree(root): + + # sum = 0 #Initialize sum + transformTreeUtil(root) + +# A utility function to prindorder traversal of a +# binary tree +def printInorder(root): + if (root == None): + return + + printInorder(root.left) + print(root.data, end = "" "") + printInorder(root.right) + +# Driver Program to test above functions +if __name__ == '__main__': + + sum=0 + root = Node(11) + root.left = Node(2) + root.right = Node(29) + root.left.left = Node(1) + root.left.right = Node(7) + root.right.left = Node(15) + root.right.right = Node(40) + root.right.right.left = Node(35) + + print(""Inorder Traversal of given tree"") + printInorder(root) + + transformTree(root) + + print(""\nInorder Traversal of transformed tree"") + printInorder(root) + + # This code is contributed by mohit kumar 29",linear,linear +"# Python3 program to construct all unique +# BSTs for keys from 1 to n + +# Binary Tree Node +"""""" A utility function to create a +new BST node """""" +class newNode: + + # Construct to create a newNode + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Utility function to print Min-heap +# level by level +def printLevelOrder(root): + + # Base Case + if (root == None): + return + + # Create an empty queue for level + # order traversal + q = [] + q.append(root) + + while (len(q)): + nodeCount = len(q) + while (nodeCount > 0) : + + node = q[0] + print(node.data, end = "" "" ) + q.pop(0) + if (node.left) : + q.append(node.left) + if (node.right) : + q.append(node.right) + nodeCount -= 1 + print() + +# A simple recursive function to convert a +# given Binary Search tree to Sorted Linked +# List root -. Root of Binary Search Tree +def BSTToSortedLL(root, head_ref): + + # Base cases + if(root == None) : + return + + # Recursively convert right subtree + BSTToSortedLL(root.right, head_ref) + + # insert root into linked list + root.right = head_ref[0] + + # Change left pointer of previous + # head to point to None + if (head_ref[0] != None): + (head_ref[0]).left = None + + # Change head of linked list + head_ref[0] = root + + # Recursively convert left subtree + BSTToSortedLL(root.left, head_ref) + +# Function to convert a sorted Linked +# List to Min-Heap. +# root -. root[0] of Min-Heap +# head -. Pointer to head node of +# sorted linked list +def SortedLLToMinHeap( root, head) : + + # Base Case + if (head == None) : + return + + # queue to store the parent nodes + q = [] + + # The first node is always the + # root node + root[0] = head[0] + + # advance the pointer to the next node + head[0] = head[0].right + + # set right child to None + root[0].right = None + + # add first node to the queue + q.append(root[0]) + + # run until the end of linked list + # is reached + while (head[0] != None) : + + # Take the parent node from the q + # and remove it from q + parent = q[0] + q.pop(0) + + # Take next two nodes from the linked + # list and Add them as children of the + # current parent node. Also in push them + # into the queue so that they will be + # parents to the future nodes + leftChild = head[0] + head[0] = head[0].right # advance linked list to next node + leftChild.right = None # set its right child to None + q.append(leftChild) + + # Assign the left child of parent + parent.left = leftChild + + if (head) : + rightChild = head[0] + head[0] = head[0].right # advance linked list to next node + rightChild.right = None # set its right child to None + q.append(rightChild) + + # Assign the right child of parent + parent.right = rightChild + +# Function to convert BST into a Min-Heap +# without using any extra space +def BSTToMinHeap(root): + + # head of Linked List + head = [None] + + # Convert a given BST to Sorted Linked List + BSTToSortedLL(root, head) + + # set root as None + root = [None] + + # Convert Sorted Linked List to Min-Heap + SortedLLToMinHeap(root, head) + return root + +# Driver Code +if __name__ == '__main__': + + """""" Constructing below tree + 8 + / \ + 4 12 + / \ / \ + 2 6 10 14 + """""" + root = newNode(8) + root.left = newNode(4) + root.right = newNode(12) + root.right.left = newNode(10) + root.right.right = newNode(14) + root.left.left = newNode(2) + root.left.right = newNode(6) + + root = BSTToMinHeap(root) + + """""" Output - Min Heap + 2 + / \ + 4 6 + / \ / \ + 8 10 12 14 + """""" + printLevelOrder(*root) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,linear +"# Python3 implementation to convert the +# given BST to Min Heap + +# structure of a node of BST + + +class Node: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# function for the inorder traversal +# of the tree so as to store the node +# values in 'arr' in sorted order + + +def inorderTraversal(root, arr): + if root == None: + return + + # first recur on left subtree + inorderTraversal(root.left, arr) + + # then copy the data of the node + arr.append(root.data) + + # now recur for right subtree + inorderTraversal(root.right, arr) + +# function to convert the given +# BST to MIN HEAP performs preorder +# traversal of the tree + + +def BSTToMinHeap(root, arr, i): + if root == None: + return + + # first copy data at index 'i' of + # 'arr' to the node + i[0] += 1 + root.data = arr[i[0]] + + # then recur on left subtree + BSTToMinHeap(root.left, arr, i) + + # now recur on right subtree + BSTToMinHeap(root.right, arr, i) + +# utility function to convert the +# given BST to MIN HEAP + + +def convertToMinHeapUtil(root): + + # vector to store the data of + # all the nodes of the BST + arr = [] + i = [-1] + + # inorder traversal to populate 'arr' + inorderTraversal(root, arr) + + # BST to MIN HEAP conversion + BSTToMinHeap(root, arr, i) + +# function for the preorder traversal +# of the tree + + +def preorderTraversal(root): + if root == None: + return + + # first print the root's data + print(root.data, end="" "") + + # then recur on left subtree + preorderTraversal(root.left) + + # now recur on right subtree + preorderTraversal(root.right) + + +# Driver's Code +if __name__ == '__main__': + + # BST formation + root = Node(4) + root.left = Node(2) + root.right = Node(6) + root.left.left = Node(1) + root.left.right = Node(3) + root.right.left = Node(5) + root.right.right = Node(7) + + # Function call + convertToMinHeapUtil(root) + print(""Preorder Traversal:"") + preorderTraversal(root) + +# This code is contributed +# by PranchalK",linear,linear +"# Python3 program to convert a Binary tree +# to BST using sets as containers. + +# Binary Tree Node +"""""" A utility function to create a +new BST node """""" +class newNode: + + # Construct to create a newNode + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# function to store the nodes in set +# while doing inorder traversal. +def storeinorderInSet(root, s): + + if (not root) : + return + + # visit the left subtree first + storeinorderInSet(root.left, s) + + # insertion takes order of O(logn) + # for sets + s.add(root.data) + + # visit the right subtree + storeinorderInSet(root.right, s) + +# Time complexity = O(nlogn) + +# function to copy items of set one by one +# to the tree while doing inorder traversal +def setToBST(s, root) : + + # base condition + if (not root): + return + + # first move to the left subtree and + # update items + setToBST(s, root.left) + + # iterator initially pointing to + # the beginning of set + it = next(iter(s)) + + # copying the item at beginning of + # set(sorted) to the tree. + root.data = it + + # now erasing the beginning item from set. + s.remove(it) + + # now move to right subtree + # and update items + setToBST(s, root.right) + +# T(n) = O(nlogn) time + +# Converts Binary tree to BST. +def binaryTreeToBST(root): + + s = set() + + # populating the set with the tree's + # inorder traversal data + storeinorderInSet(root, s) + + # now sets are by default sorted as + # they are implemented using self- + # balancing BST + + # copying items from set to the tree + # while inorder traversal which makes a BST + setToBST(s, root) + +# Time complexity = O(nlogn), +# Auxiliary Space = O(n) for set. + +# function to do inorder traversal +def inorder(root) : + + if (not root) : + return + inorder(root.left) + print(root.data, end = "" "") + inorder(root.right) + +# Driver Code +if __name__ == '__main__': + + root = newNode(5) + root.left = newNode(7) + root.right = newNode(9) + root.right.left = newNode(10) + root.left.left = newNode(1) + root.left.right = newNode(6) + root.right.right = newNode(11) + + """""" Constructing tree given in + the above figure + 5 + / \ + 7 9 + /\ / \ + 1 6 10 11 """""" + + # converting the above Binary tree to BST + binaryTreeToBST(root) + print(""Inorder traversal of BST is: "") + inorder(root) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,nlogn +"# Class to create a new Tree Node +class newNode: + def __init__(self, data: int): + self.data = data + self.left = None + self.right = None + +def inorder(root: newNode): + + if root: + inorder(root.left) + print(root.data, end="" "") + inorder(root.right) + +def merge(root1: newNode, root2: newNode): + + # s1 is stack to hold nodes of first BST + s1 = [] + + # Current node of first BST + current1 = root1 + + # s2 is stack to hold nodes of first BST + s2 = [] + + # Current node of second BST + current2 = root2 + + # If first BST is empty then the output is the + # inorder traversal of the second BST + if not root1: + return inorder(root2) + + # If the second BST is empty then the output is the + # inorder traversal of the first BST + if not root2: + return inorder(root1) + + # Run the loop while there are nodes not yet printed. + # The nodes may be in stack(explored, but not printed) + # or may be not yet explored + while current1 or s1 or current2 or s2: + + # Following steps follow iterative Inorder Traversal + if current1 or current2: + + # Reach the leftmost node of both BSTs and push ancestors of + # leftmost nodes to stack s1 and s2 respectively + if current1: + s1.append(current1) + current1 = current1.left + + if current2: + s2.append(current2) + current2 = current2.left + + else: + + # If we reach a NULL node and either of the stacks is empty, + # then one tree is exhausted, print the other tree + + if not s1: + while s2: + current2 = s2.pop() + current2.left = None + inorder(current2) + return + if not s2: + while s1: + current1 = s1.pop() + current1.left = None + inorder(current1) + return + + # Pop an element from both stacks and compare the + # popped elements + current1 = s1.pop() + current2 = s2.pop() + + # If element of first tree is smaller, then print it + # and push the right subtree. If the element is larger, + # then we push it back to the corresponding stack. + if current1.data < current2.data: + print(current1.data, end="" "") + current1 = current1.right + s2.append(current2) + current2 = None + + else: + print(current2.data, end="" "") + current2 = current2.right + s1.append(current1) + current1 = None + +# Driver code + +def main(): + + # Let us create the following tree as first tree + # 3 + # / \ + # 1 5 + + root1 = newNode(3) + root1.left = newNode(1) + root1.right = newNode(5) + + # Let us create the following tree as second tree + # 4 + # / \ + # 2 6 + # + + root2 = newNode(4) + root2.left = newNode(2) + root2.right = newNode(6) + + merge(root1, root2) + + +if __name__ == ""__main__"": + main() + +# This code is contributed by Koushik Reddy Bukkasamudram",logn,linear +"# Python program to Merge two BSTs with limited extra space + +# Structure of a BST Node +class Node: + def __init__(self, val): + self.val = val + self.left = None + self.right = None + + +def mergeTwoBST(root1, root2): + res = [] + s1, s2 = [], [] + + while root1 or root2 or s1 or s2: + while root1: + s1.append(root1) + root1 = root1.left + + while root2: + s2.append(root2) + root2 = root2.left + + # Step 3 Case 1:- + if not s2 or (s1 and s1[-1].val <= s2[-1].val): + root1 = s1[-1] + del s1[-1] + res.append(root1.val) + root1 = root1.right + + # Step 3 case 2 :- + else: + root2 = s2[-1] + del s2[-1] + res.append(root2.val) + root2 = root2.right + + return res + + +# Driver program to test above functions +if __name__ == '__main__': + root1 = None + root2 = None + + ''' + Let us create the following tree as first tree + 3 + / \ + 1 5 + ''' + + root1 = Node(3) + root1.left = Node(1) + root1.right = Node(5) + + ''' + Let us create the following tree as second tree + 4 + / \ + 2 6 + ''' + + root2 = Node(4) + root2.left = Node(2) + root2.right = Node(6) + + ans = mergeTwoBST(root1, root2) + for x in ans: + print (x, end="" "") + +# This code is contributed by Tapesh(tapeshdua420)",logn,linear +"# Python3 program to find the node with minimum value in bst + +# A binary tree node + + +class Node: + + # Constructor to create a new node + def __init__(self, key): + self.data = key + self.left = None + self.right = None + + +"""""" Give a binary search tree and a number, +inserts a new node with the given number in +the correct place in the tree. Returns the new +root pointer which the caller should then use +(the standard trick to avoid using reference +parameters). """""" + + +def insert(node, data): + + # 1. If the tree is empty, return a new, + # single node + if node is None: + return (Node(data)) + + else: + # 2. Otherwise, recur down the tree + if data <= node.data: + node.left = insert(node.left, data) + else: + node.right = insert(node.right, data) + + # Return the (unchanged) node pointer + return node + + +"""""" Given a non-empty binary search tree, +return the minimum data value found in that +tree. Note that the entire tree does not need +to be searched. """""" + + +def minValue(node): + current = node + + # loop down to find the leftmost leaf + while(current.left is not None): + current = current.left + + return current.data + + +# Driver code +if __name__ == '__main__': + root = None + root = insert(root, 4) + insert(root, 2) + insert(root, 1) + insert(root, 3) + insert(root, 6) + insert(root, 5) + + # Function call + print(""\nMinimum value in BST is %d"" % (minValue(root))) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python program for an efficient solution to check if +# a given array can represent Preorder traversal of +# a Binary Search Tree + +INT_MIN = -2**32 + +def canRepresentBST(pre): + + # Create an empty stack + s = [] + + # Initialize current root as minimum possible value + root = INT_MIN + + # Traverse given array + for value in pre: + #NOTE:value is equal to pre[i] according to the + #given algo + + # If we find a node who is on the right side + # and smaller than root, return False + if value < root : + return False + + # If value(pre[i]) is in right subtree of stack top, + # Keep removing items smaller than value + # and make the last removed items as new root + while(len(s) > 0 and s[-1] < value) : + root = s.pop() + + # At this point either stack is empty or value + # is smaller than root, push value + s.append(value) + + return True + +# Driver Program +pre1 = [40 , 30 , 35 , 80 , 100] +print (""true"" if canRepresentBST(pre1) == True else ""false"") +pre2 = [40 , 30 , 35 , 20 , 80 , 100] +print (""true"" if canRepresentBST(pre2) == True else ""false"") + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python3 program to illustrate if a given array can represent +# a preorder traversal of a BST or not +import sys + +preIndex = 0 + +# We are actually not building the tree +def buildBST_helper(n, pre, Min, Max): + global preIndex + if (preIndex >= n): + return + + if (Min <= pre[preIndex] and pre[preIndex] <= Max): + # build node + rootData = pre[preIndex] + preIndex+=1 + + # build left subtree + buildBST_helper(n, pre, Min, rootData) + + # build right subtree + buildBST_helper(n, pre, rootData, Max) + # else + # return NULL + +def canRepresentBST(arr, N): + global preIndex + # code here + Min, Max = sys.maxsize, -sys.maxsize + + buildBST_helper(N, arr, Min, Max) + + if preIndex == N: + return True + + return False + +preorder1 = [ 2, 4, 3 ] +"""""" + 2 + \ + 4 + / + 3 + +"""""" +n1 = len(preorder1) + +if (not canRepresentBST(preorder1, n1)): + print(""preorder1 can represent BST""); +else: + print(""preorder1 can not represent BST :("") + +preorder2 = [ 5, 3, 4, 1, 6, 10 ] +n2 = len(preorder2) +"""""" + 5 + / \ + 3 1 + \ / \ + 4 6 10 + +"""""" +if (canRepresentBST(preorder2, n2)): + print(""preorder2 can represent BST"") +else: + print(""preorder2 can not represent BST :("") + +preorder3 = [ 5, 3, 4, 8, 6, 10 ] +n3 = len(preorder3) +"""""" + 5 + / \ + 3 8 + \ / \ + 4 6 10 +"""""" +if (not canRepresentBST(preorder3, n3)): + print(""preorder3 can represent BST"") +else: + print(""preorder3 can not represent BST :("")",logn,linear +"# A recursive python program to find LCA of two nodes +# n1 and n2 + +# 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 LCA of n1 and n2. The function assumes +# that both n1 and n2 are present in BST + + +def lca(root, n1, n2): + + # Base Case + if root is None: + return None + + # If both n1 and n2 are smaller than root, then LCA + # lies in left + if(root.data > n1 and root.data > n2): + return lca(root.left, n1, n2) + + # If both n1 and n2 are greater than root, then LCA + # lies in right + if(root.data < n1 and root.data < n2): + return lca(root.right, n1, n2) + + return root + +# Driver program to test above function + + +# Driver code +root = Node(20) +root.left = Node(8) +root.right = Node(22) +root.left.left = Node(4) +root.left.right = Node(12) +root.left.right.left = Node(10) +root.left.right.right = Node(14) + + +# Function calls +n1 = 10 +n2 = 14 +t = lca(root, n1, n2) +print(""LCA of %d and %d is %d"" % (n1, n2, t.data)) + +n1 = 14 +n2 = 8 +t = lca(root, n1, n2) +print(""LCA of %d and %d is %d"" % (n1, n2, t.data)) + +n1 = 10 +n2 = 22 +t = lca(root, n1, n2) +print(""LCA of %d and %d is %d"" % (n1, n2, t.data)) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",logn,constant +"# A recursive python program to find LCA of two nodes +# n1 and n2 + +# 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 LCA of n1 and n2. +# The function assumes that both +# n1 and n2 are present in BST + + +def lca(root, n1, n2): + while root: + # If both n1 and n2 are smaller than root, + # then LCA lies in left + if root.data > n1 and root.data > n2: + root = root.left + + # If both n1 and n2 are greater than root, + # then LCA lies in right + elif root.data < n1 and root.data < n2: + root = root.right + + else: + break + + return root + + +# Driver code +if __name__ == '__main__': + root = Node(20) + root.left = Node(8) + root.right = Node(22) + root.left.left = Node(4) + root.left.right = Node(12) + root.left.right.left = Node(10) + root.left.right.right = Node(14) + + # Function calls + n1 = 10 + n2 = 14 + t = lca(root, n1, n2) + print(""LCA of %d and %d is %d"" % (n1, n2, t.data)) + + n1 = 14 + n2 = 8 + t = lca(root, n1, n2) + print(""LCA of %d and %d is %d"" % (n1, n2, t.data)) + + n1 = 10 + n2 = 22 + t = lca(root, n1, n2) + print(""LCA of %d and %d is %d"" % (n1, n2, t.data)) +# This Code is Contributed by Sumit Bhardwaj (Timus)",constant,constant +"# A Python3 program to check for Identical +# BSTs without building the trees + +# # The main function that checks if two +# arrays a[] and b[] of size n construct +# same BST. The two values 'min' and 'max' +# decide whether the call is made for left +# subtree or right subtree of a parent +# element. The indexes i1 and i2 are the +# indexes in (a[] and b[]) after which we +# search the left or right child. Initially, +# the call is made for INT_MIN and INT_MAX +# as 'min' and 'max' respectively, because +# root has no parent. i1 and i2 are just +# after the indexes of the parent element in a[] and b[]. */ +def isSameBSTUtil(a, b, n, i1, i2, min, max): + + # # Search for a value satisfying the + # constraints of min and max in a[] and + # b[]. If the parent element is a leaf + # node then there must be some elements + # in a[] and b[] satisfying constraint. */ + j, k = i1, i2 + while j < n: + if (a[j] > min and a[j] < max): + break; + j += 1 + while k min and b[k] < max): + break + k += 1 + + # If the parent element is leaf in both arrays */ + if (j == n and k == n): + return True + + # Return false if any of the following is true + # a) If the parent element is leaf in one array, + # but non-leaf in other. + # b) The elements satisfying constraints are + # not same. We either search for left + # child or right child of the parent + # element (decided by min and max values). + # The child found must be same in both arrays */ + if (((j == n) ^ (k == n)) or a[j] != b[k]): + return False + + # Make the current child as parent and + # recursively check for left and right + # subtrees of it. Note that we can also + # pass a[k] in place of a[j] as they + # are both are same */ + return isSameBSTUtil(a, b, n, j + 1, k + 1, a[j], max) and isSameBSTUtil(a, b, n, j + 1, k + 1, min, a[j]) #Left Subtree + +# A wrapper over isSameBSTUtil() +def isSameBST(a, b, n): + return isSameBSTUtil(a, b, n, 0, 0, -10**9, 10**9) + +# Driver code +if __name__ == '__main__': + a = [8, 3, 6, 1, 4, 7, 10, 14, 13] + b = [8, 10, 14, 3, 6, 4, 1, 7, 13] + n = len(a) + + if(isSameBST(a, b, n)): + print(""BSTs are same"") + else: + print(""BSTs not same"") + +# This code is contributed by mohit kumar 29.",linear,quadratic +"# Python3 program to find k'th largest +# element in BST + +class Node: + + # Constructor to create a new node + def __init__(self, data): + self.key = data + self.left = None + self.right = None + +# A function to find k'th largest +# element in a given tree. +def kthLargestUtil(root, k, c): + + # Base cases, the second condition + # is important to avoid unnecessary + # recursive calls + if root == None or c[0] >= k: + return + + # Follow reverse inorder traversal + # so that the largest element is + # visited first + kthLargestUtil(root.right, k, c) + + # Increment count of visited nodes + c[0] += 1 + + # If c becomes k now, then this is + # the k'th largest + if c[0] == k: + print(""K'th largest element is"", + root.key) + return + + # Recur for left subtree + kthLargestUtil(root.left, k, c) + +# Function to find k'th largest element +def kthLargest(root, k): + + # Initialize count of nodes + # visited as 0 + c = [0] + + # Note that c is passed by reference + kthLargestUtil(root, k, c) + +# A utility function to insert a new +# node with given key in BST */ +def insert(node, key): + + # If the tree is empty, + # return a new node + if node == None: + return Node(key) + + # Otherwise, recur down the tree + if key < node.key: + node.left = insert(node.left, key) + elif key > node.key: + node.right = insert(node.right, key) + + # return the (unchanged) node pointer + return node + +# Driver Code +if __name__ == '__main__': + + # Let us create following BST + # 50 + # / \ + # 30 70 + # / \ / \ + # 20 40 60 80 */ + root = None + root = insert(root, 50) + insert(root, 30) + insert(root, 20) + insert(root, 40) + insert(root, 70) + insert(root, 60) + insert(root, 80) + + for k in range(1,8): + kthLargest(root, k) + +# This code is contributed by PranchalK",logn,linear +"# Python3 code for finding K-th largest +# Node using O(1) extra memory and +# reverse Morris traversal. + +# helper function to create a new Node +class newNode: + def __init__(self, data): + self.data = data + self.right = self.left = None + +def KthLargestUsingMorrisTraversal(root, k): + curr = root + Klargest = None + + # count variable to keep count + # of visited Nodes + count = 0 + + while (curr != None): + + # if right child is None + if (curr.right == None): + + # first increment count and + # check if count = k + count += 1 + if (count == k): + Klargest = curr + + # otherwise move to the left child + curr = curr.left + + else: + + # find inorder successor of + # current Node + succ = curr.right + + while (succ.left != None and + succ.left != curr): + succ = succ.left + + if (succ.left == None): + + # set left child of successor + # to the current Node + succ.left = curr + + # move current to its right + curr = curr.right + + # restoring the tree back to + # original binary search tree + # removing threaded links + else: + + succ.left = None + count += 1 + if (count == k): + Klargest = curr + + # move current to its left child + curr = curr.left + + return Klargest + +# Driver Code +if __name__ == '__main__': + + # Constructed binary tree is + # 4 + # / \ + # 2 7 + # / \ / \ + # 1 3 6 10 + root = newNode(4) + root.left = newNode(2) + root.right = newNode(7) + root.left.left = newNode(1) + root.left.right = newNode(3) + root.right.left = newNode(6) + root.right.right = newNode(10) + + print(""Finding K-th largest Node in BST : "", + KthLargestUsingMorrisTraversal(root, 2).data) + +# This code is contributed by PranchalK",constant,linear +"# Python 3 program to find k'th +# largest element in BST + +# A BST node +class Node: + + # Constructor to create a new node + def __init__(self, data): + self.key = data + self.left = None + self.right = None + +# A function to find +def KSmallestUsingMorris(root, k): + + # Count to iterate over elements + # till we get the kth smallest number + count = 0 + + ksmall = -9999999999 # store the Kth smallest + curr = root # to store the current node + + while curr != None: + + # Like Morris traversal if current does + # not have left child rather than + # printing as we did in inorder, we + # will just increment the count as the + # number will be in an increasing order + if curr.left == None: + count += 1 + + # if count is equal to K then we + # found the kth smallest, so store + # it in ksmall + if count == k: + ksmall = curr.key + + # go to current's right child + curr = curr.right + else: + + # we create links to Inorder Successor + # and count using these links + pre = curr.left + while (pre.right != None and + pre.right != curr): + pre = pre.right + + # building links + if pre.right == None: + + # link made to Inorder Successor + pre.right = curr + curr = curr.left + + # While breaking the links in so made + # temporary threaded tree we will check + # for the K smallest condition + else: + + # Revert the changes made in if part + # (break link from the Inorder Successor) + pre.right = None + + count += 1 + + # If count is equal to K then we + # found the kth smallest and so + # store it in ksmall + if count == k: + ksmall = curr.key + + curr = curr.right + return ksmall # return the found value + +# A utility function to insert a new +# node with given key in BST +def insert(node, key): + + # If the tree is empty, + # return a new node + if node == None: + return Node(key) + + # Otherwise, recur down the tree + if key < node.key: + node.left = insert(node.left, key) + elif key > node.key: + node.right = insert(node.right, key) + + # return the (unchanged) node pointer + return node + +# Driver Code +if __name__ == '__main__': + + # Let us create following BST + # 50 + # / \ + # 30 70 + # / \ / \ + # 20 40 60 80 + root = None + root = insert(root, 50) + insert(root, 30) + insert(root, 20) + insert(root, 40) + insert(root, 70) + insert(root, 60) + insert(root, 80) + + for k in range(1,8): + print(KSmallestUsingMorris(root, k), + end = "" "") + +# This code is contributed by PranchalK",constant,linear +"# Python 3 program to check if a given array +# is sorted or not. + +# Function that returns true if array is Inorder +# traversal of any Binary Search Tree or not. +def isInorder(arr, n): + + # Array has one or no element + if (n == 0 or n == 1): + return True + + for i in range(1, n, 1): + + # Unsorted pair found + if (arr[i - 1] > arr[i]): + return False + + # No unsorted pair found + return True + +# Driver code +if __name__ == '__main__': + arr = [19, 23, 25, 30, 45] + n = len(arr) + + if (isInorder(arr, n)): + print(""Yes"") + else: + print(""No"") + +# This code is contributed by +# Sahil_Shelangia",constant,linear +"# Python3 program to check if two BSTs contains +# same set of elements + +# BST Node +class Node: + def __init__(self): + self.val = 0 + self.left = None + self.right = None + +# Utility function to create Node +def Node_(val1): + + temp = Node() + temp.val = val1 + temp.left = temp.right = None + return temp + +s = {} + +# function to insert elements of the +# tree to map m +def insertToHash(root): + + if (root == None): + return + insertToHash(root.left) + s.add(root.data) + insertToHash(root.right) + +# function to check if the two BSTs contain +# same set of elements +def checkBSTs(root1, root2): + + # Base cases + if (root1 != None and root2 != None) : + return True + if ((root1 == None and root2 != None) or + (root1 != None and root2 == None)): + return False + + # Create two hash sets and store + # elements both BSTs in them. + s1 = {} + s2 = {} + s = s1 + insertToHash(root1) + s1 = s + s = s2 + insertToHash(root2) + s2 = s + + # Return True if both hash sets + # contain same elements. + return (s1 == (s2)) + +# Driver code + +# First BST +root1 = Node_(15) +root1.left = Node_(10) +root1.right = Node_(20) +root1.left.left = Node_(5) +root1.left.right = Node_(12) +root1.right.right = Node_(25) + +# Second BST +root2 = Node_(15) +root2.left = Node_(12) +root2.right = Node_(20) +root2.left.left = Node_(5) +root2.left.left.right = Node_(10) +root2.right.right = Node_(25) + +# check if two BSTs have same set of elements +if (checkBSTs(root1, root2)): + print(""YES"") +else: + print(""NO"") + +# This code is contributed by Arnab Kundu",linear,linear +"# Python3 program to check if two BSTs contains +# same set of elements + +# BST Node +class Node: + def __init__(self): + self.data = 0 + self.left = None + self.right = None + +# Utility function to create Node +def Node_(val1): + + temp = Node() + temp.data = val1 + temp.left = temp.right = None + return temp + +v = [] + +# function to insert elements of the +# tree to map m +def storeInorder(root): + + if (root == None): + return + storeInorder(root.left) + v.append(root.data) + storeInorder(root.right) + +# function to check if the two BSTs contain +# same set of elements +def checkBSTs(root1, root2): + + # Base cases + if (root1 == None and root2 == None) : + return True + if ((root1 == None and root2 != None) or \ + (root1 != None and root2 == None)): + return False + + # Create two hash sets and store + # elements both BSTs in them. + v1 = [] + v2 = [] + v = v1 + storeInorder(root1) + v1 = v + v = v2 + storeInorder(root2) + v2 = v + + # Return True if both hash sets + # contain same elements. + return (v1 == v2) + +# Driver code + +# First BST +root1 = Node_(15) +root1.left = Node_(10) +root1.right = Node_(20) +root1.left.left = Node_(5) +root1.left.right = Node_(12) +root1.right.right = Node_(25) + +# Second BST +root2 = Node_(15) +root2.left = Node_(12) +root2.right = Node_(20) +root2.left.left = Node_(5) +root2.left.left.right = Node_(10) +root2.right.right = Node_(25) + +# check if two BSTs have same set of elements +if (checkBSTs(root1, root2)): + print(""YES"") +else: + print(""NO"") + +# This code is contributed by SHUBHAMSINGH10",linear,linear +"# Python3 implementation to count pairs +# from two BSTs whose sum is equal to a +# given value x + +# Structure of a node of BST +class getNode: + + def __init__(self, data): + + self.data = data + self.left = None + self.right = None + +# Function to count pairs from two BSTs +# whose sum is equal to a given value x +def countPairs(root1, root2, x): + + # If either of the tree is empty + if (root1 == None or root2 == None): + return 0 + + # Stack 'st1' used for the inorder + # traversal of BST 1 + # stack 'st2' used for the reverse + # inorder traversal of BST 2 + st1 = [] + st2 = [] + + count = 3 + + # The loop will break when either + # of two traversals gets completed + while (1): + + # To find next node in inorder + # traversal of BST 1 + while (root1 != None): + st1.append(root1) + root1 = root1.left + + # To find next node in reverse + # inorder traversal of BST 2 + while (root2 != None): + st2.append(root2) + root2 = root2.right + + # If either gets empty then corresponding + # tree traversal is completed + if (len(st1) or len(st2)): + break + + top1 = st1[len(st1) - 1] + top2 = st2[len(st2) - 1] + + # If the sum of the node's is equal to 'x' + if ((top1.data + top2.data) == x): + + # Increment count + count += 1 + + # Pop nodes from the respective stacks + st1.remove(st1[len(st1) - 1]) + st2.remove(st2[len(st2) - 1]) + + # Insert next possible node in the + # respective stacks + root1 = top1.right + root2 = top2.left + + # Move to next possible node in the + # inorder traversal of BST 1 + elif ((top1.data + top2.data) < x): + st1.remove(st1[len(st1) - 1]) + root1 = top1.right + + # Move to next possible node in the + # reverse inorder traversal of BST 2 + else: + st2.remove(st2[len(st2) - 1]) + root2 = top2.left + + # Required count of pairs + return count + +# Driver code +if __name__ == '__main__': + + # Formation of BST 1 + ''' 5 + / \ + 3 7 + / \ / \ + 2 4 6 8 + ''' + root1 = getNode(5) + root1.left = getNode(3) + root1.right = getNode(7) + root1.left.left = getNode(2) + root1.left.right = getNode(4) + root1.right.left = getNode(6) + root1.right.right = getNode(8) + + # Formation of BST 2 + ''' 10 + / \ + 6 15 + / \ / \ + 3 8 11 18 + ''' + root2 = getNode(10) + root2.left = getNode(6) + root2.right = getNode(15) + root2.left.left = getNode(3) + root2.left.right = getNode(8) + root2.right.left = getNode(11) + root2.right.right = getNode(18) + + x = 16 + + print(""Pairs = "", countPairs(root1, root2, x)) + +# This code is contributed by bgangwar59",logn,linear +"# Python program to find closest +# value in Binary search Tree + +_MIN=-2147483648 +_MAX=2147483648 + +# Helper function that allocates +# a new node with the given data +# and None left and right pointers. +class newNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +"""""" A utility function to insert a new node with +given key in BST """""" +def insert(node,key): + + """""" If the tree is empty, return a new node """""" + if (node == None): + return newNode(key) + + """""" Otherwise, recur down the tree """""" + if (key < node.data): + node.left = insert(node.left, key) + elif (key > node.data): + node.right = insert(node.right, key) + + """""" return the (unchanged) node pointer """""" + return node + + +"""""" Function to count nodes in + a binary search tree using + Morris Inorder traversal"""""" +def counNodes(root): + + # Initialise count of nodes as 0 + count = 0 + + if (root == None): + return count + + current = root + while (current != None): + + if (current.left == None): + + # Count node if its left is None + count+=1 + + # Move to its right + current = current.right + + else: + """""" Find the inorder predecessor of current """""" + pre = current.left + + while (pre.right != None and + pre.right != current): + pre = pre.right + + """""" Make current as right child of its + inorder predecessor """""" + if(pre.right == None): + + pre.right = current + current = current.left + else: + + pre.right = None + + # Increment count if the current + # node is to be visited + count += 1 + current = current.right + + return count + + + +"""""" Function to find median in + O(n) time and O(1) space + using Morris Inorder traversal"""""" +def findMedian(root): + if (root == None): + return 0 + count = counNodes(root) + currCount = 0 + current = root + + while (current != None): + + if (current.left == None): + + # count current node + currCount += 1 + + # check if current node is the median + # Odd case + if (count % 2 != 0 and + currCount == (count + 1)//2): + return prev.data + + # Even case + elif (count % 2 == 0 and + currCount == (count//2)+1): + return (prev.data + current.data)//2 + + # Update prev for even no. of nodes + prev = current + + #Move to the right + current = current.right + + else: + + """""" Find the inorder predecessor of current """""" + pre = current.left + while (pre.right != None and + pre.right != current): + pre = pre.right + + """""" Make current as right child + of its inorder predecessor """""" + if (pre.right == None): + + pre.right = current + current = current.left + else: + + pre.right = None + + prev = pre + + # Count current node + currCount+= 1 + + # Check if the current node is the median + if (count % 2 != 0 and + currCount == (count + 1) // 2 ): + return current.data + + elif (count%2 == 0 and + currCount == (count // 2) + 1): + return (prev.data+current.data)//2 + + # update prev node for the case of even + # no. of nodes + prev = current + current = current.right + + +# Driver Code +if __name__ == '__main__': + + """""" Constructed binary tree is + 50 + / \ + 30 70 + / \ / \ + 20 40 60 80 """""" + + root = newNode(50) + insert(root, 30) + insert(root, 20) + insert(root, 40) + insert(root, 70) + insert(root, 60) + insert(root, 80) + print(""Median of BST is "",findMedian(root)) + + + +# This code is contributed +# Shubham Singh(SHUBHAMSINGH10)",constant,linear +"# Python program to find largest +# BST in a Binary Tree. + +INT_MIN = -2147483648 +INT_MAX = 2147483647 + +# Helper function that allocates a new +# node with the given data and None left +# and right pointers. +class newNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Returns Information about subtree. The +# Information also includes size of largest +# subtree which is a BST +def largestBSTBT(root): + +# Base cases : When tree is empty or it has + # one child. + if (root == None): + return 0, INT_MIN, INT_MAX, 0, True + if (root.left == None and root.right == None) : + return 1, root.data, root.data, 1, True + + # Recur for left subtree and right subtrees + l = largestBSTBT(root.left) + r = largestBSTBT(root.right) + + # Create a return variable and initialize its + # size. + ret = [0, 0, 0, 0, 0] + ret[0] = (1 + l[0] + r[0]) + + # If whole tree rooted under current root is + # BST. + if (l[4] and r[4] and l[1] < + root.data and r[2] > root.data) : + + ret[2] = min(l[2], root.data) + ret[1] = max(r[1], root.data) + + # Update answer for tree rooted under + # current 'root' + ret[3] = max(l[3], r[3]) + 1; + ret[4] = True + + return ret + + + # If whole tree is not BST, return maximum + # of left and right subtrees + ret[3] = max(l[3], r[3]) + ret[4] = False + + return ret + +# Driver Code +if __name__ == '__main__': + + """"""Let us construct the following Tree + 60 + / \ + 65 70 + / + 50 """""" + root = newNode(60) + root.left = newNode(65) + root.right = newNode(70) + root.left.left = newNode(50) + print(""Size of the largest BST is"", + largestBSTBT(root)[3]) + +# This code is contributed +# Shubham Singh(SHUBHAMSINGH10) +# Naman Sharma (NAMANSHARMA1805)",linear,linear +"# Python3 program to remove BST keys +# outside the given range + +# A BST node has key, and left and right +# pointers. A utility function to create +# a new BST node with key as given num +class newNode: + + # Constructor to create a new node + def __init__(self, data): + self.key = data + self.left = None + self.right = None + +# Removes all nodes having value outside +# the given range and returns the root +# of modified tree +def removeOutsideRange(root, Min, Max): + + # Base Case + if root == None: + return None + + # First fix the left and right + # subtrees of root + root.left = removeOutsideRange(root.left, + Min, Max) + root.right = removeOutsideRange(root.right, + Min, Max) + + # Now fix the root. There are 2 + # possible cases for root + # 1.a) Root's key is smaller than + # min value (root is not in range) + if root.key < Min: + rChild = root.right + return rChild + + # 1.b) Root's key is greater than max + # value (root is not in range) + if root.key > Max: + lChild = root.left + return lChild + + # 2. Root is in range + return root + + +# A utility function to insert a given +# key to BST +def insert(root, key): + if root == None: + return newNode(key) + if root.key > key: + root.left = insert(root.left, key) + else: + root.right = insert(root.right, key) + return root + +# Utility function to traverse the binary +# tree after conversion +def inorderTraversal(root): + if root: + inorderTraversal( root.left) + print(root.key, end = "" "") + inorderTraversal( root.right) + +# Driver Code +if __name__ == '__main__': + root = None + root = insert(root, 6) + root = insert(root, -13) + root = insert(root, 14) + root = insert(root, -8) + root = insert(root, 15) + root = insert(root, 13) + root = insert(root, 7) + + print(""Inorder traversal of the given tree is:"", + end = "" "") + inorderTraversal(root) + + root = removeOutsideRange(root, -10, 13) + print() + print(""Inorder traversal of the modified tree is:"", + end = "" "") + inorderTraversal(root) + +# This code is contributed by PranchalK",constant,linear +"# Python program to find BST keys in given range + +# 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 + +# The function prints all the keys in the given range +# [k1..k2]. Assumes that k1 < k2 +def Print(root, k1, k2): + + # Base Case + if root is None: + return + + # Since the desired o/p is sorted, recurse for left + # subtree first. If root.data is greater than k1, then + # only we can get o/p keys in left subtree + if k1 < root.data : + Print(root.left, k1, k2) + + # If root's data lies in range, then prints root's data + if k1 <= root.data and k2 >= root.data: + print (root.data,end=' ') + + # recursively call the right subtree + Print(root.right, k1, k2) + +# Driver function to test above function +k1 = 10 ; k2 = 25 ; +root = Node(20) +root.left = Node(8) +root.right = Node(22) +root.left.left = Node(4) +root.left.right = Node(12) + +Print(root, k1, k2) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",logn,linear +"# Python3 code to print BST keys in given Range +# in constant space using Morris traversal. + +# Helper function to create a new node +class newNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Function to print the keys in range +def RangeTraversal(root, n1, n2): + if root == None: + return + + curr = root + while curr: + if curr.left == None: + + # check if current node lies + # between n1 and n2 + if curr.data <= n2 and curr.data >= n1: + print(curr.data, end = "" "") + curr = curr.right + else: + pre = curr.left + + # finding the inorder predecessor- + # inorder predecessor is the right + # most in left subtree or the left + # child, i.e in BST it is the + # maximum(right most) in left subtree. + while (pre.right != None and + pre.right != curr): + pre = pre.right + + if pre.right == None: + pre.right = curr; + curr = curr.left + else: + pre.right = None + + # check if current node lies + # between n1 and n2 + if curr.data <= n2 and curr.data >= n1: + print(curr.data, end = "" "") + curr = curr.right + +# Driver Code +if __name__ == '__main__': + + # Constructed binary tree is + # 4 + # / \ + # 2 7 + # / \ / \ + # 1 3 6 10 + root = newNode(4) + root.left = newNode(2) + root.right = newNode(7) + root.left.left = newNode(1) + root.left.right = newNode(3) + root.right.left = newNode(6) + root.right.right = newNode(10) + + RangeTraversal(root, 4, 12) + +# This code is contributed by PranchalK",constant,linear +"# Python3 program to count BST nodes +# within a given range + +# Utility function to create new node +class newNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Returns count of nodes in BST in +# range [low, high] +def getCount(root, low, high): + + # Base case + if root == None: + return 0 + + # Special Optional case for improving + # efficiency + if root.data == high and root.data == low: + return 1 + + # If current node is in range, then + # include it in count and recur for + # left and right children of it + if root.data <= high and root.data >= low: + return (1 + getCount(root.left, low, high) + + getCount(root.right, low, high)) + + # If current node is smaller than low, + # then recur for right child + elif root.data < low: + return getCount(root.right, low, high) + + # Else recur for left child + else: + return getCount(root.left, low, high) + +# Driver Code +if __name__ == '__main__': + + # Let us construct the BST shown in + # the above figure + root = newNode(10) + root.left = newNode(5) + root.right = newNode(50) + root.left.left = newNode(1) + root.right.left = newNode(40) + root.right.right = newNode(100) + + # Let us constructed BST shown in above example + # 10 + # / \ + # 5 50 + # / / \ + # 1 40 100 + l = 5 + h = 45 + print(""Count of nodes between ["", l, "", "", h,""] is "", + getCount(root, l, h)) + +# This code is contributed by PranchalK",linear,constant +"# Python3 program to find Sum Of All +# Elements smaller than or equal to +# Kth Smallest Element In BST + +INT_MAX = 2147483647 + +# Binary Tree Node +"""""" utility that allocates a newNode +with the given key """""" +class createNode: + + # Construct to create a newNode + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# A utility function to insert a new +# Node with given key in BST and also +# maintain lcount ,Sum +def insert(root, key) : + + # If the tree is empty, return a new Node + if (root == None) : + return createNode(key) + + # Otherwise, recur down the tree + if (root.data > key) : + root.left = insert(root.left, key) + + else if (root.data < key): + root.right = insert(root.right, key) + + # return the (unchanged) Node pointer + return root + +# function return sum of all element smaller +# than and equal to Kth smallest element +def ksmallestElementSumRec(root, k, count) : + + # Base cases + if (root == None) : + return 0 + if (count[0] > k[0]) : + return 0 + + # Compute sum of elements in left subtree + res = ksmallestElementSumRec(root.left, k, count) + if (count[0] >= k[0]) : + return res + + # Add root's data + res += root.data + + # Add current Node + count[0] += 1 + if (count[0] >= k[0]) : + return res + + # If count is less than k, return + # right subtree Nodes + return res + ksmallestElementSumRec(root.right, + k, count) + +# Wrapper over ksmallestElementSumRec() +def ksmallestElementSum(root, k): + count = [0] + return ksmallestElementSumRec(root, k, count) + +# Driver Code +if __name__ == '__main__': + + """""" 20 + / \ + 8 22 + / \ + 4 12 + / \ + 10 14 + """""" + root = None + root = insert(root, 20) + root = insert(root, 8) + root = insert(root, 4) + root = insert(root, 12) + root = insert(root, 10) + root = insert(root, 14) + root = insert(root, 22) + + k = [3] + print(ksmallestElementSum(root, k)) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",logn,constant +"# Python3 program to find predecessor +# and successor in a BST + +# A utility function to create a +# new BST node +class newNode: + + # Constructor to create a new node + def __init__(self, data): + self.key = data + self.left = None + self.right = None + +# Function that finds predecessor and +# successor of key in BST. +def findPreSuc(root, pre, suc, key): + if root == None: + return + + # Search for given key in BST. + while root != None: + + # If root is given key. + if root.key == key: + + # the minimum value in right + # subtree is predecessor. + if root.right: + suc[0] = root.right + while suc[0].left: + suc[0] = suc[0].left + + # the maximum value in left + # subtree is successor. + if root.left: + pre[0] = root.left + while pre[0].right: + pre[0] = pre[0].right + + return + + # If key is greater than root, then + # key lies in right subtree. Root + # could be predecessor if left + # subtree of key is null. + elif root.key < key: + pre[0] = root + root = root.right + + # If key is smaller than root, then + # key lies in left subtree. Root + # could be successor if right + # subtree of key is null. + else: + suc[0] = root + root = root.left + +# A utility function to insert +# a new node with given key in BST +def insert(node, key): + if node == None: + return newNode(key) + if key < node.key: + node.left = insert(node.left, key) + else: + node.right = insert(node.right, key) + return node + +# Driver Code +if __name__ == '__main__': + key = 65 # Key to be searched in BST + + # Let us create following BST + # 50 + # / \ + # / \ + # 30 70 + # / \ / \ + # / \ / \ + # 20 40 60 80 + + root = None + root = insert(root, 50) + insert(root, 30) + insert(root, 20) + insert(root, 40) + insert(root, 70) + insert(root, 60) + insert(root, 80) + + pre, suc = [None], [None] + + findPreSuc(root, pre, suc, key) + if pre[0] != None: + print(""Predecessor is"", pre[0].key) + else: + print(""-1"") + + if suc[0] != None: + print(""Successor is"", suc[0].key) + else: + print(""-1"") + +# This code is contributed by PranchalK",constant,linear +"# Python3 program to find a pair with +# given sum using hashing +import sys +import math + + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def insert(root, data): + if root is None: + return Node(data) + if(data < root.data): + root.left = insert(root.left, data) + if(data > root.data): + root.right = insert(root.right, data) + return root + + +def findPairUtil(root, summ, unsorted_set): + if root is None: + return False + if findPairUtil(root.left, summ, unsorted_set): + return True + if unsorted_set and (summ-root.data) in unsorted_set: + print(""Pair is Found ({},{})"".format(summ-root.data, root.data)) + return True + else: + unsorted_set.add(root.data) + + return findPairUtil(root.right, summ, unsorted_set) + + +def findPair(root, summ): + unsorted_set = set() + if(not findPairUtil(root, summ, unsorted_set)): + print(""Pair do not exist!"") + + +# Driver code +if __name__ == '__main__': + root = None + root = insert(root, 15) + root = insert(root, 10) + root = insert(root, 20) + root = insert(root, 8) + root = insert(root, 12) + root = insert(root, 16) + root = insert(root, 25) + root = insert(root, 10) + summ = 28 + findPair(root, summ) + +# This code is contributed by Vikash Kumar 37",linear,linear +"# Python3 program to find pairs with given +# sum such that one element of pair exists +# in one BST and other in other BST. + +# A utility function to create a new +# BST node with key as given num +class newNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# A utility function to insert a +# given key to BST +def insert(root, key): + if root == None: + return newNode(key) + if root.data > key: + root.left = insert(root.left, key) + else: + root.right = insert(root.right, key) + return root + +# store storeInorder traversal in +# auxiliary array +def storeInorder(ptr, vect): + if ptr == None: + return + storeInorder(ptr.left, vect) + vect.append(ptr.data) + storeInorder(ptr.right, vect) + +# Function to find pair for given +# sum in different bst +# vect1[] --> stores storeInorder traversal +# of first bst +# vect2[] --> stores storeInorder traversal +# of second bst +def pairSumUtil(vect1, vect2, Sum): + + # Initialize two indexes to two + # different corners of two lists. + left = 0 + right = len(vect2) - 1 + + # find pair by moving two corners. + while left < len(vect1) and right >= 0: + + # If we found a pair + if vect1[left] + vect2[right] == Sum: + print(""("", vect1[left], "","", + vect2[right], ""),"", end = "" "") + left += 1 + right -= 1 + + # If sum is more, move to higher + # value in first lists. + else if vect1[left] + vect2[right] < Sum: + left += 1 + + # If sum is less, move to lower + # value in second lists. + else: + right -= 1 + +# Prints all pairs with given ""sum"" such that one +# element of pair is in tree with root1 and other +# node is in tree with root2. +def pairSum(root1, root2, Sum): + + # Store inorder traversals of + # two BSTs in two lists. + vect1 = [] + vect2 = [] + storeInorder(root1, vect1) + storeInorder(root2, vect2) + + # Now the problem reduces to finding a + # pair with given sum such that one + # element is in vect1 and other is in vect2. + pairSumUtil(vect1, vect2, Sum) + +# Driver Code +if __name__ == '__main__': + + # first BST + root1 = None + root1 = insert(root1, 8) + root1 = insert(root1, 10) + root1 = insert(root1, 3) + root1 = insert(root1, 6) + root1 = insert(root1, 1) + root1 = insert(root1, 5) + root1 = insert(root1, 7) + root1 = insert(root1, 14) + root1 = insert(root1, 13) + + # second BST + root2 = None + root2 = insert(root2, 5) + root2 = insert(root2, 18) + root2 = insert(root2, 2) + root2 = insert(root2, 1) + root2 = insert(root2, 3) + root2 = insert(root2, 4) + + Sum = 10 + pairSum(root1, root2, Sum) + +# This code is contributed by PranchalK",linear,linear +"# Recursive Python program to find key +# closest to k in given Binary Search Tree. + +# Utility that allocates a new node with the +# given key and NULL left and right pointers. +class newnode: + + # Constructor to create a new node + def __init__(self, data): + self.key = data + self.left = None + self.right = None + +# Function to find node with minimum +# absolute difference with given K +# min_diff --> minimum difference till now +# min_diff_key --> node having minimum absolute +# difference with K +def maxDiffUtil(ptr, k, min_diff, min_diff_key): + if ptr == None: + return + + # If k itself is present + if ptr.key == k: + min_diff_key[0] = k + return + + # update min_diff and min_diff_key by + # checking current node value + if min_diff > abs(ptr.key - k): + min_diff = abs(ptr.key - k) + min_diff_key[0] = ptr.key + + # if k is less than ptr->key then move + # in left subtree else in right subtree + if k < ptr.key: + maxDiffUtil(ptr.left, k, min_diff, + min_diff_key) + else: + maxDiffUtil(ptr.right, k, min_diff, + min_diff_key) + +# Wrapper over maxDiffUtil() +def maxDiff(root, k): + + # Initialize minimum difference + min_diff, min_diff_key = 999999999999, [-1] + + # Find value of min_diff_key (Closest + # key in tree with k) + maxDiffUtil(root, k, min_diff, min_diff_key) + + return min_diff_key[0] + +# Driver Code +if __name__ == '__main__': + root = newnode(9) + root.left = newnode(4) + root.right = newnode(17) + root.left.left = newnode(3) + root.left.right = newnode(6) + root.left.right.left = newnode(5) + root.left.right.right = newnode(7) + root.right.right = newnode(22) + root.right.right.left = newnode(20) + k = 18 + print(maxDiff(root, k)) + +# This code is contributed by PranchalK",constant,constant +"#User function Template for python3 +IMIN = -2147483648 +IMAX = 2147483647 +def largestBst(root): + if root==None: + return IMAX,IMIN,0 + if (root.left==None and root.right==None): + return root.data,root.data,1 + + left=largestBst(root.left) + right=largestBst(root.right) + + + ans=[0,0,0] + + if left[1]root.data: + ans[0]=min(left[0],right[0],root.data) + ans[1]=max(right[1],left[1],root.data) + ans[2]=1+left[2]+right[2] + return ans + + ans[0]=IMIN + ans[1]=IMAX + ans[2]=max(left[2],right[2]) + return ans + +def largestBstUtil(root): + # Return the size of the largest sub-tree which is also a BST + return largestBst(root)[2] + +# Driver Code Starts +import sys +sys.setrecursionlimit(1000000) +from collections import deque +# Tree Node +class newNode: + def __init__(self, val): + self.right = None + self.data = val + self.left = None + +# Driver Code +if __name__ == '__main__': + + """"""Let us construct the following Tree + 50 + / \ + 75 45 + / + 40 """""" + root = newNode(50) + root.left = newNode(75) + root.right = newNode(45) + root.left.left = newNode(40) + print(""Size of the largest BST is"",largestBstUtil(root))",linear,linear +"# Python3 program to add all greater values +# in every node of BST + +# A utility function to create a +# new BST node +class newNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Recursive function to add all greater +# values in every node +def modifyBSTUtil(root, Sum): + + # Base Case + if root == None: + return + + # Recur for right subtree + modifyBSTUtil(root.right, Sum) + + # Now Sum[0] has sum of nodes in right + # subtree, add root.data to sum and + # update root.data + Sum[0] = Sum[0] + root.data + root.data = Sum[0] + + # Recur for left subtree + modifyBSTUtil(root.left, Sum) + +# A wrapper over modifyBSTUtil() +def modifyBST(root): + Sum = [0] + modifyBSTUtil(root, Sum) + +# A utility function to do inorder +# traversal of BST +def inorder(root): + if root != None: + inorder(root.left) + print(root.data, end ="" "") + inorder(root.right) + +# A utility function to insert a new node +# with given data in BST +def insert(node, data): + + # If the tree is empty, return a new node + if node == None: + return newNode(data) + + # Otherwise, recur down the tree + if data <= node.data: + node.left = insert(node.left, data) + else: + node.right = insert(node.right, data) + + # return the (unchanged) node pointer + return node + +# Driver Code +if __name__ == '__main__': + + # Let us create following BST + # 50 + # / \ + # 30 70 + # / \ / \ + # 20 40 60 80 + root = None + root = insert(root, 50) + insert(root, 30) + insert(root, 20) + insert(root, 40) + insert(root, 70) + insert(root, 60) + insert(root, 80) + + modifyBST(root) + + # print inorder traversal of the + # modified BST + inorder(root) + +# This code is contributed by PranchalK",constant,linear +"# Python code to convert a sorted array +# to a balanced Binary Search Tree + +# binary tree node +class Node: + def __init__(self, d): + self.data = d + self.left = None + self.right = None + +# function to convert sorted array to a +# balanced BST +# input : sorted array of integers +# output: root node of balanced BST +def sortedArrayToBST(arr): + + if not arr: + return None + + # find middle index + mid = (len(arr)) // 2 + + # make the middle element the root + root = Node(arr[mid]) + + # left subtree of root has all + # values arr[mid] + root.right = sortedArrayToBST(arr[mid+1:]) + return root + +# A utility function to print the preorder +# traversal of the BST +def preOrder(node): + if not node: + return + + print node.data, + preOrder(node.left) + preOrder(node.right) + +# driver program to test above function +"""""" +Constructed balanced BST is + 4 +/ \ +2 6 +/ \ / \ +1 3 5 7 +"""""" + +arr = [1, 2, 3, 4, 5, 6, 7] +root = sortedArrayToBST(arr) +print ""PreOrder Traversal of constructed BST "", +preOrder(root) + +# This code is contributed by Ishita Tripathi",logn,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",linear,quadratic +"# Python3 program to correct the BST +# if two nodes are swapped +class Node: + + # Constructor to create a new node + def __init__(self, data): + + self.key = data + self.left = None + self.right = None + +# Utility function to track the nodes +# that we have to swap +def correctBstUtil(root, first, middle, + last, prev): + + if(root): + + # Recur for the left sub tree + correctBstUtil(root.left, first, + middle, last, prev) + + # If this is the first violation, mark these + # two nodes as 'first and 'middle' + if(prev[0] and root.key < prev[0].key): + if(not first[0]): + first[0] = prev[0] + middle[0] = root + else: + + # If this is the second violation, + # mark this node as last + last[0] = root + + prev[0] = root + + # Recur for the right subtree + correctBstUtil(root.right, first, + middle, last, prev) + +# A function to fix a given BST where +# two nodes are swapped. This function +# uses correctBSTUtil() to find out two +# nodes and swaps the nodes to fix the BST +def correctBst(root): + + # Followed four lines just for forming + # an array with only index 0 filled + # with None and we will update it accordingly. + # we made it null so that we can fill + # node data in them. + first = [None] + middle = [None] + last = [None] + prev = [None] + + # Setting arrays (having zero index only) + # for capturing the required node + correctBstUtil(root, first, middle, + last, prev) + + # Fixing the two nodes + if(first[0] and last[0]): + + # Swapping for first and last key values + first[0].key, last[0].key = (last[0].key, + first[0].key) + + elif(first[0] and middle[0]): + + # Swapping for first and middle key values + first[0].key, middle[0].key = (middle[0].key, + first[0].key) + + # else tree will be fine + +# Function to print inorder +# traversal of tree +def PrintInorder(root): + + if(root): + PrintInorder(root.left) + print(root.key, end = "" "") + PrintInorder(root.right) + + else: + return + +# Driver code + +# 6 +# / \ +# 10 2 +# / \ / \ +# 1 3 7 12 + +# Following 7 lines are for tree formation +root = Node(6) +root.left = Node(10) +root.right = Node(2) +root.left.left = Node(1) +root.left.right = Node(3) +root.right.left = Node(7) +root.right.right = Node(12) + +# Printing inorder traversal of normal tree +print(""inorder traversal of normal tree"") +PrintInorder(root) +print("""") + +# Function call to do the task +correctBst(root) + +# Printing inorder for corrected Bst tree +print("""") +print(""inorder for corrected BST"") + +PrintInorder(root) + +# This code is contributed by rajutkarshai",linear,linear +"# Python program to find ceil of a given value in BST + +# A Binary tree node + + +class Node: + + # Constructor to create a new node + def __init__(self, data): + self.key = data + self.left = None + self.right = None + +# Function to find ceil of a given input in BST. If input +# is more than the max key in BST, return -1 + + +def ceil(root, inp): + + # Base Case + if root == None: + return -1 + + # We found equal key + if root.key == inp: + return root.key + + # If root's key is smaller, ceil must be in right subtree + if root.key < inp: + return ceil(root.right, inp) + + # Else, either left subtree or root has the ceil value + val = ceil(root.left, inp) + return val if val >= inp else root.key + + +# Driver code +if __name__ == '__main__': + root = Node(8) + + root.left = Node(4) + root.right = Node(12) + + root.left.left = Node(2) + root.left.right = Node(6) + + root.right.left = Node(10) + root.right.right = Node(14) + + for i in range(16): + print ""% d % d"" % (i, ceil(root, i)) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",logn,logn +"# Python program to find Floor of a given value in BST + +# A Binary tree node + + +class Node: + + # Constructor to create a new node + def __init__(self, data): + self.key = data + self.left = None + self.right = None + +# Function to find Floor of a given input in BST. If input +# is more than the max key in BST, return -1 + + +def Floor(root, inp): + + # Base Case + if root == None: + return -1 + + # We found equal key + if root.key == inp: + return root.key + + # If root's key is larger, Floor must be in left subtree + if root.key > inp: + return Floor(root.left, inp) + + # Else, either right subtree or root has the Floor value + else: + floor = Floor(root.right, inp) + # exception for -1 because it is being returned in base case + return floor if floor <= inp and floor != -1 else root.key + + +# Driver code +if __name__ == '__main__': + root = Node(8) + + root.left = Node(4) + root.right = Node(12) + + root.left.left = Node(2) + root.left.right = Node(6) + + root.right.left = Node(10) + root.right.right = Node(14) + + for i in range(16): + print(i, Floor(root, i)) + +# This code is contributed by Shubham Singh",logn,logn +"# Python3 program to find floor and +# ceil of a given key in BST + +# A binary tree node has key, +# . left child and right child + + +class Node: + + def __init__(self, x): + + self.data = x + self.left = None + self.right = None + +# Helper function to find floor and +# ceil of a given key in BST + + +def floorCeilBSTHelper(root, key): + + global floor, ceil + + while (root): + if (root.data == key): + ceil = root.data + floor = root.data + return + if (key > root.data): + floor = root.data + root = root.right + else: + ceil = root.data + root = root.left + +# Display the floor and ceil of a given +# key in BST. If key is less than the min +# key in BST, floor will be -1; If key is +# more than the max key in BST, ceil will be -1; + + +def floorCeilBST(root, key): + + global floor, ceil + + # Variables 'floor' and 'ceil' + # are passed by reference + floor = -1 + ceil = -1 + + floorCeilBSTHelper(root, key) + + print(key, floor, ceil) + + +# Driver code +if __name__ == '__main__': + + floor, ceil = -1, -1 + + root = Node(8) + root.left = Node(4) + root.right = Node(12) + root.left.left = Node(2) + root.left.right = Node(6) + root.right.left = Node(10) + root.right.right = Node(14) + + for i in range(16): + floorCeilBST(root, i) + +# This code is contributed by mohit kumar 29",constant,logn +"# Python3 program of iterative traversal based +# method to find common elements in two BSTs. + +# A utility function to create a new node + + +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None + +# Function two print common elements +# in given two trees + + +def printCommon(root1, root2): + + # Create two stacks for two inorder + # traversals + s1 = [] + s2 = [] + + while 1: + + # append the Nodes of first + # tree in stack s1 + if root1: + s1.append(root1) + root1 = root1.left + + # append the Nodes of second tree + # in stack s2 + elif root2: + s2.append(root2) + root2 = root2.left + + # Both root1 and root2 are NULL here + elif len(s1) != 0 and len(s2) != 0: + root1 = s1[-1] + root2 = s2[-1] + + # If current keys in two trees are same + if root1.key == root2.key: + print(root1.key, end="" "") + s1.pop(-1) + s2.pop(-1) + + # move to the inorder successor + root1 = root1.right + root2 = root2.right + + elif root1.key < root2.key: + + # If Node of first tree is smaller, than + # that of second tree, then its obvious + # that the inorder successors of current + # Node can have same value as that of the + # second tree Node. Thus, we pop from s2 + s1.pop(-1) + root1 = root1.right + + # root2 is set to NULL, because we need + # new Nodes of tree 1 + root2 = None + elif root1.key > root2.key: + s2.pop(-1) + root2 = root2.right + root1 = None + + # Both roots and both stacks are empty + else: + break + +# A utility function to do inorder traversal + + +def inorder(root): + if root: + inorder(root.left) + print(root.key, end="" "") + inorder(root.right) + +# A utility function to insert a new Node +# with given key in BST + + +def insert(node, key): + + # If the tree is empty, return a new Node + if node == None: + return newNode(key) + + # Otherwise, recur down the tree + if key < node.key: + node.left = insert(node.left, key) + elif key > node.key: + node.right = insert(node.right, key) + + # return the (unchanged) Node pointer + return node + + +# Driver Code +if __name__ == '__main__': + + # Create first tree as shown in example + root1 = None + root1 = insert(root1, 5) + root1 = insert(root1, 1) + root1 = insert(root1, 10) + root1 = insert(root1, 0) + root1 = insert(root1, 4) + root1 = insert(root1, 7) + root1 = insert(root1, 9) + + # Create second tree as shown in example + root2 = None + root2 = insert(root2, 10) + root2 = insert(root2, 7) + root2 = insert(root2, 20) + root2 = insert(root2, 4) + root2 = insert(root2, 9) + + print(""Tree 1 : "") + inorder(root1) + print() + + print(""Tree 2 : "") + inorder(root2) + print() + + print(""Common Nodes: "") + printCommon(root1, root2) + +# This code is contributed by PranchalK",logn,linear +"# An AVL Tree based Python program to +# count inversion in an array + +# A utility function to get height of +# the tree rooted with N +def height(N): + if N == None: + return 0 + return N.height + +# A utility function to size of the +# tree of rooted with N +def size(N): + if N == None: + return 0 + return N.size + +# Helper function that allocates a new +# Node with the given key and NULL left +# and right pointers. +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None + self.height = self.size = 1 + +# A utility function to right rotate +# subtree rooted with y +def rightRotate(y): + x = y.left + T2 = x.right + + # Perform rotation + x.right = y + y.left = T2 + + # Update heights + y.height = max(height(y.left), + height(y.right)) + 1 + x.height = max(height(x.left), + height(x.right)) + 1 + + # Update sizes + y.size = size(y.left) + size(y.right) + 1 + x.size = size(x.left) + size(x.right) + 1 + + # Return new root + return x + +# A utility function to left rotate +# subtree rooted with x +def leftRotate(x): + y = x.right + T2 = y.left + + # Perform rotation + y.left = x + x.right = T2 + + # Update heights + x.height = max(height(x.left), + height(x.right)) + 1 + y.height = max(height(y.left), + height(y.right)) + 1 + + # Update sizes + x.size = size(x.left) + size(x.right) + 1 + y.size = size(y.left) + size(y.right) + 1 + + # Return new root + return y + +# Get Balance factor of Node N +def getBalance(N): + if N == None: + return 0 + return height(N.left) - height(N.right) + +# Inserts a new key to the tree rotted +# with Node. Also, updates *result (inversion count) +def insert(node, key, result): + + # 1. Perform the normal BST rotation + if node == None: + return newNode(key) + + if key < node.key: + node.left = insert(node.left, key, result) + + # UPDATE COUNT OF GREATER ELEMENTS FOR KEY + result[0] = result[0] + size(node.right) + 1 + else: + node.right = insert(node.right, key, result) + + # 2. Update height and size of this ancestor node + node.height = max(height(node.left), + height(node.right)) + 1 + node.size = size(node.left) + size(node.right) + 1 + + # 3. Get the balance factor of this ancestor + # node to check whether this node became + # unbalanced + balance = getBalance(node) + + # If this node becomes unbalanced, + # then there are 4 cases + + # Left Left Case + if (balance > 1 and key < node.left.key): + return rightRotate(node) + + # Right Right Case + if (balance < -1 and key > node.right.key): + return leftRotate(node) + + # Left Right Case + if balance > 1 and key > node.left.key: + node.left = leftRotate(node.left) + return rightRotate(node) + + # Right Left Case + if balance < -1 and key < node.right.key: + node.right = rightRotate(node.right) + return leftRotate(node) + + # return the (unchanged) node pointer + return node + +# The following function returns +# inversion count in arr[] +def getInvCount(arr, n): + root = None # Create empty AVL Tree + + result = [0] # Initialize result + + # Starting from first element, insert all + # elements one by one in an AVL tree. + for i in range(n): + + # Note that address of result is passed + # as insert operation updates result by + # adding count of elements greater than + # arr[i] on left of arr[i] + root = insert(root, arr[i], result) + + return result[0] + +# Driver Code +if __name__ == '__main__': + arr = [8, 4, 2, 1] + n = len(arr) + print(""Number of inversions count are :"", + getInvCount(arr, n)) + +# This code is contributed by PranchalK",linear,nlogn +"# Python3 program to print leaf node from +# preorder of binary search tree. + +# Binary Search +def binarySearch(inorder, l, r, d): + + mid = (l + r) >> 1 + if (inorder[mid] == d): + return mid + elif (inorder[mid] > d): + return binarySearch(inorder, l, + mid - 1, d) + else: + return binarySearch(inorder, + mid + 1, r, d) + +# Function to print Leaf Nodes by doing +# preorder traversal of tree using +# preorder and inorder arrays. +def leafNodesRec(preorder, inorder, + l, r, ind, n): + + # If l == r, therefore no right or left subtree. + # So, it must be leaf Node, print it. + if(l == r): + print(inorder[l], end = "" "") + ind[0] = ind[0] + 1 + return + + # If array is out of bound, return. + if (l < 0 or l > r or r >= n): + return + + # Finding the index of preorder element + # in inorder array using binary search. + loc = binarySearch(inorder, l, r, + preorder[ind[0]]) + + # Incrementing the index. + ind[0] = ind[0] + 1 + + # Finding on the left subtree. + leafNodesRec(preorder, inorder, + l, loc - 1, ind, n) + + # Finding on the right subtree. + leafNodesRec(preorder, inorder, + loc + 1, r, ind, n) + +# Finds leaf nodes from +# given preorder traversal. +def leafNodes(preorder, n): + + # To store inorder traversal + inorder = [0] * n + + # Copy the preorder into another array. + for i in range(n): + inorder[i] = preorder[i] + + # Finding the inorder by sorting the array. + inorder.sort() + + # Point to the index in preorder. + ind = [0] + + # Print the Leaf Nodes. + leafNodesRec(preorder, inorder, 0, + n - 1, ind, n) + + +# Driver Code +preorder = [890, 325, 290, 530, 965] +n = len(preorder) +leafNodes(preorder, n) + +# This code is contributed +# by SHUBHAMSINGH10",linear,nlogn +"# Python3 program to find rank of an +# element in a stream. + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + self.leftSize = 0 + +# Inserting a new Node. +def insert(root, data): + if root is None: + return newNode(data) + + # Updating size of left subtree. + if data <= root.data: + root.left = insert(root.left, data) + root.leftSize += 1 + else: + root.right = insert(root.right, data) + return root + +# Function to get Rank of a Node x. +def getRank(root, x): + + # Step 1. + if root.data == x: + return root.leftSize + + # Step 2. + if x < root.data: + if root.left is None: + return -1 + else: + return getRank(root.left, x) + + # Step 3. + else: + if root.right is None: + return -1 + else: + rightSize = getRank(root.right, x) + if rightSize == -1: + # x not found in right sub tree, i.e. not found in stream + return -1 + else: + return root.leftSize + 1 + rightSize + +# Driver code +if __name__ == '__main__': + arr = [5, 1, 4, 4, 5, 9, 7, 13, 3] + n = len(arr) + x = 4 + + root = None + for i in range(n): + root = insert(root, arr[i]) + + print(""Rank of"", x, ""in stream is:"", + getRank(root, x)) + x = 13 + print(""Rank of"", x, ""in stream is:"", + getRank(root, x)) + x = 8 + print(""Rank of"", x, ""in stream is:"", + getRank(root, x)) + +# This code is contributed by PranchalK",linear,linear +"# Python3 program to find rank of an +# element in a stream. + +# Driver code +if __name__ == '__main__': + a = [5, 1, 14, 4, 15, + 9, 7, 20, 11] + key = 20 + arraySize = len(a) + count = 0 + for i in range(arraySize): + if a[i] <= key: + count += 1 + + print(""Rank of"", key, + ""in stream is:"", count - 1) + +# This code is contributed by PranchalK",constant,linear +"# Python program to insert element in binary tree +class newNode(): + + def __init__(self, data): + self.key = data + self.left = None + self.right = None + +"""""" Inorder traversal of a binary tree"""""" +def inorder(temp): + + if (not temp): + return + + inorder(temp.left) + print(temp.key,end = "" "") + inorder(temp.right) + + +""""""function to insert element in binary tree """""" +def insert(temp,key): + + if not temp: + root = newNode(key) + return + q = [] + q.append(temp) + + # Do level order traversal until we find + # an empty place. + while (len(q)): + temp = q[0] + q.pop(0) + + if (not temp.left): + temp.left = newNode(key) + break + else: + q.append(temp.left) + + if (not temp.right): + temp.right = newNode(key) + break + else: + q.append(temp.right) + +# Driver code +if __name__ == '__main__': + root = newNode(10) + root.left = newNode(11) + root.left.left = newNode(7) + root.right = newNode(9) + root.right.left = newNode(15) + root.right.right = newNode(8) + + print(""Inorder traversal before insertion:"", end = "" "") + inorder(root) + + key = 12 + insert(root, key) + + print() + print(""Inorder traversal after insertion:"", end = "" "") + inorder(root) + +# This code is contributed by SHUBHAMSINGH10",np,linear +"# Python3 program to illustrate deletion in a Binary Tree + +# class to create a node with data, left child and right child. + + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Inorder traversal of a binary tree + + +def inorder(temp): + if(not temp): + return + inorder(temp.left) + print(temp.data, end="" "") + inorder(temp.right) + +# function to delete the given deepest node (d_node) in binary tree + + +def deleteDeepest(root, d_node): + q = [] + q.append(root) + while(len(q)): + temp = q.pop(0) + if temp is d_node: + temp = None + return + if temp.right: + if temp.right is d_node: + temp.right = None + return + else: + q.append(temp.right) + if temp.left: + if temp.left is d_node: + temp.left = None + return + else: + q.append(temp.left) + +# function to delete element in binary tree + + +def deletion(root, key): + if root == None: + return None + if root.left == None and root.right == None: + if root.key == key: + return None + else: + return root + key_node = None + q = [] + q.append(root) + temp = None + while(len(q)): + temp = q.pop(0) + if temp.data == key: + key_node = temp + if temp.left: + q.append(temp.left) + if temp.right: + q.append(temp.right) + if key_node: + x = temp.data + deleteDeepest(root, temp) + key_node.data = x + return root + + +# Driver code +if __name__ == '__main__': + root = Node(10) + root.left = Node(11) + root.left.left = Node(7) + root.left.right = Node(12) + root.right = Node(9) + root.right.left = Node(15) + root.right.right = Node(8) + print(""The tree before the deletion:"") + inorder(root) + key = 11 + root = deletion(root, key) + print() + print(""The tree after the deletion;"") + inorder(root) + +# This code is contributed by Monika Anandan",linear,linear +"# Python3 program to delete element in binary tree + +# class to create a node with data, left child and right child. + + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Inorder traversal of a binary tree + + +def inorder(temp): + if(not temp): + return + inorder(temp.left) + print(temp.data, end="" "") + inorder(temp.right) + + +def deletion(root, key): + if(root == None): + return None + if(root.left == None and root.right == None): + if(root.data == key): + return None + else: + return root + + key_node = None + temp = None + last = None + q = [] + q.append(root) + # Do level order traversal to find deepest + # node(temp), node to be deleted (key_node) + # and parent of deepest node(last) + while(len(q)): + + temp = q.pop(0) + + if(temp.data == key): + key_node = temp + if(temp.left): + + last = temp # storing the parent node + q.append(temp.left) + + if(temp.right): + + last = temp # storing the parent node + q.append(temp.right) + + if(key_node != None): + + key_node.data = temp.data # replacing key_node's data to deepest node's data + if(last.right == temp): + last.right = None + else: + last.left = None + + return root + + +# Driver code +if __name__ == '__main__': + root = Node(9) + root.left = Node(2) + root.left.left = Node(4) + root.left.right = Node(7) + root.right = Node(8) + + print(""Inorder traversal before deletion : "", end="""") + inorder(root) + + key = 7 + root = deletion(root, key) + print() + print(""Inorder traversal after deletion : "", end="""") + inorder(root) + +# This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear +"# Python3 implementation of tree using array +# numbering starting from 0 to n-1. +tree = [None] * 10 + + +def root(key): + if tree[0] != None: + print(""Tree already had root"") + else: + tree[0] = key + + +def set_left(key, parent): + if tree[parent] == None: + print(""Can't set child at"", (parent * 2) + 1, "", no parent found"") + else: + tree[(parent * 2) + 1] = key + + +def set_right(key, parent): + if tree[parent] == None: + print(""Can't set child at"", (parent * 2) + 2, "", no parent found"") + else: + tree[(parent * 2) + 2] = key + + +def print_tree(): + for i in range(10): + if tree[i] != None: + print(tree[i], end="""") + else: + print(""-"", end="""") + print() + + +# Driver Code +root('A') +set_right('C', 0) +set_left('D', 1) +set_right('E', 1) +set_right('F', 2) +print_tree() + +# This code is contributed by Gaurav Kumar Tailor",linear,logn +"# Python3 program to check foldable binary tree + +# A binary tree node has data, +# pointer to left child and a +# pointer to right child + + +class newNode: + def __init__(self, d): + self.data = d + self.left = None + self.right = None + +# Returns true if the given +# tree is foldable + + +def isFoldable(node): + + # base case + if node == None: + return true + + # convert left subtree to its mirror + mirror(node.left) + + # Compare the structures of the right subtree and mirrored + # left subtree + res = isStructSame(node.left, node.right) + + # Get the original tree back + mirror(node.left) + + return res + + +def isStructSame(a, b): + + if a == None and b == None: + return True + if a != None and b != None and isStructSame(a.left, b.left) and isStructSame(a.right, b.right): + return True + + return False + + +def mirror(node): + + if node == None: + return + else: + + # do the subtrees + mirror(node.left) + mirror(node.right) + + # swap the pointers in this node + temp = node.left + node.left = node.right + node.right = temp + + +# Driver Code +if __name__ == '__main__': + + ''' + The constructed binary tree is + 1 + / \ + 2 3 + \ / + 4 5 + ''' + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.right.left = newNode(4) + root.left.right = newNode(5) + + if isFoldable(root): + print(""tree is foldable"") + else: + print(""Tree is not foldable"")",linear,linear +"# Python3 program to check +# foldable binary tree + +# Utility function to create a new +# tree node + + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# Returns true if the given tree can be folded + + +def IsFoldable(root): + if (root == None): + return True + return IsFoldableUtil(root.left, root.right) + + +# A utility function that checks +# if trees with roots as n1 and n2 +# are mirror of each other +def IsFoldableUtil(n1, n2): + # If both left and right subtrees are NULL, + # then return true + if n1 == None and n2 == None: + return True + + # If one of the trees is NULL and other is not, + # then return false + if n1 == None or n2 == None: + return False + + # Otherwise check if left and + # right subtrees are mirrors of + # their counterparts + + d1 = IsFoldableUtil(n1.left, n2.right) + d2 = IsFoldableUtil(n1.right, n2.left) + return d1 and d2 + + +# Driver code +if __name__ == ""__main__"": + + """""" The constructed binary tree is + 1 + / \ + 2 3 + \ / + 4 5 +"""""" + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.right = newNode(4) + root.right.left = newNode(5) + + if IsFoldable(root): + print(""tree is foldable"") + else: + print(""tree is not foldable"") + +# This code is contributed by +# Anupam Baranwal(anupambaranwal)",linear,linear +"# class to create a node with key, left child and right child. +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + + +# Function to find whether the tree is foldable +def isFoldable(root): + + # Queue to store visited nodes + q = [] + + # Initially add the left and right nodes of root + if root != None: + q.append(root.left) + q.append(root.right) + + while (len(q) != 0): + + # Remove the front 2 nodes to + # check for None condition + p = q.pop(0) + r = q.pop(0) + + # If both are None, continue and check + # the further elements + if (p == None and r == None): + continue + + # If one of them is not None, then return False + if ((p == None and r != None) or (p != None and r == None)): + return False + + ''' Insert in the same order: + 1. left of left subtree + 2. right of right subtree + 3. right of left subtree + 4. left of right subtree + ''' + q.append(p.left) + q.append(r.right) + q.append(p.right) + q.append(r.left) + + # Only if the tree is foldable + return True + + +# Driver code +# Insert data into the tree +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.right.left = Node(4) +root.left.right = Node(5) + +# Function call +if isFoldable(root): + print(""tree is foldable"") +else: + print(""tree is not foldable"") + + # This code is contributed by mariuscristiancapatina",linear,linear +"# Python program to evaluate expression tree + +# Class to represent the nodes of syntax tree + + +class node: + def __init__(self, value): + self.left = None + self.data = value + self.right = None + +# This function receives a node of the syntax tree +# and recursively evaluate it + + +def evaluateExpressionTree(root): + + # empty tree + if root is None: + return 0 + + # leaf node + if root.left is None and root.right is None: + return int(root.data) + + # evaluate left tree + left_sum = evaluateExpressionTree(root.left) + + # evaluate right tree + right_sum = evaluateExpressionTree(root.right) + + # check which operation to apply + if root.data == '+': + return left_sum + right_sum + + elif root.data == '-': + return left_sum - right_sum + + elif root.data == '*': + return left_sum * right_sum + + else: + return left_sum // right_sum + + +# Driver function to test above problem +if __name__ == '__main__': + + # creating a sample tree + root = node('+') + root.left = node('*') + root.left.left = node('5') + root.left.right = node('-4') + root.right = node('-') + root.right.left = node('100') + root.right.right = node('20') + print (evaluateExpressionTree(root)) + + root = None + + # creating a sample tree + root = node('+') + root.left = node('*') + root.left.left = node('5') + root.left.right = node('4') + root.right = node('-') + root.right.left = node('100') + root.right.right = node('/') + root.right.right.left = node('20') + root.right.right.right = node('2') + print (evaluateExpressionTree(root)) + +# This code is contributed by Harshit Sidhwa",constant,linear +"# Python program to do inorder traversal without recursion + +# 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 + +# Iterative function for inorder tree traversal +def inOrder(root): + + # Set current to root of binary tree + current = root + stack = [] # initialize stack + + while True: + + # Reach the left most Node of the current Node + if current is not None: + + # Place pointer to a tree node on the stack + # before traversing the node's left subtree + stack.append(current) + + current = current.left + + + # BackTrack from the empty subtree and visit the Node + # at the top of the stack; however, if the stack is + # empty you are done + elif(stack): + current = stack.pop() + print(current.data, end="" "") # Python 3 printing + + # We have visited the node and its left + # subtree. Now, it's right subtree's turn + current = current.right + + else: + break + + print() + +# Driver program to test above function + +"""""" Constructed binary tree is + 1 + / \ + 2 3 + / \ + 4 5 """""" + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) + +inOrder(root) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"""""""Python3 program for finding postorder +traversal of BST from preorder traversal"""""" + +INT_MIN = -2**31 +INT_MAX = 2**31 + +# Function to find postorder traversal +# from preorder traversal. + + +def findPostOrderUtil(pre, n, minval, + maxval, preIndex): + + # If entire preorder array is traversed + # then return as no more element is left + # to be added to post order array. + if (preIndex[0] == n): + return + + # If array element does not lie in + # range specified, then it is not + # part of current subtree. + if (pre[preIndex[0]] < minval or + pre[preIndex[0]] > maxval): + return + + # Store current value, to be printed later, + # after printing left and right subtrees. + # Increment preIndex to find left and right + # subtrees, and pass this updated value to + # recursive calls. + val = pre[preIndex[0]] + preIndex[0] += 1 + + # All elements with value between minval + # and val lie in left subtree. + findPostOrderUtil(pre, n, minval, + val, preIndex) + + # All elements with value between val + # and maxval lie in right subtree. + findPostOrderUtil(pre, n, val, + maxval, preIndex) + + print(val, end="" "") + +# Function to find postorder traversal. + + +def findPostOrder(pre, n): + + # To store index of element to be + # traversed next in preorder array. + # This is passed by reference to + # utility function. + preIndex = [0] + + findPostOrderUtil(pre, n, INT_MIN, + INT_MAX, preIndex) + + +# Driver Code +if __name__ == '__main__': + pre = [40, 30, 35, 80, 100] + + n = len(pre) + + # Calling function + findPostOrder(pre, n) + +# This code is contributed by +# SHUBHAMSINGH10",linear,linear +"# Recursive Python program for level +# order traversal of Binary Tree + +# A node structure + + +class Node: + + # A utility function to create a new node + def __init__(self, key): + self.data = key + self.left = None + self.right = None + + +# Function to print level order traversal of tree +def printLevelOrder(root): + h = height(root) + for i in range(1, h+1): + printCurrentLevel(root, i) + + +# Print nodes at a current level +def printCurrentLevel(root, level): + if root is None: + return + if level == 1: + print(root.data, end="" "") + elif level > 1: + printCurrentLevel(root.left, level-1) + printCurrentLevel(root.right, level-1) + + +"""""" Compute the height of a tree--the number of nodes + along the longest path from the root node down to + the farthest leaf node +"""""" + + +def height(node): + if node is None: + return 0 + else: + # Compute the height of each subtree + lheight = height(node.left) + rheight = height(node.right) + + # Use the larger one + if lheight > rheight: + return lheight+1 + else: + return rheight+1 + + +# Driver program to test above function +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) + +print(""Level order traversal of binary tree is -"") +printLevelOrder(root) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,quadratic +"# Python program to print level +# order traversal using Queue + +# A node structure + + +class Node: + # A utility function to create a new node + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# Iterative Method to print the +# height of a binary tree + + +def printLevelOrder(root): + # Base Case + if root is None: + return + + # Create an empty queue + # for level order traversal + queue = [] + + # Enqueue Root and initialize height + queue.append(root) + + while(len(queue) > 0): + + # Print front of queue and + # remove it from queue + print(queue[0].data, end = "" "") + node = queue.pop(0) + + # Enqueue left child + if node.left is not None: + queue.append(node.left) + + # Enqueue right child + if node.right is not None: + queue.append(node.right) + + +# Driver Program to test above function +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) + +print(""Level Order Traversal of binary tree is -"") +printLevelOrder(root) +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python3 program for recursive level order +# traversal in spiral form + + +class newNode: + + # Construct to create a newNode + def __init__(self, key): + self.data = key + self.left = None + self.right = None + + +"""""" Function to print spiral traversal of a tree"""""" + + +def printSpiral(root): + + h = height(root) + + """"""ltr Left to Right. If this variable + is set, then the given level is traversed + from left to right. """""" + ltr = False + for i in range(1, h + 1): + + printGivenLevel(root, i, ltr) + + """"""Revert ltr to traverse next level + in opposite order"""""" + ltr = not ltr + + +"""""" Print nodes at a given level """""" + + +def printGivenLevel(root, level, ltr): + + if(root == None): + return + if(level == 1): + print(root.data, end="" "") + elif (level > 1): + + if(ltr): + printGivenLevel(root.left, level - 1, ltr) + printGivenLevel(root.right, level - 1, ltr) + + else: + printGivenLevel(root.right, level - 1, ltr) + printGivenLevel(root.left, level - 1, ltr) + + +"""""" Compute the ""height"" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node."""""" + + +def height(node): + + if (node == None): + return 0 + else: + + """""" compute the height of each subtree """""" + lheight = height(node.left) + rheight = height(node.right) + + """""" use the larger one """""" + if (lheight > rheight): + return(lheight + 1) + else: + return(rheight + 1) + + +# Driver Code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(7) + root.left.right = newNode(6) + root.right.left = newNode(5) + root.right.right = newNode(4) + print(""Spiral Order traversal of binary tree is"") + printSpiral(root) + +# This code is contributed +# by SHUBHAMSINGH10",linear,quadratic +"# Python3 implementation of a O(n) time +# method for spiral order traversal + +# A class to create a new node + + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def printSpiral(root): + if (root == None): + return # None check + + # Create two stacks to store + # alternate levels + s1 = [] # For levels to be printed + # from right to left + s2 = [] # For levels to be printed + # from left to right + + # append first level to first stack 's1' + s1.append(root) + + # Keep printing while any of the + # stacks has some nodes + while not len(s1) == 0 or not len(s2) == 0: + + # Print nodes of current level from s1 + # and append nodes of next level to s2 + while not len(s1) == 0: + temp = s1[-1] + s1.pop() + print(temp.data, end="" "") + + # Note that is right is appended + # before left + if (temp.right): + s2.append(temp.right) + if (temp.left): + s2.append(temp.left) + + # Print nodes of current level from s2 + # and append nodes of next level to s1 + while (not len(s2) == 0): + temp = s2[-1] + s2.pop() + print(temp.data, end="" "") + + # Note that is left is appended + # before right + if (temp.left): + s1.append(temp.left) + if (temp.right): + s1.append(temp.right) + + +# Driver Code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(7) + root.left.right = newNode(6) + root.right.left = newNode(5) + root.right.right = newNode(4) + print(""Spiral Order traversal of"", + ""binary tree is "") + printSpiral(root) + +# This code is contributed by PranchalK",linear,linear +"# Python3 implementation of above approach + +# A class to create a new node +from collections import deque + + +class newNode: + def __init__(self, data): + self.key = data + self.left = None + self.right = None + + +def spiralPrint(root): + # Declare a deque + dq = deque() + + # Insert the root of the tree into the deque + dq.append(root) + + # Create a variable that will switch in each iteration + reverse = True + + # Start iteration + while (len(dq)): + + # Save the size of the deque here itself, as in further steps the size + # of deque will frequently change + n = len(dq) + + # If we are printing left to right + if(not reverse): + + # Iterate from left to right + while (n > 0): + n -= 1 + + # Insert the child from the back of the deque + # Left child first + if (dq[0].left != None): + dq.append(dq[0].left) + + if (dq[0].right != None): + dq.append(dq[0].right) + + # Print the current processed element + print(dq[0].key, end="" "") + dq.popleft() + + # Switch reverse for next traversal + reverse = not reverse + else: + + # If we are printing right to left + # Iterate the deque in reverse order and insert the children + # from the front + while (n > 0): + n -= 1 + # Insert the child in the front of the deque + # Right child first + if (dq[-1].right != None): + dq.appendleft(dq[-1].right) + + if (dq[-1].left != None): + dq.appendleft(dq[-1].left) + + # Print the current processed element + print(dq[-1].key, end="" "") + dq.pop() + + # Switch reverse for next traversal + reverse = not reverse + + +# Driver Code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(7) + root.left.right = newNode(6) + root.right.left = newNode(5) + root.right.right = newNode(4) + print(""Spiral Order traversal of"", + ""binary tree is :"") + spiralPrint(root) + +# This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear +"# Python program for special order traversal + +# A binary tree node +class Node: + # A constructor for making a new node + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# Given a perfect binary tree print its node in +# specific order +def printSpecificLevelOrder(root): + if root is None: + return + + # Let us print root and next level first + print (root.data,end="" "") + + # Since it is perfect Binary tree, + # one of the node is needed to be checked + if root.left is not None : + print (root.left.data,end="" "") + print (root.right.data,end="" "") + + # Do anything more if there are nodes at next level + # in given perfect Binary Tree + if root.left.left is None: + return + + # Create a queue and enqueue left and right + # children of root + q = [] + q.append(root.left) + q.append(root.right) + + # We process two nodes at a time, so we need + # two variables to store two front items of queue + first = None + second = None + + # Traversal loop + while(len(q) > 0): + + # Pop two items from queue + first = q.pop(0) + second = q.pop(0) + + # Print children of first and second in reverse order + print (first.left.data,end="" "") + print (second.right.data,end="" "") + print (first.right.data,end="" "") + print (second.left.data,end="" "") + + # If first and second have grandchildren, + # enqueue them in reverse order + if first.left.left is not None: + q.append(first.left) + q.append(second.right) + q.append(first.right) + q.append(second.left) + +# Driver program to test above function + +# Perfect Binary Tree of Height 4 +root = Node(1) + +root.left= Node(2) +root.right = Node(3) + +root.left.left = Node(4) +root.left.right = Node(5) +root.right.left = Node(6) +root.right.right = Node(7) + +root.left.left.left = Node(8) +root.left.left.right = Node(9) +root.left.right.left = Node(10) +root.left.right.right = Node(11) +root.right.left.left = Node(12) +root.right.left.right = Node(13) +root.right.right.left = Node(14) +root.right.right.right = Node(15) + +root.left.left.left.left = Node(16) +root.left.left.left.right = Node(17) +root.left.left.right.left = Node(18) +root.left.left.right.right = Node(19) +root.left.right.left.left = Node(20) +root.left.right.left.right = Node(21) +root.left.right.right.left = Node(22) +root.left.right.right.right = Node(23) +root.right.left.left.left = Node(24) +root.right.left.left.right = Node(25) +root.right.left.right.left = Node(26) +root.right.left.right.right = Node(27) +root.right.right.left.left = Node(28) +root.right.right.left.right = Node(29) +root.right.right.right.left = Node(30) +root.right.right.right.right = Node(31) + +print (""Specific Level Order traversal of binary tree is"") +printSpecificLevelOrder(root); + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python3 program to reverse +# alternate levels of a tree + +# A Binary Tree Node +# Utility function to create +# a new tree node +class Node: + + # Constructor to create a new node + def __init__(self, key): + self.key = key + self.left = None + self.right = None + +def preorder(root1, root2, lvl): + + # Base cases + if (root1 == None or root2 == None): + return + + # Swap subtrees if level is even + if (lvl % 2 == 0): + t = root1.key + root1.key = root2.key + root2.key = t + + # Recur for left and right subtrees + # (Note : left of root1 is passed and + # right of root2 in first call and + # opposite in second call. + preorder(root1.left, root2.right, lvl + 1) + preorder(root1.right, root2.left, lvl + 1) + +# This function calls preorder() +# for left and right children of root +def reverseAlternate(root): + preorder(root.left, root.right, 0) + +# Inorder traversal (used to print +# initial and modified trees) +def printInorder(root): + if (root == None): + return + printInorder(root.left) + print( root.key, end = "" "") + printInorder(root.right) + +# A utility function to create a new node +def newNode(key): + temp = Node(' ') + temp.left = temp.right = None + temp.key = key + return temp + +# Driver Code +if __name__ == '__main__': + root = newNode('a') + root.left = newNode('b') + root.right = newNode('c') + root.left.left = newNode('d') + root.left.right = newNode('e') + root.right.left = newNode('f') + root.right.right = newNode('g') + root.left.left.left = newNode('h') + root.left.left.right = newNode('i') + root.left.right.left = newNode('j') + root.left.right.right = newNode('k') + root.right.left.left = newNode('l') + root.right.left.right = newNode('m') + root.right.right.left = newNode('n') + root.right.right.right = newNode('o') + + print( ""Inorder Traversal of given tree"") + printInorder(root) + + reverseAlternate(root) + + print(""\nInorder Traversal of modified tree"") + printInorder(root) + +# This code is contributed by Arnab Kundu",logn,linear +"# Python program to perform iterative preorder traversal + +# 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 + +# An iterative process to print preorder traversal of BT +def iterativePreorder(root): + + # Base CAse + if root is None: + return + + # create an empty stack and push root to it + nodeStack = [] + nodeStack.append(root) + + # Pop all items one by one. Do following for every popped item + # a) print it + # b) push its right child + # c) push its left child + # Note that right child is pushed first so that left + # is processed first */ + while(len(nodeStack) > 0): + + # Pop the top item from stack and print it + node = nodeStack.pop() + print (node.data, end="" "") + + # Push right and left children of the popped node + # to stack + if node.right is not None: + nodeStack.append(node.right) + if node.left is not None: + nodeStack.append(node.left) + +# Driver program to test above function +root = Node(10) +root.left = Node(8) +root.right = Node(2) +root.left.left = Node(3) +root.left.right = Node(5) +root.right.left = Node(2) +iterativePreorder(root) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",logn,linear +"# Tree Node +class Node: + + def __init__(self, data = 0): + self.data = data + self.left = None + self.right = None + +# Iterative function to do Preorder traversal of the tree +def preorderIterative(root): + + if (root == None): + return + + st = [] + + # start from root node (set current node to root node) + curr = root + + # run till stack is not empty or current is + # not NULL + while (len(st) or curr != None): + + # Print left children while exist + # and keep appending right into the + # stack. + while (curr != None): + + print(curr.data, end = "" "") + + if (curr.right != None): + st.append(curr.right) + + curr = curr.left + + # We reach when curr is NULL, so We + # take out a right child from stack + if (len(st) > 0): + curr = st[-1] + st.pop() + +# Driver Code + +root = Node(10) +root.left = Node(20) +root.right = Node(30) +root.left.left = Node(40) +root.left.left.left = Node(70) +root.left.right = Node(50) +root.right.left = Node(60) +root.left.left.right = Node(80) + +preorderIterative(root) + +# This code is contributed by Arnab Kundu",logn,linear +"# Python program for diagonal +# traversal of Binary Tree + +# A binary tree node +class Node: + + # Constructor to create a + # new binary tree node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +"""""" root - root of the binary tree + d - distance of current line from rightmost + -topmost slope. + diagonalPrint - multimap to store Diagonal + elements (Passed by Reference) """""" +def diagonalPrintUtil(root, d, diagonalPrintMap): + + # Base Case + if root is None: + return + + # Store all nodes of same line + # together as a vector + try : + diagonalPrintMap[d].append(root.data) + except KeyError: + diagonalPrintMap[d] = [root.data] + + # Increase the vertical distance + # if left child + diagonalPrintUtil(root.left, + d+1, diagonalPrintMap) + + # Vertical distance remains + # same for right child + diagonalPrintUtil(root.right, + d, diagonalPrintMap) + + + +# Print diagonal traversal of given binary tree +def diagonalPrint(root): + + # Create a dict to store diagonal elements + diagonalPrintMap = dict() + + # Find the diagonal traversal + diagonalPrintUtil(root, 0, diagonalPrintMap) + + print (""Diagonal Traversal of binary tree : "") + for i in diagonalPrintMap: + for j in diagonalPrintMap[i]: + print (j,end="" "") + print() + + +# Driver Program +root = Node(8) +root.left = Node(3) +root.right = Node(10) +root.left.left = Node(1) +root.left.right = Node(6) +root.right.right = Node(14) +root.right.right.left = Node(13) +root.left.right.left = Node(4) +root.left.right.right = Node(7) + +diagonalPrint(root) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,nlogn +"from collections import deque + +# A binary tree node + + +class Node: + + # Constructor to create a + # new binary tree node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def diagonal(root): + out = [] + node = root + + # queue to store left nodes + left_q = deque() + while node: + + # append data to output array + out.append(node.data) + + # if left available add it to the queue + if node.left: + left_q.appendleft(node.left) + + # if right is available change the node + if node.right: + node = node.right + else: + + # else pop the left_q + if len(left_q) >= 1: + node = left_q.pop() + else: + node = None + return out + + +# Driver Code +root = Node(8) +root.left = Node(3) +root.right = Node(10) +root.left.left = Node(1) +root.left.right = Node(6) +root.right.right = Node(14) +root.right.right.left = Node(13) +root.left.right.left = Node(4) +root.left.right.right = Node(7) + +print(diagonal(root))",linear,nlogn +"# Python Program to print diagonal traversal using queue + +# Tree Node +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None + + +def diagonalPrint(root): + if root is None: + return + + q = [] + q.append(root) + + while len(q) > 0: + size = len(q) + answer = [] + + while size > 0: + temp = q[0] + q.pop(0) + + # traversing each component; + while temp is not None: + answer.append(temp.data) + + if temp.left is not None: + q.append(temp.left) + + temp = temp.right + + size -= 1 + + result.append(answer) + + +if __name__ == '__main__': + root = Node(8) + root.left = Node(3) + root.right = Node(10) + root.left.left = Node(1) + root.left.right = Node(6) + root.right.right = Node(14) + root.right.right.left = Node(13) + root.left.right.left = Node(4) + root.left.right.right = Node(7) + + result = [] + + diagonalPrint(root) + + for i in range(len(result)): + for j in range(len(result[i])): + print(result[i][j], end="" "") + print() + +# This code is contributed by Tapesh(tapeshdua420)",linear,linear +"# Python3 program to print the diagonal traversal of binary tree + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +#root node +root=Node(0) + +# function to print in diagonal order +def traverse(): + # if the tree is empty, do not have to print + # anything + if root is None: + return + + # if root is not empty, point curr node to the + # root node + curr = root + + # Maintain a queue to store left child + q = [] + + # continue till the queue is empty and curr is null + while(len(q)!=0 or curr != None): + # if curr is not null + # 1. print the data of the curr node + # 2. if left child is present, add it to the queue + # 3. Move curr pointer to the right + if(curr != None): + print(curr.data,end="" "") + + if(curr.left != None): + q.append(curr.left) + curr = curr.right + # if curr is null, remove a node from the queue + # and point it to curr node + else: + curr = q.pop(0) + + +# Driver Code +root = Node(8) +root.left = Node(3) +root.right = Node(10) +root.left.left = Node(1) +root.left.right = Node(6) +root.right.right = Node(14) +root.right.right.left = Node(13) +root.left.right.left = Node(4) +root.left.right.right = Node(7) +traverse() + +# This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear +"# Python3 program to find density +# of a binary tree + +# A binary tree node +# Helper function to allocates a new node +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# Function to compute height and +# size of a binary tree +def heighAndSize(node, size): + + if (node == None) : + return 0 + + # compute height of each subtree + l = heighAndSize(node.left, size) + r = heighAndSize(node.right, size) + + #increase size by 1 + size[0] += 1 + + # return larger of the two + return l + 1 if(l > r) else r + 1 + +# function to calculate density +# of a binary tree +def density(root): + + if (root == None) : + return 0 + + size = [0] # To store size + + # Finds height and size + _height = heighAndSize(root, size) + + return size[0] / _height + +# Driver Code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + + print(""Density of given binary tree is "", + density(root)) + +# This code is contributed +# by SHUBHAMSINGH10",logn,linear +"#Python program to find height of full binary tree +# using preorder + +# function to return max of left subtree height +# or right subtree height +def findDepthRec(tree, n, index) : + + if (index[0] >= n or tree[index[0]] == 'l'): + return 0 + + # calc height of left subtree (In preorder + # left subtree is processed before right) + index[0] += 1 + left = findDepthRec(tree, n, index) + + # calc height of right subtree + index[0] += 1 + right = findDepthRec(tree, n, index) + return (max(left, right) + 1) + +# Wrapper over findDepthRec() +def findDepth(tree, n) : + + index = [0] + return findDepthRec(tree, n, index) + + +# Driver program to test above functions +if __name__ == '__main__': + tree= ""nlnnlll"" + n = len(tree) + + print(findDepth(tree, n)) + +# This code is contributed by SHUBHAMSINGH10",constant,linear +"# Python code to modify binary tree for +# traversal using only right pointer + +class newNode(): + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +# Function to modify tree +def modifytree(root): + + right = root.right + rightMost = root + + # if the left tree exists + if (root.left): + + # get the right-most of the + # original left subtree + rightMost = modifytree(root.left) + + # set root right to left subtree + root.right = root.left + root.left = None + + + # if the right subtree does + # not exists we are done! + if (not right): + return rightMost + + # set right pointer of right-most + # of the original left subtree + rightMost.right = right + + # modify the rightsubtree + rightMost = modifytree(right) + return rightMost + + +# printing using right pointer only +def printpre(root): + + while (root != None): + print(root.data,end="" "") + root = root.right + +# Driver code +if __name__ == '__main__': + """""" Constructed binary tree is + 10 + / \ + 8 2 + / \ + 3 5 """""" + root = newNode(10) + root.left = newNode(8) + root.right = newNode(2) + root.left.left = newNode(3) + root.left.right = newNode(5) + + modifytree(root) + printpre(root) + +# This code is contributed by SHUBHAMSINGH10",linear,linear +"# Python code to modify binary tree for +# traversal using only right pointer + +# A binary tree node has data, +# left child and right child +class newNode(): + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# An iterative process to set the right +# pointer of Binary tree +def modifytree( root): + + # Base Case + if (root == None): + return + + # Create an empty stack and append root to it + nodeStack = [] + nodeStack.append(root) + + ''' Pop all items one by one. + Do following for every popped item + a) print + b) append its right child + c) append its left child + Note that right child is appended first + so that left is processed first ''' + pre = None + while (len(nodeStack)): + + # Pop the top item from stack + node = nodeStack[-1] + nodeStack.pop() + + # append right and left children of + # the popped node to stack + if (node.right): + nodeStack.append(node.right) + if (node.left): + nodeStack.append(node.left) + + # check if some previous node exists + if (pre != None): + + # set the right pointer of + # previous node to current + pre.right = node + + # set previous node as current node + pre = node + +# printing using right pointer only +def printpre( root): + while (root != None): + print(root.data, end = "" "") + root = root.right + +# Driver code + +''' Constructed binary tree is + 10 + / \ + 8 2 +/ \ +3 5 +''' +root = newNode(10) +root.left = newNode(8) +root.right = newNode(2) +root.left.left = newNode(3) +root.left.right = newNode(5) + +modifytree(root) +printpre(root) + +# This code is contributed by SHUBHAMSINGH10",linear,linear +"# Python program to construct tree using inorder and +# preorder traversals + +# 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 + +""""""Recursive function to construct binary of size len from + Inorder traversal in[] and Preorder traversal pre[]. Initial values + of inStrt and inEnd should be 0 and len -1. The function doesn't + do any error checking for cases where inorder and preorder + do not form a tree """""" +def buildTree(inOrder, preOrder, inStrt, inEnd): + + if (inStrt > inEnd): + return None + + # Pick current node from Preorder traversal using + # preIndex and increment preIndex + tNode = Node(preOrder[buildTree.preIndex]) + buildTree.preIndex += 1 + + # If this node has no children then return + if inStrt == inEnd : + return tNode + + # Else find the index of this node in Inorder traversal + inIndex = search(inOrder, inStrt, inEnd, tNode.data) + + # Using index in Inorder Traversal, construct left + # and right subtrees + tNode.left = buildTree(inOrder, preOrder, inStrt, inIndex-1) + tNode.right = buildTree(inOrder, preOrder, inIndex + 1, inEnd) + + return tNode + +# UTILITY FUNCTIONS +# Function to find index of value in arr[start...end] +# The function assumes that value is present in inOrder[] + +def search(arr, start, end, value): + for i in range(start, end + 1): + if arr[i] == value: + return i + +def printInorder(node): + if node is None: + return + + # first recur on left child + printInorder(node.left) + + # then print the data of node + print (node.data,end=' ') + + # now recur on right child + printInorder(node.right) + +# Driver program to test above function +inOrder = ['D', 'B', 'E', 'A', 'F', 'C'] +preOrder = ['A', 'B', 'D', 'E', 'C', 'F'] +# Static variable preIndex +buildTree.preIndex = 0 +root = buildTree(inOrder, preOrder, 0, len(inOrder)-1) + +# Let us test the build tree by printing Inorder traversal +print (""Inorder traversal of the constructed tree is"") +printInorder(root) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,quadratic +"# Python3 program to construct tree using inorder +# and preorder traversals + +# A binary tree node has data, pointer to left child +# and a pointer to right child +class Node: + + def __init__(self, x): + + self.data = x + self.left = None + self.right = None + +# Recursive function to construct binary of size +# len from Inorder traversal in[] and Preorder traversal +# pre[]. Initial values of inStrt and inEnd should be +# 0 and len -1. The function doesn't do any error +# checking for cases where inorder and preorder +# do not form a tree +def buildTree(inn, pre, inStrt, inEnd): + + global preIndex, mp + + if (inStrt > inEnd): + return None + + # Pick current node from Preorder traversal + # using preIndex and increment preIndex + curr = pre[preIndex] + preIndex += 1 + tNode = Node(curr) + + # If this node has no children then return + if (inStrt == inEnd): + return tNode + + # Else find the index of this + # node in Inorder traversal + inIndex = mp[curr] + + # Using index in Inorder traversal, + # construct left and right subtress + tNode.left = buildTree(inn, pre, inStrt, + inIndex - 1) + tNode.right = buildTree(inn, pre, inIndex + 1, + inEnd) + + return tNode + +# This function mainly creates an +# unordered_map, then calls buildTree() +def buldTreeWrap(inn, pre, lenn): + + global mp + + # Store indexes of all items so that we + # we can quickly find later + # unordered_map mp; + for i in range(lenn): + mp[inn[i]] = i + + return buildTree(inn, pre, 0, lenn - 1) + +# This function is here just to test buildTree() +def printInorder(node): + + if (node == None): + return + + printInorder(node.left) + print(node.data, end = "" "") + printInorder(node.right) + +# Driver code +if __name__ == '__main__': + + mp = {} + preIndex = 0 + + inn = [ 'D', 'B', 'E', 'A', 'F', 'C' ] + pre = [ 'A', 'B', 'D', 'E', 'C', 'F' ] + lenn = len(inn) + + root = buldTreeWrap(inn, pre,lenn) + + # Let us test the built tree by printing + # Inorder traversal + print(""Inorder traversal of "" + ""the constructed tree is"") + + printInorder(root) + +# This code is contributed by mohit kumar 29",linear,linear +"# Python3 program to construct a tree using +# inorder and preorder traversal +class TreeNode: + + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +s = set() +st = [] + +# Function to build tree using given traversal +def buildTree(preorder, inorder, n): + root = None; + + pre = 0 + in_t = 0 + + while pre < n: + node = None; + + while True: + node = TreeNode(preorder[pre]) + + if (root == None): + root = node; + + if (len(st) > 0): + if (st[-1] in s): + s.discard(st[-1]); + st[-1].right = node; + st.pop(); + + else: + st[-1].left = node; + + st.append(node); + + if pre>=n or preorder[pre] == inorder[in_t]: + pre += 1 + break + pre += 1 + + node = None; + + while (len(st) > 0 and in_t < n and st[-1].val == inorder[in_t]): + node = st[-1]; + st.pop(); + in_t += 1 + + + if (node != None): + s.add(node); + st.append(node); + + return root; + +# Function to print tree in_t Inorder +def printInorder( node): + + if (node == None): + return; + + ''' first recur on left child ''' + printInorder(node.left); + + ''' then print data of node ''' + print(node.val, end="" ""); + + ''' now recur on right child ''' + printInorder(node.right); + +# Driver code +if __name__=='__main__': + + in_t = [ 9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 ] + pre = [ 1, 2, 4, 8, 9, 5, 10, 10, 3, 6, 7, 12, 13 ] + l = len(in_t) + + root = buildTree(pre, in_t, l); + + printInorder(root); + + # This code is contributed by rutvik_56.",linear,linear +"# Python program to construct tree using +# inorder and level order traversals + +# A binary tree node + + +class Node: + + # Constructor to create a new node + def __init__(self, key): + self.data = key + self.left = None + self.right = None + + +""""""Recursive function to construct binary tree of size n from +Inorder traversal ino[] and Level Order traversal level[]. +The function doesn't do any error checking for cases +where inorder and levelorder do not form a tree """""" + + +def buildTree(level, ino): + + # If ino array is not empty + if ino: + + # Check if that element exist in level order + for i in range(0, len(level)): + + if level[i] in ino: + + # Create a new node with + # the matched element + node = Node(level[i]) + + # Get the index of the matched element + # in level order array + io_index = ino.index(level[i]) + break + + # Construct left and right subtree + node.left = buildTree(level, ino[0:io_index]) + node.right = buildTree(level, ino[io_index + 1:len(ino)]) + return node + + else: + return None + + +def printInorder(node): + if node is None: + return + + # first recur on left child + printInorder(node.left) + + # then print the data of node + print(node.data, end="" "") + + # now recur on right child + printInorder(node.right) + +# Driver code + + +levelorder = [20, 8, 22, 4, 12, 10, 14] +inorder = [4, 8, 10, 12, 14, 20, 22] + +ino_len = len(inorder) +root = buildTree(levelorder, inorder) + +# Let us test the build tree by +# printing Inorder traversal +print(""Inorder traversal of the constructed tree is"") +printInorder(root) + +# This code is contributed by 'Vaibhav Kumar'",linear,cubic +"# Python program to create a Complete Binary Tree from +# its linked list representation + +# Linked List node +class ListNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.next = None + +# Binary Tree Node structure +class BinaryTreeNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Class to convert the linked list to Binary Tree +class Conversion: + + # Constructor for storing head of linked list + # and root for the Binary Tree + def __init__(self, data = None): + self.head = None + self.root = None + + def push(self, new_data): + + # Creating a new linked list node and storing data + new_node = ListNode(new_data) + + # Make next of new node as head + new_node.next = self.head + + # Move the head to point to new node + self.head = new_node + + def convertList2Binary(self): + + # Queue to store the parent nodes + q = [] + + # Base Case + if self.head is None: + self.root = None + return + + # 1.) The first node is always the root node, + # and add it to the queue + self.root = BinaryTreeNode(self.head.data) + q.append(self.root) + + # Advance the pointer to the next node + self.head = self.head.next + + # Until the end of linked list is reached, do: + while(self.head): + + # 2.a) Take the parent node from the q and + # and remove it from q + parent = q.pop(0) # Front of queue + + # 2.c) Take next two nodes from the linked list. + # We will add them as children of the current + # parent node in step 2.b. + # Push them into the queue so that they will be + # parent to the future node + leftChild= None + rightChild = None + + leftChild = BinaryTreeNode(self.head.data) + q.append(leftChild) + self.head = self.head.next + if(self.head): + rightChild = BinaryTreeNode(self.head.data) + q.append(rightChild) + self.head = self.head.next + + #2.b) Assign the left and right children of parent + parent.left = leftChild + parent.right = rightChild + + def inorderTraversal(self, root): + if(root): + self.inorderTraversal(root.left) + print (root.data,end="" "") + self.inorderTraversal(root.right) + +# Driver Program to test above function + +# Object of conversion class +conv = Conversion() +conv.push(36) +conv.push(30) +conv.push(25) +conv.push(15) +conv.push(12) +conv.push(10) + +conv.convertList2Binary() + +print (""Inorder Traversal of the constructed Binary Tree is:"") +conv.inorderTraversal(conv.root) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",np,linear +"# Python3 program to construct binary +# tree from given array in level +# order fashion Tree Node + +# Helper function that allocates a +#new node +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# Function to insert nodes in level order +def insertLevelOrder(arr, i, n): + root = None + # Base case for recursion + if i < n: + root = newNode(arr[i]) + + # insert left child + root.left = insertLevelOrder(arr, 2 * i + 1, n) + + # insert right child + root.right = insertLevelOrder(arr, 2 * i + 2, n) + + return root + +# Function to print tree nodes in +# InOrder fashion +def inOrder(root): + if root != None: + inOrder(root.left) + print(root.data,end="" "") + inOrder(root.right) + +# Driver Code +if __name__ == '__main__': + arr = [1, 2, 3, 4, 5, 6, 6, 6, 6] + n = len(arr) + root = None + root = insertLevelOrder(arr, 0, n) + inOrder(root) + +# This code is contributed by PranchalK and Improved by Thangaraj",linear,linear +"# Python3 program for construction of +# full binary tree + +# A binary tree node has data, pointer +# to left child and a pointer to right child +class Node: + + def __init__(self, data): + + self.data = data + self.left = None + self.right = None + +# A recursive function to construct +# Full from pre[] and post[]. +# preIndex is used to keep track +# of index in pre[]. l is low index +# and h is high index for the +# current subarray in post[] +def constructTreeUtil(pre: list, post: list, + l: int, h: int, + size: int) -> Node: + global preIndex + + # Base case + if (preIndex >= size or l > h): + return None + + # The first node in preorder traversal + # is root. So take the node at preIndex + # from preorder and make it root, and + # increment preIndex + root = Node(pre[preIndex]) + preIndex += 1 + + # If the current subarray has only + # one element, no need to recur + if (l == h or preIndex >= size): + return root + + # Search the next element + # of pre[] in post[] + i = l + while i <= h: + if (pre[preIndex] == post[i]): + break + + i += 1 + + # Use the index of element + # found in postorder to divide + # postorder array in two parts. + # Left subtree and right subtree + if (i <= h): + root.left = constructTreeUtil(pre, post, + l, i, size) + root.right = constructTreeUtil(pre, post, + i + 1, h-1, + size) + + return root + +# The main function to construct +# Full Binary Tree from given +# preorder and postorder traversals. +# This function mainly uses constructTreeUtil() +def constructTree(pre: list, + post: list, + size: int) -> Node: + + global preIndex + + return constructTreeUtil(pre, post, 0, + size - 1, size) + +# A utility function to print +# inorder traversal of a Binary Tree +def printInorder(node: Node) -> None: + + if (node is None): + return + + printInorder(node.left) + print(node.data, end = "" "") + + printInorder(node.right) + +# Driver code +if __name__ == ""__main__"": + + pre = [ 1, 2, 4, 8, 9, 5, 3, 6, 7 ] + post = [ 8, 9, 4, 5, 2, 6, 7, 3, 1 ] + size = len(pre) + + preIndex = 0 + + root = constructTree(pre, post, size) + + print(""Inorder traversal of "" + ""the constructed tree: "") + + printInorder(root) + +# This code is contributed by sanjeev2552",logn,constant +"# Python3 program to construct full binary +# tree using its preorder traversal and +# preorder traversal of its mirror tree + +# Utility function to create a new tree node +class newNode: + def __init__(self,data): + self.data = data + self.left = self.right = None + +# A utility function to print inorder +# traversal of a Binary Tree +def printInorder(node): + if (node == None) : + return + printInorder(node.left) + print(node.data, end = "" "") + printInorder(node.right) + +# A recursive function to construct Full +# binary tree from pre[] and preM[]. +# preIndex is used to keep track of index +# in pre[]. l is low index and h is high +# index for the current subarray in preM[] +def constructBinaryTreeUtil(pre, preM, preIndex, + l, h, size): + # Base case + if (preIndex >= size or l > h) : + return None , preIndex + + # The first node in preorder traversal + # is root. So take the node at preIndex + # from preorder and make it root, and + # increment preIndex + root = newNode(pre[preIndex]) + preIndex += 1 + + # If the current subarray has only + # one element, no need to recur + if (l == h): + return root, preIndex + + # Search the next element of + # pre[] in preM[] + i = 0 + for i in range(l, h + 1): + if (pre[preIndex] == preM[i]): + break + + # construct left and right subtrees + # recursively + if (i <= h): + + root.left, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, + i, h, size) + root.right, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, + l + 1, i - 1, size) + + # return root + return root, preIndex + +# function to construct full binary tree +# using its preorder traversal and preorder +# traversal of its mirror tree +def constructBinaryTree(root, pre, preMirror, size): + + preIndex = 0 + preMIndex = 0 + + root, x = constructBinaryTreeUtil(pre, preMirror, preIndex, + 0, size - 1, size) + + Print Inorder(root) + +# Driver code +if __name__ ==""__main__"": + + preOrder = [1, 2, 4, 5, 3, 6, 7] + preOrderMirror = [1, 3, 7, 6, 2, 5, 4] + + size = 7 + root = newNode(0) + + constructBinaryTree(root, preOrder, + preOrderMirror, size) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,quadratic +"# key structure to store a binary tree node +class Node: + def __init__(self, key, left = None, right = None): + self.key = key + self.left = left + self.right = right + +# Utility function to print binary tree nodes in-order fashion +def inorder(node): + if node: + inorder(node.left) + print(node.key, end = ' ') + inorder(node.right) + +# Function to construct a binary tree +# from specified ancestor matrix +def constructBT(mat): + + # get number of rows in the matrix + N = len(mat) + + # create an empty multi-dict + dict = {} + + # Use sum as key and row numbers as values in the multi-dict + for i in range(N): + + # find the sum of the current row + total = sum(mat[i]) + + # insert the sum and row number into the dict + dict.setdefault(total, []).append(i) + + # node[i] will store node for i in constructed tree + node = [Node(-1)] * N + last = 0 + + # the value of parent[i] is true if parent is set for i'th node + parent = [False] * N + + # Traverse the dictionary in sorted order (default behavior) + for key in dict.keys(): + for row in dict.get(key): + last = row + + # create a new node + node[row] = Node(row) + + # if leaf node, do nothing + if key == 0: + continue + + # traverse row + for i in range(N): + + # do if parent is not set and ancestor exits + if not parent[i] and mat[row][i] == 1: + + # check for the unoccupied node + if node[row].left is None: + node[row].left = node[i] + else: + node[row].right = node[i] + + # set parent for i'th node + parent[i] = True + + # last processed node is the root + return node[last] + +# Construct a Binary Tree from Ancestor Matrix +if __name__ == '__main__': + + mat = [[0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 1, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 0, 0]] + + root = constructBT(mat) + inorder(root) + +# This code is contributed by Priyadarshini Kumari",quadratic,quadratic +"# Python3 program to construct ancestor +# matrix for given tree. + +class newnode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# anc[] stores all ancestors of current node. +# This function fills ancestors for all nodes. +# It also returns size of tree. Size of tree +# is used to print ancestor matrix. +def ancestorMatrixRec(root, anc): + global mat, MAX + + # base case + if root == None: + return 0 + + # Update all ancestors of current node + data = root.data + for i in range(len(anc)): + mat[anc[i]][data] = 1 + + # Push data to list of ancestors + anc.append(data) + + # Traverse left and right subtrees + l = ancestorMatrixRec(root.left, anc) + r = ancestorMatrixRec(root.right, anc) + + # Remove data from list the list of ancestors + # as all descendants of it are processed now. + anc.pop(-1) + + return l + r + 1 + +# This function mainly calls ancestorMatrixRec() +def ancestorMatrix(root): + + # Create an empty ancestor array + anc = [] + + # Fill ancestor matrix and find + # size of tree. + n = ancestorMatrixRec(root, anc) + + # Print the filled values + for i in range(n): + for j in range(n): + print(mat[i][j], end = "" "") + print() + +# Driver Code +MAX = 100 +mat = [[0] * MAX for i in range(MAX)] + +# Construct the following binary tree +# 5 +# / \ +# 1 2 +# / \ / +# 0 4 3 +root = newnode(5) +root.left = newnode(1) +root.right = newnode(2) +root.left.left = newnode(0) +root.left.right = newnode(4) +root.right.left = newnode(3) + +ancestorMatrix(root) + +# This code is contributed by PranchalK",quadratic,quadratic +"# Python3 program to construct ancestor +# matrix for given tree. +size = 6 + +M = [[0 for j in range(size)] + for i in range(size)] + +# A binary tree node +class Node: + + def __init__(self, data): + + self.left = None + self.right = None + self.data = data + +# Helper function to create a new node +def newnode(data): + + temp = Node(data) + + return temp + +def printMatrix(): + + for i in range(size): + for j in range(size): + print(M[i][j], end = ' ') + + print() + +# First PreOrder Traversal +def MatrixUtil(root, index): + + if (root == None): + return + + preData = root.data + + # Since there is no ancestor for + # root node, so we doesn't assign + # it's value as 1 + if (index == -1): + index = root.data + else: + M[index][preData] = 1 + + MatrixUtil(root.left, preData) + MatrixUtil(root.right, preData) + +def Matrix(root): + + # Call Func MatrixUtil + MatrixUtil(root, -1) + + # Applying Transitive Closure + # for the given Matrix + for i in range(size): + for j in range(size): + for k in range(size): + M[j][k] = (M[j][k] or + (M[j][i] and + M[i][k])) + + # Printing Matrix + printMatrix() + +# Driver code +if __name__==""__main__"": + + root = newnode(5) + root.left = newnode(1) + root.right = newnode(2) + root.left.left = newnode(0) + root.left.right = newnode(4) + root.right.left = newnode(3) + + Matrix(root) + +# This code is contributed by rutvik_56",quadratic,quadratic +"# Python3 program to construct tree from +# inorder traversal + +# Helper class that allocates a new node +# with the given data and None left and +# right pointers. +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Prototypes of a utility function to get +# the maximum value in inorder[start..end] + +# Recursive function to construct binary of +# size len from Inorder traversal inorder[]. +# Initial values of start and end should be +# 0 and len -1. +def buildTree (inorder, start, end): + if start > end: + return None + + # Find index of the maximum element + # from Binary Tree + i = Max (inorder, start, end) + + # Pick the maximum value and make it root + root = newNode(inorder[i]) + + # If this is the only element in + # inorder[start..end], then return it + if start == end: + return root + + # Using index in Inorder traversal, + # construct left and right subtress + root.left = buildTree (inorder, start, i - 1) + root.right = buildTree (inorder, i + 1, end) + + return root + +# UTILITY FUNCTIONS + +# Function to find index of the maximum +# value in arr[start...end] +def Max(arr, strt, end): + i, Max = 0, arr[strt] + maxind = strt + for i in range(strt + 1, end + 1): + if arr[i] > Max: + Max = arr[i] + maxind = i + return maxind + +# This function is here just to test buildTree() +def printInorder (node): + if node == None: + return + + # first recur on left child + printInorder (node.left) + + # then print the data of node + print(node.data, end = "" "") + + # now recur on right child + printInorder (node.right) + +# Driver Code +if __name__ == '__main__': + + # Assume that inorder traversal of + # following tree is given + # 40 + # / \ + # 10 30 + # / \ + #5 28 + + inorder = [5, 10, 40, 30, 28] + Len = len(inorder) + root = buildTree(inorder, 0, Len - 1) + + # Let us test the built tree by + # printing Inorder traversal + print(""Inorder traversal of the"", + ""constructed tree is "") + printInorder(root) + +# This code is contributed by PranchalK",linear,quadratic +"# Python3 program to construct tree using +# inorder and postorder traversals + +# Helper function that allocates +# a new node +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# Recursive function to construct binary +# of size n from Inorder traversal in[] +# and Postorder traversal post[]. Initial +# values of inStrt and inEnd should be +# 0 and n -1. The function doesn't do any +# error checking for cases where inorder +# and postorder do not form a tree +def buildUtil(In, post, inStrt, inEnd, pIndex): + + # Base case + if (inStrt > inEnd): + return None + + # Pick current node from Postorder traversal + # using postIndex and decrement postIndex + node = newNode(post[pIndex[0]]) + pIndex[0] -= 1 + + # If this node has no children + # then return + if (inStrt == inEnd): + return node + + # Else find the index of this node + # in Inorder traversal + iIndex = search(In, inStrt, inEnd, node.data) + + # Using index in Inorder traversal, + # construct left and right subtress + node.right = buildUtil(In, post, iIndex + 1, + inEnd, pIndex) + node.left = buildUtil(In, post, inStrt, + iIndex - 1, pIndex) + + return node + +# This function mainly initializes index +# of root and calls buildUtil() +def buildTree(In, post, n): + pIndex = [n - 1] + return buildUtil(In, post, 0, n - 1, pIndex) + +# Function to find index of value in +# arr[start...end]. The function assumes +# that value is postsent in in[] +def search(arr, strt, end, value): + i = 0 + for i in range(strt, end + 1): + if (arr[i] == value): + break + return i + +# This function is here just to test +def preOrder(node): + if node == None: + return + print(node.data,end="" "") + preOrder(node.left) + preOrder(node.right) + +# Driver code +if __name__ == '__main__': + In = [4, 8, 2, 5, 1, 6, 3, 7] + post = [8, 4, 5, 2, 6, 7, 3, 1] + n = len(In) + + root = buildTree(In, post, n) + + print(""Preorder of the constructed tree :"") + preOrder(root) + +# This code is contributed by PranchalK",linear,quadratic +"# Python3 program to construct tree using inorder +# and postorder traversals + +# A binary tree node has data, pointer to left +# child and a pointer to right child +class Node: + + def __init__(self, x): + + self.data = x + self.left = None + self.right = None + +# Recursive function to construct binary of size n +# from Inorder traversal in[] and Postorder traversal +# post[]. Initial values of inStrt and inEnd should +# be 0 and n -1. The function doesn't do any error +# checking for cases where inorder and postorder +# do not form a tree +def buildUtil(inn, post, innStrt, innEnd): + + global mp, index + + # Base case + if (innStrt > innEnd): + return None + + # Pick current node from Postorder traversal + # using postIndex and decrement postIndex + curr = post[index] + node = Node(curr) + index -= 1 + + # If this node has no children then return + if (innStrt == innEnd): + return node + + # Else find the index of this node inn + # Inorder traversal + iIndex = mp[curr] + + # Using index inn Inorder traversal, + # construct left and right subtrees + node.right = buildUtil(inn, post, + iIndex + 1, innEnd) + node.left = buildUtil(inn, post, innStrt, + iIndex - 1) + + return node + +# This function mainly creates an unordered_map, +# then calls buildTreeUtil() +def buildTree(inn, post, lenn): + + global index + + # Store indexes of all items so that we + # we can quickly find later + for i in range(lenn): + mp[inn[i]] = i + + # Index in postorder + index = lenn - 1 + return buildUtil(inn, post, 0, lenn - 1) + +# This function is here just to test +def preOrder(node): + + if (node == None): + return + + print(node.data, end = "" "") + preOrder(node.left) + preOrder(node.right) + +# Driver Code +if __name__ == '__main__': + + inn = [ 4, 8, 2, 5, 1, 6, 3, 7 ] + post = [ 8, 4, 5, 2, 6, 7, 3, 1 ] + n = len(inn) + mp, index = {}, 0 + + root = buildTree(inn, post, n) + + print(""Preorder of the constructed tree :"") + preOrder(root) + +# This code is contributed by mohit kumar 29",linear,linear +"# Python program for above approach + +# A binary tree node has data, pointer +# to left child and a pointer to right +# child +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None + +# Tree building function +def buildTree(inorder, post, n): + # Create Stack of type Node + st = [] + # Create Set of type Node + set = [] + # Initialise postIndex with n - 1 + postIndex = n - 1 + # Initialise root with NULL + root = None + + p = n-1 + i = n-1 + + while p >= 0: + # Initialise node with NULL + node = None + + # Run loop + while True: + + # initialize new node + node = Node(post[p]) + + # check if root is equal to null + if root == None: + root = node + + # If size of set is greater than 0 + if len(st) > 0: + + # If st top is present in the set s + if st[-1] in set: + set.remove(st[-1]) + st[-1].left = node + st.pop() + else: + st[-1].right = node + + st.append(node) + + p -= 1 + if post[p+1] == inorder[i] or p < 0: + break + + node = None + + # If the stack is not empty and st top data is equal to in[i] + while len(st) > 0 and i >= 0 and st[-1].data == inorder[i]: + node = st[-1] + # Pop elements from stack + st.pop() + i -= 1 + + # if node not equal to None + if node != None: + set.append(node) + st.append(node) + + # Return root + return root + +# for print preOrder Traversal + + +def preOrder(node): + if node == None: + return + print(node.data, end="" "") + preOrder(node.left) + preOrder(node.right) + + +# Driver Code +if __name__ == '__main__': + inorder = [4, 8, 2, 5, 1, 6, 3, 7] + post = [8, 4, 5, 2, 6, 7, 3, 1] + n = len(inorder) + + # Function Call + root = buildTree(inorder, post, n) + + print(""Preorder of the constructed tree :"") + + # Function Call for preOrder + preOrder(root) + +# This code is contributed by Tapesh(tapeshdua420)",linear,linear +"# Python3 program to create a doubly linked +# list out of given a ternary tree. + +# Custom node class. +class newNode: + + def __init__(self, data): + + self.data = data + self.left = None + self.right = None + self.middle = None + +class GFG: + + def __init__(self): + + # Tail of the linked list. + self.tail = None + + # Function to push the node to the tail. + def push(self, node): + + # To put the node at the end of + # the already existing tail. + self.tail.right = node + + # To point to the previous node. + node.left = self.tail + + # Middle pointer should point to + # nothing so null. initiate right + # pointer to null. + node.middle = node.right = None + + # Update the tail position. + self.tail = node + + # Create a doubly linked list out of given + # a ternary tree By traversing the tree in + # preorder fashion. + def ternaryTree(self, node, head): + + if node == None: + return + + left = node.left + middle = node.middle + right = node.right + + if self.tail != node: + + # Already root is in the tail so dont push + # the node when it was root.In the first + # case both node and tail have root in them. + self.push(node) + + # First the left child is to be taken. + # Then middle and then right child. + self.ternaryTree(left, head) + self.ternaryTree(middle, head) + self.ternaryTree(right, head) + + def startTree(self, root): + + # Initiate the head and tail with root. + head = root + self.tail = root + self.ternaryTree(root, head) + + # Since the head,root are passed + # with reference the changes in + # root will be reflected in head. + return head + + # Utility function for printing double linked list. + def printList(self, head): + + print(""Created Double Linked list is:"") + + while head: + print(head.data, end = "" "") + head = head.right + +# Driver code +if __name__ == '__main__': + + # Constructing ternary tree as shown + # in above figure + root = newNode(30) + root.left = newNode(5) + root.middle = newNode(11) + root.right = newNode(63) + root.left.left = newNode(1) + root.left.middle = newNode(4) + root.left.right = newNode(8) + root.middle.left = newNode(6) + root.middle.middle = newNode(7) + root.middle.right = newNode(15) + root.right.left = newNode(31) + root.right.middle = newNode(55) + root.right.right = newNode(65) + + # The function which initiates the list + # process returns the head. + head = None + gfg = GFG() + head = gfg.startTree(root) + + gfg.printList(head) + +# This code is contributed by Winston Sebastian Pais",linear,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",linear,linear +"# Python3 program to conStruct a +# binary tree from the given String + +# Helper class that allocates a new node + + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# This function is here just to test + + +def preOrder(node): + if (node == None): + return + print(node.data, end=' ') + preOrder(node.left) + preOrder(node.right) + +# function to return the index of +# close parenthesis + + +def findIndex(Str, si, ei): + if (si > ei): + return -1 + + # Inbuilt stack + s = [] + for i in range(si, ei + 1): + + # if open parenthesis, push it + if (Str[i] == '('): + s.append(Str[i]) + + # if close parenthesis + elif (Str[i] == ')'): + if (s[-1] == '('): + s.pop(-1) + + # if stack is empty, this is + # the required index + if len(s) == 0: + return i + # if not found return -1 + return -1 + +# function to conStruct tree from String + + +def treeFromString(Str, si, ei): + + # Base case + if (si > ei): + return None + + # new root + root = newNode(ord(Str[si]) - ord('0')) + index = -1 + + # if next char is '(' find the + # index of its complement ')' + if (si + 1 <= ei and Str[si + 1] == '('): + index = findIndex(Str, si + 1, ei) + + # if index found + if (index != -1): + + # call for left subtree + root.left = treeFromString(Str, si + 2, + index - 1) + + # call for right subtree + root.right = treeFromString(Str, index + 2, + ei - 1) + return root + + +# Driver Code +if __name__ == '__main__': + Str = ""4(2(3)(1))(6(5))"" + root = treeFromString(Str, 0, len(Str) - 1) + preOrder(root) + +# This code is contributed by pranchalK",linear,quadratic +"# A simple inorder traversal based program to convert a +# Binary Tree to DLL + +# A Binary Tree node +class Node: + + # Constructor to create a new tree node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Standard Inorder traversal of tree +def inorder(root): + + if root is not None: + inorder(root.left) + print (""\t%d"" %(root.data),end="" "") + inorder(root.right) + +# Changes left pointers to work as previous pointers +# in converted DLL +# The function simply does inorder traversal of +# Binary Tree and updates +# left pointer using previously visited node +def fixPrevPtr(root): + if root is not None: + fixPrevPtr(root.left) + root.left = fixPrevPtr.pre + fixPrevPtr.pre = root + fixPrevPtr(root.right) + +# Changes right pointers to work as next pointers in +# converted DLL +def fixNextPtr(root): + + prev = None + # Find the right most node in BT or last node in DLL + while(root and root.right != None): + root = root.right + + # Start from the rightmost node, traverse back using + # left pointers + # While traversing, change right pointer of nodes + while(root and root.left != None): + prev = root + root = root.left + root.right = prev + + # The leftmost node is head of linked list, return it + return root + +# The main function that converts BST to DLL and returns +# head of DLL +def BTToDLL(root): + + # Set the previous pointer + fixPrevPtr(root) + + # Set the next pointer and return head of DLL + return fixNextPtr(root) + +# Traversses the DLL from left to right +def printList(root): + while(root != None): + print (""\t%d"" %(root.data),end="" "") + root = root.right + +# Driver program to test above function +root = Node(10) +root.left = Node(12) +root.right = Node(15) +root.left.left = Node(25) +root.left.right = Node(30) +root.right.left = Node(36) + +print (""Inorder Tree Traversal"") +inorder(root) + +# Static variable pre for function fixPrevPtr +fixPrevPtr.pre = None +head = BTToDLL(root) + +print (""\nDLL Traversal"") +printList(head) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python3 program to convert a given Binary Tree to Doubly Linked List +class Node: + def __init__(self, data): + self.data = data + self.left = self.right = None + +class BinaryTree: + # A simple recursive function to convert a given + # Binary tree to Doubly Linked List + # root --> Root of Binary Tree + # head --> Pointer to head node of created doubly linked list + root, head = None, None + + def BToDll(self, root: Node): + if root is None: + return + + # Recursively convert right subtree + self.BToDll(root.right) + + # Insert root into doubly linked list + root.right = self.head + + # Change left pointer of previous head + if self.head is not None: + self.head.left = root + + # Change head of doubly linked list + self.head = root + + # Recursively convert left subtree + self.BToDll(root.left) + + @staticmethod + def print_list(head: Node): + print('Extracted Double Linked list is:') + while head is not None: + print(head.data, end = ' ') + head = head.right + +# Driver program to test above function +if __name__ == '__main__': + + """""" + Constructing below tree + 5 + // \\ + 3 6 + // \\ \\ + 1 4 8 + // \\ // \\ + 0 2 7 9 + """""" + tree = BinaryTree() + tree.root = Node(5) + tree.root.left = Node(3) + tree.root.right = Node(6) + tree.root.left.left = Node(1) + tree.root.left.right = Node(4) + tree.root.right.right = Node(8) + tree.root.left.left.left = Node(0) + tree.root.left.left.right = Node(2) + tree.root.right.right.left = Node(7) + tree.root.right.right.right = Node(9) + + tree.BToDll(tree.root) + tree.print_list(tree.head) + +# This code is contributed by Rajat Srivastava",linear,linear +"# Python3 program to convert a tree +# into its sum tree + +# Node definition +class node: + + def __init__(self, data): + self.left = None + self.right = None + self.data = data + +# Convert a given tree to a tree where +# every node contains sum of values of +# nodes in left and right subtrees +# in the original tree +def toSumTree(Node) : + + # Base case + if(Node == None) : + return 0 + + # Store the old value + old_val = Node.data + + # Recursively call for left and + # right subtrees and store the sum as + # new value of this node + Node.data = toSumTree(Node.left) + \ + toSumTree(Node.right) + + # Return the sum of values of nodes + # in left and right subtrees and + # old_value of this node + return Node.data + old_val + +# A utility function to print +# inorder traversal of a Binary Tree +def printInorder(Node) : + if (Node == None) : + return + printInorder(Node.left) + print(Node.data, end = "" "") + printInorder(Node.right) + +# Utility function to create a new Binary Tree node +def newNode(data) : + temp = node(0) + temp.data = data + temp.left = None + temp.right = None + + return temp + +# Driver Code +if __name__ == ""__main__"": + root = None + x = 0 + + # Constructing tree given in the above figure + root = newNode(10) + root.left = newNode(-2) + root.right = newNode(6) + root.left.left = newNode(8) + root.left.right = newNode(-4) + root.right.left = newNode(7) + root.right.right = newNode(5) + + toSumTree(root) + + # Print inorder traversal of the converted + # tree to test result of toSumTree() + print(""Inorder Traversal of the resultant tree is: "") + printInorder(root) + +# This code is contributed by Arnab Kundu",constant,constant +"# Python3 program to store sum of nodes +# in left subtree in every node + +# Binary Tree Node + +# utility that allocates a new Node +# with the given key +class newNode: + + # Construct to create a new node + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# Function to modify a Binary Tree so +# that every node stores sum of values +# in its left child including its own value +def updatetree(root): + + # Base cases + if (not root): + return 0 + if (root.left == None and + root.right == None) : + return root.data + + # Update left and right subtrees + leftsum = updatetree(root.left) + rightsum = updatetree(root.right) + + # Add leftsum to current node + root.data += leftsum + + # Return sum of values under root + return root.data + rightsum + +# Utility function to do inorder traversal +def inorder(node) : + + if (node == None) : + return + inorder(node.left) + print(node.data, end = "" "") + inorder(node.right) + +# Driver Code +if __name__ == '__main__': + + """""" Let us construct below tree + 1 + / \ + 2 3 + / \ \ + 4 5 6 """""" + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.right.right = newNode(6) + + updatetree(root) + + print(""Inorder traversal of the modified tree is"") + inorder(root) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,linear +"# Python3 program to convert a binary +# tree to its mirror + +# Utility function to create a new +# tree node + + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + + +"""""" Change a tree so that the roles of the + left and right pointers are swapped at + every node. + +So the tree... + 4 + / \ + 2 5 + / \ + 1 3 + +is changed to... + 4 + / \ + 5 2 + / \ + 3 1 +"""""" + + +def mirror(node): + + if (node == None): + return + else: + + temp = node + + """""" do the subtrees """""" + mirror(node.left) + mirror(node.right) + + """""" swap the pointers in this node """""" + temp = node.left + node.left = node.right + node.right = temp + + +"""""" Helper function to print Inorder traversal."""""" + + +def inOrder(node): + + if (node == None): + return + + inOrder(node.left) + print(node.data, end="" "") + inOrder(node.right) + + +# Driver code +if __name__ == ""__main__"": + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + + """""" Print inorder traversal of + the input tree """""" + print(""Inorder traversal of the"", + ""constructed tree is"") + inOrder(root) + + """""" Convert tree to its mirror """""" + mirror(root) + + """""" Print inorder traversal of + the mirror tree """""" + print(""\nInorder traversal of"", + ""the mirror tree is "") + inOrder(root) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,linear +"# Python3 program to convert a Binary +# Tree to its mirror + +# A binary tree node has data, pointer to +# left child and a pointer to right child +# Helper function that allocates a new node +# with the given data and None left and +# right pointers + + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +''' Change a tree so that the roles of the left + and right pointers are swapped at every node. + So the tree... + 4 + / \ + 2 5 + / \ + 1 3 + + is changed to... + 4 + / \ + 5 2 + / \ + 3 1 + ''' + + +def mirror(root): + + if (root == None): + return + + q = [] + q.append(root) + + # Do BFS. While doing BFS, keep swapping + # left and right children + while (len(q)): + + # pop top node from queue + curr = q[0] + q.pop(0) + + # swap left child with right child + curr.left, curr.right = curr.right, curr.left + + # append left and right children + if (curr.left): + q.append(curr.left) + if (curr.right): + q.append(curr.right) + + +"""""" Helper function to print Inorder traversal."""""" + + +def inOrder(node): + if (node == None): + return + inOrder(node.left) + print(node.data, end="" "") + inOrder(node.right) + + +# Driver code +root = newNode(1) +root.left = newNode(2) +root.right = newNode(3) +root.left.left = newNode(4) +root.left.right = newNode(5) + +"""""" Print inorder traversal of the input tree """""" +print(""Inorder traversal of the constructed tree is"") +inOrder(root) + +"""""" Convert tree to its mirror """""" +mirror(root) + +"""""" Print inorder traversal of the mirror tree """""" +print(""\nInorder traversal of the mirror tree is"") +inOrder(root) + +# This code is contributed by SHUBHAMSINGH10",linear,linear +"# Python3 program to convert Binary Tree +# into Doubly Linked List where the nodes +# are represented spirally. + +# Binary tree node +class newNode: + + # Constructor to create a newNode + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +"""""" Given a reference to the head of a list + and a node, inserts the node on the front + of the list. """""" +def push(head_ref, node): + + # Make right of given node as + # head and left as None + node.right = (head_ref) + node.left = None + + # change left of head node to + # given node + if ((head_ref) != None): + (head_ref).left = node + + # move the head to point to + # the given node + (head_ref) = node + +# Function to prints contents of DLL +def printList(node): + i = 0 + while (i < len(node)): + + print(node[i].data, end = "" "") + i += 1 + +"""""" Function to print corner node at each level """""" +def spiralLevelOrder(root): + + # Base Case + if (root == None): + return + + # Create an empty deque for doing spiral + # level order traversal and enqueue root + q = [] + q.append(root) + + # create a stack to store Binary + # Tree nodes to insert into DLL later + stk = [] + + level = 0 + while (len(q)): + + # nodeCount indicates number of + # Nodes at current level. + nodeCount = len(q) + + # Dequeue all Nodes of current level + # and Enqueue all Nodes of next level + if (level&1): # odd level + while (nodeCount > 0): + + # dequeue node from front & + # push it to stack + node = q[0] + q.pop(0) + stk.append(node) + + # insert its left and right children + # in the back of the deque + if (node.left != None): + q.append(node.left) + if (node.right != None): + q.append(node.right) + + nodeCount -= 1 + + else: # even level + + while (nodeCount > 0): + + # dequeue node from the back & + # push it to stack + node = q[-1] + q.pop(-1) + stk.append(node) + + # inserts its right and left + # children in the front of + # the deque + if (node.right != None): + q.insert(0, node.right) + if (node.left != None): + q.insert(0, node.left) + nodeCount -= 1 + level += 1 + + # head pointer for DLL + head = [] + + # pop all nodes from stack and push + # them in the beginning of the list + while (len(stk)): + + head.append(stk[0]) + stk.pop(0) + + print(""Created DLL is:"") + printList(head) + +# Driver Code +if __name__ == '__main__': + + """"""Let us create Binary Tree as + shown in above example """""" + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.right.left = newNode(6) + root.right.right = newNode(7) + + root.left.left.left = newNode(8) + root.left.left.right = newNode(9) + root.left.right.left = newNode(10) + root.left.right.right = newNode(11) + #root.right.left.left = newNode(12) + root.right.left.right = newNode(13) + root.right.right.left = newNode(14) + #root.right.right.right = newNode(15) + + spiralLevelOrder(root) + +# This code is contributed +# by SHUBHAMSINGH10",linear,linear +"// C Program to convert a Binary Tree +// to a Circular Doubly Linked List +#include +#include + +// To represents a node of a Binary Tree +typedef struct Node { + struct Node *left, *right; + int data; +} Node; + +// A function that appends rightList at the end +// of leftList. +Node* concatenate(Node* leftList, Node* rightList) +{ + // If either of the list is empty + // then return the other list + if (leftList == NULL) + return rightList; + if (rightList == NULL) + return leftList; + + // Store the last Node of left List + Node* leftLast = leftList->left; + + // Store the last Node of right List + Node* rightLast = rightList->left; + + // Connect the last node of Left List + // with the first Node of the right List + leftLast->right = rightList; + rightList->left = leftLast; + + // Left of first node points to + // the last node in the list + leftList->left = rightLast; + + // Right of last node refers to the first + // node of the List + rightLast->right = leftList; + + return leftList; +} + +// Function converts a tree to a circular Linked List +// and then returns the head of the Linked List +Node* bTreeToCList(Node* root) +{ + if (root == NULL) + return NULL; + + // Recursively convert left and right subtrees + Node* left = bTreeToCList(root->left); + Node* right = bTreeToCList(root->right); + + // Make a circular linked list of single node + // (or root). To do so, make the right and + // left pointers of this node point to itself + root->left = root->right = root; + + // Step 1 (concatenate the left list with the list + // with single node, i.e., current node) + // Step 2 (concatenate the returned list with the + // right List) + return concatenate(concatenate(left, root), right); +} + +// Display Circular Link List +void displayCList(Node* head) +{ + printf(""Circular Linked List is :\n""); + Node* itr = head; + do { + printf(""%d "", itr->data); + itr = itr->right; + } while (head != itr); + printf(""\n""); +} + +// Create a new Node and return its address +Node* newNode(int data) +{ + Node* temp = (Node*)malloc(sizeof(Node)); + temp->data = data; + temp->left = temp->right = NULL; + return temp; +} + +// Driver Program to test above function +int main() +{ + Node* root = newNode(10); + root->left = newNode(12); + root->right = newNode(15); + root->left->left = newNode(25); + root->left->right = newNode(30); + root->right->left = newNode(36); + + Node* head = bTreeToCList(root); + displayCList(head); + + return 0; +} + +// This code is contributed by Aditya Kumar (adityakumar129)",logn,linear +"# Python3 Program to convert a Binary +# Tree to a Circular Doubly Linked List + + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# A function that appends rightList +# at the end of leftList. + + +def concatenate(leftList, rightList): + + # If either of the list is empty + # then return the other list + if (leftList == None): + return rightList + if (rightList == None): + return leftList + + # Store the last Node of left List + leftLast = leftList.left + + # Store the last Node of right List + rightLast = rightList.left + + # Connect the last node of Left List + # with the first Node of the right List + leftLast.right = rightList + rightList.left = leftLast + + # Left of first node points to + # the last node in the list + leftList.left = rightLast + + # Right of last node refers to + # the first node of the List + rightLast.right = leftList + + return leftList + +# Function converts a tree to a circular +# Linked List and then returns the head +# of the Linked List + + +def bTreeToCList(root): + if (root == None): + return None + + # Recursively convert left and + # right subtrees + left = bTreeToCList(root.left) + right = bTreeToCList(root.right) + + # Make a circular linked list of single + # node (or root). To do so, make the + # right and left pointers of this node + # point to itself + root.left = root.right = root + + # Step 1 (concatenate the left list + # with the list with single + # node, i.e., current node) + # Step 2 (concatenate the returned list + # with the right List) + return concatenate(concatenate(left, + root), right) + +# Display Circular Link List + + +def displayCList(head): + print(""Circular Linked List is :"") + itr = head + first = 1 + while (head != itr or first): + print(itr.data, end="" "") + itr = itr.right + first = 0 + print() + + +# Driver Code +if __name__ == '__main__': + root = newNode(10) + root.left = newNode(12) + root.right = newNode(15) + root.left.left = newNode(25) + root.left.right = newNode(30) + root.right.left = newNode(36) + + head = bTreeToCList(root) + displayCList(head) + +# This code is contributed by PranchalK",logn,linear +"# Class to define a node +# structure of the tree +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# Function to convert ternary +# expression to a Binary tree +# It returns the root node +# of the tree +def convert_expression(expression, i): + if i >= len(expression): + return None + + # Create a new node object + # for the expression at + # ith index + root = Node(expression[i]) + + i += 1 + + # if current character of + # ternary expression is '?' + # then we add next character + # as a left child of + # current node + if (i < len(expression) and + expression[i] is ""?""): + root.left = convert_expression(expression, i + 1) + + # else we have to add it + # as a right child of + # current node expression[0] == ':' + elif i < len(expression): + root.right = convert_expression(expression, i + 1) + return root + +# Function to print the tree +# in a pre-order traversal pattern +def print_tree(root): + if not root: + return + print(root.data, end=' ') + print_tree(root.left) + print_tree(root.right) + +# Driver Code +if __name__ == ""__main__"": + string_expression = ""a?b?c:d:e"" + root_node = convert_expression(string_expression, 0) + print_tree(root_node) + +# This code is contributed +# by Kanav Malhotra",linear,linear +"# Python3 program for Minimum swap required +# to convert binary tree to binary search tree + +# Inorder Traversal of Binary Tree +def inorder(a, n, index): + + global v + + # If index is greater or equal to + # vector size + if (index >= n): + return + + inorder(a, n, 2 * index + 1) + + # Push elements in vector + v.append(a[index]) + inorder(a, n, 2 * index + 2) + +# Function to find minimum swaps +# to sort an array +def minSwaps(): + + global v + t = [[0, 0] for i in range(len(v))] + ans = -2 + + for i in range(len(v)): + t[i][0], t[i][1] = v[i], i + + t, i = sorted(t), 0 + + while i < len(t): + + # break + # second element is equal to i + if (i == t[i][1]): + i += 1 + continue + else: + + # Swapping of elements + t[i][0], t[t[i][1]][0] = t[t[i][1]][0], t[i][0] + t[i][1], t[t[i][1]][1] = t[t[i][1]][1], t[i][1] + + # Second is not equal to i + if (i == t[i][1]): + i -= 1 + + i += 1 + + ans += 1 + + return ans + +# Driver Code +if __name__ == '__main__': + + v = [] + a = [ 5, 6, 7, 8, 9, 10, 11 ] + n = len(a) + inorder(a, n, 0) + + print(minSwaps()) + +# This code is contributed by mohit kumar 29",linear,nlogn +"# Python3 program to check children +# sum property + +# Helper class that allocates a new +# node with the given data and None +# left and right pointers. + + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# returns 1 if children sum property +# holds for the given node and both +# of its children + + +def isSumProperty(node): + + # left_data is left child data and + # right_data is for right child data + left_data = 0 + right_data = 0 + + # If node is None or it's a leaf + # node then return true + if(node == None or (node.left == None and + node.right == None)): + return 1 + else: + + # If left child is not present then + # 0 is used as data of left child + if(node.left != None): + left_data = node.left.data + + # If right child is not present then + # 0 is used as data of right child + if(node.right != None): + right_data = node.right.data + + # if the node and both of its children + # satisfy the property return 1 else 0 + if((node.data == left_data + right_data) and + isSumProperty(node.left) and + isSumProperty(node.right)): + return 1 + else: + return 0 + + +# Driver Code +if __name__ == '__main__': + root = newNode(10) + root.left = newNode(8) + root.right = newNode(2) + root.left.left = newNode(3) + root.left.right = newNode(5) + root.right.right = newNode(2) + + # Function call + if(isSumProperty(root)): + print(""The given tree satisfies the"", + ""children sum property "") + else: + print(""The given tree does not satisfy"", + ""the children sum property "") + +# This code is contributed by PranchalK",logn,linear +"# Python program to check if two nodes in a binary +# tree are cousins + +# A Binary Tree Node +class Node: + + # Constructor to create a new Binary Tree + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +def isSibling(root, a , b): + + # Base Case + if root is None: + return 0 + + return ((root.left == a and root.right ==b) or + (root.left == b and root.right == a)or + isSibling(root.left, a, b) or + isSibling(root.right, a, b)) + +# Recursive function to find level of Node 'ptr' in +# a binary tree +def level(root, ptr, lev): + + # Base Case + if root is None : + return 0 + if root == ptr: + return lev + + # Return level if Node is present in left subtree + l = level(root.left, ptr, lev+1) + if l != 0: + return l + + # Else search in right subtree + return level(root.right, ptr, lev+1) + + +# Returns 1 if a and b are cousins, otherwise 0 +def isCousin(root,a, b): + + # 1. The two nodes should be on the same level in + # the binary tree + # The two nodes should not be siblings(means that + # they should not have the same parent node + + if ((level(root,a,1) == level(root, b, 1)) and + not (isSibling(root, a, b))): + return 1 + else: + return 0 + + +# Driver program to test 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.right.right = Node(15) +root.right.left = Node(6) +root.right.right = Node(7) +root.right.left.right = Node(8) + +node1 = root.left.right +node2 = root.right.right + +print (""Yes"" if isCousin(root, node1, node2) == 1 else ""No"") + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python program to check if all leaves are at same level + +# 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 + +# Recursive function which check whether all leaves are at +# same level +def checkUtil(root, level): + + # Base Case + if root is None: + return True + + # If a tree node is encountered + if root.left is None and root.right is None: + + # When a leaf node is found first time + if check.leafLevel == 0 : + check.leafLevel = level # Set first leaf found + return True + + # If this is not first leaf node, compare its level + # with first leaf's level + return level == check.leafLevel + + # If this is not first leaf node, compare its level + # with first leaf's level + return (checkUtil(root.left, level+1)and + checkUtil(root.right, level+1)) + +def check(root): + level = 0 + check.leafLevel = 0 + return (checkUtil(root, level)) + +# Driver program to test above function +root = Node(12) +root.left = Node(5) +root.left.left = Node(3) +root.left.right = Node(9) +root.left.left.left = Node(1) +root.left.right.left = Node(2) + +if(check(root)): + print ""Leaves are at same level"" +else: + print ""Leaves are not at same level"" + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python3 program to check if all leaf nodes +# are at same level of binary tree +INT_MAX = 2**31 +INT_MIN = -2**31 + +# Tree Node +# returns a new tree Node +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# return true if all leaf nodes are +# at same level, else false +def checkLevelLeafNode(root) : + + if (not root) : + return 1 + + # create a queue for level + # order traversal + q = [] + q.append(root) + + result = INT_MAX + level = 0 + + # traverse until the queue is empty + while (len(q)): + size = len(q) + level += 1 + + # traverse for complete level + while(size > 0 or len(q)): + temp = q[0] + q.pop(0) + + # check for left child + if (temp.left) : + q.append(temp.left) + + # if its leaf node + if(not temp.left.right and + not temp.left.left): + + # if it's first leaf node, + # then update result + if (result == INT_MAX): + result = level + + # if it's not first leaf node, + # then compare the level with + # level of previous leaf node + elif (result != level): + return 0 + + # check for right child + if (temp.right) : + q.append(temp.right) + + # if it's leaf node + if (not temp.right.left and + not temp.right.right): + + # if it's first leaf node till now, + # then update the result + if (result == INT_MAX): + result = level + + # if it is not the first leaf node, + # then compare the level with level + # of previous leaf node + elif(result != level): + return 0 + size -= 1 + return 1 + +# Driver Code +if __name__ == '__main__': + + # construct a tree + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.right = newNode(4) + root.right.left = newNode(5) + root.right.right = newNode(6) + + result = checkLevelLeafNode(root) + if (result) : + print(""All leaf nodes are at same level"") + else: + print(""Leaf nodes not at same level"") + +# This code is contributed by SHUBHAMSINGH10",linear,linear +"# Python3 program to check if there +# exist an edge whose removal creates +# two trees of same size + +# utility function to create a new node +class newNode: + def __init__(self, x): + self.data = x + self.left = self.right = None + +# To calculate size of tree +# with given root +def count(root): + if (root == None): + return 0 + return (count(root.left) + + count(root.right) + 1) + +# This function returns true if there +# is an edge whose removal can divide +# the tree in two halves n is size of tree +def checkRec(root, n): + + # Base cases + if (root == None): + return False + + # Check for root + if (count(root) == n - count(root)): + return True + + # Check for rest of the nodes + return (checkRec(root.left, n) or + checkRec(root.right, n)) + +# This function mainly uses checkRec() +def check(root): + + # Count total nodes in given tree + n = count(root) + + # Now recursively check all nodes + return checkRec(root, n) + +# Driver code +if __name__ == '__main__': + root = newNode(5) + root.left = newNode(1) + root.right = newNode(6) + root.left.left = newNode(3) + root.right.left = newNode(7) + root.right.right = newNode(4) + + if check(root): + print(""YES"") + else: + print(""NO"") + +# This code is contributed by PranchalK",linear,quadratic +"# Python3 program to check if there exist +# an edge whose removal creates two trees +# of same size +class Node: + + def __init__(self, x): + + self.key = x + self.left = None + self.right = None + +# To calculate size of tree with +# given root +def count(node): + + if (node == None): + return 0 + + return (count(node.left) + + count(node.right) + 1) + +# This function returns size of tree rooted +# with given root. It also set ""res"" as true +# if there is an edge whose removal divides +# tree in two halves.n is size of tree +def checkRec(root, n): + + global res + + # Base case + if (root == None): + return 0 + + # Compute sizes of left and right children + c = (checkRec(root.left, n) + 1 + + checkRec(root.right, n)) + + # If required property is true for + # current node set ""res"" as true + if (c == n - c): + res = True + + # Return size + return c + +# This function mainly uses checkRec() +def check(root): + + # Count total nodes in given tree + n = count(root) + + # Initialize result and recursively + # check all nodes + # bool res = false; + checkRec(root, n) + +# Driver code +if __name__ == '__main__': + + res = False + root = Node(5) + root.left = Node(1) + root.right = Node(6) + root.left.left = Node(3) + root.right.left = Node(7) + root.right.right = Node(4) + + check(root) + + if res: + print(""YES"") + else: + print(""NO"") + +# This code is contributed by mohit kumar 29",linear,linear +"# Python3 program to check if two Leaf +# Traversal of Two Binary Trees is same or not + +# Binary Tree node + + +class Node: + def __init__(self, x): + self.data = x + self.left = self.right = None + + def isLeaf(self): + return (self.left == None and + self.right == None) + +# Returns true of leaf traversal of +# two trees is same, else false + + +def isSame(root1, root2): + + # Create empty stacks. These stacks are going + # to be used for iterative traversals. + s1 = [] + s2 = [] + + s1.append(root1) + s2.append(root2) + + # Loop until either of two stacks + # is not empty + while (len(s1) != 0 or len(s2) != 0): + + # If one of the stacks is empty means other + # stack has extra leaves so return false + if (len(s1) == 0 or len(s2) == 0): + return False + + temp1 = s1.pop(-1) + while (temp1 != None and not temp1.isLeaf()): + + # append right and left children of temp1. + # Note that right child is inserted + # before left + if (temp1.right != None): + s1.append(temp1. right) + if (temp1.left != None): + s1.append(temp1.left) + temp1 = s1.pop(-1) + + # same for tree2 + temp2 = s2.pop(-1) + while (temp2 != None and not temp2.isLeaf()): + if (temp2.right != None): + s2.append(temp2.right) + if (temp2.left != None): + s2.append(temp2.left) + temp2 = s2.pop(-1) + + # If one is None and other is not, + # then return false + if (temp1 == None and temp2 != None): + return False + if (temp1 != None and temp2 == None): + return False + + # If both are not None and data is + # not same return false + if (temp1 != None and temp2 != None): + if (temp1.data != temp2.data): + return False + + # If control reaches this point, + # all leaves are matched + return True + + +# Driver Code +if __name__ == '__main__': + + # Let us create trees in above example 1 + root1 = Node(1) + root1.left = Node(2) + root1.right = Node(3) + root1.left.left = Node(4) + root1.right.left = Node(6) + root1.right.right = Node(7) + + root2 = Node(0) + root2.left = Node(1) + root2.right = Node(5) + root2.left.right = Node(4) + root2.right.left = Node(6) + root2.right.right = Node(7) + + if (isSame(root1, root2)): + print(""Same"") + else: + print(""Not Same"") + +# This code is contributed by pranchalK",nlogn,linear +"# Python3 program to find deepest +# left leaf Binary search Tree + +# Helper function that allocates a +# new node with the given data and +# None left and right pairs. +class getNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# function to check whether a binary +# tree is a full binary tree or not +def isFullBinaryTree( root) : + + # if tree is empty + if (not root) : + return True + + # queue used for level order + # traversal + q = [] + + # append 'root' to 'q' + q.append(root) + + # traverse all the nodes of the + # binary tree level by level + # until queue is empty + while (not len(q)): + + # get the pointer to 'node' + # at front of queue + node = q[0] + q.pop(0) + + # if it is a leaf node then continue + if (node.left == None and + node.right == None): + continue + + # if either of the child is not None + # and the other one is None, then + # binary tree is not a full binary tee + if (node.left == None or + node.right == None): + return False + + # append left and right childs + # of 'node' on to the queue 'q' + q.append(node.left) + q.append(node.right) + + # binary tree is a full binary tee + return True + +# Driver Code +if __name__ == '__main__': + root = getNode(1) + root.left = getNode(2) + root.right = getNode(3) + root.left.left = getNode(4) + root.left.right = getNode(5) + + if (isFullBinaryTree(root)) : + print(""Yes"" ) + else: + print(""No"") + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",constant,linear +""""""" Program to check if a given Binary +Tree is balanced like a Red-Black Tree """""" + +# Helper function that allocates a new +# node with the given data and None +# left and right pointers. +class newNode: + + # Construct to create a new node + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# Returns returns tree if the Binary +# tree is balanced like a Red-Black +# tree. This function also sets value +# in maxh and minh (passed by +# reference). maxh and minh are set +# as maximum and minimum heights of root. +def isBalancedUtil(root, maxh, minh) : + + # Base case + if (root == None) : + + maxh = minh = 0 + return True + + + lmxh=0 + + # To store max and min + # heights of left subtree + lmnh=0 + + # To store max and min + # heights of right subtree + rmxh, rmnh=0,0 + + # Check if left subtree is balanced, + # also set lmxh and lmnh + if (isBalancedUtil(root.left, lmxh, lmnh) == False) : + return False + + # Check if right subtree is balanced, + # also set rmxh and rmnh + if (isBalancedUtil(root.right, rmxh, rmnh) == False) : + return False + + # Set the max and min heights of + # this node for the parent call + maxh = max(lmxh, rmxh) + 1 + minh = min(lmnh, rmnh) + 1 + + # See if this node is balanced + if (maxh <= 2 * minh) : + return True + + return False + + +# A wrapper over isBalancedUtil() +def isBalanced(root) : + + maxh, minh =0,0 + return isBalancedUtil(root, maxh, minh) + +# Driver Code +if __name__ == '__main__': + root = newNode(10) + root.left = newNode(5) + root.right = newNode(100) + root.right.left = newNode(50) + root.right.right = newNode(150) + root.right.left.left = newNode(40) + if (isBalanced(root)): + print(""Balanced"") + else: + print(""Not Balanced"") + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,linear +"MAX = 100 + +# class for a tree node +class Node: + def __init__(self): + self.key = ' ' + self.left = None + self.right = None + +# A utility function to create a new BST node +def newNode(item): + temp = Node() + temp.key = item + return temp + +# A utility function to store inorder traversal of tree rooted +# with root in an array arr[]. Note that i is passed as reference +def storeInorder(root, i): + if (root == None): + return '$' + res = storeInorder(root.left, i) + res += root.key + res += storeInorder(root.right, i) + return res + +# A utility function to store preorder traversal of tree rooted +# with root in an array arr[]. Note that i is passed as reference +def storePreOrder(root, i): + if (root == None): + return '$' + res = root.key + res += storePreOrder(root.left, i) + res += storePreOrder(root.right, i) + return res + +# This function returns true if S is a subtree of T, otherwise false +def isSubtree(T, S): + # base cases + if (S == None): + return True + if (T == None): + return False + + # Store Inorder traversals of T and S in inT[0..m-1] + # and inS[0..n-1] respectively + m = 0 + n = 0 + inT = storeInorder(T, m) + inS = storeInorder(S, n) + + # If inS[] is not a substring of inT[], return false + res = True + if inS in inT: + res = True + else: + res = False + if(res == False): + return res + + # Store Preorder traversals of T and S in preT[0..m-1] + # and preS[0..n-1] respectively + m = 0 + n = 0 + preT = storePreOrder(T, m) + preS = storePreOrder(S, n) + + # If preS[] is not a substring of preT[], return false + # Else return true + if preS in preT: + return True + else: + return False + +# Driver program to test above function +T = newNode('a') +T.left = newNode('b') +T.right = newNode('d') +T.left.left = newNode('c') +T.right.right = newNode('e') + +S = newNode('a') +S.left = newNode('b') +S.left.left = newNode('c') +S.right = newNode('d') + +if (isSubtree(T, S)): + print(""Yes: S is a subtree of T"") +else: + print(""No: S is NOT a subtree of T"") + + # This code is contributed by rj13to.",linear,linear +"# Python3 program to check if two +# trees are mirror of each other + +# A binary tree node +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Given two trees, return true +# if they are mirror of each other +def areMirror(a, b): + + # Base case : Both empty + if a is None and b is None: + return True + + # If only one is empty + if a is None or b is None: + return False + + # Both non-empty, compare them + # recursively. Note that in + # recursive calls, we pass left + # of one tree and right of other tree + return (a.data == b.data and + areMirror(a.left, b.right) and + areMirror(a.right , b.left)) + +# Driver code +root1 = Node(1) +root2 = Node(1) + +root1.left = Node(2) +root1.right = Node(3) +root1.left.left = Node(4) +root1.left.right = Node(5) + +root2.left = Node(3) +root2.right = Node(2) +root2.right.left = Node(5) +root2.right.right = Node(4) + +if areMirror(root1, root2): + print (""Yes"") +else: + print (""No"") + +# This code is contributed by AshishR",logn,linear +"# Python3 implementation to check whether +# the two binary trees are mirrors of each +# other or not + +# Utility function to create and return +# a new node for a binary tree +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# function to check whether the two binary +# trees are mirrors of each other or not +def areMirrors(root1, root2): + st1 = [] + st2 = [] + while (1): + + # iterative inorder traversal of 1st tree + # and reverse inorder traversal of 2nd tree + while (root1 and root2): + + # if the corresponding nodes in the + # two traversal have different data + # values, then they are not mirrors + # of each other. + if (root1.data != root2.data): + return ""No"" + + st1.append(root1) + st2.append(root2) + root1 = root1.left + root2 = root2.right + + # if at any point one root becomes None and + # the other root is not None, then they are + # not mirrors. This condition verifies that + # structures of tree are mirrors of each other. + if (not (root1 == None and root2 == None)): + return ""No"" + + if (not len(st1) == 0 and not len(st2) == 0): + root1 = st1[-1] + root2 = st2[-1] + st1.pop(-1) + st2.pop(-1) + + # we have visited the node and its left + # subtree. Now, it's right subtree's turn + root1 = root1.right + + # we have visited the node and its right + # subtree. Now, it's left subtree's turn + root2 = root2.left + + # both the trees have been + # completely traversed + else: + break + + # trees are mirrors of each other + return ""Yes"" + +# Driver Code +if __name__ == '__main__': + + # 1st binary tree formation + root1 = newNode(1) # 1 + root1.left = newNode(3) # / \ + root1.right = newNode(2) # 3 2 + root1.right.left = newNode(5)# / \ + root1.right.right = newNode(4) # 5 4 + + # 2nd binary tree formation + root2 = newNode(1) # 1 + root2.left = newNode(2) # / \ + root2.right = newNode(3) # 2 3 + root2.left.left = newNode(4)# / \ + root2.left.right = newNode(5)# 4 5 + + print(areMirrors(root1, root2)) + +# This code is contributed by pranchalK",linear,linear +"# Python3 program to program to check if a +# given Binary Tree is symmetric or not + +# Helper function that allocates a new +# node with the given data and None +# left and right pairs. +class newNode: + + # Constructor to create a new node + def __init__(self, key): + self.key = key + self.left = None + self.right = None + +# function to check if a given +# Binary Tree is symmetric or not +def isSymmetric( root) : + + # if tree is empty + if (root == None) : + return True + + # If it is a single tree node, + # then it is a symmetric tree. + if(not root.left and not root.right): + return True + + q = [] + + # Add root to queue two times so that + # it can be checked if either one + # child alone is NULL or not. + q.append(root) + q.append(root) + + # To store two nodes for checking + # their symmetry. + leftNode = 0 + rightNode = 0 + + while(not len(q)): + + # Remove first two nodes to + # check their symmetry. + leftNode = q[0] + q.pop(0) + + rightNode = q[0] + q.pop(0) + + # if both left and right nodes + # exist, but have different + # values-. inequality, return False + if(leftNode.key != rightNode.key): + return False + + # append left child of left subtree + # node and right child of right + # subtree node in queue. + if(leftNode.left and rightNode.right) : + q.append(leftNode.left) + q.append(rightNode.right) + + # If only one child is present + # alone and other is NULL, then + # tree is not symmetric. + elif (leftNode.left or rightNode.right) : + return False + + # append right child of left subtree + # node and left child of right subtree + # node in queue. + if(leftNode.right and rightNode.left): + q.append(leftNode.right) + q.append(rightNode.left) + + # If only one child is present + # alone and other is NULL, then + # tree is not symmetric. + elif(leftNode.right or rightNode.left): + return False + + return True + +# Driver Code +if __name__ == '__main__': + + # Let us construct the Tree + # shown in the above figure + root = newNode(1) + root.left = newNode(2) + root.right = newNode(2) + root.left.left = newNode(3) + root.left.right = newNode(4) + root.right.left = newNode(4) + root.right.right = newNode(3) + if (isSymmetric(root)) : + print(""The given tree is Symmetric"") + else: + print(""The given tree is not Symmetric"") + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",logn,linear +"''' A binary tree node has key, pointer to left + child and a pointer to right child ''' + +class Node: + + def __init__(self, key): + + self.key=key + self.left = None + self.right = None + +# To create a newNode of tree and return pointer +def newNode(key): + + temp = Node(key) + return temp + +# Takes two parameters - same initially and +# calls recursively +def printMiddleLevelUtil(a, b): + + # Base case e + if (a == None or b == None): + return; + + # Fast pointer has reached the leaf so print + # value at slow pointer + if ((b.left == None) and (b.right == None)): + print(a.key, end=' ') + + return; + + # Recursive call + # root.left.left and root.left.right will + # print same value + # root.right.left and root.right.right + # will print same value + # So we use any one of the condition + if (b.left.left): + printMiddleLevelUtil(a.left, b.left.left); + printMiddleLevelUtil(a.right, b.left.left); + + else: + printMiddleLevelUtil(a.left, b.left); + printMiddleLevelUtil(a.right, b.left); + +# Main printing method that take a Tree as input +def printMiddleLevel(node): + + printMiddleLevelUtil(node, node); + +# Driver program to test above functions +if __name__=='__main__': + + + n1 = newNode(1); + n2 = newNode(2); + n3 = newNode(3); + n4 = newNode(4); + n5 = newNode(5); + n6 = newNode(6); + n7 = newNode(7); + + n2.left = n4; + n2.right = n5; + n3.left = n6; + n3.right = n7; + n1.left = n2; + n1.right = n3; + + printMiddleLevel(n1); + +# This code is contributed by rutvik_56",logn,linear +"# Python3 program to print the longest +# leaf to leaf path + +# Tree node structure used in the program +MAX_PATH_SIZE = 1000 + +class Node: + + def __init__(self, x): + self.data = x + self.left = None + self.right = None + +# Prints given root to leafAllpaths +# with underscores +def printPath(size): + + global Allpaths + + # Find the minimum horizontal distance + # value in current root to leafAllpaths + minimum_Hd = 10**19 + + p = [] + + # Find minimum horizontal distance + for it in range(size): + p = Allpaths[it] + minimum_Hd = min(minimum_Hd, p[0]) + + # Print the root to leafAllpaths with ""_"" + # that indicate the related position + for it in range(size): + + # Current tree node + p = Allpaths[it] + noOfUnderScores = abs(p[0] - minimum_Hd) + + # Print underscore + for i in range(noOfUnderScores): + print(end = ""_ "") + + # Print current key + print(p[1]) + + print(""=============================="") + +# A utility function print all path from root to leaf +# working of this function is similar to function of +# ""Print_vertical_order"" : Print paths of binary tree +# in vertical order +# https://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/ +def printAllPathsUtil(root, HD, order): + + # Base case + global Allpaths + + if (root == None): + return + + # Leaf node + if (root.left == None and root.right == None): + + # Add leaf node and then print path + Allpaths[order] = [HD, root.data] + printPath(order + 1) + return + + # Store current path information + Allpaths[order] = [HD, root.data] + + # Call left sub_tree + printAllPathsUtil(root.left, HD - 1, order + 1) + + # Call left sub_tree + printAllPathsUtil(root.right, HD + 1, order + 1) + +def printAllPaths(root): + + global Allpaths + + # Base case + if (root == None): + return + + printAllPathsUtil(root, 0, 0) + +# Driver code +if __name__ == '__main__': + + Allpaths = [ [0, 0] for i in range(MAX_PATH_SIZE)] + + root = Node('A') + root.left = Node('B') + root.right = Node('C') + root.left.left = Node('D') + root.left.right = Node('E') + root.right.left = Node('F') + root.right.right = Node('G') + + printAllPaths(root) + +# This code is contributed by mohit kumar 29",logn,constant +"# Recursive Python3 program to print +# odd level nodes + +# Utility method to create a node +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +def printOddNodes(root, isOdd = True): + + # If empty tree + if (root == None): + return + + # If current node is of odd level + if (isOdd): + print(root.data, end = "" "") + + # Recur for children with isOdd + # switched. + printOddNodes(root.left, not isOdd) + printOddNodes(root.right, not isOdd) + +# Driver code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + printOddNodes(root) + +# This code is contributed by PranchalK",linear,linear +"# Iterative Python3 program to print odd +# level nodes + +# A Binary Tree Node +# Utility function to create a +# new tree Node +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# Iterative method to do level order +# traversal line by line +def printOddNodes(root) : + + # Base Case + if (root == None): + return + + # Create an empty queue for + # level order traversal + q = [] + + # Enqueue root and initialize + # level as odd + q.append(root) + isOdd = True + + while (1) : + + # nodeCount (queue size) indicates + # number of nodes at current level. + nodeCount = len(q) + if (nodeCount == 0) : + break + + # Dequeue all nodes of current level + # and Enqueue all nodes of next level + while (nodeCount > 0): + + node = q[0] + if (isOdd): + print(node.data, end = "" "") + q.pop(0) + if (node.left != None) : + q.append(node.left) + if (node.right != None) : + q.append(node.right) + nodeCount -= 1 + + isOdd = not isOdd + +# Driver Code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + printOddNodes(root) + +# This code is contributed +# by SHUBHAMSINGH10",linear,linear +"# Python3 program to find the all +# full nodes in a given binary tree + +# Binary Tree Node +"""""" utility that allocates a newNode +with the given key """""" +class newNode: + + # Construct to create a newNode + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# Traverses given tree in Inorder +# fashion and prints all nodes that +# have both children as non-empty. +def findFullNode(root) : + + if (root != None) : + + findFullNode(root.left) + if (root.left != None and + root.right != None) : + print(root.data, end = "" "") + findFullNode(root.right) + +# Driver Code +if __name__ == '__main__': + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.right.left = newNode(5) + root.right.right = newNode(6) + root.right.left.right = newNode(7) + root.right.right.right = newNode(8) + root.right.left.right.left = newNode(9) + findFullNode(root) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,linear +"# Python3 Program to print sum of all +# the elements of a binary tree + +# Binary Tree Node +class newNode: + + # Utility function to create a new node + def __init__(self, key): + self.key = key + self.left = None + self.right = None + +# Function to find sum of all the element +def sumBT(root): + # sum variable to track the sum of + # all variables. + sum = 0 + + q = [] + + # Pushing the first level. + q.append(root) + + # Pushing elements at each level from + # the tree. + while len(q) > 0: + temp = q.pop(0) + + # After popping each element from queue + # add its data to the sum variable. + sum += temp.key + + if (temp.left != None): + q.append(temp.left) + if temp.right != None: + q.append(temp.right) + + return sum + + +# Driver Code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.right.left = newNode(6) + root.right.right = newNode(7) + root.right.left.right = newNode(8) + + print(""Sum of all elements in the binary tree is: "", sumBT(root)) + +# This code is contributed by +# Abhijeet Kumar(abhijeet19403)",linear,linear +"# Python3 implementation to find the Sum of +# all the parent nodes having child node x + +# function to get a new node +class getNode: + def __init__(self, data): + + # put in the data + self.data = data + self.left = self.right = None + +# function to find the Sum of all the +# parent nodes having child node x +def SumOfParentOfX(root, Sum, x): + + # if root == None + if (not root): + return + + # if left or right child of root is 'x', + # then add the root's data to 'Sum' + if ((root.left and root.left.data == x) or + (root.right and root.right.data == x)): + Sum[0] += root.data + + # recursively find the required parent + # nodes in the left and right subtree + SumOfParentOfX(root.left, Sum, x) + SumOfParentOfX(root.right, Sum, x) + +# utility function to find the Sum of all +# the parent nodes having child node x +def SumOfParentOfXUtil(root, x): + Sum = [0] + SumOfParentOfX(root, Sum, x) + + # required Sum of parent nodes + return Sum[0] + +# Driver Code +if __name__ == '__main__': + + # binary tree formation + root = getNode(4) # 4 + root.left = getNode(2) # / \ + root.right = getNode(5) # 2 5 + root.left.left = getNode(7) # / \ / \ + root.left.right = getNode(2) # 7 2 2 3 + root.right.left = getNode(2) + root.right.right = getNode(3) + + x = 2 + + print(""Sum = "", SumOfParentOfXUtil(root, x)) + +# This code is contributed by PranchalK",linear,linear +"# Python3 program to find sum of +# all left leaves +from collections import deque + +# A binary tree node +class Node: + + def __init__(self, x): + + self.key = x + self.left = None + self.right = None + +# Return the sum of left leaf nodes +def sumOfLeftLeaves(root): + + if (root == None): + return 0 + + # A queue of pairs to do bfs traversal + # and keep track if the node is a left + # or right child if boolean value + # is true then it is a left child. + q = deque() + q.append([root, 0]) + sum = 0 + + # Do bfs traversal + while (len(q) > 0): + temp = q[0][0] + is_left_child = q[0][1] + q.popleft() + + # If temp is a leaf node and + # left child of its parent + if (not temp.left and + not temp.right and + is_left_child): + sum = sum + temp.key + + # If it is not leaf then + # push its children nodes + # into queue + if (temp.left): + + # Boolean value is true + # here because it is left + # child of its parent + q.append([temp.left, 1]) + + if (temp.right): + + # Boolean value is false + # here because it is + # right child of its parent + q.append([temp.right, 0]) + + return sum + +# Driver Code +if __name__ == '__main__': + + root = Node(20) + root.left = Node(9) + root.right = Node(49) + root.right.left = Node(23) + root.right.right = Node(52) + root.right.right.left = Node(50) + root.left.left = Node(5) + root.left.right = Node(12) + root.left.right.right = Node(12) + + print(""Sum of left leaves is"", + sumOfLeftLeaves(root)) + +# This code is contributed by mohit kumar 29",linear,linear +"# Python Code to find sum of nodes on the longest path from root to leaf node +# using level order traversal + +# Building a tree node having left and right pointers set to null initially +class Node: + def __init__(self, element): + self.data = element + self.left = None + self.right = None + +# To store current Node,it's level and sum in the path +class Element: + def __init__(self, data, level, sum): + self.data = data + self.level = level + self.sum = sum + + +class Solution: + def longestPathLeaf(self, root): + + # maxSumLevel stores maximum sum so far in the path + # maxLevel stores maximum level so far + + maxSumLevel = root.data + maxLevel = 0 + + # queue to implement level order traversal + que = [] + + # Each element variable stores the current Node, it's level, sum in the path + e = Element(root, 0, root.data) + + # push the root element + que.append(e) + + # do level order traversal on the tree + while len(que) != 0: + + front = que[0] + curr = front.data + del que[0] + + # if the level of current front element is greater than the maxLevel so far then update maxSum + if front.level > maxLevel: + maxSumLevel = front.sum + maxLevel = front.level + + # if another path competes then update if the sum is greater than the previous path of same height + elif front.level == maxLevel and front.sum > maxSumLevel: + maxSumLevel = front.sum + + # push the left element if exists + if curr.left != None: + e = Element(curr.left, front.level+1, curr.left.data+front.sum) + que.append(e) + + # push the right element if exists + if curr.right != None: + e = Element(curr.right, front.level+1, + curr.right.data+front.sum) + que.append(e) + + # return the answer + return maxSumLevel + + +# Helper function +if __name__ == '__main__': + s = Solution() + root = Node(4) + root.left = Node(2) + root.right = Node(5) + root.left.left = Node(7) + root.left.right = Node(1) + root.right.left = Node(2) + root.right.right = Node(3) + root.left.right.left = Node(6) + + print(s.longestPathLeaf(root)) + +# This code is contributed by Tapesh(tapeshdua420)",linear,linear +"# Python program to find maximumpath sum between two leaves +# of a binary tree + +INT_MIN = -2**32 + +# 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 + +# Utility function to find maximum sum between any +# two leaves. This function calculates two values: +# 1) Maximum path sum between two leaves which are stored +# in res +# 2) The maximum root to leaf path sum which is returned +# If one side of root is empty, then it returns INT_MIN + + +def maxPathSumUtil(root, res): + + # Base Case + if root is None: + return 0 + + # if root is leaf node we can return root.data + if not root.left and not root.right: + return root.data + + # Find maximumsum in left and right subtree. Also + # find maximum root to leaf sums in left and right + # subtrees ans store them in ls and rs + ls = maxPathSumUtil(root.left, res) + rs = maxPathSumUtil(root.right, res) + + # If both left and right children exist + if root.left is not None and root.right is not None: + + # update result if needed + res[0] = max(res[0], ls + rs + root.data) + + # Return maximum possible value for root being + # on one side + return max(ls, rs) + root.data + + # If any of the two children is empty, return + # root sum for root being on one side + if root.left is None: + return rs + root.data + else: + return ls + root.data + +# The main function which returns sum of the maximum +# sum path betwee ntwo leaves. THis function mainly +# uses maxPathSumUtil() + + +def maxPathSum(root): + res = [INT_MIN] + res1 = maxPathSumUtil(root, res) + # we have to check if root.left is None or root.right is None + # for ex:- 10 + # / \ + # None -5 + # this will return INT_MIN but answer is 5 which is res1 + if root.left and root.right: + return res[0] + return max(res[0], res1) + + +# Driver program to test above function +root = Node(-15) +root.left = Node(5) +root.right = Node(6) +root.left.left = Node(-8) +root.left.right = Node(1) +root.left.left.left = Node(2) +root.left.left.right = Node(6) +root.right.left = Node(3) +root.right.right = Node(9) +root.right.right.right = Node(0) +root.right.right.right.left = Node(4) +root.right.right.right.right = Node(-1) +root.right.right.right.right.left = Node(10) + +print(""Max pathSum of the given binary tree is"", maxPathSum(root)) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python3 program to print all paths +# with sum k + +# utility function to print contents of +# a vector from index i to it's end + + +def printVector(v, i): + for j in range(i, len(v)): + print(v[j], end="" "") + print() + + +# Binary Tree Node +"""""" utility that allocates a newNode +with the given key """""" + + +class newNode: + + # Construct to create a newNode + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# This function prints all paths +# that have sum k + + +def printKPathUtil(root, path, k): + + # empty node + if (not root): + return + + # add current node to the path + path.append(root.data) + + # check if there's any k sum path + # in the left sub-tree. + printKPathUtil(root.left, path, k) + + # check if there's any k sum path + # in the right sub-tree. + printKPathUtil(root.right, path, k) + + # check if there's any k sum path that + # terminates at this node + # Traverse the entire path as + # there can be negative elements too + f = 0 + for j in range(len(path) - 1, -1, -1): + f += path[j] + + # If path sum is k, print the path + if (f == k): + printVector(path, j) + + # Remove the current element + # from the path + path.pop(-1) + +# A wrapper over printKPathUtil() + + +def printKPath(root, k): + + path = [] + printKPathUtil(root, path, k) + + +# Driver Code +if __name__ == '__main__': + + root = newNode(1) + root.left = newNode(3) + root.left.left = newNode(2) + root.left.right = newNode(1) + root.left.right.left = newNode(1) + root.right = newNode(-1) + root.right.left = newNode(4) + root.right.left.left = newNode(1) + root.right.left.right = newNode(2) + root.right.right = newNode(5) + root.right.right.right = newNode(2) + + k = 5 + printKPath(root, k) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",logn,linear +"# Python3 program to find if there is a +# subtree with given sum + +# Binary Tree Node +"""""" utility that allocates a newNode +with the given key """""" +class newnode: + + # Construct to create a newNode + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# function to check if there exist any +# subtree with given sum +# cur_sum -. sum of current subtree +# from ptr as root +# sum_left -. sum of left subtree from +# ptr as root +# sum_right -. sum of right subtree +# from ptr as root +def sumSubtreeUtil(ptr,cur_sum,sum): + + # base condition + if (ptr == None): + cur_sum[0] = 0 + return False + + # Here first we go to left sub-tree, + # then right subtree then first we + # calculate sum of all nodes of subtree + # having ptr as root and assign it as cur_sum + # cur_sum = sum_left + sum_right + ptr.data + # after that we check if cur_sum == sum + sum_left, sum_right = [0], [0] + x=sumSubtreeUtil(ptr.left, sum_left, sum) + y=sumSubtreeUtil(ptr.right, sum_right, sum) + cur_sum[0] = (sum_left[0] + + sum_right[0] + ptr.data) + return ((x or y)or (cur_sum[0] == sum)) + +# Wrapper over sumSubtreeUtil() +def sumSubtree(root, sum): + + # Initialize sum of subtree with root + cur_sum = [0] + + return sumSubtreeUtil(root, cur_sum, sum) + +# Driver Code +if __name__ == '__main__': + + root = newnode(8) + root.left = newnode(5) + root.right = newnode(4) + root.left.left = newnode(9) + root.left.right = newnode(7) + root.left.right.left = newnode(1) + root.left.right.right = newnode(12) + root.left.right.right.right = newnode(2) + root.right.right = newnode(11) + root.right.right.left = newnode(3) + sum = 22 + + if (sumSubtree(root, sum)) : + print(""Yes"" ) + else: + print(""No"") + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",logn,linear +"# Python3 implementation to count subtrees +# that Sum up to a given value x + +# class to get a new node + + +class getNode: + def __init__(self, data): + + # put in the data + self.data = data + self.left = self.right = None + +# function to count subtrees that +# Sum up to a given value x + + +def countSubtreesWithSumX(root, count, x): + + # if tree is empty + if (not root): + return 0 + + # Sum of nodes in the left subtree + ls = countSubtreesWithSumX(root.left, + count, x) + + # Sum of nodes in the right subtree + rs = countSubtreesWithSumX(root.right, + count, x) + + # Sum of nodes in the subtree + # rooted with 'root.data' + Sum = ls + rs + root.data + + # if true + if (Sum == x): + count[0] += 1 + + # return subtree's nodes Sum + return Sum + +# utility function to count subtrees +# that Sum up to a given value x + + +def countSubtreesWithSumXUtil(root, x): + + # if tree is empty + if (not root): + return 0 + + count = [0] + + # Sum of nodes in the left subtree + ls = countSubtreesWithSumX(root.left, + count, x) + + # Sum of nodes in the right subtree + rs = countSubtreesWithSumX(root.right, + count, x) + + # if tree's nodes Sum == x + if ((ls + rs + root.data) == x): + count[0] += 1 + + # required count of subtrees + return count[0] + + +# Driver Code +if __name__ == '__main__': + + # binary tree creation + # 5 + # / \ + # -10 3 + # / \ / \ + # 9 8 -4 7 + root = getNode(5) + root.left = getNode(-10) + root.right = getNode(3) + root.left.left = getNode(9) + root.left.right = getNode(8) + root.right.left = getNode(-4) + root.right.right = getNode(7) + + x = 7 + + print(""Count ="", + countSubtreesWithSumXUtil(root, x)) + +# This code is contributed by PranchalK",logn,linear +"# Python3 program to find if there is +# a subtree with given sum + +# Structure of a node of binary tree + + +class Node: + + def __init__(self, data): + + self.data = data + self.left = None + self.right = None + +# Function to get a new node + + +def getNode(data): + + # Allocate space + newNode = Node(data) + return newNode + + +count = 0 +ptr = None + +# Utility function to count subtrees that +# sum up to a given value x + + +def countSubtreesWithSumXUtil(root, x): + + global count, ptr + + l = 0 + r = 0 + + if (root == None): + return 0 + + l += countSubtreesWithSumXUtil(root.left, x) + r += countSubtreesWithSumXUtil(root.right, x) + + if (l + r + root.data == x): + count += 1 + + if (ptr != root): + return l + root.data + r + + return count + + +# Driver code +if __name__ == '__main__': + + ''' binary tree creation + 5 + / \ + -10 3 + / \ / \ + 9 8 -4 7 + ''' + + root = getNode(5) + root.left = getNode(-10) + root.right = getNode(3) + root.left.left = getNode(9) + root.left.right = getNode(8) + root.right.left = getNode(-4) + root.right.right = getNode(7) + + x = 7 + ptr = root + + print(""Count = "" + str(countSubtreesWithSumXUtil( + root, x))) + +# This code is contributed by pratham76",logn,linear +"# Python3 Implementation to find the maximum Spiral Sum + +# Structure of a node in binary tree +class Node: + + def __init__(self, data): + + self.data = data + self.left = None + self.right = None + +# function to find the maximum sum contiguous subarray +# implementing kadane's algorithm +def maxSum(Arr): + + currSum = maxSum = 0 + for element in Arr: + currSum = max(currSum + element, element) + maxSum = max(maxSum, currSum) + + return maxSum + +# function to find maximum spiral sum +def maxSpiralSum(root): + + # if tree is empty + if not root: + return 0 + + # create two stacks to stopre alternative levels + stack_s1 = [] # from levels right to left + stack_s2 = [] # from levels left to right + + # store spiral order traversal in Arr + Arr = [] + stack_s1.append(root) + + # traversing tree in spiral form + # until there are elements in any one + # of the stack + while stack_s1 or stack_s2: + + # traverse current level from s1 and + # push node of next level to s2 + while stack_s1: + + temp = stack_s1.pop() + + # append temp-> data to Arr + Arr.append(temp.data) + + if temp.right: + stack_s2.append(temp.right) + if temp.left: + stack_s2.append(temp.left) + + # traverse current level from s2 and + # push node of next level to s1 + while stack_s2: + + temp = stack_s2.pop() + + # append temp-> data to Arr + Arr.append(temp.data) + + if temp.left: + stack_s1.append(temp.left) + if temp.right: + stack_s1.append(temp.right) + + return maxSum(Arr) + +# Driver code +if __name__ == ""__main__"": + + root = Node(-2) + root.left = Node(-3) + root.right = Node(4) + root.left.left = Node(5) + root.left.right = Node(1) + root.right.left = Node(-2) + root.right.right = Node(-1) + root.left.left.left = Node(-3) + root.right.right.right = Node(2) + + print(""Maximum Spiral Sum is : "", maxSpiralSum(root)) + +# This code is contributed by +# Mayank Chaudhary (chaudhary_19)",linear,linear +"# Python3 implementation to find the sum +# of leaf node at minimum level +from collections import deque + +# Structure of a node in binary tree +class Node: + + def __init__(self, data): + + self.data = data + self.left = None + self.right = None + +# function to find the sum of leaf nodes +# at minimum level +def sumOfLeafNodesAtLeafLevel(root): + + # if tree is empty + if not root: + return 0 + + # if there is only root node + if not root.left and not root.right: + return root.data + + # Queue used for level order traversal + Queue = deque() + sum = f = 0 + + # push root node in the queue + Queue.append(root) + + while not f: + + # count no. of nodes present at current level + nc = len(Queue) + + # traverse current level nodes + while nc: + top = Queue.popleft() + + # if node is leaf node + if not top.left and not top.right: + sum += top.data + + # set flag = 1 to signify that + # we have encountered the minimum level + f = 1 + else: + + # if top's left or right child exist + # push them to Queue + if top.left: + Queue.append(top.left) + if top.right: + Queue.append(top.right) + nc -= 1 + + # return the sum + return sum + +# Driver code +if __name__ == ""__main__"": + + # binary tree creation + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + root.left.right.left = Node(8) + root.right.left.right = Node(9) + + print(""Sum = "", sumOfLeafNodesAtLeafLevel(root)) + +# This code is contributed by +# Mayank Chaudhary (chaudhary_19)",linear,linear +"# Python3 implementation of above approach + + +# Structure of a node in binary tree +class Node: + + def __init__(self, data): + + self.data = data + self.left = None + self.right = None + + +mp = dict() +def solve(root,level): + if(root == None): + return + if root.left == None and root.right == None : + try: + mp[level].append(root.data) + except: + mp[level] = [root.data] + solve(root.left, level+1) + solve(root.right, level+1) + +def minLeafSum(root): + + solve(root, 0) + sum = 0 + for x, i in enumerate(sorted(mp)): + for j in mp[i]: + sum += j + return sum + + + +# Driver code +if __name__ == ""__main__"": + + # binary tree creation + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + + print(""Sum = "", minLeafSum(root)) + +# This code is contributed by +# Abhijeet Kumar(abhijeet19403)",linear,linear +"# Python3 program to find if +# there is a root to sum path + +# 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 + + +"""""" + Given a tree and a sum, return + true if there is a path from the root + down to a leaf, such that + adding up all the values along the path + equals the given sum. + + Strategy: subtract the node + value from the sum when recurring down, + and check to see if the sum + is 0 when you run out of tree. +"""""" +# s is the sum + + +def hasPathSum(node, s): + ans = 0 + subSum = s - node.data + + # If we reach a leaf node and sum becomes 0, then + # return True + if(subSum == 0 and node.left == None and node.right == None): + return True + + # Otherwise check both subtrees + if node.left is not None: + ans = ans or hasPathSum(node.left, subSum) + if node.right is not None: + ans = ans or hasPathSum(node.right, subSum) + + return ans + +# Driver's Code +if __name__ == ""__main__"": + s = 21 + root = Node(10) + root.left = Node(8) + root.right = Node(2) + root.left.right = Node(5) + root.left.left = Node(3) + root.right.left = Node(2) + + # Function call + if hasPathSum(root, s): + print(""There is a root-to-leaf path with sum %d"" % (s)) + else: + print(""There is no root-to-leaf path with sum %d"" % (s)) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",logn,linear +"# Python program to find sum of all paths from root to leaves + +# 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 + +# Returns sums of all root to leaf paths. The first parameter is root +# of current subtree, the second paramete""r is value of the number +# formed by nodes from root to this node +def treePathsSumUtil(root, val): + + # Base Case + if root is None: + return 0 + + # Update val + val = (val*10 + root.data) + + # If current node is leaf, return the current value of val + if root.left is None and root.right is None: + return val + + # Recur sum of values for left and right subtree + return (treePathsSumUtil(root.left, val) + + treePathsSumUtil(root.right, val)) + +# A wrapper function over treePathSumUtil() +def treePathsSum(root): + + # Pass the initial value as 0 as ther is nothing above root + return treePathsSumUtil(root, 0) + +# Driver function to test above function +root = Node(6) +root.left = Node(3) +root.right = Node(5) +root.left.left = Node(2) +root.left.right = Node(5) +root.right.right = Node(4) +root.left.right.left = Node(7) +root.left.right.right = Node(4) +print (""Sum of all paths is"", treePathsSum(root)) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python program to find sum of all paths from root to leaves + +# 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 + + +def treePathsSumUtil(root, currPath, allPath): + + # Base Case + if root is None: + return + + # append the root data in string format in currPath + currPath.append(str(root.data)) + + # if we found a leaf node we copy the currPath to allPath + if root.left is None and root.right is None: + allPath.append(currPath.copy()) + + # traverse in the left subtree + treePathsSumUtil(root.left, currPath, allPath) + + # traverse in the right subtree + treePathsSumUtil(root.right, currPath, allPath) + + # remove the current element from the path + del currPath[-1] + + +def treePathsSum(root): + # store all the root to leaf path in allPath + allPath = [] + + treePathsSumUtil(root, [], allPath) + # store the sum + s = 0 + + for pathNumber in allPath: + # join the pathNumbers to convert them into the number to calculate sum + k = """".join(pathNumber) + s += int(k) + return s + + +# Driver function to test above function +root = Node(6) +root.left = Node(3) +root.right = Node(5) +root.left.left = Node(2) +root.left.right = Node(5) +root.right.right = Node(4) +root.left.right.left = Node(7) +root.left.right.right = Node(4) +print(""Sum of all paths is"", treePathsSum(root)) + +# this code is contributed by Vivek Maddeshiya",linear,quadratic +"""""""Find root of tree where children +sum for every node id is given"""""" + +def findRoot(arr, n) : + + # Every node appears once as an id, and + # every node except for the root appears + # once in a sum. So if we subtract all + # the sums from all the ids, we're left + # with the root id. + root = 0 + for i in range(n): + root += (arr[i][0] - arr[i][1]) + return root + +# Driver Code +if __name__ == '__main__': + + arr = [[1, 5], [2, 0], + [3, 0], [4, 0], + [5, 5], [6, 5]] + n = len(arr) + print(findRoot(arr, n)) + +# This code is contributed +# by SHUBHAMSINGH10",constant,linear +"# Python code to find LCA of given +# two nodes in a tree + +maxn = 100005 + +# the graph +g = [[] for i in range(maxn)] + +# level of each node +level = [0] * maxn + +e = [] +l = [] +h = [0] * maxn + +# the segment tree +st = [0] * (5 * maxn) + +# adding edges to the graph(tree) +def add_edge(u: int, v: int): + g[u].append(v) + g[v].append(u) + +# assigning level to nodes +def levelling(src: int): + for i in range(len(g[src])): + des = g[src][i] + if not level[des]: + level[des] = level[src] + 1 + leveling(des) + +visited = [False] * maxn + +# storing the dfs traversal +# in the array e +def dfs(src: int): + e.append(src) + visited[src] = True + for i in range(len(g[src])): + des = g[src][i] + if not visited[des]: + dfs(des) + e.append(src) + +# making the array l +def setting_l(n: int): + for i in range(len(e)): + l.append(level[e[i]]) + +# making the array h +def setting_h(n: int): + for i in range(n + 1): + h[i] = -1 + for i in range(len(e)): + + # if is already stored + if h[e[i]] == -1: + h[e[i]] = i + +# Range minimum query to return the index +# of minimum in the subarray L[qs:qe] +def RMQ(ss: int, se: int, qs: int, qe: int, i: int) -> int: + global st + if ss > se: + return -1 + + # out of range + if se < qs or qe < ss: + return -1 + + # in the range + if qs <= ss and se <= qe: + return st[i] + + mid = (se + ss) >> 1 + stt = RMQ(ss, mid, qs, qe, 2 * i + 1) + en = RMQ(mid + 1, se, qs, qe, 2 * i + 2) + + if stt != -1 and en != -1: + if l[stt] < l[en]: + return stt + return en + elif stt != -1: + return stt + elif en != -1: + return en + +# constructs the segment tree +def segmentTreeConstruction(ss: int, se: int, i: int): + if ss > se: + return + if ss == se: # leaf + st[i] = ss + return + + mid = (ss + se) >> 1 + segmentTreeConstruction(ss, mid, 2 * i + 1) + segmentTreeConstruction(mid + 1, se, 2 * i + 2) + + if l[st[2 * i + 1]] < l[st[2 * i + 2]]: + st[i] = st[2 * i + 1] + else: + st[i] = st[2 * i + 2] + +# Function to get LCA +def LCA(x: int, y: int) -> int: + if h[x] > h[y]: + x, y = y, x + return e[RMQ(0, len(l) - 1, h[x], h[y], 0)] + +# Driver Code +if __name__ == ""__main__"": + + # n=number of nodes in the tree + # q=number of queries to answer + n = 15 + q = 5 + + # making the tree + # /* + # 1 + # / | \ + # 2 3 4 + # | \ + # 5 6 + # / | \ + # 8 7 9 (right of 5) + # / | \ | \ + # 10 11 12 13 14 + # | + # 15 + # */ + add_edge(1, 2) + add_edge(1, 3) + add_edge(1, 4) + add_edge(3, 5) + add_edge(4, 6) + add_edge(5, 7) + add_edge(5, 8) + add_edge(5, 9) + add_edge(7, 10) + add_edge(7, 11) + add_edge(7, 12) + add_edge(9, 13) + add_edge(9, 14) + add_edge(12, 15) + + level[1] = 1 + leveling(1) + dfs(1) + setting_l(n) + setting_h(n) + + segmentTreeConstruction(0, len(l) - 1, 0) + + print(LCA(10, 15)) + print(LCA(11, 14)) + +# This code is contributed by +# sanjeev2552",linear,nlogn +"# Python3 program to find maximum difference +# between node and its ancestor + +_MIN = -2147483648 +_MAX = 2147483648 + +# Helper function that allocates a new +# node with the given data and None left +# and right pointers. + + +class newNode: + + # Constructor to create a new node + def __init__(self, key): + self.key = key + self.left = None + self.right = None + + +"""""" +Recursive function to calculate maximum +ancestor-node difference in binary tree. +It updates value at 'res' to store the +result. The returned value of this function +is minimum value in subtree rooted with 't' """""" + + +def maxDiffUtil(t, res): + """""" Returning Maximum value if node + is not there (one child case) """""" + if (t == None): + return _MAX, res + + """""" If leaf node then just return + node's value """""" + if (t.left == None and t.right == None): + return t.key, res + + """""" Recursively calling left and right + subtree for minimum value """""" + a, res = maxDiffUtil(t.left, res) + b, res = maxDiffUtil(t.right, res) + val = min(a, b) + + """""" Updating res if (node value - minimum + value from subtree) is bigger than res """""" + res = max(res, t.key - val) + + """""" Returning minimum value got so far """""" + return min(val, t.key), res + + +"""""" This function mainly calls maxDiffUtil() """""" + + +def maxDiff(root): + + # Initialising result with minimum value + res = _MIN + x, res = maxDiffUtil(root, res) + return res + + +"""""" Helper function to print inorder +traversal of binary tree """""" + + +def inorder(root): + + if (root): + + inorder(root.left) + prf(""%d "", root.key) + inorder(root.right) + + +# Driver Code +if __name__ == '__main__': + + """""" + Let us create Binary Tree shown + in above example """""" + root = newNode(8) + root.left = newNode(3) + + root.left.left = newNode(1) + root.left.right = newNode(6) + root.left.right.left = newNode(4) + root.left.right.right = newNode(7) + + root.right = newNode(10) + root.right.right = newNode(14) + root.right.right.left = newNode(13) + print(maxDiff(root)) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,linear +"# Python3 program to count +# number of ways to color +# a N node skewed tree with +# k colors such that parent +# and children have different +# colors. + +# fast_way is recursive +# method to calculate power +def fastPow(N, K): + if (K == 0): + return 1; + + temp = fastPow(N, int(K / 2)); + if (K % 2 == 0): + return temp * temp; + else: + return N * temp * temp; + +def countWays(N, K): + return K * fastPow(K - 1, N - 1); + +# Driver Code +N = 3; +K = 3; +print(countWays(N, K)); + +# This code is contributed by mits",constant,logn +"# Python Program to calculate size of the tree iteratively + +# Node Structure +class newNode: + def __init__(self,data): + self.data = data + self.left = self.right = None + +# Return size of tree +def sizeoftree(root): + if root == None: + return 0 + q = [] + q.append(root) + count = 1 + while(len(q) != 0): + root = q.pop(0) + if(root.left): + q.append(root.left) + count += 1 + if(root.right): + q.append(root.right) + count += 1 + return count + +# Driver Program +root = newNode(1) +root.left = newNode(2) +root.right = newNode(3) +root.left.left = newNode(4) +root.left.right = newNode(5) +print(sizeoftree(root)) + +# This is code is contributed by simranjenny84",np,linear +"# Program to find height of tree by Iteration Method + +# A binary tree node +class Node: + + # Constructor to create new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Iterative method to find height of Binary Tree +def treeHeight(root): + + # Base Case + if root is None: + return 0 + + # Create a empty queue for level order traversal + q = [] + + # Enqueue Root and Initialize Height + q.append(root) + height = 0 + + while(True): + + # nodeCount(queue size) indicates number of nodes + # at current level + nodeCount = len(q) + if nodeCount == 0 : + return height + + height += 1 + + # Dequeue all nodes of current level and Enqueue + # all nodes of next level + while(nodeCount > 0): + node = q[0] + q.pop(0) + if node.left is not None: + q.append(node.left) + if node.right is not None: + q.append(node.right) + + nodeCount -= 1 + + +# Driver program to test above function +# Let us create binary tree shown in above diagram +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) + +print (""Height of tree is"", treeHeight(root)) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python 3 program to find +# height of complete binary +# tree from total nodes. +import math +def height(N): + return math.ceil(math.log2(N + 1)) - 1 + +# driver node +N = 6 +print(height(N)) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,constant +"# Program to find height of the tree considering +# only even level leaves. + +# Helper class that allocates a new node with the +# given data and None left and right pointers. +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +def heightOfTreeUtil(root, isEven): + + # Base Case + if (not root): + return 0 + + if (not root.left and not root.right): + if (isEven): + return 1 + else: + return 0 + + # left stores the result of left subtree, + # and right stores the result of right subtree + left = heightOfTreeUtil(root.left, not isEven) + right = heightOfTreeUtil(root.right, not isEven) + + #If both left and right returns 0, it means + # there is no valid path till leaf node + if (left == 0 and right == 0): + return 0 + + return (1 + max(left, right)) + +def heightOfTree(root): + return heightOfTreeUtil(root, False) + +# Driver Code +if __name__ == '__main__': + + # Let us create binary tree shown + # in above diagram + root = newNode(1) + + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.left.right.left = newNode(6) + print(""Height of tree is"", + heightOfTree(root)) + +# This code is contributed by PranchalK",linear,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",linear,quadratic +"# Python3 program to find the diameter of binary tree + +# 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 + + +# The function Compute the ""height"" of a tree. Height is the +# number of nodes along the longest path from the root node +# down to the farthest leaf node. + +def height(node): + + # Base Case : Tree is empty + if node is None: + return 0 + + # If tree is not empty then height = 1 + max of left + # height and right heights + return 1 + max(height(node.left), height(node.right)) + +# Function to get the diameter of a binary tree + + +def diameter(root): + + # Base Case when tree is empty + if root is None: + return 0 + + # Get the height of left and right sub-trees + lheight = height(root.left) + rheight = height(root.right) + + # Get the diameter of left and right sub-trees + ldiameter = diameter(root.left) + rdiameter = diameter(root.right) + + # Return max of the following tree: + # 1) Diameter of left subtree + # 2) Diameter of right subtree + # 3) Height of left subtree + height of right subtree +1 + return max(lheight + rheight + 1, max(ldiameter, rdiameter)) + + +# Driver Code +if __name__ == ""__main__"": + """""" + Constructed binary tree is + 1 + / \ + 2 3 + / \ + 4 5 + """""" + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + + # Function Call + print(diameter(root)) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,quadratic +"# Python3 program to find the diameter of a binary tree +# A binary tree Node + + +class Node: + + # Constructor to create a new Node + def __init__(self, data): + self.data = data + self.left = self.right = None + +# utility class to pass height object + + +class Height: + def __init(self): + self.h = 0 + +# Optimised recursive function to find diameter +# of binary tree + + +def diameterOpt(root, height): + + # to store height of left and right subtree + lh = Height() + rh = Height() + + # base condition- when binary tree is empty + if root is None: + height.h = 0 + return 0 + + # ldiameter --> diameter of left subtree + # rdiameter --> diameter of right subtree + + # height of left subtree and right subtree is obtained from lh and rh + # and returned value of function is stored in ldiameter and rdiameter + + ldiameter = diameterOpt(root.left, lh) + rdiameter = diameterOpt(root.right, rh) + + # height of tree will be max of left subtree + # height and right subtree height plus1 + + height.h = max(lh.h, rh.h) + 1 + + # return maximum of the following + # 1)left diameter + # 2)right diameter + # 3)left height + right height + 1 + return max(lh.h + rh.h + 1, max(ldiameter, rdiameter)) + +# function to calculate diameter of binary tree + + +def diameter(root): + height = Height() + return diameterOpt(root, height) + + +# Driver Code +if __name__ == ""__main__"": + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + + """""" + Constructed binary tree is + 1 + / \ + 2 3 + / \ + 4 5 + """""" + + print(""The diameter of the binary tree is:"", end="" "") + # Function Call + print(diameter(root)) + +# This code is contributed by Shweta Singh(shweta44)",linear,linear +"# Simple Python3 program to find diameter +# of a binary tree. + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# Function to find height of a tree +def height(root, ans): + if (root == None): + return 0 + + left_height = height(root.left, ans) + + right_height = height(root.right, ans) + + # update the answer, because diameter + # of a tree is nothing but maximum + # value of (left_height + right_height + 1) + # for each node + ans[0] = max(ans[0], 1 + left_height + + right_height) + + return 1 + max(left_height, + right_height) + +# Computes the diameter of binary +# tree with given root. +def diameter(root): + if (root == None): + return 0 + ans = [-999999999999] # This will store + # the final answer + height_of_tree = height(root, ans) + return ans[0] + +# Driver code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + + print(""Diameter is"", diameter(root)) + +# This code is contributed by PranchalK",logn,linear +"# Python3 program to find closest +# value in Binary search Tree + +_MIN = -2147483648 +_MAX = 2147483648 + +# Helper function that allocates a new +# node with the given data and None +# left and right pointers. +class newnode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# utility function to return level +# of given node +def getDeepestRightLeafNode(root) : + + if (not root): + return None + + # create a queue for level + # order traversal + q = [] + q.append(root) + + result = None + + # traverse until the queue is empty + while (len(q)): + temp = q[0] + q.pop(0) + + if (temp.left): + q.append(temp.left) + + # Since we go level by level, the last + # stored right leaf node is deepest one + if (temp.right): + q.append(temp.right) + if (not temp.right.left and + not temp.right.right): + result = temp.right + + return result + +# Driver Code +if __name__ == '__main__': + + # create a binary tree + root = newnode(1) + root.left = newnode(2) + root.right = newnode(3) + root.left.right = newnode(4) + root.right.left = newnode(5) + root.right.right = newnode(6) + root.right.left.right = newnode(7) + root.right.right.right = newnode(8) + root.right.left.right.left = newnode(9) + root.right.right.right.right = newnode(10) + + result = getDeepestRightLeafNode(root) + if result: + print(""Deepest Right Leaf Node ::"", + result.data) + else: + print(""No result, right leaf not found"") + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,linear +"""""""Python3 program to find value of the +deepest node in a given binary tree"""""" + +# A Binary Tree Node +# Utility function to create a +# new tree node +class newNode: + + # Constructor to create a newNode + def __init__(self, data): + self.data= data + self.left = None + self.right = None + self.visited = False + +# maxLevel : keeps track of maximum +# level seen so far. +# res : Value of deepest node so far. +# level : Level of root +def find(root, level, maxLevel, res): + + if (root != None): + level += 1 + find(root.left, level, maxLevel, res) + + # Update level and rescue + if (level > maxLevel[0]): + + res[0] = root.data + maxLevel[0] = level + + find(root.right, level, maxLevel, res) + +# Returns value of deepest node +def deepestNode(root) : + + # Initialize result and max level + res = [-1] + maxLevel = [-1] + + # Updates value ""res"" and ""maxLevel"" + # Note that res and maxLen are passed + # by reference. + find(root, 0, maxLevel, res) + return res[0] + +# Driver Code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.right.left = newNode(5) + root.right.right = newNode(6) + root.right.left.right = newNode(7) + root.right.right.right = newNode(8) + root.right.left.right.left = newNode(9) + print(deepestNode(root)) + +# This code is contributed by +# SHUBHAMSINGH10",linear,linear +"# A Python3 program to find value of the +# deepest node in a given binary tree by method 3 +from collections import deque + +class new_Node: + def __init__(self, key): + self.data = key + self.left = self.right = None + +def deepestNode(root): + if root == None: + return 0 + q = deque() + q.append(root) + node = None + while len(q) != 0: + node = q.popleft() + if node.left is not None: + q.append(node.left) + if node.right is not None: + q.append(node.right) + return node.data + +# Driver Code +if __name__ == '__main__': + + root = new_Node(1) + root.left = new_Node(2) + root.right = new_Node(3) + root.left.left = new_Node(4) + root.right.left = new_Node(5) + root.right.right = new_Node(6) + root.right.left.right = new_Node(7) + root.right.right.right = new_Node(8) + root.right.left.right.left = new_Node(9) + + # Calculating height of tree + levels = deepestNode(root) + + # Printing the deepest node + print(levels) + +# This code is contributed by Aprajita Chhawi",linear,linear +"# Python3 program to find deepest +# left leaf Binary search Tree + +_MIN = -2147483648 +_MAX = 2147483648 + +# Helper function that allocates a new +# node with the given data and None +# left and right pointers. +class newnode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# utility function to return deepest +# left leaf node +def getDeepestLeftLeafNode(root) : + + if (not root): + return None + + # create a queue for level + # order traversal + q = [] + q.append(root) + + result = None + + # traverse until the queue is empty + while (len(q)): + temp = q[0] + q.pop(0) + + if (temp.left): + q.append(temp.left) + if (not temp.left.left and + not temp.left.right): + result = temp.left + + # Since we go level by level, + # the last stored right leaf + # node is deepest one + if (temp.right): + q.append(temp.right) + + return result + +# Driver Code +if __name__ == '__main__': + + # create a binary tree + root = newnode(1) + root.left = newnode(2) + root.right = newnode(3) + root.left.Left = newnode(4) + root.right.left = newnode(5) + root.right.right = newnode(6) + root.right.left.right = newnode(7) + root.right.right.right = newnode(8) + root.right.left.right.left = newnode(9) + root.right.right.right.right = newnode(10) + + result = getDeepestLeftLeafNode(root) + if result: + print(""Deepest Left Leaf Node ::"", + result.data) + else: + print(""No result, Left leaf not found"") + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,linear +"# Python program to find the maximum width of +# binary tree using Level Order Traversal. + +# 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 get the maximum width of a binary tree + + +def getMaxWidth(root): + maxWidth = 0 + h = height(root) + # Get width of each level and compare the + # width with maximum width so far + for i in range(1, h+1): + width = getWidth(root, i) + if (width > maxWidth): + maxWidth = width + return maxWidth + +# Get width of a given level + + +def getWidth(root, level): + if root is None: + return 0 + if level == 1: + return 1 + elif level > 1: + return (getWidth(root.left, level-1) + + getWidth(root.right, level-1)) + +# UTILITY FUNCTIONS +# Compute the ""height"" of a tree -- the number of +# nodes along the longest path from the root node +# down to the farthest leaf node. + + +def height(node): + if node is None: + return 0 + else: + + # compute the height of each subtree + lHeight = height(node.left) + rHeight = height(node.right) + + # use the larger one + return (lHeight+1) if (lHeight > rHeight) else (rHeight+1) + + +# Driver code +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.right = Node(8) +root.right.right.left = Node(6) +root.right.right.right = Node(7) + +"""""" +Constructed binary tree is: + 1 + / \ + 2 3 + / \ \ +4 5 8 + / \ + 6 7 +"""""" +# Function call +print (""Maximum width is %d"" % (getMaxWidth(root))) + +# This code is contributed by Naveen Aili",constant,quadratic +"# Python program to find the maximum width of binary +# tree using Level Order Traversal with queue. + +from _collections import deque + +# 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 get the maximum width of a binary tree + + +def getMaxWidth(root): + # base case + if root is None: + return 0 + q = deque() + maxWidth = 0 + + q.append(root) + + while q: + # Get the size of queue when the level order + # traversal for one level finishes + count = len(q) + + # Update the maximum node count value + maxWidth = max(count, maxWidth) + + while (count is not 0): + count = count-1 + temp = q.popleft() + if temp.left is not None: + q.append(temp.left) + + if temp.right is not None: + q.append(temp.right) + + return maxWidth + + +# Driver program to test above function +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.right = Node(8) +root.right.right.left = Node(6) +root.right.right.right = Node(7) + +"""""" +Constructed binary tree is: + 1 + / \ + 2 3 + / \ \ + 4 5 8 + / \ + 6 7 +"""""" +# Function call +print (""Maximum width is %d"" % (getMaxWidth(root))) + +# This code is contributed by Naveen Aili",constant,linear +"# Python program to find the maximum width of +# binary tree using Preorder Traversal. + +# 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 get the maximum width of a binary tree + + +def getMaxWidth(root): + h = height(root) + # Create an array that will store count of nodes at each level + count = [0] * h + + level = 0 + # Fill the count array using preorder traversal + getMaxWidthRecur(root, count, level) + + # Return the maximum value from count array + return getMax(count, h) + +# A function that fills count array with count of nodes at every +# level of given binary tree + + +def getMaxWidthRecur(root, count, level): + if root is not None: + count[level] += 1 + getMaxWidthRecur(root.left, count, level+1) + getMaxWidthRecur(root.right, count, level+1) + +# UTILITY FUNCTIONS +# Compute the ""height"" of a tree -- the number of +# nodes along the longest path from the root node +# down to the farthest leaf node. + + +def height(node): + if node is None: + return 0 + else: + # compute the height of each subtree + lHeight = height(node.left) + rHeight = height(node.right) + # use the larger one + return (lHeight+1) if (lHeight > rHeight) else (rHeight+1) + +# Return the maximum value from count array + + +def getMax(count, n): + max = count[0] + for i in range(1, n): + if (count[i] > max): + max = count[i] + return max + + +# Driver program to test above function +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.right = Node(8) +root.right.right.left = Node(6) +root.right.right.right = Node(7) + +"""""" +Constructed binary tree is: + 1 + / \ + 2 3 + / \ \ + 4 5 8 + / \ + 6 7 +"""""" + +print (""Maximum width is %d"" % (getMaxWidth(root))) + +# This code is contributed by Naveen Aili",logn,linear +"# Python code to find vertical +# width of a binary tree + +class Node: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# Function to fill hd in set. +def fillSet(root, s, hd): + if (not root): + return + + fillSet(root.left, s, hd - 1) + s.add(hd) + fillSet(root.right, s, hd + 1) + +def verticalWidth(root): + s = set() + + # Third parameter is horizontal + # distance + fillSet(root, s, 0) + + return len(s) + +if __name__ == '__main__': + + # Creating the above tree + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + root.right.left.right = Node(8) + root.right.right.right = Node(9) + + print(verticalWidth(root)) + +# This code is contributed by PranchalK",linear,linear +"# Python program to determine whether +# vertical level l of binary tree +# is sorted or not. +from collections import deque +from sys import maxsize + +INT_MIN = -maxsize + +# Structure of a tree node. +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + +# Helper function to determine if +# vertical level l of given binary +# tree is sorted or not. +def isSorted(root: Node, level: int) -> bool: + + # If root is null, then the answer is an + # empty subset and an empty subset is + # always considered to be sorted. + if root is None: + return True + + # Variable to store previous + # value in vertical level l. + prevVal = INT_MIN + + # Variable to store current level + # while traversing tree vertically. + currLevel = 0 + + # Variable to store current node + # while traversing tree vertically. + currNode = Node(0) + + # Declare queue to do vertical order + # traversal. A pair is used as element + # of queue. The first element in pair + # represents the node and the second + # element represents vertical level + # of that node. + q = deque() + + # Insert root in queue. Vertical level + # of root is 0. + q.append((root, 0)) + + # Do vertical order traversal until + # all the nodes are not visited. + while q: + currNode = q[0][0] + currLevel = q[0][1] + q.popleft() + + # Check if level of node extracted from + # queue is required level or not. If it + # is the required level then check if + # previous value in that level is less + # than or equal to value of node. + if currLevel == level: + if prevVal <= currNode.key: + prevVal = currNode.key + else: + return False + + # If left child is not NULL then push it + # in queue with level reduced by 1. + if currNode.left: + q.append((currNode.left, currLevel - 1)) + + # If right child is not NULL then push it + # in queue with level increased by 1. + if currNode.right: + q.append((currNode.right, currLevel + 1)) + + # If the level asked is not present in the + # given binary tree, that means that level + # will contain an empty subset. Therefore answer + # will be true. + return True + +# Driver Code +if __name__ == ""__main__"": + + # /* + # 1 + # / \ + # 2 5 + # / \ + # 7 4 + # / + # 6 + # */ + + root = Node(1) + root.left = Node(2) + root.right = Node(5) + root.left.left = Node(7) + root.left.right = Node(4) + root.left.right.left = Node(6) + + level = -1 + if isSorted(root, level): + print(""Yes"") + else: + print(""No"") + +# This code is contributed by +# sanjeev2552",linear,linear +"# Python3 program to determine whether +# binary tree is level sorted or not. +from queue import Queue + +# Function to create new tree node. +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None + +# Function to determine if given binary +# tree is level sorted or not. +def isSorted(root): + + # to store maximum value of previous + # level. + prevMax = -999999999999 + + # to store minimum value of current + # level. + minval = None + + # to store maximum value of current + # level. + maxval = None + + # to store number of nodes in current + # level. + levelSize = None + + # queue to perform level order traversal. + q = Queue() + q.put(root) + + while (not q.empty()): + + # find number of nodes in current + # level. + levelSize = q.qsize() + + minval = 999999999999 + maxval = -999999999999 + + # traverse current level and find + # minimum and maximum value of + # this level. + while (levelSize > 0): + root = q.queue[0] + q.get() + + levelSize -= 1 + + minval = min(minval, root.key) + maxval = max(maxval, root.key) + + if (root.left): + q.put(root.left) + + if (root.right): + q.put(root.right) + + # if minimum value of this level + # is not greater than maximum + # value of previous level then + # given tree is not level sorted. + if (minval <= prevMax): + return 0 + + # maximum value of this level is + # previous maximum value for + # next level. + prevMax = maxval + return 1 + +# Driver Code +if __name__ == '__main__': + + # + # 1 + # / + # 4 + # \ + # 6 + # / \ + # 8 9 + # / \ + # 12 10 + root = newNode(1) + root.left = newNode(4) + root.left.right = newNode(6) + root.left.right.left = newNode(8) + root.left.right.right = newNode(9) + root.left.right.left.left = newNode(12) + root.left.right.right.right = newNode(10) + + if (isSorted(root)): + print(""Sorted"") + else: + print(""Not sorted"") + +# This code is contributed by PranchalK",linear,linear +"# Python program to count leaf nodes in Binary Tree + +# 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 get the count of leaf nodes in binary tree +def getLeafCount(node): + if node is None: + return 0 + if(node.left is None and node.right is None): + return 1 + else: + return getLeafCount(node.left) + getLeafCount(node.right) + + +# Driver program to test above function +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) + +print (""Leaf count of the tree is %d"" %(getLeafCount(root))) + +#This code is contributed by Nikhil Kumar Singh(nickzuck_007)",logn,linear +"# Python3 program to count total number +# of non-leaf nodes in a binary tree + +# class that allocates a new node with the +#given data and None left and right pointers. +class newNode: + def __init__(self,data): + self.data = data + self.left = self.right = None + +# Computes the number of non-leaf +# nodes in a tree. +def countNonleaf(root): + + # Base cases. + if (root == None or (root.left == None and + root.right == None)): + return 0 + + # If root is Not None and its one of + # its child is also not None + return (1 + countNonleaf(root.left) + + countNonleaf(root.right)) + +# Driver Code +if __name__ == '__main__': + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + print(countNonleaf(root)) + +# This code is contributed by PranchalK",logn,linear +" +# Python program to count +# half nodes in a Binary Tree +# using iterative approach + +# A node structure +class Node: + + # A utility function to create a new node + def __init__(self ,key): + self.data = key + self.left = None + self.right = None + +# Iterative Method to count half nodes of binary tree +def gethalfCount(root): + + # Base Case + if root is None: + return 0 + + # Create an empty queue for level order traversal + queue = [] + + # Enqueue Root and initialize count + queue.append(root) + + count = 0 #initialize count for half nodes + while(len(queue) > 0): + + node = queue.pop(0) + + # if it is half node then increment count + if node.left is not None and node.right is None or node.left is None and node.right is not None: + count = count+1 + + #Enqueue left child + if node.left is not None: + queue.append(node.left) + + # Enqueue right child + if node.right is not None: + queue.append(node.right) + + return count + +#Driver Program to test above function + +root = Node(2) +root.left = Node(7) +root.right = Node(5) +root.left.right = Node(6) +root.left.right.left = Node(1) +root.left.right.right = Node(11) +root.right.right = Node(9) +root.right.right.left = Node(4) + + +print ""%d"" %(gethalfCount(root))",linear,linear +"# Python program to count half nodes in a binary tree + +# A node structure +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# Function to get the count of half Nodes in a binary tree +def gethalfCount(root): + if root == None: + return 0 + res = 0 + if(root.left == None and root.right != None) or \ + (root.left != None and root.right == None): + res += 1 + res += (gethalfCount(root.left) + \ + gethalfCount(root.right)) + return res + +# Driver program +''' 2 + / \ + 7 5 + \ \ + 6 9 + / \ / + 1 11 4 + Let us create Binary Tree shown in + above example ''' + +root = newNode(2) +root.left = newNode(7) +root.right = newNode(5) +root.left.right = newNode(6) +root.left.right.left = newNode(1) +root.left.right.right = newNode(11) +root.right.right = newNode(9) +root.right.right.left = newNode(4) +print(gethalfCount(root)) + +# This code is contributed by simranjenny84",linear,linear +" +# Python program to count +# full nodes in a Binary Tree +# using iterative approach + +# A node structure +class Node: + # A utility function to create a new node + def __init__(self ,key): + self.data = key + self.left = None + self.right = None + +# Iterative Method to count full nodes of binary tree +def getfullCount(root): + # Base Case + if root is None: + return 0 + + # Create an empty queue for level order traversal + queue = [] + + # Enqueue Root and initialize count + queue.append(root) + + count = 0 #initialize count for full nodes + while(len(queue) > 0): + node = queue.pop(0) + + # if it is full node then increment count + if node.left is not None and node.right is not None: + count = count+1 + + # Enqueue left child + if node.left is not None: + queue.append(node.left) + + # Enqueue right child + if node.right is not None: + queue.append(node.right) + + return count + +# Driver Program to test above function +root = Node(2) +root.left = Node(7) +root.right = Node(5) +root.left.right = Node(6) +root.left.right.left = Node(1) +root.left.right.right = Node(11) +root.right.right = Node(9) +root.right.right.left = Node(4) + + +print(getfullCount(root))",linear,linear +"# Python program to count full +# nodes in a Binary Tree +class newNode(): + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +# Function to get the count of +# full Nodes in a binary tree +def getfullCount(root): + + if (root == None): + return 0 + + res = 0 + if (root.left and root.right): + res += 1 + + res += (getfullCount(root.left) + + getfullCount(root.right)) + return res + + +# Driver code +if __name__ == '__main__': + """""" 2 + / \ + 7 5 + \ \ + 6 9 + / \ / + 1 11 4 + Let us create Binary Tree as shown + """""" + + root = newNode(2) + root.left = newNode(7) + root.right = newNode(5) + root.left.right = newNode(6) + root.left.right.left = newNode(1) + root.left.right.right = newNode(11) + root.right.right = newNode(9) + root.right.right.left = newNode(4) + + print(getfullCount(root)) + +# This code is contributed by SHUBHAMSINGH10",linear,linear +"#! /usr/bin/env python3 + +# connect nodes at same level using level order traversal +import sys + + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + self.nextRight = None + + def __str__(self): + return '{}'.format(self.data) + + +def printLevelByLevel(root): + # print level by level + if root: + node = root + while node: + print('{}'.format(node.data), end=' ') + node = node.nextRight + print() + if root.left: + printLevelByLevel(root.left) + else: + printLevelByLevel(root.right) + + +def inorder(root): + if root: + inorder(root.left) + print(root.data, end=' ') + inorder(root.right) + + +def connect(root): + # set nextRight of all nodes of a tree + queue = [] + queue.append(root) + # null marker to represent end of current level + queue.append(None) + # do level order of tree using None markers + while queue: + p = queue.pop(0) + if p: + # next element in queue represents + # next node at current level + p.nextRight = queue[0] + # pus left and right children of current node + if p.left: + queue.append(p.left) + if p.right: + queue.append(p.right) + else if queue: + queue.append(None) + + +def main(): + """"""Driver program to test above functions. + Constructed binary tree is + 10 + / \ + 8 2 + / \ + 3 90 + """""" + + root = Node(10) + root.left = Node(8) + root.right = Node(2) + root.left.left = Node(3) + root.right.right = Node(90) + + # Populates nextRight pointer in all nodes + connect(root) + + # Let us check the values of nextRight pointers + print(""Following are populated nextRight pointers in \n"" + ""the tree (-1 is printed if there is no nextRight) \n"") + if(root.nextRight != None): + print(""nextRight of %d is %d \n"" %(root.data,root.nextRight.data)) + else: + print(""nextRight of %d is %d \n"" %(root.data,-1)) + if(root.left.nextRight != None): + print(""nextRight of %d is %d \n"" %(root.left.data,root.left.nextRight.data)) + else: + print(""nextRight of %d is %d \n"" %(root.left.data,-1)) + if(root.right.nextRight != None): + print(""nextRight of %d is %d \n"" %(root.right.data,root.right.nextRight.data)) + else: + print(""nextRight of %d is %d \n"" %(root.right.data,-1)) + if(root.left.left.nextRight != None): + print(""nextRight of %d is %d \n"" %(root.left.left.data,root.left.left.nextRight.data)) + else: + print(""nextRight of %d is %d \n"" %(root.left.left.data,-1)) + if(root.right.right.nextRight != None): + print(""nextRight of %d is %d \n"" %(root.right.right.data,root.right.right.nextRight.data)) + else: + print(""nextRight of %d is %d \n"" %(root.right.right.data,-1)) + + print() + + +if __name__ == ""__main__"": + main() + +# This code is contributed by Ram Basnet",linear,linear +"# Iterative program to connect all the adjacent nodes at the same level in a binary tree +class newnode: + def __init__(self, data): + self.data = data + self.left = self.right = self.nextRight = None + +# setting right pointer to next right node + +# 10 ----------> NULL +# / \ +# 8 --->2 --------> NULL +# / +# 3 ----------------> NULL + + +def connect(root): + + # Base condition + if root is None: + return + + # Create an empty queue like level order traversal + queue = [] + queue.append(root) + while len(queue) != 0: + + # size indicates no. of nodes at current level + size = len(queue) + + # for keeping track of previous node + prev = newnode(None) + for i in range(size): + temp = queue.pop(0) + if temp.left: + queue.append(temp.left) + if temp.right: + queue.append(temp.right) + if prev != None: + prev.nextRight = temp + prev = temp + prev.nextRight = None + + +# Driver Code +if __name__ == '__main__': + + # Constructed binary tree is + # 10 + # / \ + # 8 2 + # / + # 3 + root = newnode(10) + root.left = newnode(8) + root.right = newnode(2) + root.left.left = newnode(3) + + # Populates nextRight pointer in all nodes + connect(root) + + # Let us check the values of nextRight pointers + print(""Following are populated nextRight"", + ""pointers in the tree (-1 is printed"", + ""if there is no nextRight)"") + print(""nextRight of"", root.data, ""is "", end="""") + if root.nextRight: + print(root.nextRight.data) + else: + print(-1) + print(""nextRight of"", root.left.data, ""is "", end="""") + if root.left.nextRight: + print(root.left.nextRight.data) + else: + print(-1) + print(""nextRight of"", root.right.data, ""is "", end="""") + if root.right.nextRight: + print(root.right.nextRight.data) + else: + print(-1) + print(""nextRight of"", root.left.left.data, ""is "", end="""") + if root.left.left.nextRight: + print(root.left.left.nextRight.data) + else: + print(-1) + +# This code is contributed by Vivek Maddeshiya",linear,linear +"# Python3 implementation to find the +# level having Maximum number of Nodes + +# Importing Queue +from queue import Queue + +# Helper class that allocates a new +# node with the given data and None +# left and right pointers. +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# function to find the level +# having Maximum number of Nodes +def maxNodeLevel(root): + if (root == None): + return -1 + + q = Queue() + q.put(root) + + # Current level + level = 0 + + # Maximum Nodes at same level + Max = -999999999999 + + # Level having Maximum Nodes + level_no = 0 + + while (1): + + # Count Nodes in a level + NodeCount = q.qsize() + + if (NodeCount == 0): + break + + # If it is Maximum till now + # Update level_no to current level + if (NodeCount > Max): + Max = NodeCount + level_no = level + + # Pop complete current level + while (NodeCount > 0): + Node = q.queue[0] + q.get() + if (Node.left != None): + q.put(Node.left) + if (Node.right != None): + q.put(Node.right) + NodeCount -= 1 + + # Increment for next level + level += 1 + + return level_no + +# Driver Code +if __name__ == '__main__': + + # binary tree formation + root = newNode(2) # 2 + root.left = newNode(1) # / \ + root.right = newNode(3) # 1 3 + root.left.left = newNode(4) # / \ \ + root.left.right = newNode(6) # 4 6 8 + root.right.right = newNode(8) # / + root.left.right.left = newNode(5)# 5 + + print(""Level having Maximum number of Nodes : "", + maxNodeLevel(root)) + +# This code is contributed by Pranchalk",linear,linear +"# Python program to print largest value +# on each level of binary tree + +INT_MIN = -2147483648 + +# Helper function that allocates a new +# node with the given data and None left +# and right pointers. + + +class newNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# function to find largest values + + +def largestValueInEachLevel(root): + if (not root): + return + q = [] + nc = 10 + max = 0 + q.append(root) + while (1): + # node count for the current level + nc = len(q) + + # if true then all the nodes of + # the tree have been traversed + if (nc == 0): + break + + # maximum element for the current + # level + max = INT_MIN + while (nc): + + # get the front element from 'q' + front = q[0] + + # remove front element from 'q' + q = q[1:] + + # if true, then update 'max' + if (max < front.data): + max = front.data + + # if left child exists + if (front.left): + q.append(front.left) + + # if right child exists + if (front.right != None): + q.append(front.right) + nc -= 1 + + # print maximum element of + # current level + print(max, end="" "") + + +# Driver Code +if __name__ == '__main__': + """""" Let us construct the following Tree + 4 + / \ + 9 2 + / \ \ + 3 5 7 """""" + root = newNode(4) + root.left = newNode(9) + root.right = newNode(2) + root.left.left = newNode(3) + root.left.right = newNode(5) + root.right.right = newNode(7) + + # Function call + largestValueInEachLevel(root) + +# This code is contributed +# Shubham Singh(SHUBHAMSINGH10)",constant,linear +"# Python3 program to find closest +# value in Binary search Tree + +_MIN = -2147483648 +_MAX = 2147483648 + +# Helper function that allocates a new +# node with the given data and None +# left and right pointers. +class getnode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# utility function to return level +# of given node +def getlevel(root, data): + + q = [] + level = 1 + q.append(root) + + # extra None is appended to keep track + # of all the nodes to be appended + # before level is incremented by 1 + q.append(None) + while (len(q)): + temp = q[0] + q.pop(0) + if (temp == None) : + if len(q) == 0: + return 0 + if (q[0] != None): + q.append(None) + level += 1 + else : + if (temp.data == data) : + return level + if (temp.left): + q.append(temp.left) + if (temp.right) : + q.append(temp.right) + return 0 + +# Driver Code +if __name__ == '__main__': + + # create a binary tree + root = getnode(20) + root.left = getnode(10) + root.right = getnode(30) + root.left.left = getnode(5) + root.left.right = getnode(15) + root.left.right.left = getnode(12) + root.right.left = getnode(25) + root.right.right = getnode(40) + + # return level of node + level = getlevel(root, 30) + if level != 0: + print(""level of node 30 is"", level) + else: + print(""node 30 not found"") + + level = getlevel(root, 12) + if level != 0: + print(""level of node 12 is"", level) + else: + print(""node 12 not found"") + + level = getlevel(root, 25) + if level != 0: + print(""level of node 25 is"", level) + else: + print(""node 25 not found"") + + level = getlevel(root, 27) + if level != 0: + print(""level of node 27 is"", level) + else: + print(""node 27 not found"") + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,linear +"# Python program to remove all half nodes + +# A binary tree node +class Node: + # Constructor for creating a new node + def __init__(self , data): + self.data = data + self.left = None + self.right = None + +# For inorder traversal +def printInorder(root): + if root is not None: + printInorder(root.left) + print (root.data,end="" "") + printInorder(root.right) + +# Removes all nodes with only one child and returns +# new root(note that root may change) +def RemoveHalfNodes(root): + if root is None: + return None + + # Recur to left tree + root.left = RemoveHalfNodes(root.left) + + # Recur to right tree + root.right = RemoveHalfNodes(root.right) + + # if both left and right child is None + # the node is not a Half node + if root.left is None and root.right is None: + return root + + # If current nodes is a half node with left child + # None then it's right child is returned and + # replaces it in the given tree + if root.left is None: + new_root = root.right + temp = root + root = None + del(temp) + return new_root + + if root.right is None: + new_root = root.left + temp = root + root = None + del(temp) + return new_root + + return root + +# Driver Program +root = Node(2) +root.left = Node(7) +root.right = Node(5) +root.left.right = Node(6) +root.left.right.left = Node(1) +root.left.right.right = Node(11) +root.right.right = Node(9) +root.right.right.left = Node(4) + +print (""Inorder traversal of given tree"") +printInorder(root) + +NewRoot = RemoveHalfNodes(root) + +print (""\nInorder traversal of the modified tree"") +printInorder(NewRoot) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",constant,linear +"# Python3 program to find the length of longest +# path with same values in a binary tree. + +# Helper function that allocates a +# new node with the given data and +# None left and right pointers. +class newNode: + def __init__(self, data): + self.val = data + self.left = self.right = None + +# Function to print the longest path +# of same values +def length(node, ans): + if (not node): + return 0 + + # Recursive calls to check for subtrees + left = length(node.left, ans) + right = length(node.right, ans) + + # Variables to store maximum lengths + # in two directions + Leftmax = 0 + Rightmax = 0 + + # If curr node and it's left child has same value + if (node.left and node.left.val == node.val): + Leftmax += left + 1 + + # If curr node and it's right child has same value + if (node.right and node.right.val == node.val): + Rightmax += right + 1 + + ans[0] = max(ans[0], Leftmax + Rightmax) + return max(Leftmax, Rightmax) + +# Driver function to find length of +# longest same value path +def longestSameValuePath(root): + ans = [0] + length(root, ans) + return ans[0] + +# Driver code +if __name__ == '__main__': + + # Let us construct a Binary Tree + # 4 + # / \ + # 4 4 + # / \ \ + # 4 9 5 + root = None + root = newNode(4) + root.left = newNode(4) + root.right = newNode(4) + root.left.left = newNode(4) + root.left.right = newNode(9) + root.right.right = newNode(5) + print(longestSameValuePath(root)) + +# This code is contributed by PranchalK",logn,linear +"# Python3 program to find distance of +# a given node from root. + +# A class to create a new Binary +# Tree Node +class newNode: + def __init__(self, item): + self.data = item + self.left = self.right = None + +# Returns -1 if x doesn't exist in tree. +# Else returns distance of x from root +def findDistance(root, x): + + # Base case + if (root == None): + return -1 + + # Initialize distance + dist = -1 + + # Check if x is present at root or + # in left subtree or right subtree. + if (root.data == x): + return dist + 1 + else: + dist = findDistance(root.left, x) + if dist >= 0: + return dist + 1 + else: + dist = findDistance(root.right, x) + if dist >= 0: + return dist + 1 + + return dist + +# Driver Code +if __name__ == '__main__': + + root = newNode(5) + root.left = newNode(10) + root.right = newNode(15) + root.left.left = newNode(20) + root.left.right = newNode(25) + root.left.right.right = newNode(45) + root.right.left = newNode(30) + root.right.right = newNode(35) + + print(findDistance(root, 45)) + +# This code is contributed by PranchalK",constant,linear +"# Python3 program to print right sibling +# of a node + +# A class to create a new Binary +# Tree Node +class newNode: + def __init__(self, item, parent): + self.data = item + self.left = self.right = None + self.parent = parent + +# Method to find right sibling +def findRightSibling(node, level): + if (node == None or node.parent == None): + return None + + # GET Parent pointer whose right child is not + # a parent or itself of this node. There might + # be case when parent has no right child, but, + # current node is left child of the parent + # (second condition is for that). + while (node.parent.right == node or + (node.parent.right == None and + node.parent.left == node)): + if (node.parent == None): + return None + + node = node.parent + level -= 1 + + # Move to the required child, where + # right sibling can be present + node = node.parent.right + + # find right sibling in the given subtree + # (from current node), when level will be 0 + while (level < 0): + + # Iterate through subtree + if (node.left != None): + node = node.left + else if (node.right != None): + node = node.right + else: + + # if no child are there, we cannot + # have right sibling in this path + break + + level += 1 + + if (level == 0): + return node + + # This is the case when we reach 9 node + # in the tree, where we need to again + # recursively find the right sibling + return findRightSibling(node, level) + +# Driver Code +if __name__ == '__main__': + root = newNode(1, None) + root.left = newNode(2, root) + root.right = newNode(3, root) + root.left.left = newNode(4, root.left) + root.left.right = newNode(6, root.left) + root.left.left.left = newNode(7, root.left.left) + root.left.left.left.left = newNode(10, root.left.left.left) + root.left.right.right = newNode(9, root.left.right) + root.right.right = newNode(5, root.right) + root.right.right.right = newNode(8, root.right.right) + root.right.right.right.right = newNode(12, root.right.right.right) + + # passing 10 + res = findRightSibling(root.left.left.left.left, 0) + if (res == None): + print(""No right sibling"") + else: + print(res.data) + +# This code is contributed by PranchalK",constant,linear +"# Python3 program to find next right of a +# given key using preorder traversal + +# class to create a new tree node +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None + +# Function to find next node for given node +# in same level in a binary tree by using +# pre-order traversal +def nextRightNode(root, k, level, value_level): + + # return None if tree is empty + if (root == None): + return None + + # if desired node is found, set + # value_level to current level + if (root.key == k): + value_level[0] = level + return None + + # if value_level is already set, then + # current node is the next right node + elif (value_level[0]): + if (level == value_level[0]): + return root + + # recurse for left subtree by increasing + # level by 1 + leftNode = nextRightNode(root.left, k, + level + 1, value_level) + + # if node is found in left subtree, + # return it + if (leftNode): + return leftNode + + # recurse for right subtree by + # increasing level by 1 + return nextRightNode(root.right, k, + level + 1, value_level) + +# Function to find next node of given node +# in the same level in given binary tree +def nextRightNodeUtil(root, k): + value_level = [0] + + return nextRightNode(root, k, 1, value_level) + +# A utility function to test above functions +def test(root, k): + nr = nextRightNodeUtil(root, k) + if (nr != None): + print(""Next Right of"", k, ""is"", nr.key) + else: + print(""No next right node found for"", k) + +# Driver Code +if __name__ == '__main__': + + # Let us create binary tree given in the + # above example + root = newNode(10) + root.left = newNode(2) + root.right = newNode(6) + root.right.right = newNode(5) + root.left.left = newNode(8) + root.left.right = newNode(4) + + test(root, 10) + test(root, 2) + test(root, 6) + test(root, 5) + test(root, 8) + test(root, 4) + +# This code is contributed by PranchalK",constant,linear +"# Python3 Program to find Tilt of +# Binary Tree + +# class that allocates a new node +# with the given data and +# None left and right pointers. +class newNode: + def __init__(self, data): + self.val = data + self.left = self.right = None + +# Recursive function to calculate +# Tilt of whole tree +def traverse(root, tilt): + if (not root): + return 0 + + # Compute tilts of left and right subtrees + # and find sums of left and right subtrees + left = traverse(root.left, tilt) + right = traverse(root.right, tilt) + + # Add current tilt to overall + tilt[0] += abs(left - right) + + # Returns sum of nodes under + # current tree + return left + right + root.val + +# Driver function to print Tilt +# of whole tree +def Tilt(root): + tilt = [0] + traverse(root, tilt) + return tilt[0] + +# Driver code +if __name__ == '__main__': + + # Let us construct a Binary Tree + # 4 + # / \ + # 2 9 + # / \ \ + # 3 5 7 + root = None + root = newNode(4) + root.left = newNode(2) + root.right = newNode(9) + root.left.left = newNode(3) + root.left.right = newNode(8) + root.right.right = newNode(7) + print(""The Tilt of whole tree is"", + Tilt(root)) + +# This code is contributed by PranchalK",linear,linear +"# Python3 program to find averages of +# all levels in a binary tree. + +# Helper function that allocates a +# new node with the given data and +# None left and right pointers. +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +def inorder(node, m): + if (not node): + return """" + + Str = ""("" + Str += inorder(node.left, m) + Str += str(node.data) + Str += inorder(node.right, m) + Str += "")"" + + # Subtree already present (Note that + # we use unordered_map instead of + # unordered_set because we want to print + # multiple duplicates only once, consider + # example of 4 in above subtree, it + # should be printed only once. + if (Str in m and m[Str] == 1): + print(node.data, end = "" "") + if Str in m: + m[Str] += 1 + else: + m[Str] = 1 + + return Str + +# Wrapper over inorder() +def printAllDups(root): + m = {} + inorder(root, m) + +# Driver code +if __name__ == '__main__': + root = None + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.right.left = newNode(2) + root.right.left.left = newNode(4) + root.right.right = newNode(4) + printAllDups(root) + +# This code is contributed by PranchalK",quadratic,quadratic +"# Python3 program to find largest three +# elements in a binary tree. + +# Helper function that allocates a new +# Node with the given data and None +# left and right pointers. +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# function to find three largest element +def threelargest(root, first, second, third): + if (root == None): + return + + # if data is greater than first large + # number update the top three list + if (root.data > first[0]): + third[0] = second[0] + second[0] = first[0] + first[0] = root.data + + # if data is greater than second large + # number and not equal to first update + # the bottom two list + elif (root.data > second[0] and + root.data != first[0]): + third[0] = second[0] + second[0] = root.data + + # if data is greater than third large + # number and not equal to first & second + # update the third highest list + elif (root.data > third[0] and + root.data != first[0] and + root.data != second[0]): + third[0] = root.data + + threelargest(root.left, first, + second, third) + threelargest(root.right, first, + second, third) + +# Driver Code +if __name__ == '__main__': + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.right.left = newNode(4) + root.right.right = newNode(5) + + first = [0] + second = [0] + third = [0] + threelargest(root, first, second, third) + print(""three largest elements are"", + first[0], second[0], third[0]) + +# This code is contributed by PranchalK",constant,linear +"# Python3 program to print DFS traversal +# from a given graph +from collections import defaultdict + +# This class represents a directed graph using +# adjacency list representation + + +class Graph: + + # Constructor + def __init__(self): + + # default dictionary to store graph + self.graph = defaultdict(list) + + # function to add an edge to graph + def addEdge(self, u, v): + self.graph[u].append(v) + + # A function used by DFS + def DFSUtil(self, v, visited): + + # Mark the current node as visited + # and print it + visited.add(v) + print(v, end=' ') + + # Recur for all the vertices + # adjacent to this vertex + for neighbour in self.graph[v]: + if neighbour not in visited: + self.DFSUtil(neighbour, visited) + + # The function to do DFS traversal. It uses + # recursive DFSUtil() + def DFS(self, v): + + # Create a set to store visited vertices + visited = set() + + # Call the recursive helper function + # to print DFS traversal + self.DFSUtil(v, visited) + +# Driver's code + + +# Create a graph given +# in the above diagram +if __name__ == ""__main__"": + g = Graph() + g.addEdge(0, 1) + g.addEdge(0, 2) + g.addEdge(1, 2) + g.addEdge(2, 0) + g.addEdge(2, 3) + g.addEdge(3, 3) + + print(""Following is DFS from (starting from vertex 2)"") + # Function call + g.DFS(2) + +# This code is contributed by Neelam Yadav",linear,linear +"'''Python3 program to print DFS traversal for complete graph''' +from collections import defaultdict + +# this class represents a directed graph using adjacency list representation + + +class Graph: + # Constructor + def __init__(self): + # default dictionary to store graph + self.graph = defaultdict(list) + + # Function to add an edge to graph + def addEdge(self, u, v): + self.graph[u].append(v) + # A function used by DFS + + def DFSUtil(self, v, visited): + # Mark the current node as visited and print it + visited.add(v) + print(v, end="" "") + + # recur for all the vertices adjacent to this vertex + for neighbour in self.graph[v]: + if neighbour not in visited: + self.DFSUtil(neighbour, visited) + # The function to do DFS traversal. It uses recursive DFSUtil + + def DFS(self): + # create a set to store all visited vertices + visited = set() + # call the recursive helper function to print DFS traversal starting from all + # vertices one by one + for vertex in self.graph: + if vertex not in visited: + self.DFSUtil(vertex, visited) +# Driver's code +# create a graph given in the above diagram + +if __name__ == ""__main__"": + print(""Following is Depth First Traversal \n"") + g = Graph() + g.addEdge(0, 1) + g.addEdge(0, 2) + g.addEdge(1, 2) + g.addEdge(2, 0) + g.addEdge(2, 3) + g.addEdge(3, 3) + + # Function call + g.DFS() + +# Improved by Dheeraj Kumar",linear,linear +"# Python3 program to find a mother vertex in O(V+E) time +from collections import defaultdict + +# This class represents a directed graph using adjacency list +# representation + + +class Graph: + + def __init__(self, vertices): + self.V = vertices # No. of vertices + self.graph = defaultdict(list) # default dictionary + + # A recursive function to print DFS starting from v + def DFSUtil(self, v, visited): + + # Mark the current node as visited and print it + visited[v] = True + + # Recur for all the vertices adjacent to this vertex + for i in self.graph[v]: + if visited[i] == False: + self.DFSUtil(i, visited) + + # Add w to the list of v + def addEdge(self, v, w): + self.graph[v].append(w) + + # Returns a mother vertex if exists. Otherwise returns -1 + def findMother(self): + + # visited[] is used for DFS. Initially all are + # initialized as not visited + visited = [False]*(self.V) + + # To store last finished vertex (or mother vertex) + v = 0 + + # Do a DFS traversal and find the last finished + # vertex + for i in range(self.V): + if visited[i] == False: + self.DFSUtil(i, visited) + v = i + + # If there exist mother vertex (or vertices) in given + # graph, then v must be one (or one of them) + + # Now check if v is actually a mother vertex (or graph + # has a mother vertex). We basically check if every vertex + # is reachable from v or not. + + # Reset all values in visited[] as false and do + # DFS beginning from v to check if all vertices are + # reachable from it or not. + visited = [False]*(self.V) + self.DFSUtil(v, visited) + if any(i == False for i in visited): + return -1 + else: + return v + + +# Driver code +if __name__ == '__main__': + g = Graph(7) + g.addEdge(0, 1) + g.addEdge(0, 2) + g.addEdge(1, 3) + g.addEdge(4, 1) + g.addEdge(6, 4) + g.addEdge(5, 6) + g.addEdge(5, 2) + g.addEdge(6, 0) + + # Function call + print(""A mother vertex is "" + str(g.findMother())) + +# This code is contributed by Neelam Yadav",linear,linear +"# Python 3 program to count all paths +# from a source to a destination. + +# A directed graph using adjacency +# list representation + + +class Graph: + + def __init__(self, V): + self.V = V + self.adj = [[] for i in range(V)] + + def addEdge(self, u, v): + + # Add v to u’s list. + self.adj[u].append(v) + + # Returns count of paths from 's' to 'd' + def countPaths(self, s, d): + + # Mark all the vertices + # as not visited + visited = [False] * self.V + + # Call the recursive helper + # function to print all paths + pathCount = [0] + self.countPathsUtil(s, d, visited, pathCount) + return pathCount[0] + + # A recursive function to print all paths + # from 'u' to 'd'. visited[] keeps track + # of vertices in current path. path[] + # stores actual vertices and path_index + # is current index in path[] + def countPathsUtil(self, u, d, + visited, pathCount): + visited[u] = True + + # If current vertex is same as + # destination, then increment count + if (u == d): + pathCount[0] += 1 + + # If current vertex is not destination + else: + + # Recur for all the vertices + # adjacent to current vertex + i = 0 + while i < len(self.adj[u]): + if (not visited[self.adj[u][i]]): + self.countPathsUtil(self.adj[u][i], d, + visited, pathCount) + i += 1 + + visited[u] = False + + +# Driver Code +if __name__ == '__main__': + + # Create a graph given in the + # above diagram + g = Graph(4) + g.addEdge(0, 1) + g.addEdge(0, 2) + g.addEdge(0, 3) + g.addEdge(2, 0) + g.addEdge(2, 1) + g.addEdge(1, 3) + + s = 2 + d = 3 + + # Function call + print(g.countPaths(s, d)) + +# This code is contributed by PranchalK",linear,np +"# Python3 Program to determine level +# of each node and print level +import queue + +# function to determine level of +# each node starting from x using BFS + + +def printLevels(graph, V, x): + + # array to store level of each node + level = [None] * V + marked = [False] * V + + # create a queue + que = queue.Queue() + + # enqueue element x + que.put(x) + + # initialize level of source + # node to 0 + level[x] = 0 + + # marked it as visited + marked[x] = True + + # do until queue is empty + while (not que.empty()): + + # get the first element of queue + x = que.get() + + # traverse neighbors of node x + for i in range(len(graph[x])): + + # b is neighbor of node x + b = graph[x][i] + + # if b is not marked already + if (not marked[b]): + + # enqueue b in queue + que.put(b) + + # level of b is level of x + 1 + level[b] = level[x] + 1 + + # mark b + marked[b] = True + + # display all nodes and their levels + print(""Nodes"", "" "", ""Level"") + for i in range(V): + print("" "", i, "" --> "", level[i]) + + +# Driver Code +if __name__ == '__main__': + + # adjacency graph for tree + V = 8 + graph = [[] for i in range(V)] + + graph[0].append(1) + graph[0].append(2) + graph[1].append(3) + graph[1].append(4) + graph[1].append(5) + graph[2].append(5) + graph[2].append(6) + graph[6].append(7) + + # call levels function with source as 0 + printLevels(graph, V, 0) + +# This code is contributed by PranchalK",linear,linear +"# Python3 program to find out path in +# a rectangle containing circles. +import math +import queue + +# Function to find out if there is +# any possible path or not. + + +def isPossible(m, n, k, r, X, Y): + + # Take an array of m*n size and + # initialize each element to 0. + rect = [[0] * n for i in range(m)] + + # Now using Pythagorean theorem find if a + # cell touches or within any circle or not. + for i in range(m): + for j in range(n): + for p in range(k): + if (math.sqrt((pow((X[p] - 1 - i), 2) + + pow((Y[p] - 1 - j), 2))) <= r): + rect[i][j] = -1 + + # If the starting cell comes within + # any circle return false. + if (rect[0][0] == -1): + return False + + # Now use BFS to find if there + # is any possible path or not. + + # Initialize the queue which holds + # the discovered cells whose neighbors + # are not discovered yet. + qu = queue.Queue() + + rect[0][0] = 1 + qu.put([0, 0]) + + # Discover cells until queue is not empty + while (not qu.empty()): + arr = qu.get() + elex = arr[0] + eley = arr[1] + + # Discover the eight adjacent nodes. + # check top-left cell + if ((elex > 0) and (eley > 0) and + (rect[elex - 1][eley - 1] == 0)): + rect[elex - 1][eley - 1] = 1 + v = [elex - 1, eley - 1] + qu.put(v) + + # check top cell + if ((elex > 0) and + (rect[elex - 1][eley] == 0)): + rect[elex - 1][eley] = 1 + v = [elex - 1, eley] + qu.put(v) + + # check top-right cell + if ((elex > 0) and (eley < n - 1) and + (rect[elex - 1][eley + 1] == 0)): + rect[elex - 1][eley + 1] = 1 + v = [elex - 1, eley + 1] + qu.put(v) + + # check left cell + if ((eley > 0) and + (rect[elex][eley - 1] == 0)): + rect[elex][eley - 1] = 1 + v = [elex, eley - 1] + qu.put(v) + + # check right cell + if ((eley < n - 1) and + (rect[elex][eley + 1] == 0)): + rect[elex][eley + 1] = 1 + v = [elex, eley + 1] + qu.put(v) + + # check bottom-left cell + if ((elex < m - 1) and (eley > 0) and + (rect[elex + 1][eley - 1] == 0)): + rect[elex + 1][eley - 1] = 1 + v = [elex + 1, eley - 1] + qu.put(v) + + # check bottom cell + if ((elex < m - 1) and + (rect[elex + 1][eley] == 0)): + rect[elex + 1][eley] = 1 + v = [elex + 1, eley] + qu.put(v) + + # check bottom-right cell + if ((elex < m - 1) and (eley < n - 1) and + (rect[elex + 1][eley + 1] == 0)): + rect[elex + 1][eley + 1] = 1 + v = [elex + 1, eley + 1] + qu.put(v) + + # Now if the end cell (i.e. bottom right cell) + # is 1(reachable) then we will send true. + return (rect[m - 1][n - 1] == 1) + + +# Driver Code +if __name__ == '__main__': + + # Test case 1 + m1 = 5 + n1 = 5 + k1 = 2 + r1 = 1 + X1 = [1, 3] + Y1 = [3, 3] + + # Function call + if (isPossible(m1, n1, k1, r1, X1, Y1)): + print(""Possible"") + else: + print(""Not Possible"") + + # Test case 2 + m2 = 5 + n2 = 5 + k2 = 2 + r2 = 1 + X2 = [1, 1] + Y2 = [2, 3] + + # Function call + if (isPossible(m2, n2, k2, r2, X2, Y2)): + print(""Possible"") + else: + print(""Not Possible"") + +# This code is contributed by PranchalK",quadratic,quadratic +"# Python3 program to print all paths of +# source to destination in given graph +from typing import List +from collections import deque + +# Utility function for printing +# the found path in graph +def printpath(path: List[int]) -> None: + + size = len(path) + for i in range(size): + print(path[i], end = "" "") + + print() + +# Utility function to check if current +# vertex is already present in path +def isNotVisited(x: int, path: List[int]) -> int: + + size = len(path) + for i in range(size): + if (path[i] == x): + return 0 + + return 1 + +# Utility function for finding paths in graph +# from source to destination +def findpaths(g: List[List[int]], src: int, + dst: int, v: int) -> None: + + # Create a queue which stores + # the paths + q = deque() + + # Path vector to store the current path + path = [] + path.append(src) + q.append(path.copy()) + + while q: + path = q.popleft() + last = path[len(path) - 1] + + # If last vertex is the desired destination + # then print the path + if (last == dst): + printpath(path) + + # Traverse to all the nodes connected to + # current vertex and push new path to queue + for i in range(len(g[last])): + if (isNotVisited(g[last][i], path)): + newpath = path.copy() + newpath.append(g[last][i]) + q.append(newpath) + +# Driver code +if __name__ == ""__main__"": + + # Number of vertices + v = 4 + g = [[] for _ in range(4)] + + # Construct a graph + g[0].append(3) + g[0].append(1) + g[0].append(2) + g[1].append(3) + g[2].append(0) + g[2].append(1) + + src = 2 + dst = 3 + print(""path from src {} to dst {} are"".format( + src, dst)) + + # Function for finding the paths + findpaths(g, src, dst, v) + +# This code is contributed by sanjeev2552",quadratic,quadratic +"# Python3 program to find minimum edge +# between given two vertex of Graph +import queue + +# function for finding minimum +# no. of edge using BFS +def minEdgeBFS(edges, u, v, n): + + # visited[n] for keeping track + # of visited node in BFS + visited = [0] * n + + # Initialize distances as 0 + distance = [0] * n + + # queue to do BFS. + Q = queue.Queue() + distance[u] = 0 + + Q.put(u) + visited[u] = True + while (not Q.empty()): + x = Q.get() + + for i in range(len(edges[x])): + if (visited[edges[x][i]]): + continue + + # update distance for i + distance[edges[x][i]] = distance[x] + 1 + Q.put(edges[x][i]) + visited[edges[x][i]] = 1 + return distance[v] + +# function for addition of edge +def addEdge(edges, u, v): + edges[u].append(v) + edges[v].append(u) + +# Driver Code +if __name__ == '__main__': + + # To store adjacency list of graph + n = 9 + edges = [[] for i in range(n)] + addEdge(edges, 0, 1) + addEdge(edges, 0, 7) + addEdge(edges, 1, 7) + addEdge(edges, 1, 2) + addEdge(edges, 2, 3) + addEdge(edges, 2, 5) + addEdge(edges, 2, 8) + addEdge(edges, 3, 4) + addEdge(edges, 3, 5) + addEdge(edges, 4, 5) + addEdge(edges, 5, 6) + addEdge(edges, 6, 7) + addEdge(edges, 7, 8) + u = 0 + v = 5 + print(minEdgeBFS(edges, u, v, n)) + +# This code is contributed by PranchalK",linear,linear +"# Python3 code to find minimum steps to reach +# to specific cell in minimum moves by Knight + + +class cell: + + def __init__(self, x=0, y=0, dist=0): + self.x = x + self.y = y + self.dist = dist + +# checks whether given position is +# inside the board + + +def isInside(x, y, N): + if (x >= 1 and x <= N and + y >= 1 and y <= N): + return True + return False + +# Method returns minimum step to reach +# target position + + +def minStepToReachTarget(knightpos, + targetpos, N): + + # all possible movements for the knight + dx = [2, 2, -2, -2, 1, 1, -1, -1] + dy = [1, -1, 1, -1, 2, -2, 2, -2] + + queue = [] + + # push starting position of knight + # with 0 distance + queue.append(cell(knightpos[0], knightpos[1], 0)) + + # make all cell unvisited + visited = [[False for i in range(N + 1)] + for j in range(N + 1)] + + # visit starting state + visited[knightpos[0]][knightpos[1]] = True + + # loop until we have one element in queue + while(len(queue) > 0): + + t = queue[0] + queue.pop(0) + + # if current cell is equal to target + # cell, return its distance + if(t.x == targetpos[0] and + t.y == targetpos[1]): + return t.dist + + # iterate for all reachable states + for i in range(8): + + x = t.x + dx[i] + y = t.y + dy[i] + + if(isInside(x, y, N) and not visited[x][y]): + visited[x][y] = True + queue.append(cell(x, y, t.dist + 1)) + + +# Driver Code +if __name__ == '__main__': + N = 30 + knightpos = [1, 1] + targetpos = [30, 30] + + # Function call + print(minStepToReachTarget(knightpos, + targetpos, N)) + +# This code is contributed by +# Kaustav kumar Chanda",quadratic,quadratic +"# Python program to detect cycle +# in a graph + +from collections import defaultdict + +class Graph(): + def __init__(self,vertices): + self.graph = defaultdict(list) + self.V = vertices + + def addEdge(self,u,v): + self.graph[u].append(v) + + def isCyclicUtil(self, v, visited, recStack): + + # Mark current node as visited and + # adds to recursion stack + visited[v] = True + recStack[v] = True + + # Recur for all neighbours + # if any neighbour is visited and in + # recStack then graph is cyclic + for neighbour in self.graph[v]: + if visited[neighbour] == False: + if self.isCyclicUtil(neighbour, visited, recStack) == True: + return True + elif recStack[neighbour] == True: + return True + + # The node needs to be popped from + # recursion stack before function ends + recStack[v] = False + return False + + # Returns true if graph is cyclic else false + def isCyclic(self): + visited = [False] * (self.V + 1) + recStack = [False] * (self.V + 1) + for node in range(self.V): + if visited[node] == False: + if self.isCyclicUtil(node,visited,recStack) == True: + return True + return False + +g = Graph(4) +g.addEdge(0, 1) +g.addEdge(0, 2) +g.addEdge(1, 2) +g.addEdge(2, 0) +g.addEdge(2, 3) +g.addEdge(3, 3) +if g.isCyclic() == 1: + print ""Graph contains cycle"" +else: + print ""Graph doesn't contain cycle"" + +# Thanks to Divyanshu Mehta for contributing this code",linear,linear +"# Python Program to detect cycle in an undirected graph +from collections import defaultdict + +# This class represents a undirected +# graph using adjacency list representation + + +class Graph: + + def __init__(self, vertices): + + # No. of vertices + self.V = vertices # No. of vertices + + # Default dictionary to store graph + self.graph = defaultdict(list) + + # Function to add an edge to graph + def addEdge(self, v, w): + + # Add w to v_s list + self.graph[v].append(w) + + # Add v to w_s list + self.graph[w].append(v) + + # A recursive function that uses + # visited[] and parent to detect + # cycle in subgraph reachable from vertex v. + def isCyclicUtil(self, v, visited, parent): + + # Mark the current node as visited + visited[v] = True + + # Recur for all the vertices + # adjacent to this vertex + for i in self.graph[v]: + + # If the node is not + # visited then recurse on it + if visited[i] == False: + if(self.isCyclicUtil(i, visited, v)): + return True + # If an adjacent vertex is + # visited and not parent + # of current vertex, + # then there is a cycle + elif parent != i: + return True + + return False + + # Returns true if the graph + # contains a cycle, else false. + + def isCyclic(self): + + # Mark all the vertices + # as not visited + visited = [False]*(self.V) + + # Call the recursive helper + # function to detect cycle in different + # DFS trees + for i in range(self.V): + + # Don't recur for u if it + # is already visited + if visited[i] == False: + if(self.isCyclicUtil + (i, visited, -1)) == True: + return True + + return False + + +# Create a graph given in the above diagram +g = Graph(5) +g.addEdge(1, 0) +g.addEdge(1, 2) +g.addEdge(2, 0) +g.addEdge(0, 3) +g.addEdge(3, 4) + +if g.isCyclic(): + print(""Graph contains cycle"") +else: + print(""Graph doesn't contain cycle "") +g1 = Graph(3) +g1.addEdge(0, 1) +g1.addEdge(1, 2) + + +if g1.isCyclic(): + print(""Graph contains cycle"") +else: + print(""Graph doesn't contain cycle "") + +# This code is contributed by Neelam Yadav",linear,linear +"# Python program to detect cycle in +# a directed graph + +from collections import defaultdict + +class Graph(): + def __init__(self, V): + self.V = V + self.graph = defaultdict(list) + + def addEdge(self, u, v): + self.graph[u].append(v) + + def DFSUtil(self, u, color): + # GRAY : This vertex is being processed (DFS + # for this vertex has started, but not + # ended (or this vertex is in function + # call stack) + color[u] = ""GRAY"" + + for v in self.graph[u]: + + if color[v] == ""GRAY"": + return True + + if color[v] == ""WHITE"" and self.DFSUtil(v, color) == True: + return True + + color[u] = ""BLACK"" + return False + + def isCyclic(self): + color = [""WHITE""] * self.V + + for i in range(self.V): + if color[i] == ""WHITE"": + if self.DFSUtil(i, color) == True: + return True + return False + +# Driver program to test above functions + +g = Graph(4) +g.addEdge(0, 1) +g.addEdge(0, 2) +g.addEdge(1, 2) +g.addEdge(2, 0) +g.addEdge(2, 3) +g.addEdge(3, 3) +print (""Graph contains cycle"" if g.isCyclic() == True\ + else ""Graph doesn't contain cycle"") + +# This program is contributed by Divyanshu Mehta ",linear,linear +"# Python3 program to check if there +# is a cycle of total odd weight + +# This function returns true if the current subpart +# of the forest is two colorable, else false. +def twoColorUtil(G, src, N, colorArr): + + # Assign first color to source + colorArr[src] = 1 + + # Create a queue (FIFO) of vertex numbers and + # enqueue source vertex for BFS traversal + q = [src] + + # Run while there are vertices in queue + # (Similar to BFS) + while len(q) > 0: + + u = q.pop(0) + + # Find all non-colored adjacent vertices + for v in range(0, len(G[u])): + + # An edge from u to v exists and + # destination v is not colored + if colorArr[G[u][v]] == -1: + + # Assign alternate color to this + # adjacent v of u + colorArr[G[u][v]] = 1 - colorArr[u] + q.append(G[u][v]) + + # An edge from u to v exists and destination + # v is colored with same color as u + elif colorArr[G[u][v]] == colorArr[u]: + return False + + return True + +# This function returns true if graph +# G[V][V] is two colorable, else false +def twoColor(G, N): + + # Create a color array to store colors assigned + # to all vertices. Vertex number is used as index + # in this array. The value '-1' of colorArr[i] + # is used to indicate that no color is assigned + # to vertex 'i'. The value 1 is used to indicate + # first color is assigned and value 0 indicates + # second color is assigned. + colorArr = [-1] * N + + # As we are dealing with graph, the input might + # come as a forest, thus start coloring from a + # node and if true is returned we'll know that + # we successfully colored the subpart of our + # forest and we start coloring again from a new + # uncolored node. This way we cover the entire forest. + for i in range(N): + if colorArr[i] == -1: + if twoColorUtil(G, i, N, colorArr) == False: + return False + + return True + +# Returns false if an odd cycle is present else true +# int info[][] is the information about our graph +# int n is the number of nodes +# int m is the number of informations given to us +def isOddSum(info, n, m): + + # Declaring adjacency list of a graph + # Here at max, we can encounter all the + # edges with even weight thus there will + # be 1 pseudo node for each edge + G = [[] for i in range(2*n)] + + pseudo, pseudo_count = n+1, 0 + for i in range(0, m): + + # For odd weight edges, we + # directly add it in our graph + if info[i][2] % 2 == 1: + + u, v = info[i][0], info[i][1] + G[u].append(v) + G[v].append(u) + + # For even weight edges, we break it + else: + u, v = info[i][0], info[i][1] + + # Entering a pseudo node between u---v + G[u].append(pseudo) + G[pseudo].append(u) + G[v].append(pseudo) + G[pseudo].append(v) + + # Keeping a record of number + # of pseudo nodes inserted + pseudo_count += 1 + + # Making a new pseudo node for next time + pseudo += 1 + + # We pass number graph G[][] and total number + # of node = actual number of nodes + number of + # pseudo nodes added. + return twoColor(G, n+pseudo_count) + +# Driver function +if __name__ == ""__main__"": + + # 'n' correspond to number of nodes in our + # graph while 'm' correspond to the number + # of information about this graph. + n, m = 4, 3 + info = [[1, 2, 12], + [2, 3, 1], + [4, 3, 1], + [4, 1, 20]] + + # This function break the even weighted edges in + # two parts. Makes the adjacency representation + # of the graph and sends it for two coloring. + if isOddSum(info, n, m) == True: + print(""No"") + else: + print(""Yes"") + +# This code is contributed by Rituraj Jain",linear,quadratic +"# Python3 program to implement Union-Find +# with union by rank and path compression. + +# set parent of every node to itself +# and size of node to one +def initialize(n): + global Arr, size + for i in range(n + 1): + Arr[i] = i + size[i] = 1 + +# Each time we follow a path, find +# function compresses it further +# until the path length is greater +# than or equal to 1. +def find(i): + global Arr, size + + # while we reach a node whose + # parent is equal to itself + while (Arr[i] != i): + Arr[i] = Arr[Arr[i]] # Skip one level + i = Arr[i] # Move to the new level + return i + +# A function that does union of two +# nodes x and y where xr is root node +# of x and yr is root node of y +def _union(xr, yr): + global Arr, size + if (size[xr] < size[yr]): # Make yr parent of xr + Arr[xr] = Arr[yr] + size[yr] += size[xr] + else: # Make xr parent of yr + Arr[yr] = Arr[xr] + size[xr] += size[yr] + +# The main function to check whether +# a given graph contains cycle or not +def isCycle(adj, V): + global Arr, size + + # Iterate through all edges of graph, + # find nodes connecting them. + # If root nodes of both are same, + # then there is cycle in graph. + for i in range(V): + for j in range(len(adj[i])): + x = find(i) # find root of i + y = find(adj[i][j]) # find root of adj[i][j] + + if (x == y): + return 1 # If same parent + _union(x, y) # Make them connect + return 0 + +# Driver Code +MAX_VERTEX = 101 + +# Arr to represent parent of index i +Arr = [None] * MAX_VERTEX + +# Size to represent the number of nodes +# in subgraph rooted at index i +size = [None] * MAX_VERTEX + +V = 3 + +# Initialize the values for array +# Arr and Size +initialize(V) + +# Let us create following graph +# 0 +# | \ +# | \ +# 1-----2 + +# Adjacency list for graph +adj = [[] for i in range(V)] + +adj[0].append(1) +adj[0].append(2) +adj[1].append(2) + +# call is_cycle to check if it +# contains cycle +if (isCycle(adj, V)): + print(""Graph contains Cycle."") +else: + print(""Graph does not contain Cycle."") + +# This code is contributed by PranchalK",constant,logn +"# Python3 program to find number of magical +# indices in the given array. + +# Function to count number of magical +# indices. +def solve(A, n) : + + cnt = 0 + + # Array to store parent node of + # traversal. + parent = [None] * (n + 1) + + # Array to determine whether current node + # is already counted in the cycle. + vis = [None] * (n + 1) + + # Initialize the arrays. + for i in range(0, n+1): + parent[i] = -1 + vis[i] = 0 + + for i in range(0, n): + j = i + + # Check if current node is already + # traversed or not. If node is not + # traversed yet then parent value + # will be -1. + if (parent[j] == -1) : + + # Traverse the graph until an + # already visited node is not + # found. + while (parent[j] == -1) : + parent[j] = i + j = (j + A[j] + 1) % n + + # Check parent value to ensure + # a cycle is present. + if (parent[j] == i) : + + # Count number of nodes in + # the cycle. + while (vis[j]==0) : + vis[j] = 1 + cnt = cnt + 1 + j = (j + A[j] + 1) % n + return cnt + +# Driver code +A = [ 0, 0, 0, 2 ] +n = len(A) +print (solve(A, n)) + +# This code is contributed by Manish Shaw +# (manishshaw1)",linear,linear +"# Python program to print topological sorting of a DAG +from collections import defaultdict + +# Class to represent a graph + + +class Graph: + def __init__(self, vertices): + self.graph = defaultdict(list) # dictionary containing adjacency List + self.V = vertices # No. of vertices + + # function to add an edge to graph + def addEdge(self, u, v): + self.graph[u].append(v) + + # A recursive function used by topologicalSort + def topologicalSortUtil(self, v, visited, stack): + + # Mark the current node as visited. + visited[v] = True + + # Recur for all the vertices adjacent to this vertex + for i in self.graph[v]: + if visited[i] == False: + self.topologicalSortUtil(i, visited, stack) + + # Push current vertex to stack which stores result + stack.append(v) + + # The function to do Topological Sort. It uses recursive + # topologicalSortUtil() + def topologicalSort(self): + # Mark all the vertices as not visited + visited = [False]*self.V + stack = [] + + # Call the recursive helper function to store Topological + # Sort starting from all vertices one by one + for i in range(self.V): + if visited[i] == False: + self.topologicalSortUtil(i, visited, stack) + + # Print contents of the stack + print(stack[::-1]) # return list in reverse order + + +# Driver Code +if __name__ == '__main__': + g = Graph(6) + g.addEdge(5, 2) + g.addEdge(5, 0) + g.addEdge(4, 0) + g.addEdge(4, 1) + g.addEdge(2, 3) + g.addEdge(3, 1) + + print(""Following is a Topological Sort of the given graph"") + + # Function Call + g.topologicalSort() + +# This code is contributed by Neelam Yadav",linear,linear +"# Python program to print topological sorting of a DAG +from collections import defaultdict + +# Class to represent a graph + + +class Graph: + def __init__(self, vertices): + self.graph = defaultdict(list) # dictionary containing adjacency List + self.V = vertices # No. of vertices + + # function to add an edge to graph + def addEdge(self, u, v): + self.graph[u].append(v) + + # neighbors generator given key + def neighbor_gen(self, v): + for k in self.graph[v]: + yield k + + # non recursive topological sort + def nonRecursiveTopologicalSortUtil(self, v, visited, stack): + + # working stack contains key and the corresponding current generator + working_stack = [(v, self.neighbor_gen(v))] + + while working_stack: + # get last element from stack + v, gen = working_stack.pop() + visited[v] = True + + # run through neighbor generator until it's empty + for next_neighbor in gen: + if not visited[next_neighbor]: # not seen before? + # remember current work + working_stack.append((v, gen)) + # restart with new neighbor + working_stack.append( + (next_neighbor, self.neighbor_gen(next_neighbor))) + break + else: + # no already-visited neighbor (or no more of them) + stack.append(v) + + # The function to do Topological Sort. + def nonRecursiveTopologicalSort(self): + # Mark all the vertices as not visited + visited = [False]*self.V + + # result stack + stack = [] + + # Call the helper function to store Topological + # Sort starting from all vertices one by one + for i in range(self.V): + if not(visited[i]): + self.nonRecursiveTopologicalSortUtil(i, visited, stack) + # Print contents of the stack in reverse + stack.reverse() + print(stack) + + +# Driver code +if __name__ == ""__main__"": + g = Graph(6) + g.addEdge(5, 2) + g.addEdge(5, 0) + g.addEdge(4, 0) + g.addEdge(4, 1) + g.addEdge(2, 3) + g.addEdge(3, 1) + + + # Function call + print(""The following is a Topological Sort of the given graph"") + g.nonRecursiveTopologicalSort() +# This code was based of Neelam Yadav's code, modified by Suhail Alnahari, Python-ified by Matthias Urlichhs",linear,linear +"# class to represent a graph object +class Graph: + + # Constructor + def __init__(self, edges, N): + + # A List of Lists to represent an adjacency list + self.adjList = [[] for _ in range(N)] + + # stores in-degree of a vertex + # initialize in-degree of each vertex by 0 + self.indegree = [0] * N + + # add edges to the undirected graph + for (src, dest) in edges: + + # add an edge from source to destination + self.adjList[src].append(dest) + + # increment in-degree of destination vertex by 1 + self.indegree[dest] = self.indegree[dest] + 1 + + +# Recursive function to find +# all topological orderings of a given DAG +def findAllTopologicalOrders(graph, path, discovered, N): + + # do for every vertex + for v in range(N): + + # proceed only if in-degree of current node is 0 and + # current node is not processed yet + if graph.indegree[v] == 0 and not discovered[v]: + + # for every adjacent vertex u of v, + # reduce in-degree of u by 1 + for u in graph.adjList[v]: + graph.indegree[u] = graph.indegree[u] - 1 + + # include current node in the path + # and mark it as discovered + path.append(v) + discovered[v] = True + + # recur + findAllTopologicalOrders(graph, path, discovered, N) + + # backtrack: reset in-degree + # information for the current node + for u in graph.adjList[v]: + graph.indegree[u] = graph.indegree[u] + 1 + + # backtrack: remove current node from the path and + # mark it as undiscovered + path.pop() + discovered[v] = False + + # print the topological order if + # all vertices are included in the path + if len(path) == N: + print(path) + + +# Print all topological orderings of a given DAG +def printAllTopologicalOrders(graph): + + # get number of nodes in the graph + N = len(graph.adjList) + + # create an auxiliary space to keep track of whether vertex is discovered + discovered = [False] * N + + # list to store the topological order + path = [] + + # find all topological ordering and print them + findAllTopologicalOrders(graph, path, discovered, N) + +# Driver code +if __name__ == '__main__': + + # List of graph edges as per above diagram + edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)] + + print(""All Topological sorts"") + + # Number of nodes in the graph + N = 6 + + # create a graph from edges + graph = Graph(edges, N) + + # print all topological ordering of the graph + printAllTopologicalOrders(graph) + +# This code is contributed by Priyadarshini Kumari",linear,quadratic +"# A Python program to print topological sorting of a graph +# using indegrees +from collections import defaultdict + +# Class to represent a graph +class Graph: + def __init__(self, vertices): + self.graph = defaultdict(list) # dictionary containing adjacency List + self.V = vertices # No. of vertices + + # function to add an edge to graph + def addEdge(self, u, v): + self.graph[u].append(v) + + + # The function to do Topological Sort. + def topologicalSort(self): + + # Create a vector to store indegrees of all + # vertices. Initialize all indegrees as 0. + in_degree = [0]*(self.V) + + # Traverse adjacency lists to fill indegrees of + # vertices. This step takes O(V + E) time + for i in self.graph: + for j in self.graph[i]: + in_degree[j] += 1 + + # Create an queue and enqueue all vertices with + # indegree 0 + queue = [] + for i in range(self.V): + if in_degree[i] == 0: + queue.append(i) + + # Initialize count of visited vertices + cnt = 0 + + # Create a vector to store result (A topological + # ordering of the vertices) + top_order = [] + + # One by one dequeue vertices from queue and enqueue + # adjacents if indegree of adjacent becomes 0 + while queue: + + # Extract front of queue (or perform dequeue) + # and add it to topological order + u = queue.pop(0) + top_order.append(u) + + # Iterate through all neighbouring nodes + # of dequeued node u and decrease their in-degree + # by 1 + for i in self.graph[u]: + in_degree[i] -= 1 + # If in-degree becomes zero, add it to queue + if in_degree[i] == 0: + queue.append(i) + + cnt += 1 + + # Check if there was a cycle + if cnt != self.V: + print (""There exists a cycle in the graph"") + else : + # Print topological order + print (top_order) + + +g = Graph(6) +g.addEdge(5, 2); +g.addEdge(5, 0); +g.addEdge(4, 0); +g.addEdge(4, 1); +g.addEdge(2, 3); +g.addEdge(3, 1); + +print (""Following is a Topological Sort of the given graph"") +g.topologicalSort() + +# This code is contributed by Neelam Yadav",linear,linear +"# A Python3 program for Prim's Minimum Spanning Tree (MST) algorithm. +# The program is for adjacency matrix representation of the graph + +import sys # Library for INT_MAX + + +class Graph(): + + def __init__(self, vertices): + self.V = vertices + self.graph = [[0 for column in range(vertices)] + for row in range(vertices)] + + # A utility function to print the constructed MST stored in parent[] + def printMST(self, parent): + print(""Edge \tWeight"") + for i in range(1, self.V): + print(parent[i], ""-"", i, ""\t"", self.graph[i][parent[i]]) + + # A utility function to find the vertex with + # minimum distance value, from the set of vertices + # not yet included in shortest path tree + def minKey(self, key, mstSet): + + # Initialize min value + min = sys.maxsize + + for v in range(self.V): + if key[v] < min and mstSet[v] == False: + min = key[v] + min_index = v + + return min_index + + # Function to construct and print MST for a graph + # represented using adjacency matrix representation + def primMST(self): + + # Key values used to pick minimum weight edge in cut + key = [sys.maxsize] * self.V + parent = [None] * self.V # Array to store constructed MST + # Make key 0 so that this vertex is picked as first vertex + key[0] = 0 + mstSet = [False] * self.V + + parent[0] = -1 # First node is always the root of + + for cout in range(self.V): + + # Pick the minimum distance vertex from + # the set of vertices not yet processed. + # u is always equal to src in first iteration + u = self.minKey(key, mstSet) + + # Put the minimum distance vertex in + # the shortest path tree + mstSet[u] = True + + # Update dist value of the adjacent vertices + # of the picked vertex only if the current + # distance is greater than new distance and + # the vertex in not in the shortest path tree + for v in range(self.V): + + # graph[u][v] is non zero only for adjacent vertices of m + # mstSet[v] is false for vertices not yet included in MST + # Update the key only if graph[u][v] is smaller than key[v] + if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]: + key[v] = self.graph[u][v] + parent[v] = u + + self.printMST(parent) + + +# Driver's code +if __name__ == '__main__': + g = Graph(5) + g.graph = [[0, 2, 0, 6, 0], + [2, 0, 3, 8, 5], + [0, 3, 0, 0, 7], + [6, 8, 0, 0, 9], + [0, 5, 7, 9, 0]] + + g.primMST() + + # Contributed by Divyanshu Mehta",linear,quadratic +"# Python program for Kruskal's algorithm to find +# Minimum Spanning Tree of a given connected, +# undirected and weighted graph + +# Class to represent a graph + + +class Graph: + + def __init__(self, vertices): + self.V = vertices # No. of vertices + self.graph = [] + # to store graph + + # function to add an edge to graph + def addEdge(self, u, v, w): + self.graph.append([u, v, w]) + + # A utility function to find set of an element i + # (truly uses path compression technique) + def find(self, parent, i): + if parent[i] != i: + # Reassignment of node's parent to root node as + # path compression requires + parent[i] = self.find(parent, parent[i]) + return parent[i] + + # A function that does union of two sets of x and y + # (uses union by rank) + def union(self, parent, rank, x, y): + + # Attach smaller rank tree under root of + # high rank tree (Union by Rank) + if rank[x] < rank[y]: + parent[x] = y + elif rank[x] > rank[y]: + parent[y] = x + + # If ranks are same, then make one as root + # and increment its rank by one + else: + parent[y] = x + rank[x] += 1 + + # The main function to construct MST using Kruskal's + # algorithm + def KruskalMST(self): + + result = [] # This will store the resultant MST + + # An index variable, used for sorted edges + i = 0 + + # An index variable, used for result[] + e = 0 + + # Step 1: Sort all the edges in + # non-decreasing order of their + # weight. If we are not allowed to change the + # given graph, we can create a copy of graph + self.graph = sorted(self.graph, + key=lambda item: item[2]) + + parent = [] + rank = [] + + # Create V subsets with single elements + for node in range(self.V): + parent.append(node) + rank.append(0) + + # Number of edges to be taken is equal to V-1 + while e < self.V - 1: + + # Step 2: Pick the smallest edge and increment + # the index for next iteration + u, v, w = self.graph[i] + i = i + 1 + x = self.find(parent, u) + y = self.find(parent, v) + + # If including this edge doesn't + # cause cycle, then include it in result + # and increment the index of result + # for next edge + if x != y: + e = e + 1 + result.append([u, v, w]) + self.union(parent, rank, x, y) + # Else discard the edge + + minimumCost = 0 + print(""Edges in the constructed MST"") + for u, v, weight in result: + minimumCost += weight + print(""%d -- %d == %d"" % (u, v, weight)) + print(""Minimum Spanning Tree"", minimumCost) + + +# Driver's code +if __name__ == '__main__': + g = Graph(4) + g.addEdge(0, 1, 10) + g.addEdge(0, 2, 6) + g.addEdge(0, 3, 5) + g.addEdge(1, 3, 15) + g.addEdge(2, 3, 4) + + # Function call + g.KruskalMST() + +# This code is contributed by Neelam Yadav +# Improved by James Graça-Jones",linear,nlogn +"# Python3 program to solve N Queen +# Problem using backtracking +global N +N = 4 + +def printSolution(board): + for i in range(N): + for j in range(N): + print(board[i][j], end = "" "") + print() + +# A utility function to check if a queen can +# be placed on board[row][col]. Note that this +# function is called when ""col"" queens are +# already placed in columns from 0 to col -1. +# So we need to check only left side for +# attacking queens +def isSafe(board, row, col): + + # Check this row on left side + for i in range(col): + if board[row][i] == 1: + return False + + # Check upper diagonal on left side + for i, j in zip(range(row, -1, -1), + range(col, -1, -1)): + if board[i][j] == 1: + return False + + # Check lower diagonal on left side + for i, j in zip(range(row, N, 1), + range(col, -1, -1)): + if board[i][j] == 1: + return False + + return True + +def solveNQUtil(board, col): + + # base case: If all queens are placed + # then return true + if col >= N: + return True + + # Consider this column and try placing + # this queen in all rows one by one + for i in range(N): + + if isSafe(board, i, col): + + # Place this queen in board[i][col] + board[i][col] = 1 + + # recur to place rest of the queens + if solveNQUtil(board, col + 1) == True: + return True + + # If placing queen in board[i][col + # doesn't lead to a solution, then + # queen from board[i][col] + board[i][col] = 0 + + # if the queen can not be placed in any row in + # this column col then return false + return False + +# This function solves the N Queen problem using +# Backtracking. It mainly uses solveNQUtil() to +# solve the problem. It returns false if queens +# cannot be placed, otherwise return true and +# placement of queens in the form of 1s. +# note that there may be more than one +# solutions, this function prints one of the +# feasible solutions. +def solveNQ(): + board = [ [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0] ] + + if solveNQUtil(board, 0) == False: + print (""Solution does not exist"") + return False + + printSolution(board) + return True + +# Driver Code +solveNQ() + +# This code is contributed by Divyanshu Mehta",quadratic,np +""""""" Python3 program to solve N Queen Problem using +backtracking """""" +N = 4 + +"""""" ld is an array where its indices indicate row-col+N-1 +(N-1) is for shifting the difference to store negative +indices """""" +ld = [0] * 30 + +"""""" rd is an array where its indices indicate row+col +and used to check whether a queen can be placed on +right diagonal or not"""""" +rd = [0] * 30 + +""""""column array where its indices indicates column and +used to check whether a queen can be placed in that + row or not"""""" +cl = [0] * 30 + +"""""" A utility function to print solution """""" +def printSolution(board): + for i in range(N): + for j in range(N): + print(board[i][j], end = "" "") + print() + +"""""" A recursive utility function to solve N +Queen problem """""" +def solveNQUtil(board, col): + + """""" base case: If all queens are placed + then return True """""" + if (col >= N): + return True + + """""" Consider this column and try placing + this queen in all rows one by one """""" + for i in range(N): + + """""" Check if the queen can be placed on board[i][col] """""" + """""" A check if a queen can be placed on board[row][col]. + We just need to check ld[row-col+n-1] and rd[row+coln] + where ld and rd are for left and right diagonal respectively"""""" + if ((ld[i - col + N - 1] != 1 and + rd[i + col] != 1) and cl[i] != 1): + + """""" Place this queen in board[i][col] """""" + board[i][col] = 1 + ld[i - col + N - 1] = rd[i + col] = cl[i] = 1 + + """""" recur to place rest of the queens """""" + if (solveNQUtil(board, col + 1)): + return True + + """""" If placing queen in board[i][col] + doesn't lead to a solution, + then remove queen from board[i][col] """""" + board[i][col] = 0 # BACKTRACK + ld[i - col + N - 1] = rd[i + col] = cl[i] = 0 + + """""" If the queen cannot be placed in + any row in this column col then return False """""" + return False + +"""""" This function solves the N Queen problem using +Backtracking. It mainly uses solveNQUtil() to +solve the problem. It returns False if queens +cannot be placed, otherwise, return True and +prints placement of queens in the form of 1s. +Please note that there may be more than one +solutions, this function prints one of the +feasible solutions."""""" +def solveNQ(): + board = [[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]] + if (solveNQUtil(board, 0) == False): + printf(""Solution does not exist"") + return False + printSolution(board) + return True + +# Driver Code +solveNQ() + +# This code is contributed by SHUBHAMSINGH10",linear,np +"# Python3 program for the above approach + +# Number of vertices in the graph +# define 4 4 + +# check if the colored +# graph is safe or not + + +def isSafe(graph, color): + + # check for every edge + for i in range(4): + for j in range(i + 1, 4): + if (graph[i][j] and color[j] == color[i]): + return False + return True + +# /* This function solves the m Coloring +# problem using recursion. It returns +# false if the m colours cannot be assigned, +# otherwise, return true and prints +# assignments of colours to all vertices. +# Please note that there may be more than +# one solutions, this function prints one +# of the feasible solutions.*/ + + +def graphColoring(graph, m, i, color): + + # if current index reached end + if (i == 4): + + # if coloring is safe + if (isSafe(graph, color)): + + # Print the solution + printSolution(color) + return True + return False + + # Assign each color from 1 to m + for j in range(1, m + 1): + color[i] = j + + # Recur of the rest vertices + if (graphColoring(graph, m, i + 1, color)): + return True + color[i] = 0 + return False + +# /* A utility function to print solution */ + + +def printSolution(color): + print(""Solution Exists:"" "" Following are the assigned colors "") + for i in range(4): + print(color[i], end="" "") + + +# Driver code +if __name__ == '__main__': + + # /* Create following graph and + # test whether it is 3 colorable + # (3)---(2) + # | / | + # | / | + # | / | + # (0)---(1) + # */ + graph = [ + [0, 1, 1, 1], + [1, 0, 1, 0], + [1, 1, 0, 1], + [1, 0, 1, 0], + ] + m = 3 # Number of colors + + # Initialize all color values as 0. + # This initialization is needed + # correct functioning of isSafe() + color = [0 for i in range(4)] + + # Function call + if (not graphColoring(graph, m, 0, color)): + print(""Solution does not exist"") + +# This code is contributed by mohit kumar 29",linear,quadratic +"# Python3 program for solution of M Coloring +# problem using backtracking + + +class Graph(): + + def __init__(self, vertices): + self.V = vertices + self.graph = [[0 for column in range(vertices)] + for row in range(vertices)] + + # A utility function to check + # if the current color assignment + # is safe for vertex v + def isSafe(self, v, colour, c): + for i in range(self.V): + if self.graph[v][i] == 1 and colour[i] == c: + return False + return True + + # A recursive utility function to solve m + # coloring problem + def graphColourUtil(self, m, colour, v): + if v == self.V: + return True + + for c in range(1, m + 1): + if self.isSafe(v, colour, c) == True: + colour[v] = c + if self.graphColourUtil(m, colour, v + 1) == True: + return True + colour[v] = 0 + + def graphColouring(self, m): + colour = [0] * self.V + if self.graphColourUtil(m, colour, 0) == None: + return False + + # Print the solution + print(""Solution exist and Following are the assigned colours:"") + for c in colour: + print(c, end=' ') + return True + + +# Driver Code +if __name__ == '__main__': + g = Graph(4) + g.graph = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0]] + m = 3 + + # Function call + g.graphColouring(m) + +# This code is contributed by Divyanshu Mehta",linear,quadratic +"# Python3 program for the above approach + +from queue import Queue + + +class node: + + color = 1 + edges = set() + + +def canPaint(nodes, n, m): + + # Create a visited array of n + # nodes, initialized to zero + visited = [0 for _ in range(n+1)] + + # maxColors used till now are 1 as + # all nodes are painted color 1 + maxColors = 1 + + # Do a full BFS traversal from + # all unvisited starting points + for _ in range(1, n + 1): + if visited[_]: + continue + + # If the starting point is unvisited, + # mark it visited and push it in queue + visited[_] = 1 + q = Queue() + q.put(_) + + # BFS Travel starts here + while not q.empty(): + top = q.get() + + # Checking all adjacent nodes + # to ""top"" edge in our queue + for _ in nodes[top].edges: + + # IMPORTANT: If the color of the + # adjacent node is same, increase it by 1 + + if nodes[top].color == nodes[_].color: + nodes[_].color += 1 + + # If number of colors used shoots m, + # return 0 + maxColors = max(maxColors, max( + nodes[top].color, nodes[_].color)) + + if maxColors > m: + print(maxColors) + return 0 + + # If the adjacent node is not visited, + # mark it visited and push it in queue + if not visited[_]: + visited[_] = 1 + q.put(_) + + return 1 + + +# Driver code +if __name__ == ""__main__"": + + n = 4 + graph = [[0, 1, 1, 1], + [1, 0, 1, 0], + [1, 1, 0, 1], + [1, 0, 1, 0]] + + # Number of colors + m = 3 + + # Create a vector of n+1 + # nodes of type ""node"" + # The zeroth position is just + # dummy (1 to n to be used) + nodes = [] + for _ in range(n+1): + nodes.append(node()) + + # Add edges to each node as + # per given input + for _ in range(n): + for __ in range(n): + if graph[_][__]: + + # Connect the undirected graph + nodes[_].edges.add(_) + nodes[__].edges.add(__) + + # Function call + print(canPaint(nodes, n, m)) + +# This code is contributed by harshitkap00r",linear,linear +"# Python program for Dijkstra's single +# source shortest path algorithm. The program is +# for adjacency matrix representation of the graph + +# Library for INT_MAX +import sys + + +class Graph(): + + def __init__(self, vertices): + self.V = vertices + self.graph = [[0 for column in range(vertices)] + for row in range(vertices)] + + def printSolution(self, dist): + print(""Vertex \tDistance from Source"") + for node in range(self.V): + print(node, ""\t"", dist[node]) + + # A utility function to find the vertex with + # minimum distance value, from the set of vertices + # not yet included in shortest path tree + def minDistance(self, dist, sptSet): + + # Initialize minimum distance for next node + min = sys.maxsize + + # Search not nearest vertex not in the + # shortest path tree + for u in range(self.V): + if dist[u] < min and sptSet[u] == False: + min = dist[u] + min_index = u + + return min_index + + # Function that implements Dijkstra's single source + # shortest path algorithm for a graph represented + # using adjacency matrix representation + def dijkstra(self, src): + + dist = [sys.maxsize] * self.V + dist[src] = 0 + sptSet = [False] * self.V + + for cout in range(self.V): + + # Pick the minimum distance vertex from + # the set of vertices not yet processed. + # x is always equal to src in first iteration + x = self.minDistance(dist, sptSet) + + # Put the minimum distance vertex in the + # shortest path tree + sptSet[x] = True + + # Update dist value of the adjacent vertices + # of the picked vertex only if the current + # distance is greater than new distance and + # the vertex in not in the shortest path tree + for y in range(self.V): + if self.graph[x][y] > 0 and sptSet[y] == False and \ + dist[y] > dist[x] + self.graph[x][y]: + dist[y] = dist[x] + self.graph[x][y] + + self.printSolution(dist) + + +# Driver's code +if __name__ == ""__main__"": + g = Graph(9) + g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], + [4, 0, 8, 0, 0, 0, 0, 11, 0], + [0, 8, 0, 7, 0, 4, 0, 0, 2], + [0, 0, 7, 0, 9, 14, 0, 0, 0], + [0, 0, 0, 9, 0, 10, 0, 0, 0], + [0, 0, 4, 14, 10, 0, 2, 0, 0], + [0, 0, 0, 0, 0, 2, 0, 1, 6], + [8, 11, 0, 0, 0, 0, 1, 0, 7], + [0, 0, 2, 0, 0, 0, 6, 7, 0] + ] + + g.dijkstra(0) + +# This code is contributed by Divyanshu Mehta and Updated by Pranav Singh Sambyal",linear,quadratic +"// C++ Program to find Dijkstra's shortest path using +// priority_queue in STL +#include +using namespace std; +#define INF 0x3f3f3f3f + +// iPair ==> Integer Pair +typedef pair iPair; + +// This class represents a directed graph using +// adjacency list representation +class Graph { + int V; // No. of vertices + + // In a weighted graph, we need to store vertex + // and weight pair for every edge + list >* adj; + +public: + Graph(int V); // Constructor + + // function to add an edge to graph + void addEdge(int u, int v, int w); + + // prints shortest path from s + void shortestPath(int s); +}; + +// Allocates memory for adjacency list +Graph::Graph(int V) +{ + this->V = V; + adj = new list[V]; +} + +void Graph::addEdge(int u, int v, int w) +{ + adj[u].push_back(make_pair(v, w)); + adj[v].push_back(make_pair(u, w)); +} + +// Prints shortest paths from src to all other vertices +void Graph::shortestPath(int src) +{ + // Create a priority queue to store vertices that + // are being preprocessed. This is weird syntax in C++. + // Refer below link for details of this syntax + // https://www.geeksforgeeks.org/implement-min-heap-using-stl/ + priority_queue, greater > + pq; + + // Create a vector for distances and initialize all + // distances as infinite (INF) + vector dist(V, INF); + + // Insert source itself in priority queue and initialize + // its distance as 0. + pq.push(make_pair(0, src)); + dist[src] = 0; + + /* Looping till priority queue becomes empty (or all + distances are not finalized) */ + while (!pq.empty()) { + // The first vertex in pair is the minimum distance + // vertex, extract it from priority queue. + // vertex label is stored in second of pair (it + // has to be done this way to keep the vertices + // sorted distance (distance must be first item + // in pair) + int u = pq.top().second; + pq.pop(); + + // 'i' is used to get all adjacent vertices of a + // vertex + list >::iterator i; + for (i = adj[u].begin(); i != adj[u].end(); ++i) { + // Get vertex label and weight of current + // adjacent of u. + int v = (*i).first; + int weight = (*i).second; + + // If there is shorted path to v through u. + if (dist[v] > dist[u] + weight) { + // Updating distance of v + dist[v] = dist[u] + weight; + pq.push(make_pair(dist[v], v)); + } + } + } + + // Print shortest distances stored in dist[] + printf(""Vertex Distance from Source\n""); + for (int i = 0; i < V; ++i) + printf(""%d \t\t %d\n"", i, dist[i]); +} + +// Driver's code +int main() +{ + // create the graph given in above figure + int V = 9; + Graph g(V); + + // making above shown graph + g.addEdge(0, 1, 4); + g.addEdge(0, 7, 8); + g.addEdge(1, 2, 8); + g.addEdge(1, 7, 11); + g.addEdge(2, 3, 7); + g.addEdge(2, 8, 2); + g.addEdge(2, 5, 4); + g.addEdge(3, 4, 9); + g.addEdge(3, 5, 14); + g.addEdge(4, 5, 10); + g.addEdge(5, 6, 2); + g.addEdge(6, 7, 1); + g.addEdge(6, 8, 6); + g.addEdge(7, 8, 7); + + // Function call + g.shortestPath(0); + + return 0; +}",linear,nlogn +"# Python3 program for Bellman-Ford's single source +# shortest path algorithm. + +# Class to represent a graph + +class Graph: + + def __init__(self, vertices): + self.V = vertices # No. of vertices + self.graph = [] + + # function to add an edge to graph + def addEdge(self, u, v, w): + self.graph.append([u, v, w]) + + # utility function used to print the solution + def printArr(self, dist): + print(""Vertex Distance from Source"") + for i in range(self.V): + print(""{0}\t\t{1}"".format(i, dist[i])) + + # The main function that finds shortest distances from src to + # all other vertices using Bellman-Ford algorithm. The function + # also detects negative weight cycle + def BellmanFord(self, src): + + # Step 1: Initialize distances from src to all other vertices + # as INFINITE + dist = [float(""Inf"")] * self.V + dist[src] = 0 + + # Step 2: Relax all edges |V| - 1 times. A simple shortest + # path from src to any other vertex can have at-most |V| - 1 + # edges + for _ in range(self.V - 1): + # Update dist value and parent index of the adjacent vertices of + # the picked vertex. Consider only those vertices which are still in + # queue + for u, v, w in self.graph: + if dist[u] != float(""Inf"") and dist[u] + w < dist[v]: + dist[v] = dist[u] + w + + # Step 3: check for negative-weight cycles. The above step + # guarantees shortest distances if graph doesn't contain + # negative weight cycle. If we get a shorter path, then there + # is a cycle. + + for u, v, w in self.graph: + if dist[u] != float(""Inf"") and dist[u] + w < dist[v]: + print(""Graph contains negative weight cycle"") + return + + # print all distance + self.printArr(dist) + + +# Driver's code +if __name__ == '__main__': + g = Graph(5) + g.addEdge(0, 1, -1) + g.addEdge(0, 2, 4) + g.addEdge(1, 2, 3) + g.addEdge(1, 3, 2) + g.addEdge(1, 4, 2) + g.addEdge(3, 2, 5) + g.addEdge(3, 1, 1) + g.addEdge(4, 3, -3) + + # function call + g.BellmanFord(0) + +# Initially, Contributed by Neelam Yadav +# Later On, Edited by Himanshu Garg",linear,quadratic +"# Python3 Program for Floyd Warshall Algorithm + +# Number of vertices in the graph +V = 4 + +# Define infinity as the large +# enough value. This value will be +# used for vertices not connected to each other +INF = 99999 + +# Solves all pair shortest path +# via Floyd Warshall Algorithm + + +def floydWarshall(graph): + """""" dist[][] will be the output + matrix that will finally + have the shortest distances + between every pair of vertices """""" + """""" initializing the solution matrix + same as input graph matrix + OR we can say that the initial + values of shortest distances + are based on shortest paths considering no + intermediate vertices """""" + + dist = list(map(lambda i: list(map(lambda j: j, i)), graph)) + + """""" Add all vertices one by one + to the set of intermediate + vertices. + ---> Before start of an iteration, + we have shortest distances + between all pairs of vertices + such that the shortest + distances consider only the + vertices in the set + {0, 1, 2, .. k-1} as intermediate vertices. + ----> After the end of a + iteration, vertex no. k is + added to the set of intermediate + vertices and the + set becomes {0, 1, 2, .. k} + """""" + for k in range(V): + + # pick all vertices as source one by one + for i in range(V): + + # Pick all vertices as destination for the + # above picked source + for j in range(V): + + # If vertex k is on the shortest path from + # i to j, then update the value of dist[i][j] + dist[i][j] = min(dist[i][j], + dist[i][k] + dist[k][j] + ) + printSolution(dist) + + +# A utility function to print the solution +def printSolution(dist): + print(""Following matrix shows the shortest distances\ + between every pair of vertices"") + for i in range(V): + for j in range(V): + if(dist[i][j] == INF): + print(""%7s"" % (""INF""), end="" "") + else: + print(""%7d\t"" % (dist[i][j]), end=' ') + if j == V-1: + print() + + +# Driver's code +if __name__ == ""__main__"": + """""" + 10 + (0)------->(3) + | /|\ + 5 | | + | | 1 + \|/ | + (1)------->(2) + 3 """""" + graph = [[0, 5, INF, 10], + [INF, 0, 3, INF], + [INF, INF, 0, 1], + [INF, INF, INF, 0] + ] + # Function call + floydWarshall(graph) +# This code is contributed by Mythri J L",quadratic,cubic +"# Dynamic Programming based Python3 +# program to find shortest path with + +# A Dynamic programming based function +# to find the shortest path from u to v +# with exactly k edges. +def shortestPath(graph, u, v, k): + global V, INF + + # Table to be filled up using DP. The + # value sp[i][j][e] will store weight + # of the shortest path from i to j + # with exactly k edges + sp = [[None] * V for i in range(V)] + for i in range(V): + for j in range(V): + sp[i][j] = [None] * (k + 1) + + # Loop for number of edges from 0 to k + for e in range(k + 1): + for i in range(V): # for source + for j in range(V): # for destination + + # initialize value + sp[i][j][e] = INF + + # from base cases + if (e == 0 and i == j): + sp[i][j][e] = 0 + if (e == 1 and graph[i][j] != INF): + sp[i][j][e] = graph[i][j] + + # go to adjacent only when number + # of edges is more than 1 + if (e > 1): + for a in range(V): + + # There should be an edge from + # i to a and a should not be + # same as either i or j + if (graph[i][a] != INF and i != a and + j!= a and sp[a][j][e - 1] != INF): + sp[i][j][e] = min(sp[i][j][e], graph[i][a] + + sp[a][j][e - 1]) + + return sp[u][v][k] + +# Driver Code + +# Define number of vertices in +# the graph and infinite value +V = 4 +INF = 999999999999 + +# Let us create the graph shown +# in above diagram +graph = [[0, 10, 3, 2], + [INF, 0, INF, 7], + [INF, INF, 0, 6], + [INF, INF, INF, 0]] +u = 0 +v = 3 +k = 2 +print(""Weight of the shortest path is"", + shortestPath(graph, u, v, k)) + +# This code is contributed by PranchalK",np,cubic +"# Python3 code for printing shortest path between +# two vertices of unweighted graph + +# utility function to form edge between two vertices +# source and dest +def add_edge(adj, src, dest): + + adj[src].append(dest); + adj[dest].append(src); + +# a modified version of BFS that stores predecessor +# of each vertex in array p +# and its distance from source in array d +def BFS(adj, src, dest, v, pred, dist): + + # a queue to maintain queue of vertices whose + # adjacency list is to be scanned as per normal + # DFS algorithm + queue = [] + + # boolean array visited[] which stores the + # information whether ith vertex is reached + # at least once in the Breadth first search + visited = [False for i in range(v)]; + + # initially all vertices are unvisited + # so v[i] for all i is false + # and as no path is yet constructed + # dist[i] for all i set to infinity + for i in range(v): + + dist[i] = 1000000 + pred[i] = -1; + + # now source is first to be visited and + # distance from source to itself should be 0 + visited[src] = True; + dist[src] = 0; + queue.append(src); + + # standard BFS algorithm + while (len(queue) != 0): + u = queue[0]; + queue.pop(0); + for i in range(len(adj[u])): + + if (visited[adj[u][i]] == False): + visited[adj[u][i]] = True; + dist[adj[u][i]] = dist[u] + 1; + pred[adj[u][i]] = u; + queue.append(adj[u][i]); + + # We stop BFS when we find + # destination. + if (adj[u][i] == dest): + return True; + + return False; + +# utility function to print the shortest distance +# between source vertex and destination vertex +def printShortestDistance(adj, s, dest, v): + + # predecessor[i] array stores predecessor of + # i and distance array stores distance of i + # from s + pred=[0 for i in range(v)] + dist=[0 for i in range(v)]; + + if (BFS(adj, s, dest, v, pred, dist) == False): + print(""Given source and destination are not connected"") + + # vector path stores the shortest path + path = [] + crawl = dest; + path.append(crawl); + + while (pred[crawl] != -1): + path.append(pred[crawl]); + crawl = pred[crawl]; + + + # distance from source is in distance array + print(""Shortest path length is : "" + str(dist[dest]), end = '') + + # printing path from source to destination + print(""\nPath is : : "") + + for i in range(len(path)-1, -1, -1): + print(path[i], end=' ') + +# Driver program to test above functions +if __name__=='__main__': + + # no. of vertices + v = 8; + + # array of vectors is used to store the graph + # in the form of an adjacency list + adj = [[] for i in range(v)]; + + # Creating graph given in the above diagram. + # add_edge function takes adjacency list, source + # and destination vertex as argument and forms + # an edge between them. + add_edge(adj, 0, 1); + add_edge(adj, 0, 3); + add_edge(adj, 1, 2); + add_edge(adj, 3, 4); + add_edge(adj, 3, 7); + add_edge(adj, 4, 5); + add_edge(adj, 4, 6); + add_edge(adj, 4, 7); + add_edge(adj, 5, 6); + add_edge(adj, 6, 7); + source = 0 + dest = 7; + printShortestDistance(adj, source, dest, v); + + # This code is contributed by rutvik_56",linear,linear +"# Python program to get least cost path in a grid from +# top-left to bottom-right +from functools import cmp_to_key + +ROW = 5 +COL = 5 + +def mycmp(a,b): + + if (a.distance == b.distance): + if (a.x != b.x): + return (a.x - b.x) + else: + return (a.y - b.y) + return (a.distance - b.distance) + +# structure for information of each cell +class cell: + + def __init__(self,x, y, distance): + self.x = x + self.y = y + self.distance = distance + +# Utility method to check whether a point is +# inside the grid or not +def isInsideGrid(i, j): + return (i >= 0 and i < ROW and j >= 0 and j < COL) + +# Method returns minimum cost to reach bottom +# right from top left +def shortest(grid, row, col): + dis = [[0 for i in range(col)]for j in range(row)] + + # initializing distance array by INT_MAX + for i in range(row): + for j in range(col): + dis[i][j] = 1000000000 + + # direction arrays for simplification of getting + # neighbour + dx = [-1, 0, 1, 0] + dy = [0, 1, 0, -1] + + st = [] + + # insert (0, 0) cell with 0 distance + st.append(cell(0, 0, 0)) + + # initialize distance of (0, 0) with its grid value + dis[0][0] = grid[0][0] + + # loop for standard dijkstra's algorithm + while (len(st)!=0): + + # get the cell with minimum distance and delete + # it from the set + k = st[0] + st = st[1:] + + # looping through all neighbours + for i in range(4): + + x = k.x + dx[i] + y = k.y + dy[i] + + # if not inside boundary, ignore them + if (isInsideGrid(x, y) == 0): + continue + + # If distance from current cell is smaller, then + # update distance of neighbour cell + if (dis[x][y] > dis[k.x][k.y] + grid[x][y]): + # update the distance and insert new updated + # cell in set + dis[x][y] = dis[k.x][k.y] + grid[x][y] + st.append(cell(x, y, dis[x][y])) + + st.sort(key=cmp_to_key(mycmp)) + + # uncomment below code to print distance + # of each cell from (0, 0) + + # for i in range(row): + # for j in range(col): + # print(dis[i][j] ,end= "" "") + # print() + + # dis[row - 1][col - 1] will represent final + # distance of bottom right cell from top left cell + return dis[row - 1][col - 1] + +# Driver code to test above methods + +grid = [[31, 100, 65, 12, 18], [10, 13, 47, 157, 6], [100, 113, 174, 11, 33], [88, 124, 41, 20, 140],[99, 32, 111, 41, 20]] +print(shortest(grid, ROW, COL)) + +# This code is contributed by shinjanpatra",quadratic,quadratic +"# Python3 program to replace all of the O's in the matrix +# with their shortest distance from a guard +from collections import deque as queue + +# store dimensions of the matrix +M = 5 +N = 5 + + +# These arrays are used to get row and column +# numbers of 4 neighbors of a given cell +row = [-1, 0, 1, 0] +col = [0, 1, 0, -1] + +# return true if row number and column number +# is in range +def isValid(i, j): + if ((i < 0 or i > M - 1) or (j < 0 or j > N - 1)): + return False + + return True + +# return true if current cell is an open area and its +# distance from guard is not calculated yet +def isSafe(i, j,matrix, output): + + if (matrix[i][j] != 'O' or output[i][j] != -1): + return False + + return True + +# Function to replace all of the O's in the matrix +# with their shortest distance from a guard +def findDistance(matrix): + output = [[ -1 for i in range(N)]for i in range(M)] + q = queue() + + # finding Guards location and adding into queue + for i in range(M): + for j in range(N): + + # initialize each cell as -1 + output[i][j] = -1 + if (matrix[i][j] == 'G'): + pos = [i, j, 0] + q.appendleft(pos) + + # guard has 0 distance + output[i][j] = 0 + + + + # do till queue is empty + while (len(q) > 0): + + # get the front cell in the queue and update + # its adjacent cells + curr = q.pop() + x, y, dist = curr[0], curr[1], curr[2] + + # do for each adjacent cell + for i in range(4): + + # if adjacent cell is valid, has path and + # not visited yet, en-queue it. + + if isValid(x + row[i], y + col[i]) and isSafe(x + row[i], y + col[i], matrix, output) : + output[x + row[i]][y + col[i]] = dist + 1 + + pos = [x + row[i], y + col[i], dist + 1] + q.appendleft(pos) + + # print output matrix + + for i in range(M): + for j in range(N): + if output[i][j] > 0: + print(output[i][j], end="" "") + else: + print(output[i][j],end="" "") + print() + + +# Driver code + +matrix = [['O', 'O', 'O', 'O', 'G'], + ['O', 'W', 'W', 'O', 'O'], + ['O', 'O', 'O', 'W', 'O'], + ['G', 'W', 'W', 'W', 'O'], + ['O', 'O', 'O', 'O', 'G']] + +findDistance(matrix) + +# This code is contributed by mohit kumar 29",quadratic,quadratic +"# Python program to find articulation points in an undirected graph + +from collections import defaultdict + +# This class represents an undirected graph +# using adjacency list representation +class Graph: + + def __init__(self, vertices): + self.V = vertices # No. of vertices + self.graph = defaultdict(list) # default dictionary to store graph + self.Time = 0 + + # function to add an edge to graph + def addEdge(self, u, v): + self.graph[u].append(v) + self.graph[v].append(u) + + '''A recursive function that find articulation points + using DFS traversal + u --> The vertex to be visited next + visited[] --> keeps track of visited vertices + disc[] --> Stores discovery times of visited vertices + parent[] --> Stores parent vertices in DFS tree + ap[] --> Store articulation points''' + def APUtil(self, u, visited, ap, parent, low, disc): + + # Count of children in current node + children = 0 + + # Mark the current node as visited and print it + visited[u]= True + + # Initialize discovery time and low value + disc[u] = self.Time + low[u] = self.Time + self.Time += 1 + + # Recur for all the vertices adjacent to this vertex + for v in self.graph[u]: + # If v is not visited yet, then make it a child of u + # in DFS tree and recur for it + if visited[v] == False : + parent[v] = u + children += 1 + self.APUtil(v, visited, ap, parent, low, disc) + + # Check if the subtree rooted with v has a connection to + # one of the ancestors of u + low[u] = min(low[u], low[v]) + + # u is an articulation point in following cases + # (1) u is root of DFS tree and has two or more children. + if parent[u] == -1 and children > 1: + ap[u] = True + + #(2) If u is not root and low value of one of its child is more + # than discovery value of u. + if parent[u] != -1 and low[v] >= disc[u]: + ap[u] = True + + # Update low value of u for parent function calls + elif v != parent[u]: + low[u] = min(low[u], disc[v]) + + + # The function to do DFS traversal. It uses recursive APUtil() + def AP(self): + + # Mark all the vertices as not visited + # and Initialize parent and visited, + # and ap(articulation point) arrays + visited = [False] * (self.V) + disc = [float(""Inf"")] * (self.V) + low = [float(""Inf"")] * (self.V) + parent = [-1] * (self.V) + ap = [False] * (self.V) # To store articulation points + + # Call the recursive helper function + # to find articulation points + # in DFS tree rooted with vertex 'i' + for i in range(self.V): + if visited[i] == False: + self.APUtil(i, visited, ap, parent, low, disc) + + for index, value in enumerate (ap): + if value == True: print (index,end="" "") + + # Create a graph given in the above diagram +g1 = Graph(5) +g1.addEdge(1, 0) +g1.addEdge(0, 2) +g1.addEdge(2, 1) +g1.addEdge(0, 3) +g1.addEdge(3, 4) + +print (""\nArticulation points in first graph "") +g1.AP() + +g2 = Graph(4) +g2.addEdge(0, 1) +g2.addEdge(1, 2) +g2.addEdge(2, 3) +print (""\nArticulation points in second graph "") +g2.AP() + + +g3 = Graph (7) +g3.addEdge(0, 1) +g3.addEdge(1, 2) +g3.addEdge(2, 0) +g3.addEdge(1, 3) +g3.addEdge(1, 4) +g3.addEdge(1, 6) +g3.addEdge(3, 5) +g3.addEdge(4, 5) +print (""\nArticulation points in third graph "") +g3.AP() + +# This code is contributed by Neelam Yadav",linear,linear +"# Program to count islands in boolean 2D matrix +class Graph: + + def __init__(self, row, col, g): + self.ROW = row + self.COL = col + self.graph = g + + # A function to check if a given cell + # (row, col) can be included in DFS + def isSafe(self, i, j, visited): + # row number is in range, column number + # is in range and value is 1 + # and not yet visited + return (i >= 0 and i < self.ROW and + j >= 0 and j < self.COL and + not visited[i][j] and self.graph[i][j]) + + # A utility function to do DFS for a 2D + # boolean matrix. It only considers + # the 8 neighbours as adjacent vertices + + def DFS(self, i, j, visited): + + # These arrays are used to get row and + # column numbers of 8 neighbours + # of a given cell + rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] + colNbr = [-1, 0, 1, -1, 1, -1, 0, 1] + + # Mark this cell as visited + visited[i][j] = True + + # Recur for all connected neighbours + for k in range(8): + if self.isSafe(i + rowNbr[k], j + colNbr[k], visited): + self.DFS(i + rowNbr[k], j + colNbr[k], visited) + + # The main function that returns + # count of islands in a given boolean + # 2D matrix + + def countIslands(self): + # Make a bool array to mark visited cells. + # Initially all cells are unvisited + visited = [[False for j in range(self.COL)]for i in range(self.ROW)] + + # Initialize count as 0 and traverse + # through the all cells of + # given matrix + count = 0 + for i in range(self.ROW): + for j in range(self.COL): + # If a cell with value 1 is not visited yet, + # then new island found + if visited[i][j] == False and self.graph[i][j] == 1: + # Visit all cells in this island + # and increment island count + self.DFS(i, j, visited) + count += 1 + + return count + + +graph = [[1, 1, 0, 0, 0], + [0, 1, 0, 0, 1], + [1, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 1]] + + +row = len(graph) +col = len(graph[0]) + +g = Graph(row, col, graph) + +print(""Number of islands is:"") +print(g.countIslands()) + +# This code is contributed by Neelam Yadav",quadratic,quadratic +"# Program to count islands in boolean 2D matrix +class Graph: + + def __init__(self, row, col, graph): + self.ROW = row + self.COL = col + self.graph = graph + + # A utility function to do DFS for a 2D + # boolean matrix. It only considers + # the 8 neighbours as adjacent vertices + def DFS(self, i, j): + if i < 0 or i >= len(self.graph) or j < 0 or j >= len(self.graph[0]) or self.graph[i][j] != 1: + return + + # mark it as visited + self.graph[i][j] = -1 + + # Recur for 8 neighbours + self.DFS(i - 1, j - 1) + self.DFS(i - 1, j) + self.DFS(i - 1, j + 1) + self.DFS(i, j - 1) + self.DFS(i, j + 1) + self.DFS(i + 1, j - 1) + self.DFS(i + 1, j) + self.DFS(i + 1, j + 1) + + # The main function that returns + # count of islands in a given boolean + # 2D matrix + def countIslands(self): + # Initialize count as 0 and traverse + # through the all cells of + # given matrix + count = 0 + for i in range(self.ROW): + for j in range(self.COL): + # If a cell with value 1 is not visited yet, + # then new island found + if self.graph[i][j] == 1: + # Visit all cells in this island + # and increment island count + self.DFS(i, j) + count += 1 + + return count + + +graph = [ + [1, 1, 0, 0, 0], + [0, 1, 0, 0, 1], + [1, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 1] +] + + +row = len(graph) +col = len(graph[0]) + +g = Graph(row, col, graph) + +print(""Number of islands is:"", g.countIslands()) + +# This code is contributed by Shivam Shrey",quadratic,quadratic +"# Python3 program to find +# the number of islands using +# Disjoint Set data structure. + +# Class to represent +# Disjoint Set Data structure +class DisjointUnionSets: + def __init__(self, n): + self.rank = [0] * n + self.parent = [0] * n + self.n = n + self.makeSet() + + def makeSet(self): + + # Initially, all elements are in their + # own set. + for i in range(self.n): + self.parent[i] = i + + # Finds the representative of the set that x + # is an element of + def find(self, x): + if (self.parent[x] != x): + + # if x is not the parent of itself, + # then x is not the representative of + # its set. + # so we recursively call Find on its parent + # and move i's node directly under the + # representative of this set + self.parent[x]=self.find(self.parent[x]) + + return self.parent[x] + + # Unites the set that includes x and + # the set that includes y + def Union(self, x, y): + + # Find the representatives(or the root nodes) + # for x an y + xRoot = self.find(x) + yRoot = self.find(y) + + # Elements are in the same set, + # no need to unite anything. + if xRoot == yRoot: + return + + # If x's rank is less than y's rank + # Then move x under y so that depth of tree + # remains less + if self.rank[xRoot] < self.rank[yRoot]: + parent[xRoot] = yRoot + + # Else if y's rank is less than x's rank + # Then move y under x so that depth of tree + # remains less + elif self.rank[yRoot] < self.rank[xRoot]: + self.parent[yRoot] = xRoot + + else: + + # Else if their ranks are the same + # Then move y under x (doesn't matter + # which one goes where) + self.parent[yRoot] = xRoot + + # And increment the result tree's + # rank by 1 + self.rank[xRoot] = self.rank[xRoot] + 1 + +# Returns number of islands in a[][] +def countIslands(a): + n = len(a) + m = len(a[0]) + + dus = DisjointUnionSets(n * m) + + # The following loop checks for its neighbours + # and unites the indexes if both are 1. + for j in range(0, n): + for k in range(0, m): + + # If cell is 0, nothing to do + if a[j][k] == 0: + continue + + # Check all 8 neighbours and do a Union + # with neighbour's set if neighbour is + # also 1 + if j + 1 < n and a[j + 1][k] == 1: + dus.Union(j * (m) + k, + (j + 1) * (m) + k) + if j - 1 >= 0 and a[j - 1][k] == 1: + dus.Union(j * (m) + k, + (j - 1) * (m) + k) + if k + 1 < m and a[j][k + 1] == 1: + dus.Union(j * (m) + k, + (j) * (m) + k + 1) + if k - 1 >= 0 and a[j][k - 1] == 1: + dus.Union(j * (m) + k, + (j) * (m) + k - 1) + if (j + 1 < n and k + 1 < m and + a[j + 1][k + 1] == 1): + dus.Union(j * (m) + k, (j + 1) * + (m) + k + 1) + if (j + 1 < n and k - 1 >= 0 and + a[j + 1][k - 1] == 1): + dus.Union(j * m + k, (j + 1) * + (m) + k - 1) + if (j - 1 >= 0 and k + 1 < m and + a[j - 1][k + 1] == 1): + dus.Union(j * m + k, (j - 1) * + m + k + 1) + if (j - 1 >= 0 and k - 1 >= 0 and + a[j - 1][k - 1] == 1): + dus.Union(j * m + k, (j - 1) * + m + k - 1) + + # Array to note down frequency of each set + c = [0] * (n * m) + numberOfIslands = 0 + for j in range(n): + for k in range(n): + if a[j][k] == 1: + x = dus.find(j * m + k) + + # If frequency of set is 0, + # increment numberOfIslands + if c[x] == 0: + numberOfIslands += 1 + c[x] += 1 + else: + c[x] += 1 + return numberOfIslands + +# Driver Code +a = [[1, 1, 0, 0, 0], + [0, 1, 0, 0, 1], + [1, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 1]] +print(""Number of Islands is:"", countIslands(a)) + +# This code is contributed by ankush_953",quadratic,quadratic +"# Python3 program to count walks from +# u to v with exactly k edges + +# Number of vertices in the graph +V = 4 + +# A naive recursive function to count +# walks from u to v with k edges +def countwalks(graph, u, v, k): + + # Base cases + if (k == 0 and u == v): + return 1 + if (k == 1 and graph[u][v]): + return 1 + if (k <= 0): + return 0 + + # Initialize result + count = 0 + + # Go to all adjacents of u and recur + for i in range(0, V): + + # Check if is adjacent of u + if (graph[u][i] == 1): + count += countwalks(graph, i, v, k-1) + + return count + +# Driver Code + +# Let us create the graph shown in above diagram +graph = [[0, 1, 1, 1, ], + [0, 0, 0, 1, ], + [0, 0, 0, 1, ], + [0, 0, 0, 0] ] + +u = 0; v = 3; k = 2 +print(countwalks(graph, u, v, k)) + +# This code is contributed by Smitha Dinesh Semwal.",linear,quadratic +"# Python3 program to count walks from +# u to v with exactly k edges + +# Number of vertices +V = 4 + +# A Dynamic programming based function +# to count walks from u to v with k edges + + +def countwalks(graph, u, v, k): + + # Table to be filled up using DP. + # The value count[i][j][e] will/ + # store count of possible walks + # from i to j with exactly k edges + count = [[[0 for k in range(k + 1)] + for i in range(V)] + for j in range(V)] + + # Loop for number of edges from 0 to k + for e in range(0, k + 1): + # For Source + for i in range(V): + # For Destination + for j in range(V): + # Initialize value + # count[i][j][e] = 0 + + # From base cases + if (e == 0 and i == j): + count[i][j][e] = 1 + if (e == 1 and graph[i][j] != 0): + count[i][j][e] = 1 + + # Go to adjacent only when number + # of edges is more than 1 + if (e > 1): + + for a in range(V): + + # Adjacent of i + if (graph[i][a] != 0): + count[i][j][e] += count[a][j][e - 1] + + return count[u][v][k] + + +# Driver code +if __name__ == '__main__': + + # Let us create the graph shown + # in above diagram + graph = [[0, 1, 1, 1], + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 0]] + + u = 0 + v = 3 + k = 2 + + print(countwalks(graph, u, v, k)) + +# This code is contributed by Rajput-Ji",np,cubic +"# Python program to print all paths from a source to destination. + +from collections import defaultdict + +# This class represents a directed graph +# using adjacency list representation +class Graph: + + def __init__(self, vertices): + # No. of vertices + self.V = vertices + + # default dictionary to store graph + self.graph = defaultdict(list) + + # function to add an edge to graph + def addEdge(self, u, v): + self.graph[u].append(v) + + '''A recursive function to print all paths from 'u' to 'd'. + visited[] keeps track of vertices in current path. + path[] stores actual vertices and path_index is current + index in path[]''' + def printAllPathsUtil(self, u, d, visited, path): + + # Mark the current node as visited and store in path + visited[u]= True + path.append(u) + + # If current vertex is same as destination, then print + # current path[] + if u == d: + print (path) + else: + # If current vertex is not destination + # Recur for all the vertices adjacent to this vertex + for i in self.graph[u]: + if visited[i]== False: + self.printAllPathsUtil(i, d, visited, path) + + # Remove current vertex from path[] and mark it as unvisited + path.pop() + visited[u]= False + + + # Prints all paths from 's' to 'd' + def printAllPaths(self, s, d): + + # Mark all the vertices as not visited + visited =[False]*(self.V) + + # Create an array to store paths + path = [] + + # Call the recursive helper function to print all paths + self.printAllPathsUtil(s, d, visited, path) + + + +# Create a graph given in the above diagram +g = Graph(4) +g.addEdge(0, 1) +g.addEdge(0, 2) +g.addEdge(0, 3) +g.addEdge(2, 0) +g.addEdge(2, 1) +g.addEdge(1, 3) + +s = 2 ; d = 3 +print (""Following are all different paths from % d to % d :"" %(s, d)) +g.printAllPaths(s, d) +# This code is contributed by Neelam Yadav",np,quadratic +"# Python3 code to check if +# cyclic order is possible +# among strings under given +# constraints +M = 26 + +# Utility method for a depth +# first search among vertices +def dfs(g, u, visit): + visit[u] = True + + for i in range(len(g[u])): + if(not visit[g[u][i]]): + dfs(g, g[u][i], visit) + +# Returns true if all vertices +# are strongly connected i.e. +# can be made as loop +def isConnected(g, mark, s): + + # Initialize all vertices + # as not visited + visit = [False for i in range(M)] + + # Perform a dfs from s + dfs(g, s, visit) + + # Now loop through + # all characters + for i in range(M): + + # I character is marked + # (i.e. it was first or last + # character of some string) + # then it should be visited + # in last dfs (as for looping, + # graph should be strongly + # connected) */ + if(mark[i] and (not visit[i])): + return False + + # If we reach that means + # graph is connected + return True + +# return true if an order among +# strings is possible +def possibleOrderAmongString(arr, N): + + # Create an empty graph + g = {} + + # Initialize all vertices + # as not marked + mark = [False for i in range(M)] + + # Initialize indegree and + # outdegree of every + # vertex as 0. + In = [0 for i in range(M)] + out = [0 for i in range(M)] + + # Process all strings + # one by one + for i in range(N): + + # Find first and last + # characters + f = (ord(arr[i][0]) - + ord('a')) + l = (ord(arr[i][-1]) - + ord('a')) + + # Mark the characters + mark[f] = True + mark[l] = True + + # Increase indegree + # and outdegree count + In[l] += 1 + out[f] += 1 + + if f not in g: + g[f] = [] + + # Add an edge in graph + g[f].append(l) + + # If for any character + # indegree is not equal to + # outdegree then ordering + # is not possible + for i in range(M): + if(In[i] != out[i]): + return False + + return isConnected(g, mark, + ord(arr[0][0]) - + ord('a')) + +# Driver code +arr = [""ab"", ""bc"", + ""cd"", ""de"", + ""ed"", ""da""] +N = len(arr) +if(possibleOrderAmongString(arr, N) == + False): + print(""Ordering not possible"") +else: + print(""Ordering is possible"") + +# This code is contributed by avanitrachhadiya2155",linear,linear +"# Python3 program for the above approach +def maxindex(dist, n): + mi = 0 + for i in range(n): + if (dist[i] > dist[mi]): + mi = i + return mi + +def selectKcities(n, weights, k): + dist = [0]*n + centers = [] + + for i in range(n): + dist[i] = 10**9 + + # index of city having the + # maximum distance to it's + # closest center + max = 0 + for i in range(k): + centers.append(max) + for j in range(n): + + # updating the distance + # of the cities to their + # closest centers + dist[j] = min(dist[j], weights[max][j]) + + # updating the index of the + # city with the maximum + # distance to it's closest center + max = maxindex(dist, n) + + # Printing the maximum distance + # of a city to a center + # that is our answer + # print() + print(dist[max]) + + # Printing the cities that + # were chosen to be made + # centers + for i in centers: + print(i, end = "" "") + +# Driver Code +if __name__ == '__main__': + n = 4 + weights = [ [ 0, 4, 8, 5 ], + [ 4, 0, 10, 7 ], + [ 8, 10, 0, 9 ], + [ 5, 7, 9, 0 ] ] + k = 2 + + # Function Call + selectKcities(n, weights, k) + +# This code is contributed by mohit kumar 29.",constant,quadratic +"# Python3 program to find minimum time required to make all +# oranges rotten +from collections import deque + +# function to check whether a cell is valid / invalid + + +def isvalid(i, j): + return (i >= 0 and j >= 0 and i < 3 and j < 5) + +# Function to check whether the cell is delimiter +# which is (-1, -1) + + +def isdelim(temp): + return (temp[0] == -1 and temp[1] == -1) + +# Function to check whether there is still a fresh +# orange remaining + + +def checkall(arr): + for i in range(3): + for j in range(5): + if (arr[i][j] == 1): + return True + return False + +# This function finds if it is +# possible to rot all oranges or not. +# If possible, then it returns +# minimum time required to rot all, +# otherwise returns -1 + + +def rotOranges(arr): + + # Create a queue of cells + Q = deque() + temp = [0, 0] + ans = 1 + + # Store all the cells having + # rotten orange in first time frame + for i in range(3): + for j in range(5): + if (arr[i][j] == 2): + temp[0] = i + temp[1] = j + Q.append([i, j]) + + # Separate these rotten oranges + # from the oranges which will rotten + # due the oranges in first time + # frame using delimiter which is (-1, -1) + temp[0] = -1 + temp[1] = -1 + Q.append([-1, -1]) + # print(Q) + + # Process the grid while there are + # rotten oranges in the Queue + while False: + + # This flag is used to determine + # whether even a single fresh + # orange gets rotten due to rotten + # oranges in current time + # frame so we can increase + # the count of the required time. + flag = False + print(len(Q)) + + # Process all the rotten + # oranges in current time frame. + while not isdelim(Q[0]): + temp = Q[0] + print(len(Q)) + + # Check right adjacent cell that if it can be rotten + if (isvalid(temp[0] + 1, temp[1]) and arr[temp[0] + 1][temp[1]] == 1): + + # if this is the first orange to get rotten, increase + # count and set the flag. + if (not flag): + ans, flag = ans + 1, True + + # Make the orange rotten + arr[temp[0] + 1][temp[1]] = 2 + + # append the adjacent orange to Queue + temp[0] += 1 + Q.append(temp) + + temp[0] -= 1 # Move back to current cell + + # Check left adjacent cell that if it can be rotten + if (isvalid(temp[0] - 1, temp[1]) and arr[temp[0] - 1][temp[1]] == 1): + if (not flag): + ans, flag = ans + 1, True + arr[temp[0] - 1][temp[1]] = 2 + temp[0] -= 1 + Q.append(temp) # append this cell to Queue + temp[0] += 1 + + # Check top adjacent cell that if it can be rotten + if (isvalid(temp[0], temp[1] + 1) and arr[temp[0]][temp[1] + 1] == 1): + if (not flag): + ans, flag = ans + 1, True + arr[temp[0]][temp[1] + 1] = 2 + temp[1] += 1 + Q.append(temp) # Push this cell to Queue + temp[1] -= 1 + + # Check bottom adjacent cell if it can be rotten + if (isvalid(temp[0], temp[1] - 1) and arr[temp[0]][temp[1] - 1] == 1): + if (not flag): + ans, flag = ans + 1, True + arr[temp[0]][temp[1] - 1] = 2 + temp[1] -= 1 + Q.append(temp) # append this cell to Queue + Q.popleft() + + # Pop the delimiter + Q.popleft() + + # If oranges were rotten in + # current frame than separate the + # rotten oranges using delimiter + # for the next frame for processing. + if (len(Q) == 0): + temp[0] = -1 + temp[1] = -1 + Q.append(temp) + + # If Queue was empty than no rotten oranges left to process so exit + + # Return -1 if all arranges could not rot, otherwise return ans. + return ans + 1 if(checkall(arr)) else -1 + + +# Driver program +if __name__ == '__main__': + arr = [[2, 1, 0, 2, 1], + [1, 0, 1, 2, 1], + [1, 0, 0, 2, 1]] + ans = rotOranges(arr) + if (ans == -1): + print(""All oranges cannot rotn"") + else: + print(""Time required for all oranges to rot => "", ans) + + # This code is contributed by mohit kumar 29",quadratic,quadratic +"# Python 3 program to find whether an array +# is subset of another array + +# Return 1 if arr2[] is a subset of +# arr1[] + + +def isSubset(arr1, arr2, m, n): + i = 0 + j = 0 + for i in range(n): + for j in range(m): + if(arr2[i] == arr1[j]): + break + + # If the above inner loop was + # not broken at all then arr2[i] + # is not present in arr1[] + if (j == m): + return 0 + + # If we reach here then all + # elements of arr2[] are present + # in arr1[] + return 1 + + +# Driver code +if __name__ == ""__main__"": + + arr1 = [11, 1, 13, 21, 3, 7] + arr2 = [11, 3, 7, 1] + + m = len(arr1) + n = len(arr2) + + if(isSubset(arr1, arr2, m, n)): + print(""arr2[] is subset of arr1[] "") + else: + print(""arr2[] is not a subset of arr1[]"") + +# This code is contributed by ita_c",constant,quadratic +"# Python3 program to find whether an array +# is subset of another array + +# Return 1 if arr2[] is a subset of arr1[] + + +def isSubset(arr1, arr2, m, n): + i = 0 + + quickSort(arr1, 0, m-1) + for i in range(n): + if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1): + return 0 + + # If we reach here then all elements + # of arr2[] are present in arr1[] + return 1 + +# FOLLOWING FUNCTIONS ARE ONLY FOR +# SEARCHING AND SORTING PURPOSE +# Standard Binary Search function + + +def binarySearch(arr, low, high, x): + if(high >= low): + mid = (low + high)//2 + + # Check if arr[mid] is the first + # occurrence of x. + # arr[mid] is first occurrence if x is + # one of the following + # is true: + # (i) mid == 0 and arr[mid] == x + # (ii) arr[mid-1] < x and arr[mid] == x + if((mid == 0 or x > arr[mid-1]) and (arr[mid] == x)): + return mid + elif(x > arr[mid]): + return binarySearch(arr, (mid + 1), high, x) + else: + return binarySearch(arr, low, (mid - 1), x) + + return -1 + + +def partition(A, si, ei): + x = A[ei] + i = (si - 1) + + for j in range(si, ei): + if(A[j] <= x): + i += 1 + A[i], A[j] = A[j], A[i] + A[i + 1], A[ei] = A[ei], A[i + 1] + return (i + 1) + +# Implementation of Quick Sort +# A[] --> Array to be sorted +# si --> Starting index +# ei --> Ending index + + +def quickSort(A, si, ei): + # Partitioning index + if(si < ei): + pi = partition(A, si, ei) + quickSort(A, si, pi - 1) + quickSort(A, pi + 1, ei) + + +# Driver code +arr1 = [11, 1, 13, 21, 3, 7] +arr2 = [11, 3, 7, 1] + +m = len(arr1) +n = len(arr2) + +if(isSubset(arr1, arr2, m, n)): + print(""arr2[] is subset of arr1[] "") +else: + print(""arr2[] is not a subset of arr1[] "") + + +# This code is contributed by chandan_jnu",linear,nlogn +"# Python3 program to find whether an array +# is subset of another array + +# Return 1 if arr2[] is a subset of arr1[] */ + + +def isSubset(arr1, arr2, m, n): + i = 0 + j = 0 + if m < n: + return 0 + + arr1.sort() + arr2.sort() + + while i < n and j < m: + if arr1[j] < arr2[i]: + j += 1 + elif arr1[j] == arr2[i]: + j += 1 + i += 1 + elif arr1[j] > arr2[i]: + return 0 + return False if i < n else True + + +# Driver code +arr1 = [11, 1, 13, 21, 3, 7] +arr2 = [11, 3, 7, 1] + +m = len(arr1) +n = len(arr2) +if isSubset(arr1, arr2, m, n) == True: + print(""arr2 is subset of arr1 "") +else: + printf(""arr2 is not a subset of arr1 "") + +# This code is contributed by Shrikant13",constant,nlogn +"# Python3 program to find whether an array +# is subset of another array + +# Return true if arr2[] is a subset +# of arr1[] + + +def isSubset(arr1, m, arr2, n): + + # Using STL set for hashing + hashset = set() + + # hset stores all the values of arr1 + for i in range(0, m): + hashset.add(arr1[i]) + + # Loop to check if all elements + # of arr2 also lies in arr1 + for i in range(0, n): + if arr2[i] in hashset: + continue + else: + return False + + return True + + +# Driver Code +if __name__ == '__main__': + + arr1 = [11, 1, 13, 21, 3, 7] + arr2 = [11, 3, 7, 1] + + m = len(arr1) + n = len(arr2) + + if (isSubset(arr1, m, arr2, n)): + print(""arr2[] is subset of arr1[] "") + else: + print(""arr2[] is not a subset of arr1[] "") + +# This code is contributed by akhilsaini",linear,nlogn +"# Python3 code +arr1 = [11, 1, 13, 21, 3, 7] +arr2 = [11, 3, 7, 1] +m = len(arr1) +n = len(arr2) +s = set() +for i in range(m): + s.add(arr1[i]) + +p = len(s) +for i in range(n): + s.add(arr2[i]) + +if (len(s) == p): + print(""arr2[] is subset of arr1[] "") + +else: + print(""arr2[] is not subset of arr1[] "") + + # This code is contributed by divyeshrabadiya07.",linear,linear +"# Python3 program to find whether an array +# is subset of another array + +# Return true if arr2[] is a subset of arr1[] + + +def isSubset(arr1, m, arr2, n): + + # Create a Frequency Table using STL + frequency = {} + + # Increase the frequency of each element + # in the frequency table. + for i in range(0, m): + if arr1[i] in frequency: + frequency[arr1[i]] = frequency[arr1[i]] + 1 + else: + frequency[arr1[i]] = 1 + + # Decrease the frequency if the + # element was found in the frequency + # table with the frequency more than 0. + # else return 0 and if loop is + # completed return 1. + for i in range(0, n): + if (frequency[arr2[i]] > 0): + frequency[arr2[i]] -= 1 + else: + return False + + return True + + +# Driver Code +if __name__ == '__main__': + + arr1 = [11, 1, 13, 21, 3, 7] + arr2 = [11, 3, 7, 1] + + m = len(arr1) + n = len(arr2) + + if (isSubset(arr1, m, arr2, n)): + print(""arr2[] is subset of arr1[] "") + else: + print(""arr2[] is not a subset of arr1[] "") + +# This code is contributed by akhilsaini",linear,linear +"# This python program tells if there exists a pair in array whose sum results in x. + +# Function to find and print pair + + +def chkPair(A, size, x): + for i in range(0, size - 1): + for j in range(i + 1, size): + if (A[i] + A[j] == x): + return 1 + return 0 + + +if __name__ == ""__main__"": + A = [0, -1, 2, -3, 1] + x = -2 + size = len(A) + + if (chkPair(A, size, x)): + print(""Yes"") + + else: + print(""No"") + + # This code is contributed by rakeshsahni",constant,quadratic +"# Python program to check for the sum +# condition to be satisfied + + +def hasArrayTwoCandidates(A, arr_size, sum): + + # sort the array + quickSort(A, 0, arr_size-1) + l = 0 + r = arr_size-1 + + # traverse the array for the two elements + while l < r: + if (A[l] + A[r] == sum): + return 1 + elif (A[l] + A[r] < sum): + l += 1 + else: + r -= 1 + return 0 + +# Implementation of Quick Sort +# A[] --> Array to be sorted +# si --> Starting index +# ei --> Ending index + + +def quickSort(A, si, ei): + if si < ei: + pi = partition(A, si, ei) + quickSort(A, si, pi-1) + quickSort(A, pi + 1, ei) + +# Utility function for partitioning +# the array(used in quick sort) + + +def partition(A, si, ei): + x = A[ei] + i = (si-1) + for j in range(si, ei): + if A[j] <= x: + i += 1 + + # This operation is used to swap + # two variables is python + A[i], A[j] = A[j], A[i] + + A[i + 1], A[ei] = A[ei], A[i + 1] + + return i + 1 + + +# Driver program to test the functions +A = [1, 4, 45, 6, 10, -8] +n = 16 +if (hasArrayTwoCandidates(A, len(A), n)): + print(""Yes"") +else: + print(""No"") + +# This code is contributed by __Devesh Agrawal__",constant,nlogn +"# Python program to check for the sum +# condition to be satisfied + + +def binarySearch(A, low, high, searchKey): + m = 0 + while (low <= high): + m = (high + low) // 2 + # Check if searchKey is present at mid + if (A[m] == searchKey): + return 1 + # If searchKey greater, ignore left half + if (A[m] < searchKey): + low = m + 1 + # If searchKey is smaller, ignore right half + else: + high = m - 1 + # if we reach here, then element was + # not present + return 0 + + +def checkTwoSum(A, arr_size, sum): + + # sort the array + A.sort() + l = 0 + r = arr_size-1 + + # Traversing all element in an array search for searchKey + i = 0 + while i < arr_size-1: + searchKey = sum-A[i] + # calling binarySearch function + if(binarySearch(A, i+1, r, searchKey) == 1): + return 1 + i = i+1 + + return 0 + + +# Driver program to test the functions +A = [1, 4, 45, 6, 10, -8] +n = 14 +if (checkTwoSum(A, len(A), n)): + print(""Yes"") +else: + print(""No"")",constant,nlogn +"# Python program to find if there are +# two elements with given sum + +# function to check for the given sum +# in the array + + +def printPairs(arr, arr_size, sum): + + # Create an empty hash map + # using an hashmap allows us to store the indices + hashmap = {} + + for i in range(0, arr_size): + temp = sum-arr[i] + if (temp in hashmap): + print('Yes') + return + hashmap[arr[i]] = i + print(""No"") + + +# driver code +A = [1, 4, 45, 6, 10, 8] +n = 16 +printPairs(A, len(A), n) + +# This code will also work in case the array has the same number twice +# and target is the sum of those numbers +# Eg: Array = [4,6,4] Target = 8 + +# This code is contributed by __Achyut Upadhyay__",linear,linear +"# Code in Python3 to tell if there +# exists a pair in array whose +# sum results in x. + +# Function to print pairs + + +def printPairs(a, n, x): + + rem = [] + + for i in range(x): + + # Initializing the rem + # values with 0's. + rem.append(0) + + for i in range(n): + if (a[i] < x): + + # Perform the remainder operation + # only if the element is x, as + # numbers greater than x can't + # be used to get a sum x.Updating + # the count of remainders. + rem[a[i] % x] += 1 + + # Traversing the remainder list from + # start to middle to find pairs + for i in range(1, x // 2): + if (rem[i] > 0 and rem[x - i] > 0): + + # The elements with remainders + # i and x-i will result to a + # sum of x. Once we get two + # elements which add up to x, + # we print x and break. + print(""Yes"") + break + + # Once we reach middle of + # remainder array, we have to + # do operations based on x. + if (i >= x // 2): + if (x % 2 == 0): + if (rem[x // 2] > 1): + + # If x is even and we have more + # than 1 elements with remainder + # x/2, then we will have two + # distinct elements which add up + # to x. if we dont have than 1 + # element, print ""No"". + print(""Yes"") + else: + print(""No"") + else: + + # When x is odd we continue + # the same process which we + # did in previous loop. + if (rem[x // 2] > 0 and + rem[x - x // 2] > 0): + print(""Yes"") + else: + print(""No"") + + +# Driver Code +A = [1, 4, 45, 6, 10, 8] +n = 16 +arr_size = len(A) + +# Function calling +printPairs(A, arr_size, n) + +# This code is contributed by subhammahato348",constant,linear +"# Python3 program to find the minimum +# number of operations required to +# make all elements of array equal +from collections import defaultdict + +# Function for min operation +def minOperation(arr, n): + + # Insert all elements in hash. + Hash = defaultdict(lambda:0) + for i in range(0, n): + Hash[arr[i]] += 1 + + # find the max frequency + max_count = 0 + for i in Hash: + if max_count < Hash[i]: + max_count = Hash[i] + + # return result + return n - max_count + +# Driver Code +if __name__ == ""__main__"": + + arr = [1, 5, 2, 1, 3, 2, 1] + n = len(arr) + print(minOperation(arr, n)) + +# This code is contributed +# by Rituraj Jain",linear,linear +"# Python program to find maximum distance between two +# same occurrences of a number. + +# Function to find maximum distance between equal elements +def maxDistance(arr, n): + + # Used to store element to first index mapping + mp = {} + + # Traverse elements and find maximum distance between + # same occurrences with the help of map. + maxDict = 0 + for i in range(n): + + # If this is first occurrence of element, insert its + # index in map + if arr[i] not in mp.keys(): + mp[arr[i]] = i + + # Else update max distance + else: + maxDict = max(maxDict, i-mp[arr[i]]) + + return maxDict + +# Driver Program +if __name__=='__main__': + arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2] + n = len(arr) + print (maxDistance(arr, n)) + +# Contributed By: Harshit Sidhwa",linear,linear +"# python3 program to find maximum number of 2D points that lie on the same line. + +from collections import defaultdict +from math import gcd +from typing import DefaultDict, List, Tuple + +IntPair = Tuple[int, int] + + +def normalized_slope(a: IntPair, b: IntPair) -> IntPair: + """""" + Returns normalized (rise, run) tuple. We won't return the actual rise/run + result in order to avoid floating point math, which leads to faulty + comparisons. + + See + https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems + """""" + run = b[0] - a[0] + + # normalize undefined slopes to (1, 0) + if run == 0: + return (1, 0) + + # normalize to left-to-right + if run < 0: + a, b = b, a + run = b[0] - a[0] + + rise = b[1] - a[1] + # Normalize by greatest common divisor. + # math.gcd only works on positive numbers. + gcd_ = gcd(abs(rise), run) + return ( + rise // gcd_, + run // gcd_, + ) + + +def maximum_points_on_same_line(points: List[List[int]]) -> int: + # You need at least 3 points to potentially have non-collinear points. + # For [0, 2] points, all points are on the same line. + if len(points) < 3: + return len(points) + + # Note that every line we find will have at least 2 points. + # There will be at least one line because len(points) >= 3. + # Therefore, it's safe to initialize to 0. + max_val = 0 + + for a_index in range(0, len(points) - 1): + # All lines in this iteration go through point a. + # Note that lines a-b and a-c cannot be parallel. + # Therefore, if lines a-b and a-c have the same slope, they're the same + # line. + a = tuple(points[a_index]) + # Fresh lines already have a, so default=1 + slope_counts: DefaultDict[IntPair, int] = defaultdict(lambda: 1) + + for b_index in range(a_index + 1, len(points)): + b = tuple(points[b_index]) + slope_counts[normalized_slope(a, b)] += 1 + + max_val = max( + max_val, + max(slope_counts.values()), + ) + + return max_val + + +print(maximum_points_on_same_line([ + [-1, 1], + [0, 0], + [1, 1], + [2, 2], + [3, 3], + [3, 4], +])) + +# This code is contributed by Jose Alvarado Torre",linear,quadratic +"# Python3 implementation of the +# above approach + +# Function to find the Duplicates, +# if duplicate occurs 2 times or +# more than 2 times in array so, +# it will print duplicate value +# only once at output +def findDuplicates(arr, Len): + + # Initialize ifPresent as false + ifPresent = False + + # ArrayList to store the output + a1 = [] + for i in range(Len - 1): + for j in range(i + 1, Len): + + # Checking if element is + # present in the ArrayList + # or not if present then break + if (arr[i] == arr[j]): + if arr[i] in a1: + break + + # If element is not present in the + # ArrayList then add it to ArrayList + # and make ifPresent at true + else: + a1.append(arr[i]) + ifPresent = True + + # If duplicates is present + # then print ArrayList + if (ifPresent): + print(a1, end = "" "") + else: + print(""No duplicates present in arrays"") + +# Driver Code +arr = [ 12, 11, 40, 12, 5, 6, 5, 12, 11 ] +n = len(arr) + +findDuplicates(arr, n) + +# This code is contributed by rag2127",linear,quadratic +"# Python3 program to find duplicates +# using dictionary approach. +def printDuplicates(arr): + dict = {} + + for ele in arr: + try: + dict[ele] += 1 + except: + dict[ele] = 1 + + for item in dict: + + # if frequency is more than 1 + # print the element + if(dict[item] > 1): + print(item, end="" "") + + print(""\n"") + +# Driver Code +if __name__ == ""__main__"": + list = [12, 11, 40, 12, + 5, 6, 5, 12, 11] + printDuplicates(list) + +# This code is contributed +# by Sushil Bhile",linear,linear +"# Python program to find top k elements in a stream + +# Function to print top k numbers +def kTop(a, n, k): + + # list of size k + 1 to store elements + top = [0 for i in range(k + 1)] + + # dictionary to keep track of frequency + freq = {i:0 for i in range(k + 1)} + + # iterate till the end of stream + for m in range(n): + + # increase the frequency + if a[m] in freq.keys(): + freq[a[m]] += 1 + else: + freq[a[m]] = 1 + + # store that element in top vector + top[k] = a[m] + + i = top.index(a[m]) + i -= 1 + + while i >= 0: + + # compare the frequency and swap if higher + # frequency element is stored next to it + if (freq[top[i]] < freq[top[i + 1]]): + t = top[i] + top[i] = top[i + 1] + top[i + 1] = t + + # if frequency is same compare the elements + # and swap if next element is high + else if ((freq[top[i]] == freq[top[i + 1]]) and (top[i] > top[i + 1])): + t = top[i] + top[i] = top[i + 1] + top[i + 1] = t + else: + break + i -= 1 + + # print top k elements + i = 0 + while i < k and top[i] != 0: + print(top[i],end="" "") + i += 1 + print() + +# Driver program to test above function +k = 4 +arr = [ 5, 2, 1, 3, 2 ] +n = len(arr) +kTop(arr, n, k) + +# This code is contributed by Sachin Bisht",linear,quadratic +"# Python3 program to find the most +# frequent element in an array. +def mostFrequent(arr, n): + maxcount = 0; + element_having_max_freq = 0; + for i in range(0, n): + count = 0 + for j in range(0, n): + if(arr[i] == arr[j]): + count += 1 + if(count > maxcount): + maxcount = count + element_having_max_freq = arr[i] + + return element_having_max_freq; + +# Driver Code +arr = [40,50,30,40,50,30,30] +n = len(arr) +print(mostFrequent(arr, n)) + +# This code is contributed by Arpit Jain",constant,quadratic +"# Python3 program to find the most +# frequent element in an array. + + +def mostFrequent(arr, n): + + # Sort the array + arr.sort() + + # find the max frequency using + # linear traversal + max_count = 1 + res = arr[0] + curr_count = 1 + + for i in range(1, n): + if (arr[i] == arr[i - 1]): + curr_count += 1 + else: + curr_count = 1 + + # If last element is most frequent + if (curr_count > max_count): + max_count = curr_count + res = arr[i - 1] + + return res + + +# Driver Code +arr = [40,50,30,40,50,30,30] +n = len(arr) +print(mostFrequent(arr, n)) + +# This code is contributed by Smitha Dinesh Semwal.",constant,nlogn +"# Python3 program to find the most +# frequent element in an array. +import math as mt + +def mostFrequent(arr, n): + + # Insert all elements in Hash. + Hash = dict() + for i in range(n): + if arr[i] in Hash.keys(): + Hash[arr[i]] += 1 + else: + Hash[arr[i]] = 1 + + # find the max frequency + max_count = 0 + res = -1 + for i in Hash: + if (max_count < Hash[i]): + res = i + max_count = Hash[i] + + return res + +# Driver Code +arr = [ 40,50,30,40,50,30,30] +n = len(arr) +print(mostFrequent(arr, n)) + +# This code is contributed +# by Mohit kumar 29",linear,linear +"def maxFreq(arr, n): + + # Using moore's voting algorithm + res = 0 + count = 1 + + for i in range(1, n): + if (arr[i] == arr[res]): + count += 1 + else: + count -= 1 + + if (count == 0): + res = i + count = 1 + + return arr[res] + +# Driver code +arr = [ 40, 50, 30, 40, 50, 30, 30 ] +n = len(arr) +freq = maxFreq(arr, n) +count = 0 + +for i in range (n): + if(arr[i] == freq): + count += 1 + +print(""Element "", maxFreq(arr , n), + "" occurs "", count, "" times"") + +# This code is contributed by shivanisinghss2110",constant,linear +"# Python3 implementation to +# find first element +# occurring k times + +# function to find the +# first element occurring +# k number of times +def firstElement(arr, n, k): + + # dictionary to count + # occurrences of + # each element + for i in arr: + count=0 + for j in arr: + if i==j: + count=count+1 + if count == k: + return i + + # no element occurs k times + return -1 + +# Driver Code +if __name__==""__main__"": + + arr = [1, 7, 4, 3, 4, 8, 7]; + n = len(arr) + k = 2 + print(firstElement(arr, n, k)) + +# This code is contributed by Arpit Jain",constant,quadratic +"# Python3 implementation to +# find first element +# occurring k times + +# function to find the +# first element occurring +# k number of times +def firstElement(arr, n, k): + + # dictionary to count + # occurrences of + # each element + count_map = {}; + for i in range(0, n): + if(arr[i] in count_map.keys()): + count_map[arr[i]] += 1 + else: + count_map[arr[i]] = 1 + i += 1 + + for i in range(0, n): + + # if count of element == k , + # then it is the required + # first element + if (count_map[arr[i]] == k): + return arr[i] + i += 1 + + # no element occurs k times + return -1 + +# Driver Code +if __name__==""__main__"": + + arr = [1, 7, 4, 3, 4, 8, 7]; + n = len(arr) + k = 2 + print(firstElement(arr, n, k)) + +# This code is contributed +# by Abhishek Sharma",linear,linear +"# importing counter from collections +from collections import Counter + +# Python3 implementation to find +# first element occurring k times +# function to find the first element +# occurring k number of times +def firstElement(arr, n, k): + + # calculating frequencies using Counter + count_map = Counter(arr) + + for i in range(0, n): + + # If count of element == k , + # then it is the required + # first element + if (count_map[arr[i]] == k): + return arr[i] + i += 1 + + # No element occurs k times + return -1 + + +# Driver Code +if __name__ == ""__main__"": + + arr = [1, 7, 4, 3, 4, 8, 7] + n = len(arr) + k = 2 + print(firstElement(arr, n, k)) + +# This code is contributed by vikkycirus",linear,nlogn +"# A Python3 program to find all symmetric +# pairs in a given array of pairs. + +# Print all pairs that have +# a symmetric counterpart +def findSymPairs(arr, row): + + # This loop for selection of one pair + for i in range(0, row): + + # This loop for searching of symmetric pair + for j in range(i + 1, row): + + # Condition of symmetric pair + if (arr[i][0] == arr[j][1] and arr[i][1] == arr[j][0]): + print(""("",arr[i][0],"","",arr[i][1],"")"") + +# Driver Code +if __name__ == '__main__': + arr = [[0 for i in range(2)] + for i in range(5)] + arr[0][0], arr[0][1] = 11, 20 + arr[1][0], arr[1][1] = 30, 40 + arr[2][0], arr[2][1] = 5, 10 + arr[3][0], arr[3][1] = 40, 30 + arr[4][0], arr[4][1] = 10, 5 + findSymPairs(arr, 5) + +# This code is contributed by Arpit Jain",constant,quadratic +"# A Python3 program to find all symmetric +# pairs in a given array of pairs. + +# Print all pairs that have +# a symmetric counterpart +def findSymPairs(arr, row): + + # Creates an empty hashMap hM + hM = dict() + + # Traverse through the given array + for i in range(row): + + # First and second elements + # of current pair + first = arr[i][0] + sec = arr[i][1] + + # If found and value in hash matches with first + # element of this pair, we found symmetry + if (sec in hM.keys() and hM[sec] == first): + print(""("", sec,"","", first, "")"") + + else: # Else put sec element of + # this pair in hash + hM[first] = sec + +# Driver Code +if __name__ == '__main__': + arr = [[0 for i in range(2)] + for i in range(5)] + arr[0][0], arr[0][1] = 11, 20 + arr[1][0], arr[1][1] = 30, 40 + arr[2][0], arr[2][1] = 5, 10 + arr[3][0], arr[3][1] = 40, 30 + arr[4][0], arr[4][1] = 10, 5 + findSymPairs(arr, 5) + +# This code is contributed by Mohit Kumar",linear,linear +"# Python3 program to find the only +# repeating element in an array where +# elements are from 1 to N-1. + + +def findRepeating(arr, N): + for i in range(N): + for j in range(i + 1, N): + if (arr[i] == arr[j]): + return arr[i] + + +# Driver's Code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed by Arpit Jain",constant,quadratic +"# Python3 program to find the only +# repeating element in an array where +# elements are from 1 to N-1. + + +def findRepeating(arr, N): + arr.sort() + for i in range(1, N): + if(arr[i] != i+1): + return arr[i] + + +# Driver's Code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed by Arpit Jain",constant,nlogn +"# Python3 program to find the only +# repeating element in an array +# where elements are from 1 to n-1. + + +def findRepeating(arr, N): + s = set() + for i in range(N): + if arr[i] in s: + return arr[i] + s.add(arr[i]) + + # If input is correct, we should + # never reach here + return -1 + + +# Driver code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed +# by Shrikant13",linear,linear +"# Python3 program to find the only +# repeating element in an array where +# elements are from 1 to N-1. + + +def findRepeating(arr, N): + + # Find array sum and subtract sum + # first n-1 natural numbers from it + # to find the result. + return sum(arr) - (((N - 1) * N) // 2) + + +# Driver's Code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed +# by mohit kumar",constant,linear +"# Python3 program to find the only +# repeating element in an array where +# elements are from 1 to N-1. + + +def findRepeating(arr, N): + + # res is going to store value of + # 1 ^ 2 ^ 3 .. ^ (N-1) ^ arr[0] ^ + # arr[1] ^ .... arr[n-1] + res = 0 + for i in range(0, N-1): + res = res ^ (i+1) ^ arr[i] + res = res ^ arr[N-1] + + return res + + +# Driver code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed by Smitha Dinesh Semwal.",constant,linear +"# Python3 program to find the only +# repeating element in an array +# where elements are from 1 to N-1. + +# Function to find repeated element + + +def findRepeating(arr, N): + + missingElement = 0 + + # indexing based + for i in range(0, N): + + element = arr[abs(arr[i])] + + if(element < 0): + missingElement = arr[i] + break + + arr[abs(arr[i])] = -arr[abs(arr[i])] + + return abs(missingElement) + + +# Driver code +if __name__ == ""__main__"": + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + N = len(arr) + + # Function call + print(findRepeating(arr, N)) + +# This code is contributed by Smitha Dinesh Semwal.",constant,linear +"class GFG : + @staticmethod + def findDuplicate( nums) : + slow = nums[0] + fast = nums[0] + while True : + slow = nums[slow] + fast = nums[nums[fast]] + if((slow != fast) == False) : + break + fast = nums[0] + while (slow != fast) : + slow = nums[slow] + fast = nums[fast] + return slow + @staticmethod + def main( args) : + arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] + + # Function call + ans = GFG.findDuplicate(arr) + print(ans) + +if __name__==""__main__"": + GFG.main([]) + + # This code is contributed by aadityaburujwale.",constant,linear +"# Python 3program to find one of the repeating +# elements in a read only array +from math import sqrt + +# Function to find one of the repeating +# elements +def findRepeatingNumber(arr, n): + + for i in arr: + count = 0; + for j in arr: + if i == j: + count=count+1 + if(count>1): + return i + + # return -1 if no repeating element exists + return -1 + +# Driver Code +if __name__ == '__main__': + + # read only array, not to be modified + arr = [1, 1, 2, 3, 5, 4] + + # array of size 6(n + 1) having + # elements between 1 and 5 + n = 5 + + print(""One of the numbers repeated in the array is:"", + findRepeatingNumber(arr, n)) + +# This code is contributed by Arpit Jain",constant,quadratic +"# Python Program to Find the top three repeated numbers + +# User defined Pair class +import sys + +class Pair: + def __init__(self,first = 0,second = 0): + self.first = first + self.second = second + +# Function to print top three repeated numbers +def top3Repeated(arr, n): + + # There should be atleast two elements + if (n < 3): + print(""Invalid Input"") + return + + # Count Frequency of each element + arr.sort() + freq = {} + for i in range(n): + if (arr[i] in freq): + freq[arr[i]] = 1 + freq[arr[i]] + else: + freq[arr[i]] = 1 + + # Initialize first value of each variable + # of Pair type is INT_MIN + x = Pair() + y = Pair() + z = Pair() + x.first = y.first = z.first = -sys.maxsize -1 + + for curr,curr2 in freq.items(): + # If frequency of current element + # is not zero and greater than + # frequency of first largest element + if (int(curr2) > x.first): + + # Update second and third largest + z.first = y.first + z.second = y.second + y.first = x.first + y.second = x.second + + # Modify values of x Number + x.first = int((curr2)) + x.second = int((curr)) + + # If frequency of current element is + # not zero and frequency of current + # element is less than frequency of + # first largest element, but greater + # than y element + elif (int((curr2)) > y.first): + # Modify values of third largest + z.first = y.first + z.second = y.second + + # Modify values of second largest + y.first = int((curr2)) + y.second = int((curr)) + + # If frequency of current element + # is not zero and frequency of + # current element is less than + # frequency of first element and + # second largest, but greater than + # third largest. + elif (int((curr2)) > z.first): + + # Modify values of z Number + z.first = int((curr2)) + z.second = int((curr)) + + print(f""Three largest elements are {x.second} {y.second} {z.second}"") + +# Driver's Code +arr = [ 3, 4, 2, 3, 16, 3, 15, 16, 15, 15, 16, 2, 3 ] +n = len(arr) +top3Repeated(arr, n) + +# This code is contributed by shinjanpatra",linear,linear +"# A simple Python 3 program to +# group multiple occurrences of +# individual array elements + +# A simple method to group all +# occurrences of individual elements +def groupElements(arr, n): + + # Initialize all elements + # as not visited + visited = [False] * n + for i in range(0, n): + visited[i] = False + + # Traverse all elements + for i in range(0, n): + + # Check if this is + # first occurrence + if (visited[i] == False): + + # If yes, print it and + # all subsequent occurrences + print(arr[i], end = "" "") + for j in range(i + 1, n): + + if (arr[i] == arr[j]): + + print(arr[i], end = "" "") + visited[j] = True + +# Driver Code +arr = [4, 6, 9, 2, 3, + 4, 9, 6, 10, 4] +n = len(arr) +groupElements(arr, n) + +# This code is contributed +# by Smitha",linear,quadratic +"# Python3 program to group multiple +# occurrences of individual array elements + +# A hashing based method to group +# all occurrences of individual elements +def orderedGroup(arr): + + # Creates an empty hashmap + hM = {} + + # Traverse the array elements, and store + # count for every element in HashMap + for i in range(0, len(arr)): + + # Increment count of elements + # in HashMap + hM[arr[i]] = hM.get(arr[i], 0) + 1 + + # Traverse array again + for i in range(0, len(arr)): + + # Check if this is first occurrence + count = hM.get(arr[i], None) + if count != None: + + # If yes, then print + # the element 'count' times + for j in range(0, count): + print(arr[i], end = "" "") + + # And remove the element from HashMap. + del hM[arr[i]] + +# Driver Code +if __name__ == ""__main__"": + + arr = [10, 5, 3, 10, 10, 4, 1, 3] + orderedGroup(arr) + +# This code is contributed by Rituraj Jain",linear,linear +"# A Simple python 3 program to check +# if two sets are disjoint + +# Returns true if set1[] and set2[] are disjoint, else false +def areDisjoint(set1, set2, m, n): + # Take every element of set1[] and search it in set2 + for i in range(0, m): + for j in range(0, n): + if (set1[i] == set2[j]): + return False + + # If no element of set1 is present in set2 + return True + + +# Driver program +set1 = [12, 34, 11, 9, 3] +set2 = [7, 2, 1, 5] +m = len(set1) +n = len(set2) +print(""yes"") if areDisjoint(set1, set2, m, n) else("" No"") + +# This code ia contributed by Smitha Dinesh Semwal",constant,quadratic +"# A Simple Python 3 program to check +# if two sets are disjoint + +# Returns true if set1[] and set2[] +# are disjoint, else false +def areDisjoint(set1, set2, m, n): + # Sort the given two sets + set1.sort() + set2.sort() + + # Check for same elements + # using merge like process + i = 0; j = 0 + while (i < m and j < n): + + if (set1[i] < set2[j]): + i += 1 + elif (set2[j] < set1[i]): + j += 1 + else: # if set1[i] == set2[j] + return False + return True + + +# Driver Code +set1 = [12, 34, 11, 9, 3] +set2 = [7, 2, 1, 5] +m = len(set1) +n = len(set2) + +print(""Yes"") if areDisjoint(set1, set2, m, n) else print(""No"") + +# This code is contributed by Smitha Dinesh Semwal",constant,nlogn +"# Python3 program to +# check if two sets are +# distinct or not +# This function prints +# all distinct elements +def areDisjoint(set1, set2, + n1, n2): + + # Creates an empty hashset + myset = set([]) + + # Traverse the first set + # and store its elements in hash + for i in range (n1): + myset.add(set1[i]) + + # Traverse the second set + # and check if any element of it + # is already in hash or not. + for i in range (n2): + if (set2[i] in myset): + return False + return True + +# Driver method to test above method +if __name__ == ""__main__"": + + set1 = [10, 5, 3, 4, 6] + set2 = [8, 7, 9, 3] + + n1 = len(set1) + n2 = len(set2) + + if (areDisjoint(set1, set2, + n1, n2)): + print (""Yes"") + else: + print(""No"") + +# This code is contributed by Chitranayal",linear,linear +"# Python3 program to find Non-overlapping sum +from collections import defaultdict + +# Function for calculating +# Non-overlapping sum of two array +def findSum(A, B, n): + + # Insert elements of both arrays + Hash = defaultdict(lambda:0) + for i in range(0, n): + Hash[A[i]] += 1 + Hash[B[i]] += 1 + + # calculate non-overlapped sum + Sum = 0 + for x in Hash: + if Hash[x] == 1: + Sum += x + + return Sum + +# Driver code +if __name__ == ""__main__"": + + A = [5, 4, 9, 2, 3] + B = [2, 8, 7, 6, 3] + + # size of array + n = len(A) + + # Function call + print(findSum(A, B, n)) + +# This code is contributed +# by Rituraj Jain",linear,linear +"# Python 3 simple program to find elements +# which are not present in second array + +# Function for finding elements which +# are there in a[] but not in b[]. +def findMissing(a, b, n, m): + + for i in range(n): + for j in range(m): + if (a[i] == b[j]): + break + + if (j == m - 1): + print(a[i], end = "" "") + +# Driver code +if __name__ == ""__main__"": + + a = [ 1, 2, 6, 3, 4, 5 ] + b = [ 2, 4, 3, 1, 0 ] + n = len(a) + m = len(b) + findMissing(a, b, n, m) + +# This code is contributed +# by ChitraNayal",constant,quadratic +"# Python3 efficient program to find elements +# which are not present in second array + +# Function for finding elements which +# are there in a[] but not in b[]. +def findMissing(a, b, n, m): + + # Store all elements of second + # array in a hash table + s = dict() + for i in range(m): + s[b[i]] = 1 + + # Print all elements of first array + # that are not present in hash table + for i in range(n): + if a[i] not in s.keys(): + print(a[i], end = "" "") + +# Driver code +a = [ 1, 2, 6, 3, 4, 5 ] +b = [ 2, 4, 3, 1, 0 ] +n = len(a) +m = len(b) +findMissing(a, b, n, m) + +# This code is contributed by mohit kumar",linear,linear +"# Python3 program to find given +# two array are equal or not + +# Returns true if arr1[0..n-1] and +# arr2[0..m-1] contain same elements. + + +def areEqual(arr1, arr2, N, M): + + # If lengths of array are not + # equal means array are not equal + if (N != M): + return False + + # Sort both arrays + arr1.sort() + arr2.sort() + + # Linearly compare elements + for i in range(0, N): + if (arr1[i] != arr2[i]): + return False + + # If all elements were same. + return True + + +# Driver Code +if __name__ == ""__main__"": + arr1 = [3, 5, 2, 5, 2] + arr2 = [2, 3, 5, 5, 2] + n = len(arr1) + m = len(arr2) + + if (areEqual(arr1, arr2, n, m)): + print(""Yes"") + else: + print(""No"")",constant,nlogn +"# Python3 program for the above approach + +# Returns true if arr1[0..N-1] and +# arr2[0..M-1] contain same elements. + + +def is_arr_equal(arr1, arr2): + # Check if the length of arrays are + # equal or not: A Easy Logic Check + if len(arr1) != len(arr2): + return False + + # Create a dict named count to + # store counts of each element + count = {} + # Store the elements of arr1 + # and their counts in the dictionary + for i in arr1: + if i in count: + # Element already in dict, simply increment its count + count[i] += 1 + else: + # Element found for first time, initialize it with value 1. + count[i] = 1 + + # Traverse through arr2 and compare + # the elements and its count with + # the elements of arr1 + for i in arr2: + # Return false if the element + # is not in count or if any element + # appears more no. of times than in arr1 + if i not in count or count[i] == 0: + return False + else: + # If element is found, decrement + # its value in the dictionary + count[i] -= 1 + # Return true if both arr1 and + # arr2 are equal + return True + + +# Driver Code +if __name__ == ""__main__"": + arr1 = [3, 5, 2, 5, 2] + arr2 = [2, 3, 5, 5, 2] + + if is_arr_equal(arr1, arr2): + print(""Yes"") + else: + print(""No"")",linear,linear +"# Python3 code to find maximum shortest +# distance from endpoints + +# function to find maximum shortest distance +def find_maximum(a, n, k): + + # stores the shortest distance of every + # element in original array. + b = dict() + + for i in range(n): + x = a[i] + + # shortest distance from ends + d = min(1 + i, n - i) + if x not in b.keys(): + b[x] = d + else: + + # if duplicates are found, b[x] + # is replaced with minimum of the + # previous and current position's + # shortest distance*/ + b[x] = min(d, b[x]) + + ans = 10**9 + for i in range(n): + x = a[i] + + # similar elements ignore them + # cause we need distinct elements + if (x != (k - x) and (k - x) in b.keys()): + ans = min(max(b[x], b[k - x]), ans) + + return ans + +# Driver code +a = [3, 5, 8, 6, 7] +K = 11 +n = len(a) +print(find_maximum(a, n, K)) + +# This code is contributed by mohit kumar",linear,linear +"# Python library for binary search +from bisect import bisect_left + +# A sorting based C++ program to find missing +# elements from an array + +# Print all elements of range [low, high] that +# are not present in arr[0..n-1] + +def printMissing(arr, n, low, high): + + # Sort the array + arr.sort() + + # Do binary search for 'low' in sorted + # array and find index of first element + # which either equal to or greater than + # low. + ptr = bisect_left(arr, low) + index = ptr + + # Start from the found index and linearly + # search every range element x after this + # index in arr[] + i = index + x = low + while (i < n and x <= high): + # If x doesn't match with current element + # print it + if(arr[i] != x): + print(x, end ="" "") + + # If x matches, move to next element in arr[] + else: + i = i + 1 + # Move to next element in range [low, high] + x = x + 1 + + # Print range elements that are greater than the + # last element of sorted array. + while (x <= high): + print(x, end ="" "") + x = x + 1 + + +# Driver code + +arr = [1, 3, 5, 4] +n = len(arr) +low = 1 +high = 10 +printMissing(arr, n, low, high); + +# This code is contributed by YatinGupta",linear,nlogn +"# An array-based Python3 program to +# find missing elements from an array + +# Print all elements of range +# [low, high] that are not +# present in arr[0..n-1] +def printMissing(arr, n, low, high): + + # Create boolean list of size + # high-low+1, each index i + # representing whether (i+low)th + # element found or not. + points_of_range = [False] * (high-low+1) + + for i in range(n) : + # if ith element of arr is in range + # low to high then mark corresponding + # index as true in array + if ( low <= arr[i] and arr[i] <= high ) : + points_of_range[arr[i]-low] = True + + # Traverse through the range + # and print all elements whose value + # is false + for x in range(high-low+1) : + if (points_of_range[x]==False) : + print(low+x, end = "" "") + +# Driver Code +arr = [1, 3, 5, 4] +n = len(arr) +low, high = 1, 10 +printMissing(arr, n, low, high) + +# This code is contributed +# by Shubh Bansal",linear,linear +"# A hashing based Python3 program to +# find missing elements from an array + +# Print all elements of range +# [low, high] that are not +# present in arr[0..n-1] +def printMissing(arr, n, low, high): + + # Insert all elements of + # arr[] in set + s = set(arr) + + # Traverse through the range + # and print all missing elements + for x in range(low, high + 1): + if x not in s: + print(x, end = ' ') + +# Driver Code +arr = [1, 3, 5, 4] +n = len(arr) +low, high = 1, 10 +printMissing(arr, n, low, high) + +# This code is contributed +# by SamyuktaSHegde",linear,linear +"# Python3 program to find the k-th +# missing element in a given sequence + + +# Returns k-th missing element. It returns -1 if +# no k is more than number of missing elements. +def find(a, b, k, n1, n2): + + # insert all elements of + # given sequence b[]. + s = set() + + for i in range(n2): + s.add(b[i]) + + # Traverse through increasing sequence and + # keep track of count of missing numbers. + missing = 0 + for i in range(n1): + if a[i] not in s: + missing += 1 + if missing == k: + return a[i] + return -1 + +# Driver code +a = [0, 2, 4, 6, 8, 10, 12, 14, 15] +b = [4, 10, 6, 8, 12] +n1 = len(a) +n2 = len(b) +k = 3 +print(find(a, b, k, n1, n2)) + +# This code is contributed by Shrikant13",quadratic,linear +"# Python 3 program to find a pair +# with product in given array. + +# Function to find greatest number +def findGreatest( arr , n): + + result = -1 + for i in range(n): + for j in range(n - 1): + for k in range(j + 1, n): + if (arr[j] * arr[k] == arr[i]): + result = max(result, arr[i]) + return result + +# Driver code +if __name__ == ""__main__"": + + arr = [10, 3, 5, 30, 35] + n = len(arr) + + print(findGreatest(arr, n)) + +# This code is contributed by ita_c",constant,cubic +"# Python3 program to find the largest product number +from math import sqrt + +# Function to find greatest number + + +def findGreatest(arr, n): + + # Store occurrences of all elements in hash + # array + m = dict() + + for i in arr: + m[i] = m.get(i, 0) + 1 + + # Sort the array and traverse all elements from + # end. + arr = sorted(arr) + + for i in range(n - 1, 0, -1): + + # For every element, check if there is another + # element which divides it. + j = 0 + while(j < i and arr[j] <= sqrt(arr[i])): + + if (arr[i] % arr[j] == 0): + + result = arr[i]//arr[j] + + # Check if the result value exists in array + # or not if yes the return arr[i] + if (result != arr[j] and (result in m.keys())and m[result] > 0): + return arr[i] + + # To handle the case like arr[i] = 4 and + # arr[j] = 2 + elif (result == arr[j] and (result in m.keys()) and m[result] > 1): + return arr[i] + + j += 1 + + return -1 + + +# Drivers code +arr = [10, 3, 5, 30, 35] +n = len(arr) +print(findGreatest(arr, n)) + +# This code is contributed by mohit kumar",linear,nlogn +"# A sorting based solution to find the +# minimum number of subsets of a set +# such that every subset contains distinct +# elements. + +# function to count subsets such that all +# subsets have distinct elements. +def subset(ar, n): + + # take input and initialize res = 0 + res = 0 + + # sort the array + ar.sort() + + # traverse the input array and + # find maximum frequency + for i in range(0, n) : + count = 1 + + # for each number find its repetition / frequency + for i in range(n - 1): + if ar[i] == ar[i + 1]: + count+=1 + else: + break + + # update res + res = max(res, count) + + return res + + +# Driver code +ar = [ 5, 6, 9, 3, 4, 3, 4 ] +n = len(ar) +print(subset(ar, n)) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,quadratic +"# A hashing based solution to find the +# minimum number of subsets of a set such +# that every subset contains distinct +# elements. + +# Function to count subsets such that +# all subsets have distinct elements. +def subset(arr, n): + + # Traverse the input array and + # store frequencies of elements + mp = {i:0 for i in range(10)} + for i in range(n): + mp[arr[i]] += 1 + + # Find the maximum value in map. + res = 0 + for key, value in mp.items(): + res = max(res, value) + + return res + +# Driver code +if __name__ == '__main__': + arr = [5, 6, 9, 3, 4, 3, 4] + n = len(arr) + print(subset(arr, n)) + +# This code is contributed by +# Surendra_Gangwar",linear,linear +"# Python3 program to find minimum +# element to remove so no common +# element exist in both array + +# To find no elements to remove +# so no common element exist +def minRemove(a, b, n, m): + + # To store count of array element + countA = dict() + countB = dict() + + # Count elements of a + for i in range(n): + countA[a[i]] = countA.get(a[i], 0) + 1 + + # Count elements of b + for i in range(n): + countB[b[i]] = countB.get(b[i], 0) + 1 + + # Traverse through all common + # element, and pick minimum + # occurrence from two arrays + res = 0 + for x in countA: + if x in countB.keys(): + res += min(countA[x],countB[x]) + + # To return count of + # minimum elements + return res + +# Driver Code +a = [ 1, 2, 3, 4 ] +b = [2, 3, 4, 5, 8 ] +n = len(a) +m = len(b) +print(minRemove(a, b, n, m)) + +# This code is contributed +# by mohit kumar",linear,linear +"# Python implementation to +# count items common to both +# the lists but with different +# prices + +# function to count items +# common to both +# the lists but with different prices +def countItems(list1, list2): + count = 0 + + # for each item of 'list1' + # check if it is in 'list2' + # but with a different price + for i in list1: + for j in list2: + + if i[0] == j[0] and i[1] != j[1]: + count += 1 + + # required count of items + return count + +# Driver program to test above +list1 = [(""apple"", 60), (""bread"", 20), + (""wheat"", 50), (""oil"", 30)] +list2 = [(""milk"", 20), (""bread"", 15), + (""wheat"", 40), (""apple"", 60)] + +print(""Count = "", countItems(list1, list2)) + +# This code is contributed by Ansu Kumari.",constant,quadratic +"# Python3 implementation to count +# items common to both the lists +# but with different prices + +# Details of an item +from ast import Str +from functools import cmp_to_key + +class item: + def __init__(self, name, price): + self.name = name + self.price = price + +# Function to search 'str' in 'list2[]'. +# If it exists then price associated +# with 'str' in 'list2[]' is being +# returned else -1 is returned. Here +# binary search technique is being +# applied for searching +def binary_search(list2, low, high, str): + while (low <= high): + mid = ((low + high) // 2) + + # if true the item 'str' is in 'list2' + # print(list2[mid].name,str) + if (list2[mid].name == str): + return list2[mid].price + elif (list2[mid].name < str): + low = mid + 1 + else: + high = mid - 1 + + # item 'str' is not + # in 'list2' + return -1 + +# Function to count items common to both +# the lists but with different prices +def custom_logic(a, b): + return a.name == b.name + +def countItems(list1, m, list2, n): + + # sort 'list2' in alphabetical + # order of items name + sorted(list2,key=cmp_to_key(custom_logic)) + + # initial count + count = 0 + + for i in range(m): + + # get the price of item 'list1[i]' + # from 'list2' if item in not + # present in second list then -1 + # is being obtained + r = binary_search(list2, 0, + n - 1, + list1[i].name) + + # if item is present in list2 + # with a different price + if ((r != -1) and (r != list1[i].price)): + count += 1 + + # Required count of items + return count + +# Driver code +list1=[item(""apple"", 60), + item(""bread"", 20), + item(""wheat"", 50), + item(""oil"", 30)] +list2=[item(""milk"", 20), + item(""bread"", 15), + item(""wheat"", 40), + item(""apple"", 60)] +m = len(list1) +n = len(list2) +print(f""Count = {countItems(list1, m,list2, n)}"") + +# This code is contributed by shinjanpatra",constant,nlogn +"# Python3 implementation to count items common to both +# the lists but with different prices + +# details of an item +class item: + def __init__(self, name, price): + self.name = name + self.price = price + +# function to count items common to both +# the lists but with different prices +def countItems(list1, m,list2, n): + + # 'um' implemented as hash table that contains + # item name as the key and price as the value + # associated with the key + um = {} + count = 0 + + # insert elements of 'list1' in 'um' + for i in range(m): + um[list1[i].name] = list1[i].price; + + # for each element of 'list2' check if it is + # present in 'um' with a different price + # value + for i in range(n): + if ((um.get(list2[i].name) != None) and (um[list2[i].name] != list2[i].price)): + count+=1 + + # required count of items + return count + + +# Driver program to test above +list1=[item(""apple"", 60), + item(""bread"", 20), + item(""wheat"", 50), + item(""oil"", 30)] +list2=[item(""milk"", 20), + item(""bread"", 15), + item(""wheat"", 40), + item(""apple"", 60)] +m = len(list1) +n = len(list2) + +print(""Count = "" ,countItems(list1, m, list2, n)) + + +# This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear +"# Function to print common strings +# with minimum index sum +def find(list1, list2): + res = [] # resultant list + max_possible_sum = len(list1) + len(list2) - 2 + + # iterating over sum in ascending order + for sum in range(max_possible_sum + 1): + + # iterating over one list and check index + # (Corresponding to given sum) in other list + for i in range(sum + 1): + + # put common strings in resultant list + if (i < len(list1) and + (sum - i) < len(list2) and + list1[i] == list2[sum - i]): + res.append(list1[i]) + + # if common string found then break as we are + # considering index sums in increasing order. + if (len(res) > 0): + break + + # print the resultant list + for i in range(len(res)): + print(res[i], end = "" "") + +# Driver code + +# Creating list1 +list1 = [] +list1.append(""GeeksforGeeks"") +list1.append(""Udemy"") +list1.append(""Coursera"") +list1.append(""edX"") + +# Creating list2 +list2 = [] +list2.append(""Codecademy"") +list2.append(""Khan Academy"") +list2.append(""GeeksforGeeks"") + +find(list1, list2) + +# This code is contributed by Mohit Kumar",linear,linear +"# Hashing based Python3 program to find +# common elements with minimum index sum +import sys + +# Function to print common strings +# with minimum index sum +def find(list1, list2): + + # Mapping strings to their indices + Map = {} + for i in range(len(list1)): + Map[list1[i]] = i + + # Resultant list + res = [] + + minsum = sys.maxsize + + for j in range(len(list2)): + if list2[j] in Map: + + # If current sum is smaller + # than minsum + Sum = j + Map[list2[j]] + + if (Sum < minsum): + minsum = Sum + res.clear() + res.append(list2[j]) + + # If index sum is same then put this + # string in resultant list as well + else if (Sum == minsum): + res.append(list2[j]) + + # Print result + print(*res, sep = "" "") + +# Driver code + +# Creating list1 +list1 = [] +list1.append(""GeeksforGeeks"") +list1.append(""Udemy"") +list1.append(""Coursera"") +list1.append(""edX"") + +# Creating list2 +list2 = [] +list2.append(""Codecademy"") +list2.append(""Khan Academy"") +list2.append(""GeeksforGeeks"") +find(list1, list2) + +# This code is contributed by avanitrachhadiya2155",linear,linear +"# Python 3 program to find a pair with +# given sum such that every element of +# pair is in different rows. +MAX = 100 + +# Function to find pair for given +# sum in matrix mat[][] --> given matrix +# n --> order of matrix +# sum --> given sum for which we +# need to find pair +def pairSum(mat, n, sum): + + # First sort all the rows + # in ascending order + for i in range(n): + mat[i].sort() + + # Select i'th row and find pair for + # element in i'th row in j'th row + # whose summation is equal to given sum + for i in range(n - 1): + for j in range(i + 1, n): + left = 0 + right = n - 1 + while (left < n and right >= 0): + if ((mat[i][left] + mat[j][right]) == sum): + print( ""("", mat[i][left], + "", "", mat[j][right], ""), "", + end = "" "") + left += 1 + right -= 1 + + else: + if ((mat[i][left] + + mat[j][right]) < sum): + left += 1 + else: + right -= 1 + +# Driver Code +if __name__ == ""__main__"": + n = 4 + sum = 11 + mat = [[1, 3, 2, 4], + [5, 8, 7, 6], + [9, 10, 13, 11], + [12, 0, 14, 15]] + pairSum(mat, n, sum) + +# This code is contributed +# by ChitraNayal",constant,cubic +"# A Program to prints common element +# in all rows of matrix + +# Specify number of rows and columns +M = 4 +N = 5 + +# prints common element in all +# rows of matrix +def printCommonElements(mat): + + mp = dict() + + # initialize 1st row elements + # with value 1 + for j in range(N): + mp[mat[0][j]] = 1 + + # traverse the matrix + for i in range(1, M): + for j in range(N): + + # If element is present in the + # map and is not duplicated in + # current row. + if (mat[i][j] in mp.keys() and + mp[mat[i][j]] == i): + + # we increment count of the + # element in map by 1 + mp[mat[i][j]] = i + 1 + + # If this is last row + if i == M - 1: + print(mat[i][j], end = "" "") + +# Driver Code +mat = [[1, 2, 1, 4, 8], + [3, 7, 8, 5, 1], + [8, 7, 7, 3, 1], + [8, 1, 2, 7, 9]] + +printCommonElements(mat) + +# This code is contributed +# by mohit kumar 29",linear,quadratic +"# Python program to find all +# permutations of a given row + +# Function to find all +# permuted rows of a given row r +def permutatedRows(mat, m, n, r): + + + # Creating an empty set + s=set() + + # Count frequencies of + # elements in given row r + for j in range(n): + s.add(mat[r][j]) + + # Traverse through all remaining rows + for i in range(m): + + # we do not need to check + # for given row r + if i == r: + continue + + # initialize hash i.e + # count frequencies + # of elements in row i + for j in range(n): + if mat[i][j] not in s: + + # to avoid the case when last + # element does not match + j = j - 2 + break; + if j + 1 != n: + continue + print(i) + + + +# Driver program to run the case +m = 4 +n = 4 +r = 3 +mat = [[3, 1, 4, 2], + [1, 6, 9, 3], + [1, 2, 3, 4], + [4, 3, 2, 1]] + +permutatedRows(mat, m, n, r) + +# This code is contributed +# by Upendra Singh Bartwal.",linear,quadratic +"# Python3 code to make a permutation +# of numbers from 1 to n using +# minimum changes. + +def makePermutation (a, n): + + # Store counts of all elements. + count = dict() + for i in range(n): + if count.get(a[i]): + count[a[i]] += 1 + else: + count[a[i]] = 1; + + next_missing = 1 + for i in range(n): + if count[a[i]] != 1 or a[i] > n or a[i] < 1: + count[a[i]] -= 1 + + # Find next missing element to put + # in place of current element. + while count.get(next_missing): + next_missing+=1 + + # Replace with next missing and + # insert the missing element in hash. + a[i] = next_missing + count[next_missing] = 1 + +# Driver Code +A = [ 2, 2, 3, 3 ] +n = len(A) +makePermutation(A, n) + +for i in range(n): + print(A[i], end = "" "") + +# This code is contributed by ""Sharad_Bhardwaj"".",linear,nlogn +"# Python3 implementation of simple method +# to find count of pairs with given sum. + +# Returns number of pairs in arr[0..n-1] +# with sum equal to 'sum' + + +def getPairsCount(arr, n, sum): + + count = 0 # Initialize result + + # Consider all possible pairs + # and check their sums + for i in range(0, n): + for j in range(i + 1, n): + if arr[i] + arr[j] == sum: + count += 1 + + return count + + +# Driver function +arr = [1, 5, 7, -1, 5] +n = len(arr) +sum = 6 +print(""Count of pairs is"", + getPairsCount(arr, n, sum)) + +# This code is contributed by Smitha Dinesh Semwal",constant,quadratic +"# Python code to implement the approach +import bisect + +# Function to find the count of pairs + + +def getPairsCount(arr, n, k): + arr.sort() + x, c = 0, 0 + for i in range(n-1): + x = k-arr[i] + + # Lower bound from i+1 + y = bisect.bisect_left(arr, x, i+1, n) + + # Upper bound from i+1 + z = bisect.bisect(arr, x, i+1, n) + c = c+z-y + return c + + +# Driver function +arr = [1, 5, 7, -1, 5] +n = len(arr) +k = 6 + +# Function call +print(""Count of pairs is"", getPairsCount(arr, n, k)) + +# This code is contributed by Pushpesh Raj",constant,nlogn +"# Python 3 implementation of simple method +# to find count of pairs with given sum. +import sys + +# Returns number of pairs in arr[0..n-1] +# with sum equal to 'sum' + + +def getPairsCount(arr, n, sum): + + m = [0] * 1000 + + # Store counts of all elements in map m + for i in range(0, n): + m[arr[i]] += 1 + + twice_count = 0 + + # Iterate through each element and increment + # the count (Notice that every pair is + # counted twice) + for i in range(0, n): + + twice_count += m[sum - arr[i]] + + # if (arr[i], arr[i]) pair satisfies the + # condition, then we need to ensure that + # the count is decreased by one such + # that the (arr[i], arr[i]) pair is not + # considered + if (sum - arr[i] == arr[i]): + twice_count -= 1 + + # return the half of twice_count + return int(twice_count / 2) + + +# Driver function +arr = [1, 5, 7, -1, 5] +n = len(arr) +sum = 6 + +print(""Count of pairs is"", getPairsCount(arr, + n, sum)) + +# This code is contributed by +# Smitha Dinesh Semwal",linear,linear +"# Python implementation of simple method to find count of +# pairs with given sum. + +# Returns number of pairs in arr[0..n-1] with sum equal to 'sum' + + +def getPairsCount(arr, n, sum): + unordered_map = {} + count = 0 + for i in range(n): + if sum - arr[i] in unordered_map: + count += unordered_map[sum - arr[i]] + if arr[i] in unordered_map: + unordered_map[arr[i]] += 1 + else: + unordered_map[arr[i]] = 1 + return count + + +# Driver code +arr = [1, 5, 7, -1, 5] +n = len(arr) +sum = 6 +print('Count of pairs is', getPairsCount(arr, n, sum)) + +# This code is contributed by Manish Thapa",linear,linear +"# A Python3 implementation to count +# quadruples from four sorted arrays +# whose sum is equal to a given value x + +# function to count all quadruples +# from four sorted arrays whose sum +# is equal to a given value x +def countquadruples(arr1, arr2, + arr3, arr4, n, x): + count = 0 + + # generate all possible + # quadruples from the four + # sorted arrays + for i in range(n): + for j in range(n): + for k in range(n): + for l in range(n): + + # check whether elements of + # quadruple sum up to x or not + if (arr1[i] + arr2[j] + + arr3[k] + arr4[l] == x): + count += 1 + + # required count of quadruples + return count + +# Driver Code +arr1 = [1, 4, 5, 6] +arr2 = [2, 3, 7, 8] +arr3 = [1, 4, 6, 10] +arr4 = [2, 4, 7, 8 ] +n = len(arr1) +x = 30 +print(""Count = "", countquadruples(arr1, arr2, + arr3, arr4, n, x)) + +# This code is contributed +# by Shrikant13",constant,np +"# Python implementation to count quadruples from +# four sorted arrays whose sum is equal to a +# given value x + +# find the 'value' in the given array 'arr[]' +# binary search technique is applied +def isPresent(arr,low,high,value): + while(low<=high): + mid=(low+high)//2 + # 'value' found + if(arr[mid]==value): + return True + elif(arr[mid]>value): + high=mid-1 + else: + low=mid+1 + # 'value' not found + return False + +# function to count all quadruples from four +# sorted arrays whose sum is equal to a given value x + +def countQuadruples(arr1,arr2,arr3,arr4,n,x): + count=0 + + #generate all triplets from the 1st three arrays + for i in range(n): + for j in range(n): + for k in range(n): + # calculate the sum of elements in + # the triplet so generated + T=arr1[i]+arr2[j]+arr3[k] + + # check if 'x-T' is present in 4th + # array or not + if(isPresent(arr4,0,n-1,x-T)): + # increment count + count=count+1 + # required count of quadruples + return count + +# Driver program to test above + +# four sorted arrays each of size 'n' +arr1=[1, 4, 5, 6] +arr2=[2, 3, 7, 8] +arr3=[1, 4, 6, 10] +arr4=[2, 4, 7, 8] + +n=len(arr1) +x=30 +print(""Count = {}"".format(countQuadruples(arr1,arr2,arr3,arr4,n,x))) + +# This code is contributed by Pushpesh Raj.",constant,cubic +"# Python3 implementation to +# count quadruples from four +# sorted arrays whose sum is +# equal to a given value x +# count pairs from the two +# sorted array whose sum +# is equal to the given 'value' +def countPairs(arr1, arr2, + n, value): + + count = 0 + l = 0 + r = n - 1 + + # traverse 'arr1[]' from + # left to right + # traverse 'arr2[]' from + # right to left + while (l < n and r >= 0): + sum = arr1[l] + arr2[r] + + # if the 'sum' is equal + # to 'value', then + # increment 'l', decrement + # 'r' and increment 'count' + if (sum == value): + l += 1 + r -= 1 + count += 1 + + # if the 'sum' is greater + # than 'value', then decrement r + elif (sum > value): + r -= 1 + + # else increment l + else: + l += 1 + + # required count of pairs + # print(count) + return count + +# function to count all quadruples +# from four sorted arrays whose sum +# is equal to a given value x +def countQuadruples(arr1, arr2, + arr3, arr4, + n, x): + count = 0 + + # generate all pairs from + # arr1[] and arr2[] + for i in range(0, n): + for j in range(0, n): + + # calculate the sum of + # elements in the pair + # so generated + p_sum = arr1[i] + arr2[j] + + # count pairs in the 3rd + # and 4th array having + # value 'x-p_sum' and then + # accumulate it to 'count + count += int(countPairs(arr3, arr4, + n, x - p_sum)) + # required count of quadruples + return count + +# Driver code +arr1 = [1, 4, 5, 6] +arr2 = [2, 3, 7, 8] +arr3 = [1, 4, 6, 10] +arr4 = [2, 4, 7, 8] +n = len(arr1) +x = 30 +print(""Count = "", countQuadruples(arr1, arr2, + arr3, arr4, + n, x)) + +# This code is contributed by Stream_Cipher",constant,cubic +"# Python implementation to count quadruples from +# four sorted arrays whose sum is equal to a +# given value x + +# function to count all quadruples from four sorted +# arrays whose sum is equal to a given value x +def countQuadruples(arr1, arr2, arr3, arr4, n, x): + count = 0 + + # unordered_map 'um' implemented as hash table + # for tuples + m = {} + + # count frequency of each sum obtained from the + # pairs of arr1[] and arr2[] and store them in 'um' + for i in range(n): + for j in range(n): + if (arr1[i] + arr2[j]) in m: + m[arr1[i] + arr2[j]] += 1 + else: + m[arr1[i] + arr2[j]] = 1 + + # generate pair from arr3[] and arr4[] + for k in range(n): + for l in range(n): + + # calculate the sum of elements in + # the pair so generated + p_sum = arr3[k] + arr4[l] + + # if 'x-p_sum' is present in 'um' then + # add frequency of 'x-p_sum' to 'count' + if (x - p_sum) in m: + count += m[x - p_sum] + + # required count of quadruples + return count + +# Driver program to test above + +# four sorted arrays each of size 'n' +arr1 = [1, 4, 5, 6] +arr2 = [2, 3, 7, 8 ] +arr3 = [1, 4, 6, 10] +arr4 = [2, 4, 7, 8 ] + +n = len(arr1) +x = 30 +print(""Count ="", countQuadruples(arr1, arr2, arr3, arr4, n, x)) + +# This code is contributed by avanitrachhadiya2155",quadratic,quadratic +"# Python3 program for +# the above approach +arr = [ 10, 2, -2, -20, 10 ] +n = len(arr) +k = -10 +res = 0 + +# Calculate all subarrays +for i in range(n): + summ = 0 + for j in range(i, n): + + # Calculate required sum + summ += arr[j] + + # Check if sum is equal to + # required sum + if summ == k: + res += 1 + +print(res) + +# This code is contributed by kavan155gondalia",constant,quadratic +"# Python3 program to find the number of +# subarrays with sum exactly equal to k. +from collections import defaultdict + +# Function to find number of subarrays +# with sum exactly equal to k. +def findSubarraySum(arr, n, Sum): + + # Dictionary to store number of subarrays + # starting from index zero having + # particular value of sum. + prevSum = defaultdict(lambda : 0) + + res = 0 + + # Sum of elements so far. + currsum = 0 + + for i in range(0, n): + + # Add current element to sum so far. + currsum += arr[i] + + # If currsum is equal to desired sum, + # then a new subarray is found. So + # increase count of subarrays. + if currsum == Sum: + res += 1 + + # currsum exceeds given sum by currsum - sum. + # Find number of subarrays having + # this sum and exclude those subarrays + # from currsum by increasing count by + # same amount. + if (currsum - Sum) in prevSum: + res += prevSum[currsum - Sum] + + + # Add currsum value to count of + # different values of sum. + prevSum[currsum] += 1 + + return res + +if __name__ == ""__main__"": + + arr = [10, 2, -2, -20, 10] + Sum = -10 + n = len(arr) + print(findSubarraySum(arr, n, Sum)) + +# This code is contributed by Rituraj Jain",linear,linear +"# Python 3 program to find all +# pairs in both arrays whose +# sum is equal to given value x + +# Function to print all pairs +# in both arrays whose sum is +# equal to given value x +def findPairs(arr1, arr2, n, m, x): + + for i in range(0, n): + for j in range(0, m): + if (arr1[i] + arr2[j] == x): + print(arr1[i], arr2[j]) + +# Driver code +arr1 = [1, 2, 3, 7, 5, 4] +arr2 = [0, 7, 4, 3, 2, 1] +n = len(arr1) +m = len(arr2) +x = 8 +findPairs(arr1, arr2, n, m, x) + +# This code is contributed by Smitha Dinesh Semwal",constant,quadratic +"# Python3 program to find all +# pair in both arrays whose +# sum is equal to given value x + +# Function to find all pairs +# in both arrays whose sum is +# equal to given value x +def findPairs(arr1, arr2, n, m, x): + + # Insert all elements of + # first array in a hash + s = set() + for i in range (0, n): + s.add(arr1[i]) + + # Subtract sum from second + # array elements one by one + # and check it's present in + # array first or not + for j in range(0, m): + if ((x - arr2[j]) in s): + print((x - arr2[j]), '', arr2[j]) + +# Driver code +arr1 = [1, 0, -4, 7, 6, 4] +arr2 = [0, 2, 4, -3, 2, 1] +x = 8 + +n = len(arr1) +m = len(arr2) +findPairs(arr1, arr2, n, m, x) + +# This code is contributed +# by ihritik",linear,linear +"# Python3 program to count cumulative +# frequencies of elements in an unsorted array. +def countFreq(a, n): + + # Insert elements and their + # frequencies in hash map. + hm = {} + for i in range(0, n): + hm[a[i]] = hm.get(a[i], 0) + 1 + + # Declare a set + st = set() + + # Insert the element and + # its frequency in a set + for x in hm: + st.add((x, hm[x])) + + cumul = 0 + + # Iterate the set and print + # the cumulative frequency + for x in sorted(st): + cumul += x[1] + print(x[0], cumul) + +# Driver Code +if __name__ == ""__main__"": + + a = [1, 3, 2, 4, 2, 1] + n = len(a) + countFreq(a, n) + +# This code is contributed by Rituraj Jain",linear,nlogn +"# Python3 program to print the cumulative +# frequency according to the order given + +# Function to print the cumulative frequency +# according to the order given +def countFreq(a, n): + + # Insert elements and their + # frequencies in hash map. + hm = dict() + for i in range(n): + hm[a[i]] = hm.get(a[i], 0) + 1 + + cumul = 0 + + # traverse in the array + for i in range(n): + + # add the frequencies + cumul += hm[a[i]] + + # if the element has not been + # visited previously + if(hm[a[i]] > 0): + print(a[i], ""->"", cumul) + + # mark the hash 0 + # as the element's cumulative + # frequency has been printed + hm[a[i]] = 0 + +# Driver Code +a = [1, 3, 2, 4, 2, 1] +n = len(a) +countFreq(a, n) + +# This code is contributed by mohit kumar",linear,linear +"# Used for sorting by frequency. And if frequency is same, +# then by appearance +from functools import cmp_to_key + +def sortByVal(a,b): + + # If frequency is same then sort by index + if (a[1] == b[1]): + return a[0] - b[0] + + return b[1] - a[1] + +# function to sort elements by frequency +def sortByFreq(a, n): + res = [] + m = {} + v = [] + + for i in range(n): + + # Map m is used to keep track of count + # of elements in array + if(a[i] in m): + m[a[i]] = m[a[i]]+1 + else: + m[a[i]] = 1 + + for key,value in m.items(): + v.append([key,value]) + + # Sort the element of array by frequency + v.sort(key = cmp_to_key(sortByVal)) + + for i in range(len(v)): + while(v[i][1]): + res.append(v[i][0]) + v[i][1] -= 1 + + return res + + +# Driver program + +a = [ 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 ] +n = len(a) +res = [] +res = sortByFreq(a, n) + +for i in range(len(res)): + print(res[i],end = "" "") + + +# This code is contributed by shinjanpatra",linear,linear +"# A simple python program to find pair +# whose sum already exists in array + +# Function to find pair whose sum +# exists in arr[] +def findPair(arr, n): + found = False + for i in range(0, n): + for j in range(i + 1, n): + for k in range(0, n): + if (arr[i] + arr[j] == arr[k]): + print(arr[i], arr[j]) + found = True + + if (found == False): + print(""Not exist"") + +# Driver code +if __name__ == '__main__': + arr = [ 10, 4, 8, 13, 5 ] + n = len(arr) + findPair(arr, n) + +# This code contributed by 29AjayKumar",constant,cubic +"# Python3 program to find pair whose +# sum already exist in array + +# Function to find pair whose +# sum exists in arr[] +def findPair(arr, n): + + # hash to store all element of array + s = {i : 1 for i in arr} + + found = False + + for i in range(n): + for j in range(i + 1, n): + + # check if sum already exists or not + if arr[i] + arr[j] in s.keys(): + print(arr[i], arr[j]) + found = True + if found == False: + print(""Not exist"") + +# Driver code +arr = [10, 4, 8, 13, 5] + +n = len(arr) + +findPair(arr, n) + +# This code is contributed +# by Mohit Kumar",quadratic,quadratic +"# Python3 implementation to find such pairs + +# Function to find pair such that (a % b = k) +def printPairs(arr, n, k): + + isPairFound = True + + # Consider each and every pair + for i in range(0, n): + + for j in range(0, n): + + # Print if their modulo equals to k + if (i != j and arr[i] % arr[j] == k): + + print(""("", arr[i], "", "", arr[j], "")"", + sep = """", end = "" "") + isPairFound = True + + return isPairFound + +# Driver Code +arr = [2, 3, 5, 4, 7] +n = len(arr) +k = 3 +if (printPairs(arr, n, k) == False): + print(""No such pair exists"") + +# This article is contributed by Smitha Dinesh Semwal.",constant,quadratic +"# Python3 program to find all pairs +# such that a % b = k. + +# Utility function to find the divisors +# of n and store in vector v[] +import math as mt + +def findDivisors(n): + + v = [] + + # Vector is used to store the divisors + for i in range(1, mt.floor(n**(.5)) + 1): + if (n % i == 0): + + # If n is a square number, push + # only one occurrence + if (n / i == i): + v.append(i) + else: + v.append(i) + v.append(n // i) + + return v + +# Function to find pairs such that (a%b = k) +def printPairs(arr, n, k): + + # Store all the elements in the map + # to use map as hash for finding elements + # in O(1) time. + occ = dict() + for i in range(n): + occ[arr[i]] = True + + isPairFound = False + + for i in range(n): + + # Print all the pairs with (a, b) as + # (k, numbers greater than k) as + # k % (num (> k)) = k i.e. 2%4 = 2 + if (occ[k] and k < arr[i]): + print(""("", k, "","", arr[i], "")"", end = "" "") + isPairFound = True + + # Now check for the current element as 'a' + # how many b exists such that a%b = k + if (arr[i] >= k): + + # find all the divisors of (arr[i]-k) + v = findDivisors(arr[i] - k) + + # Check for each divisor i.e. arr[i] % b = k + # or not, if yes then print that pair. + for j in range(len(v)): + if (arr[i] % v[j] == k and + arr[i] != v[j] and + occ[v[j]]): + print(""("", arr[i], "","", v[j], + "")"", end = "" "") + isPairFound = True + + return isPairFound + +# Driver Code +arr = [3, 1, 2, 5, 4] +n = len(arr) +k = 2 + +if (printPairs(arr, n, k) == False): + print(""No such pair exists"") + +# This code is contributed by mohit kumar",linear,linear +"# Python3 program to convert an array +# in reduced form +def convert(arr, n): + # Create a temp array and copy contents + # of arr[] to temp + temp = [arr[i] for i in range (n) ] + + # Sort temp array + temp.sort() + + # create a map + umap = {} + + + # One by one insert elements of sorted + # temp[] and assign them values from 0 + # to n-1 + val = 0 + for i in range (n): + umap[temp[i]] = val + val += 1 + + # Convert array by taking positions from umap + for i in range (n): + arr[i] = umap[arr[i]] + +def printArr(arr, n): + for i in range(n): + print(arr[i], end = "" "") + +# Driver Code +if __name__ == ""__main__"": + arr = [10, 20, 15, 12, 11, 50] + n = len(arr) + print(""Given Array is "") + printArr(arr, n) + convert(arr , n) + print(""\n\nConverted Array is "") + printArr(arr, n) + +# This code is contributed by Abhishek Gupta",linear,nlogn +"# Python program to return the maximum occurring character in the input string +ASCII_SIZE = 256 + + +def getMaxOccurringChar(str): + # Create array to keep the count of individual characters + # Initialize the count array to zero + count = [0] * ASCII_SIZE + + # Utility variables + max = -1 + c = '' + + # Traversing through the string and maintaining the count of + # each character + for i in str: + count[ord(i)] += 1 + + for i in str: + if max < count[ord(i)]: + max = count[ord(i)] + c = i + + return c + + +# Driver program to test the above function +str = ""sample string"" +print(""Max occurring character is"", getMaxOccurringChar(str)) + +# Although this program can be written in atmost 3 lines in Python +# the above program has been written for a better understanding of +# the reader + +# Shorter version of the program +# import collections +# str = ""sample string"" +# print ""Max occurring character is "" + +# collections.Counter(str).most_common(1)[0][0] + +# This code has been contributed by Bhavya Jain",constant,linear +"# Python program to print all words that +# have the same unique character set + +# Function to group all strings with same characters +from collections import Counter + +def groupStrings(input): + # traverse all strings one by one + # dict is an empty dictionary + dict={} + + for word in input: + # sort the current string and take it's + # sorted value as key + # sorted return list of sorted characters + # we need to join them to get key as string + # Counter() method returns dictionary with frequency of + # each character as value + wordDict=Counter(word) + + # now get list of keys + key = wordDict.keys() + + # now sort these keys + key = sorted(key) + + # join these characters to produce key string + key = ''.join(key) + + # now check if this key already exist in + # dictionary or not + # if exist then simply append current word + # in mapped list on key + # otherwise first assign empty list to key and + # then append current word in it + if key in dict.keys(): + dict[key].append(word) + else: + dict[key]=[] + dict[key].append(word) + + # now traverse complete dictionary and print + # list of mapped strings in each key separated by , + for (key,value) in dict.items(): + print (','.join(dict[key])) + +# Driver program +if __name__ == ""__main__"": + input=['may','student','students','dog','studentssess','god','cat','act','tab','bat','flow','wolf','lambs','amy','yam','balms','looped','poodle'] + groupStrings(input)",linear,linear +"# Python3 program to find out the second +# most repeated word + +# Function to find the word +def secMostRepeated(seq): + + # Store all the words with its occurrence + occ = {} + for i in range(len(seq)): + occ[seq[i]] = occ.get(seq[i], 0) + 1 + + # Find the second largest occurrence + first_max = -10**8 + sec_max = -10**8 + + for it in occ: + if (occ[it] > first_max): + sec_max = first_max + first_max = occ[it] + + elif (occ[it] > sec_max and + occ[it] != first_max): + sec_max = occ[it] + + # Return with occurrence equals + # to sec_max + for it in occ: + if (occ[it] == sec_max): + return it + +# Driver code +if __name__ == '__main__': + + seq = [ ""ccc"", ""aaa"", ""ccc"", + ""ddd"", ""aaa"", ""aaa"" ] + print(secMostRepeated(seq)) + +# This code is contributed by mohit kumar 29",linear,linear +"from collections import defaultdict +import sys + +# Python program to find the smallest element +# with frequency exactly k. +def smallestKFreq(arr, n, k): + mp = defaultdict(lambda : 0) + + + # Map is used to store the count of + # elements present in the array + for i in range(n): + mp[arr[i]] += 1 + + # Traverse the map and find minimum + # element with frequency k. + res = sys.maxsize + res1 = sys.maxsize + + for key,values in mp.items(): + + if values == k: + res = min(res, key) + return res if res != res1 else -1 + +# Driver code +arr = [2, 2, 1, 3, 1] +k = 2 +n = len(arr) +print(smallestKFreq(arr, n, k)) + +# This code is contributed by Shrikant13",linear,linear +"# Python3 code to find number +# occurring prime number of +# times with frequency >= k + +# Function to find number +# with prime occurrences +def primeOccurrences(arr, k): + map = {} + + # Insert values and their frequencies + for val in arr: + freq = 0 + + if val in map : + freq = map[val] + freq += 1 + + else : + freq = 1 + map[val] = freq + + # Traverse map and find elements + # with prime frequencies and + # frequency at least k + for entry in map : + value = map[entry] + + if isPrime(value) and value >= k: + print(entry) + +# Check if the number of occurrences +# are primes or not +def isPrime(n): + + if (n > 2 and not n % 2) or n == 1: + return False + + for i in range(3, int(n**0.5 + 1), 2): + if not n % i: + return False + + return True + + +# Driver code + +arr = [ 11, 11, 11, 23, 11, 37, + 37, 51, 51, 51, 51, 51 ] +k = 2 + +primeOccurrences(arr, k) + + +# This code is contributed by Ansu Kumari.",linear,linear +"# 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)",logn,nlogn +"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))",linear,linear +"# Python3 program to find first repeating +# element in arr[] + +# This function prints the first repeating +# element in arr[] + + +def printFirstRepeating(arr, n): + + # Initialize index of first repeating element + Min = -1 + + # Creates an empty hashset + myset = dict() + + # Traverse the input array from right to left + for i in range(n - 1, -1, -1): + + # If element is already in hash set, + # update Min + if arr[i] in myset.keys(): + Min = i + + else: # Else add element to hash set + myset[arr[i]] = 1 + + # Print the result + if (Min != -1): + print(""The first repeating element is"", + arr[Min]) + else: + print(""There are no repeating elements"") + + +# Driver Code +arr = [10, 5, 3, 4, 3, 5, 6] + +n = len(arr) +printFirstRepeating(arr, n) + +# This code is contributed by Mohit kumar 29",linear,linear +"# Python3 program to find first +# repeating element in arr[] + +# This function prints the +# first repeating element in arr[] + + +def printFirstRepeating(arr, n): + + # This will set k=1, if any + # repeating element found + k = 0 + + # max = maximum from (all elements & n) + max = n + + for i in range(n): + if (max < arr[i]): + max = arr[i] + + # Array a is for storing + # 1st time occurrence of element + # initialized by 0 + a = [0 for i in range(max + 1)] + + # Store 1 in array b + # if element is duplicate + # initialized by 0 + b = [0 for i in range(max + 1)] + + for i in range(n): + + # Duplicate element found + if (a[arr[i]]): + b[arr[i]] = 1 + k = 1 + continue + else: + + # Storing 1st occurrence of arr[i] + a[arr[i]] = i+1 + + if (k == 0): + print(""No repeating element found"") + else: + min = max + 1 + + for i in range(max + 1): + + # Trace array a & find repeating + # element with min index + if (a[i] and (min > (a[i])) and b[i]): + min = a[i] + + print(arr[min-1]) + + +# Driver code +arr = [10, 5, 3, 4, 3, 5, 6] +N = len(arr) + +printFirstRepeating(arr, N) + +# This code is contributed by avanitrachhadiya2155",linear,linear +" +# Python3 Find the sum of all non-repeated +# elements in an array + + +# Find the sum of all non-repeated elements +# in an array +def findSum(arr, n): + # sort all elements of array + arr.sort() + + sum = arr[0] + for i in range(0,n-1): + if (arr[i] != arr[i+1]): + sum = sum + arr[i+1] + + return sum + +# Driver code +def main(): + arr= [1, 2, 3, 1, 1, 4, 5, 6] + n = len(arr) + print(findSum(arr, n)) + +if __name__ == '__main__': + main() +# This code is contributed by 29AjayKumar",constant,nlogn +"# Python3 Find the sum of all +# non- repeated elements in an array + +# Find the sum of all non-repeated +# elements in an array +def findSum(arr, n): + s = set() + sum = 0 + + # Hash to store all element + # of array + for i in range(n): + if arr[i] not in s: + s.add(arr[i]) + for i in s: + sum = sum + i + + return sum + +# Driver code +arr = [1, 2, 3, 1, 1, 4, 5, 6] +n = len(arr) +print(findSum(arr, n)) + +# This code is contributed by Shrikant13",linear,linear +"# Python program for the above approach +from collections import Counter + +# Function to return the sum of distinct elements +def sumOfElements(arr, n): + + # Counter function is used to + # calculate frequency of elements of array + freq = Counter(arr) + + # Converting keys of freq dictionary to list + lis = list(freq.keys()) + + # Return sum of list + return sum(lis) + + +# Driver code +if __name__ == ""__main__"": + + arr = [1, 2, 3, 1, 1, 4, 5, 6] + n = len(arr) + + print(sumOfElements(arr, n)) + +# This code is contributed by vikkycirus",linear,linear +"# Python3 program to find first +# non-repeating element. + + +def firstNonRepeating(arr, n): + + # Loop for checking each element + for i in range(n): + j = 0 + # Checking if ith element is present in array + while(j < n): + if (i != j and arr[i] == arr[j]): + break + j += 1 + # if ith element is not present in array + # except at ith index then return element + if (j == n): + return arr[i] + + return -1 + + +# Driver code +arr = [9, 4, 9, 6, 7, 4] +n = len(arr) +print(firstNonRepeating(arr, n)) + +# This code is contributed by Anant Agarwal.",constant,quadratic +"# Efficient Python3 program to find first +# non-repeating element. +from collections import defaultdict + + +def firstNonRepeating(arr, n): + mp = defaultdict(lambda: 0) + + # Insert all array elements in hash table + for i in range(n): + mp[arr[i]] += 1 + + # Traverse array again and return + # first element with count 1. + for i in range(n): + if mp[arr[i]] == 1: + return arr[i] + return -1 + + +# Driver Code +arr = [9, 4, 9, 6, 7, 4] +n = len(arr) +print(firstNonRepeating(arr, n)) + +# This code is contributed by Shrikant13",linear,linear +"# Python3 program to print k-th distinct +# element in a given array + +# Returns k-th distinct +# element in arr. +def printKDistinct(arr, n, k): + dist_count = 0 + for i in range(n): + + # Check if current element is + # present somewhere else. + j = 0 + while j < n: + if (i != j and arr[j] == arr[i]): + break + j += 1 + + # If element is unique + if (j == n): + dist_count += 1 + + if (dist_count == k): + return arr[i] + + return -1 + +# Driver Code +ar = [1, 2, 1, 3, 4, 2] +n = len(ar) +k = 2 +print(printKDistinct(ar, n, k)) + +# This code is contributed by Mohit Kumar",constant,quadratic +"# Python3 program to print k-th +# distinct element in a given array +def printKDistinct(arr, size, KthIndex): + dict = {} + vect = [] + for i in range(size): + if(arr[i] in dict): + dict[arr[i]] = dict[arr[i]] + 1 + else: + dict[arr[i]] = 1 + for i in range(size): + if(dict[arr[i]] > 1): + continue + else: + KthIndex = KthIndex - 1 + if(KthIndex == 0): + return arr[i] + return -1 + +# Driver Code +arr = [1, 2, 1, 3, 4, 2] +size = len(arr) +print(printKDistinct(arr, size, 2)) + +# This code is contributed +# by Akhand Pratap Singh",linear,linear +"# Simple Python 3 program to find +# pairs of positive and negative +# values present in an array. + +# Print pair with negative and +# positive value + + +def printPairs(arr, n): + v = [] + + # For each element of array. + for i in range(n): + + # Try to find the negative value + # of arr[i] from i + 1 to n + for j in range(i + 1, n): + + # If absolute values are + # equal print pair. + if (abs(arr[i]) == abs(arr[j])): + v.append(abs(arr[i])) + + # If size of vector is 0, therefore + # there is no element with positive + # negative value, print ""0"" + if (len(v) == 0): + return + + # Print the pair with negative + # positive value. + for i in range(len(v)): + print(-v[i], """", v[i], end="" "") + + +# Driver Code +if __name__ == ""__main__"": + arr = [4, 8, 9, -4, 1, -1, -8, -9] + n = len(arr) + + # Function call + printPairs(arr, n) + +# This code is contributed +# by ChitraNayal",linear,quadratic +"# Python3 program to find pairs of +# positive and negative values present in +# an array. +# Print pair with negative and +# positive value + + +def printPairs(arr, n): + + s = set() + ret = [] + + # For each element of array. + for i in arr: + if abs(i) in s: + ret.append(abs(i)) + else: + s.add(abs(i)) + + ret.sort() + + for i in range(0, len(ret)): + print(-ret[i], """", ret[i], end="" "") + + +# Driver Code +if __name__ == ""__main__"": + arr = [4, 8, 9, -4, 1, -1, -8, -9] + n = len(arr) + + # Function call + printPairs(arr, n) +# This code is contributed by RohitOberoi",linear,linear +"# Python3 program to find pairs of +# positive and negative values present in +# an array + + +def printPairs(arr, n): + + hs = set() + ans = [] + for i in range(n): + if (arr[i] * -1) in hs: + + if (arr[i] < 0): + print(arr[i], end="" "") + print((arr[i] * -1), end="" "") + + else: + print((arr[i] * -1), end="" "") + print(arr[i], end="" "") + + hs.add(arr[i]) + + return + + +# Driver code +arr = [4, 8, 9, -4, 1, -1, -8, -9] +n = len(arr) + +# Function call +printPairs(arr, n) + +# This code is contributed by shinjanpatra.",linear,linear +"# Python3 program to count +# divisible pairs. + +def countDivisibles(arr, n) : + + res = 0 + + # Iterate through all pairs + for i in range(0, n) : + for j in range(i+1, n) : + + # Increment count if one divides + # other + if (arr[i] % arr[j] == 0 or + arr[j] % arr[i] == 0) : + res+=1 + + return res + +# Driver code +if __name__=='__main__': + a = [1, 2, 3, 9] + n = len(a) + print(countDivisibles(a, n) ) + +# this code is contributed by +# Smitha Dinesh Semwal ",constant,quadratic +"# Python program to count divisible pairs. +import math + +# Function to return the total count of pairs such +# that arr[i]%arr[j]==0 +def total_count(arr, N): + count = 0 + + # Storing the occurrence of every element in array + # in dictionary + freq = {} + for i in range(0, N): + if arr[i] not in freq: + freq[arr[i]] = 1 + else: + freq[arr[i]] += 1 + + # Iterating through every element and finding all the + # divisors of that element and then checking how many + # of them are present in array arr[] + for i in range(0, N): + for j in range(1, int(math.sqrt(arr[i]))+1): + if arr[i] % j == 0: + if arr[i] == j*j: + + # If divisors are equal, then take only + # one as it will be perfect square root + # of arr[i] + count += freq[j] + else: + # Else take both j and arr[i]/j as both + # will be divisors + count += freq[j]+freq[arr[i]/j] + + # As all the elements is divisible by itself and + # is counted in freq[] so reducing its count + count = count-1 + + # returning final count + return count + +arr = [1, 2, 3, 9] +N = len(arr) + +print(total_count(arr, N)) + +# This code is contributed by lokesh (lokeshmvs21).",constant,quadratic +"# Python3 implementation to find the +# longest subarray with sum divisible by k + +# Function to find the longest +# subarray with sum divisible by k + + +def longestSubarrWthSumDivByK(arr, n, k): + + # unordered map 'um' implemented + # as hash table + um = {} + + # 'mod_arr[i]' stores (sum[0..i] % k) + mod_arr = [0 for i in range(n)] + max_len = 0 + curr_sum = 0 + + # Traverse arr[] and build up + # the array 'mod_arr[]' + for i in range(n): + curr_sum += arr[i] + + # As the sum can be negative, + # taking modulo twice + mod_arr[i] = ((curr_sum % k) + k) % k + + # If true then sum(0..i) is + # divisible by k + if (mod_arr[i] == 0): + + # Update 'max_len' + max_len = i + 1 + + # If value 'mod_arr[i]' not present in + # 'um' then store it in 'um' with index + # of its first occurrence + elif (mod_arr[i] not in um): + um[mod_arr[i]] = i + + else: + # If true, then update 'max_len' + if (max_len < (i - um[mod_arr[i]])): + max_len = i - um[mod_arr[i]] + + # Return the required length of longest subarray + # with sum divisible by 'k' + return max_len + + +# Driver Code +if __name__ == '__main__': + + arr = [2, 7, 6, 1, 4, 5] + n = len(arr) + k = 3 + + print(""Length ="", + longestSubarrWthSumDivByK(arr, n, k)) + +# This code is contributed by Surendra_Gangwar, updated by Kshitij Dwivedi",linear,linear +"# function to find the longest subarray +# with sum divisible by k + + +def longestSubarrWthSumDivByK(arr, n, k): + + # unordered map 'um' implemented as + # hash table + um = {} + + max_len = 0 + curr_sum = 0 + + for i in range(n): + + curr_sum += arr[i] + mod = ((curr_sum % k) + k) % k + # if true then sum(0..i) is divisible by k + + if mod == 0: + # update 'max_len' + max_len = i + 1 + + # if value 'mod_arr[i]' not present in 'um' + # then store it in 'um' with index of its + # first occurrence + elif mod in um.keys(): + if max_len < (i - um[mod]): + max_len = i - um[mod] + + else: + um[mod] = i + + # return the required length of longest subarray with + # sum divisible by 'k' + return max_len + + +arr = [2, 7, 6, 1, 4, 5] +n = len(arr) +k = 3 +print(""Length ="", longestSubarrWthSumDivByK(arr, n, k)) + +# This code is contributed by amreshkumar3, and updated by Kshitij Dwivedi",linear,linear +"# Python3 Program to find the subarray with +# no pair sum divisible by K + +# function to find the subarray with +# no pair sum divisible by k +def subarrayDivisibleByK(arr, n, k) : + + # hash table to store the remainders + # obtained on dividing by K + mp = [0] * 1000 + + # s : starting index of the + # current subarray, e : ending + # index of the current subarray, maxs : + # starting index of the maximum + # size subarray so far, maxe : ending + # index of the maximum size subarray + # so far + s = 0; e = 0; maxs = 0; maxe = 0; + + # insert the first element in the set + mp[arr[0] % k] = mp[arr[0] % k] + 1; + + for i in range(1, n): + mod = arr[i] % k + + # Removing starting elements of current + # subarray while there is an element in + # set which makes a pair with mod[i] such + # that the pair sum is divisible. + while (mp[k - mod] != 0 or (mod == 0 + and mp[mod] != 0)) : + mp[arr[s] % k] = mp[arr[s] % k] - 1 + s = s + 1 + + # include the current element in + # the current subarray the ending + # index of the current subarray + # increments by one + mp[mod] = mp[mod] + 1 + e = e + 1 + + # compare the size of the current + # subarray with the maximum size so + # far + if ((e - s) > (maxe - maxs)) : + maxe = e + maxs = s + + print (""The maximum size is {} and the "" + "" subarray is as follows"" + .format((maxe - maxs + 1))) + + for i in range(maxs, maxe + 1) : + print (""{} "".format(arr[i]), end="""") + +# Driver Code +k = 3 +arr = [5, 10, 15, 20, 25] +n = len(arr) +subarrayDivisibleByK(arr, n, k) + +# This code is contributed by +# Manish Shaw (manishshaw1)",linear,nlogn +"# Python3 program to find special numbers +# in an array +import math as mt + +# Function to find special numbers +def divisibilityCheck(arr, n): + + # Storing all array elements in a hash + # and finding maximum element in array + s = dict() + max_ele = -10**9 + for i in range(n): + s[arr[i]] = 1 + + # finding maximum element of array + max_ele = max(max_ele, arr[i]) + + # traversing array element and storing + # the array multiples that are present + # in s in res. + res = dict() + for i in range(n): + + # Check for non-zero values only + if (arr[i] != 0): + + # checking the factor of current element + for j in range(arr[i] * 2, + max_ele + 1, arr[i]): + + # if factor is already part of + # array element then store it + if (j in s.keys()): + res[j] = 1 + + # displaying elements that are divisible + # by at least one other in array + for x in res: + print(x, end = "" "") + +# Driver code +arr = [ 2, 3, 8, 6, 9, 10] +n = len(arr) +divisibilityCheck(arr, n) + +# This code is contributed by +# Mohit Kumar 29",linear,quadratic +"# Python3 program to find +# three element from different +# three arrays such that +# a + b + c is equal to +# given sum + +# Function to check if there +# is an element from each +# array such that sum of the +# three elements is equal to +# given sum. +def findTriplet(a1, a2, a3, + n1, n2, n3, sum): + + for i in range(0 , n1): + for j in range(0 , n2): + for k in range(0 , n3): + if (a1[i] + a2[j] + + a3[k] == sum): + return True + + return False + +# Driver Code +a1 = [ 1 , 2 , 3 , 4 , 5 ] +a2 = [ 2 , 3 , 6 , 1 , 2 ] +a3 = [ 3 , 2 , 4 , 5 , 6 ] +sum = 9 +n1 = len(a1) +n2 = len(a2) +n3 = len(a3) +print(""Yes"") if findTriplet(a1, a2, a3, + n1, n2, n3, + sum) else print(""No"") + +# This code is contributed +# by Smitha",constant,cubic +"# Python3 program to find three element +# from different three arrays such +# that a + b + c is equal to +# given sum + +# Function to check if there is +# an element from each array such +# that sum of the three elements is +# equal to given sum. +def findTriplet(a1, a2, a3, + n1, n2, n3, sum): + + # Store elements of first + # array in hash + s = set() + + # sum last two arrays element + # one by one + for i in range(n1): + s.add(a1[i]) + + for i in range(n2): + for j in range(n3): + + # Consider current pair and + # find if there is an element + # in a1[] such that these three + # form a required triplet + if sum - a2[i] - a3[j] in s: + return True + return False + +# Driver code +a1 = [1, 2, 3, 4, 5] +a2 = [2, 3, 6, 1, 2] +a3 = [3, 24, 5, 6] +n1 = len(a1) +n2 = len(a2) +n3 = len(a3) +sum = 9 +if findTriplet(a1, a2, a3, + n1, n2, n3, sum) == True: + print(""Yes"") +else: + print(""No"") + +# This code is contributed by Shrikant13",linear,quadratic +"# Python program for the above approach + +# returns the length +def maxLen(arr): + + # initialize result + max_len = 0 + + # pick a starting point + for i in range(len(arr)): + + # initialize sum for every starting point + curr_sum = 0 + + # try all subarrays starting with 'i' + for j in range(i, len(arr)): + + curr_sum += arr[j] + + # if curr_sum becomes 0, then update max_len + if curr_sum == 0: + max_len = max(max_len, j-i + 1) + + return max_len + +# Driver's code +if __name__ == ""__main__"": +# test array + arr = [15, -2, 2, -8, 1, 7, 10, 13] + + # Function call + print (""Length of the longest 0 sum subarray is % d"" % maxLen(arr))",constant,quadratic +"# Python program for the above approach + +# Returns the maximum length + + +def maxLen(arr): + + # NOTE: Dictionary in python is + # implemented as Hash Maps + # Create an empty hash map (dictionary) + hash_map = {} + + # Initialize result + max_len = 0 + + # Initialize sum of elements + curr_sum = 0 + + # Traverse through the given array + for i in range(len(arr)): + + # Add the current element to the sum + curr_sum += arr[i] + + if curr_sum == 0: + max_len = i + 1 + + # NOTE: 'in' operation in dictionary + # to search key takes O(1). Look if + # current sum is seen before + if curr_sum in hash_map: + max_len = max(max_len, i - hash_map[curr_sum]) + else: + + # else put this sum in dictionary + hash_map[curr_sum] = i + + return max_len + + +# Driver's code +if __name__ == ""__main__"": + + # test array + arr = [15, -2, 2, -8, 1, 7, 10, 13] + + # Function call + print(""Length of the longest 0 sum subarray is % d"" % maxLen(arr))",linear,linear +"# Python 3 program to find length of +# the longest increasing subsequence +# whose adjacent element differ by 1 +import sys + +# function that returns the length +# of the longest increasing subsequence +# whose adjacent element differ by 1 +def longestSubsequence(a, n): + + # stores the index of elements + mp = {i:0 for i in range(13)} + + # stores the length of the longest + # subsequence that ends with a[i] + dp = [0 for i in range(n)] + + maximum = -sys.maxsize - 1 + + # iterate for all element + index = -1 + for i in range(n): + + # if a[i]-1 is present before + # i-th index + if ((a[i] - 1 ) in mp): + + # last index of a[i]-1 + lastIndex = mp[a[i] - 1] - 1 + + # relation + dp[i] = 1 + dp[lastIndex] + else: + dp[i] = 1 + + # stores the index as 1-index as we + # need to check for occurrence, hence + # 0-th index will not be possible to check + mp[a[i]] = i + 1 + + # stores the longest length + if (maximum < dp[i]): + maximum = dp[i] + index = i + + # We know last element of sequence is + # a[index]. We also know that length + # of subsequence is ""maximum"". So We + # print these many consecutive elements + # starting from ""a[index] - maximum + 1"" + # to a[index]. + for curr in range(a[index] - maximum + 1, + a[index] + 1, 1): + print(curr, end = "" "") + +# Driver Code +if __name__ == '__main__': + a = [3, 10, 3, 11, 4, 5, + 6, 7, 8, 12] + n = len(a) + longestSubsequence(a, n) + +# This code is contributed by +# Surendra_Gangwar",linear,linear +"# python program to find length of the +# longest increasing subsequence +# whose adjacent element differ by 1 + +from collections import defaultdict +import sys + +# function that returns the length of the +# longest increasing subsequence +# whose adjacent element differ by 1 + +def longestSubsequence(a, n): + mp = defaultdict(lambda:0) + + # stores the length of the longest + # subsequence that ends with a[i] + dp = [0 for i in range(n)] + maximum = -sys.maxsize + + # iterate for all element + for i in range(n): + + # if a[i]-1 is present before i-th index + if a[i] - 1 in mp: + + # last index of a[i]-1 + lastIndex = mp[a[i] - 1] - 1 + + # relation + dp[i] = 1 + dp[lastIndex] + else: + dp[i] = 1 + + # stores the index as 1-index as we need to + # check for occurrence, hence 0-th index + # will not be possible to check + mp[a[i]] = i + 1 + + # stores the longest length + maximum = max(maximum, dp[i]) + return maximum + + +# Driver Code +a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12] +n = len(a) +print(longestSubsequence(a, n)) + +# This code is contributed by Shrikant13",linear,linear +"# Python3 implementation to find longest +# subsequence such that difference between +# adjacents is one +from collections import defaultdict + +# function to find longest subsequence such +# that difference between adjacents is one +def longLenSub(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) + longLen = 0 + for i in range(n): + + # / initialize current length + # for element arr[i] as 0 + len1 = 0 + + # if 'arr[i]-1' is in 'um' and its length + # of subsequence is greater than 'len' + if (arr[i - 1] in um and + len1 < um[arr[i] - 1]): + len1 = um[arr[i] - 1] + + # f 'arr[i]+1' is in 'um' and its length + # of subsequence is greater than 'len' + if (arr[i] + 1 in um and + len1 < um[arr[i] + 1]): + len1 = um[arr[i] + 1] + + # update arr[i] subsequence + # length in 'um' + um[arr[i]] = len1 + 1 + + # update longest length + if longLen < um[arr[i]]: + longLen = um[arr[i]] + + # required longest length + # subsequence + return longLen + +# Driver code +arr = [1, 2, 3, 4, 5, 3, 2] +n = len(arr) +print(""Longest length subsequence ="", + longLenSub(arr, n)) + +# This code is contributed by Shrikant13",linear,linear +"# Python3 program to find longest +# contiguous subsequence + +# Returns length of the longest +# contiguous subsequence + + +def findLongestConseqSubseq(arr, n): + + ans = 0 + count = 0 + + # Sort the array + arr.sort() + + v = [] + + v.append(arr[0]) + + # Insert repeated elements only + # once in the vector + for i in range(1, n): + if (arr[i] != arr[i - 1]): + v.append(arr[i]) + + # Find the maximum length + # by traversing the array + for i in range(len(v)): + + # Check if the current element is + # equal to previous element +1 + if (i > 0 and v[i] == v[i - 1] + 1): + count += 1 + + # Reset the count + else: + count = 1 + + # Update the maximum + ans = max(ans, count) + + return ans + + +# Driver code +arr = [1, 2, 2, 3] +n = len(arr) + +print(""Length of the Longest contiguous subsequence is"", + findLongestConseqSubseq(arr, n)) + +# This code is contributed by avanitrachhadiya2155",linear,nlogn +"# Python program to find longest contiguous subsequence + + +def findLongestConseqSubseq(arr, n): + + s = set() + ans = 0 + + # Hash all the array elements + for ele in arr: + s.add(ele) + + # check each possible sequence from the start + # then update optimal length + for i in range(n): + + # if current element is the starting + # element of a sequence + if (arr[i]-1) not in s: + + # Then check for next elements in the + # sequence + j = arr[i] + while(j in s): + j += 1 + + # update optimal length if this length + # is more + ans = max(ans, j-arr[i]) + return ans + + +# Driver code +if __name__ == '__main__': + n = 7 + arr = [1, 9, 3, 10, 4, 20, 2] + print(""Length of the Longest contiguous subsequence is "", + findLongestConseqSubseq(arr, n)) + +# Contributed by: Harshit Sidhwa",linear,linear +"# Python program for the above approach +import bisect + + +def findLongestConseqSubseq(arr, N): + pq = [] + for i in range(N): + + # adding element from + # array to PriorityQueue + bisect.insort(pq, arr[i]) + + # Storing the first element + # of the Priority Queue + # This first element is also + # the smallest element + prev = pq[0] + pq.pop(0) + + # Taking a counter variable with value 1 + c = 1 + + # Storing value of max as 1 + # as there will always be + # one element + max = 1 + while(len(pq)): + # check if current peek + # element minus previous + # element is greater than + # 1 This is done because + # if it's greater than 1 + # then the sequence + # doesn't start or is broken here + if(pq[0] - prev > 1): + # Store the value of counter to 1 + # As new sequence may begin + c = 1 + + # Update the previous position with the + # current peek And remove it + prev = pq[0] + pq.pop(0) + + # Check if the previous + # element and peek are same + elif(pq[0] - prev == 0): + # Update the previous position with the + # current peek And remove it + prev = pq[0] + pq.pop(0) + + # If the difference + # between previous element and peek is 1 + else: + # Update the counter + # These are consecutive elements + c = c + 1 + # Update the previous position + # with the current peek And remove it + prev = pq[0] + pq.pop(0) + + # Check if current longest + # subsequence is the greatest + if(max < c): + # Store the current subsequence count as + # max + max = c + return max + + +# Driver Code +arr = [1, 9, 3, 10, 4, 20, 2] +n = 7 +print(""Length of the Longest consecutive subsequence is {}"".format( + findLongestConseqSubseq(arr, n))) + + +# This code is contributed by Pushpesh Raj",linear,nlogn +"# Python3 implementation of longest +# continuous increasing subsequence + +# Function for LIS +def findLIS(A, n): + hash = dict() + + # Initialize result + LIS_size, LIS_index = 1, 0 + + hash[A[0]] = 1 + + # iterate through array and find + # end index of LIS and its Size + for i in range(1, n): + + # If the desired key is not present + # in dictionary, it will throw key error, + # to avoid this error this is necessary + if A[i] - 1 not in hash: + hash[A[i] - 1] = 0 + + hash[A[i]] = hash[A[i] - 1] + 1 + if LIS_size < hash[A[i]]: + LIS_size = hash[A[i]] + LIS_index = A[i] + + # print LIS size + print(""LIS_size ="", LIS_size) + + # print LIS after setting start element + print(""LIS : "", end = """") + + start = LIS_index - LIS_size + 1 + while start <= LIS_index: + print(start, end = "" "") + start += 1 + +# Driver Code +if __name__ == ""__main__"": + A = [ 2, 5, 3, 7, 4, 8, 5, 13, 6 ] + n = len(A) + findLIS(A, n) + +# This code is contributed by sanjeev2552",linear,linear +"# python implementation to count subsets having +# even numbers only and all are distinct + +#function to count the required subsets +def countSubSets(arr, n): + us = set() + even_count = 0 + + # inserting even numbers in the set 'us' + # single copy of each number is retained + for i in range(n): + if arr[i] % 2 == 0: + us.add(arr[i]) + + # counting distinct even numbers + even_count = len(us) + + # total count of required subsets + return pow(2, even_count)- 1 + + +# Driver program +arr = [4, 2, 1, 9, 2, 6, 5, 3] +n = len(arr) +print(""Numbers of subset="", countSubSets(arr,n)) + +# This code is contributed by Shrikant13",linear,linear +"# 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",constant,quadratic +"# 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",linear,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",linear,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",linear,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.",constant,quadratic +"# 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",linear,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",constant,quadratic +"# 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",linear,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",constant,linear +"# 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",linear,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",linear,quadratic +"# 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",linear,nlogn +"# 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.",constant,nlogn +"# 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",linear,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",linear,quadratic +"# 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",constant,linear +"# 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",linear,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))",constant,nlogn +"# 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))",linear,linear +"# Python3 program to print the maximum elements +# giving second array higher priority + +# Function to maximize array elements +def maximizeArray(arr1, arr2, n): + + # Auxiliary array arr3 to store + # elements of arr1 & arr2 + arr3 = [0] * (2 * n) + k = 0 + + for i in range(n): + arr3[k] = arr1[i] + k += 1 + + for i in range(n): + arr3[k] = arr2[i] + k += 1 + + # Hash table to store n largest + # unique elements + hash = {} + + # Sorting arr3 in decreasing order + arr3 = sorted(arr3) + arr3 = arr3[::-1] + + # Finding n largest unique elements + # from arr3 and storing in hash + i = 0 + while (len(hash) != n): + + # If arr3 element not present in hash, + # then store this element in hash + if (arr3[i] not in hash): + hash[arr3[i]] = 1 + + i += 1 + + # Store that elements of arr2 in arr3 + # that are present in hash + k = 0 + for i in range(n): + + # If arr2 element is present in + # hash, store it in arr3 + if (arr2[i] in hash): + arr3[k] = arr2[i] + k += 1 + + del hash[arr2[i]] + + # Store that elements of arr1 in arr3 + # that are present in hash + for i in range(n): + + # If arr1 element is present + # in hash, store it in arr3 + if (arr1[i] in hash): + arr3[k] = arr1[i] + k += 1 + + del hash[arr1[i]] + + # Copying 1st n elements of + # arr3 to arr1 + for i in range(n): + arr1[i] = arr3[i] + +# Function to print array elements +def printArray(arr, n): + + for i in arr: + print(i, end = "" "") + + print() + +# Driver Code +if __name__ == '__main__': + + array1 = [ 7, 4, 8, 0, 1 ] + array2 = [ 9, 7, 2, 3, 6 ] + size = len(array1) + + maximizeArray(array1, array2, size) + printArray(array1, size) + +# This code is contributed by mohit kumar 29",linear,nlogn +"# Python3 implementation to count +# subarrays with equal number +# of 1's and 0's + +# function to count subarrays with +# equal number of 1's and 0's + + +def countSubarrWithEqualZeroAndOne(arr, n): + + # 'um' implemented as hash table + # to store frequency of values + # obtained through cumulative sum + um = dict() + curr_sum = 0 + + # Traverse original array and compute + # cumulative sum and increase count + # by 1 for this sum in 'um'. + # Adds '-1' when arr[i] == 0 + for i in range(n): + curr_sum += (-1 if (arr[i] == 0) else arr[i]) + if um.get(curr_sum): + um[curr_sum] += 1 + else: + um[curr_sum] = 1 + + count = 0 + + # traverse the hash table 'um' + for itr in um: + + # If there are more than one + # prefix subarrays with a + # particular sum + if um[itr] > 1: + count += ((um[itr] * int(um[itr] - 1)) / 2) + + # add the subarrays starting from + # 1st element and have equal + # number of 1's and 0's + if um.get(0): + count += um[0] + + # required count of subarrays + return int(count) + + +# Driver code to test above +arr = [1, 0, 0, 1, 0, 1, 1] +n = len(arr) +print(""Count ="", + countSubarrWithEqualZeroAndOne(arr, n)) + +# This code is contributed by ""Sharad_Bhardwaj"".",linear,linear +"# Python3 implementation to count subarrays +# with equal number of 1's and 0's + + +def countSubarrWithEqualZeroAndOne(arr, n): + mp = dict() + Sum = 0 + count = 0 + + for i in range(n): + + # Replacing 0's in array with -1 + if (arr[i] == 0): + arr[i] = -1 + + Sum += arr[i] + + # If Sum = 0, it implies number of + # 0's and 1's are equal from arr[0]..arr[i] + if (Sum == 0): + count += 1 + + if (Sum in mp.keys()): + count += mp[Sum] + + mp[Sum] = mp.get(Sum, 0) + 1 + + return count + + +# Driver Code +arr = [1, 0, 0, 1, 0, 1, 1] + +n = len(arr) + +print(""count ="", + countSubarrWithEqualZeroAndOne(arr, n)) + +# This code is contributed by mohit kumar",linear,linear +"# Python 3 implementation to find the length of +# longest subarray having count of 1's one +# more than count of 0's + +# function to find the length of longest +# subarray having count of 1's one more +# than count of 0's + + +def lenOfLongSubarr(arr, n): + + # unordered_map 'um' implemented as + # hash table + um = {} + sum = 0 + maxLen = 0 + + # traverse the given array + for i in range(n): + + # consider '0' as '-1' + if arr[i] == 0: + sum += -1 + else: + sum += 1 + + # when subarray starts form index '0' + if (sum == 1): + maxLen = i + 1 + + # make an entry for 'sum' if it is + # not present in 'um' + elif (sum not in um): + um[sum] = i + + # check if 'sum-1' is present in 'um' + # or not + if ((sum - 1) in um): + # update maxLength + if (maxLen < (i - um[sum - 1])): + maxLen = i - um[sum - 1] + + # required maximum length + return maxLen + + +# Driver code +if __name__ == '__main__': + arr = [0, 1, 1, 0, 0, 1] + n = len(arr) + print(""Length ="", lenOfLongSubarr(arr, n)) + +# This code is contributed by +# Surendra_Gangwar",linear,linear +"# Python3 program to find substring with equal +# number of 0's, 1's and 2's + +# Method to count number of substring which +# has equal 0, 1 and 2 +def getSubstringWithEqual012(string): + N = len(string) + + # map to store, how many times a difference + # pair has occurred previously + mp = dict() + mp[(0, 0)] = 1 + + # zc (Count of zeroes), oc(Count of 1s) + # and tc(count of twos) + # In starting all counts are zero + zc, oc, tc = 0, 0, 0 + + # looping into string + res = 0 # Initialize result + for i in range(N): + + # increasing the count of current character + if string[i] == '0': + zc += 1 + elif string[i] == '1': + oc += 1 + else: + tc += 1 # Assuming that string doesn't contain + # other characters + + # making pair of differences (z[i] - o[i], + # z[i] - t[i]) + tmp = (zc - oc, zc - tc) + + # Count of previous occurrences of above pair + # indicates that the subarrays forming from + # every previous occurrence to this occurrence + # is a subarray with equal number of 0's, 1's + # and 2's + if tmp not in mp: + res += 0 + else: + res += mp[tmp] + + # increasing the count of current difference + # pair by 1 + if tmp in mp: + mp[tmp] += 1 + else: + mp[tmp] = 1 + + return res + +# Driver's Code +if __name__ == ""__main__"": + string = ""0102010"" + print(getSubstringWithEqual012(string)) + +# This code is contributed by +# sanjeev2552",linear,nlogn +"# Python program to print all +# triplets in given array +# that form Arithmetic +# Progression + +# Function to print +# all triplets in +# given sorted array +# that forms AP +def printAllAPTriplets(arr, n) : + + s = []; + for i in range(0, n - 1) : + + for j in range(i + 1, n) : + + # Use hash to find if + # there is a previous + # element with difference + # equal to arr[j] - arr[i] + diff = arr[j] - arr[i]; + + if ((arr[i] - diff) in arr) : + print (""{} {} {}"" . + format((arr[i] - diff), + arr[i], arr[j]), + end = ""\n""); + + s.append(arr[i]); + +# Driver code +arr = [2, 6, 9, 12, 17, + 22, 31, 32, 35, 42]; +n = len(arr); +printAllAPTriplets(arr, n); + +# This code is contributed by +# Manish Shaw(manishshaw1)",linear,quadratic +"# python 3 program to print all triplets in given +# array that form Arithmetic Progression + +# Function to print all triplets in +# given sorted array that forms AP +def printAllAPTriplets(arr, n): + + for i in range(1, n - 1): + + # Search other two elements of + # AP with arr[i] as middle. + j = i - 1 + k = i + 1 + while(j >= 0 and k < n ): + + # if a triplet is found + if (arr[j] + arr[k] == 2 * arr[i]): + print(arr[j], """", arr[i], """", arr[k]) + + # Since elements are distinct, + # arr[k] and arr[j] cannot form + # any more triplets with arr[i] + k += 1 + j -= 1 + + + # If middle element is more move to + # higher side, else move lower side. + elif (arr[j] + arr[k] < 2 * arr[i]): + k += 1 + else: + j -= 1 + +# Driver code +arr = [ 2, 6, 9, 12, 17, + 22, 31, 32, 35, 42 ] +n = len(arr) +printAllAPTriplets(arr, n) + +# This article is contributed +# by Smitha Dinesh Semwal",constant,quadratic +"# Python program to find unique triplets +# that sum up to a given value. + +# Function to find unique triplets that +# sum up to a given value. +def findTriplets(nums, n, Sum): + i = 0 + j = 0 + k = 0 + + # list to store all unique triplets. + triplet = [] + + # list to store already found triplets + # to avoid duplication. + uniqTriplets = [] + + # Variable used to hold triplet + # converted to string form. + temp = """" + + # Variable used to store current + # triplet which is stored in vector + # if it is unique. + newTriplet = [0, 0, 0] + + # Sort the input array. + nums.sort() + + # Iterate over the array from the + # start and consider it as the + # first element. + for i in range(n - 2): + + # index of the first element in + # the remaining elements. + j = i + 1 + + # index of the last element. + k = n - 1 + + while(j < k): + + # If sum of triplet is equal to + # given value, then check if + # this triplet is unique or not. + # To check uniqueness, convert + # triplet to string form and + # then check if this string is + # present in set or not. If + # triplet is unique, then store + # it in list. + if(nums[i] + nums[j] + nums[k] == Sum): + temp = str(nums[i]) + "":"" + str(nums[j]) + "":"" + str(nums[k]) + if temp not in uniqTriplets: + uniqTriplets.append(temp) + newTriplet[0] = nums[i] + newTriplet[1] = nums[j] + newTriplet[2] = nums[k] + triplet.append(newTriplet) + newTriplet = [0, 0, 0] + + # Increment the first index + # and decrement the last + # index of remaining elements. + j += 1 + k -= 1 + + # If sum is greater than given + # value then to reduce sum + # decrement the last index. + elif(nums[i] + nums[j] + nums[k] > Sum): + k -= 1 + + # If sum is less than given value + # then to increase sum increment + # the first index of remaining + # elements. + else: + j += 1 + + # If no unique triplet is found, then + # return 0. + if(len(triplet) == 0): + return 0 + + # Print all unique triplets stored in + # list. + for i in range(len(triplet)): + print(triplet[i], end = "", "") + return 1 + +# Driver Code +nums = [12, 3, 6, 1, 6, 9] +n = len(nums) +Sum = 24 + +# Function call +if(not findTriplets(nums, n, Sum)): + print(""No triplets can be formed."") + +# This code is contributed by rag2127",linear,quadratic +"# A simple Python 3 program +# to find three elements whose +# sum is equal to zero + +# Prints all triplets in +# arr[] with 0 sum + + +def findTriplets(arr, n): + + found = False + for i in range(0, n-2): + + for j in range(i+1, n-1): + + for k in range(j+1, n): + + if (arr[i] + arr[j] + arr[k] == 0): + print(arr[i], arr[j], arr[k]) + found = True + + # If no triplet with 0 sum + # found in array + if (found == False): + print("" not exist "") + + +# Driver code +arr = [0, -1, 2, -3, 1] +n = len(arr) +findTriplets(arr, n) + +# This code is contributed by Smitha Dinesh Semwal",constant,cubic +"# Python3 program to find triplets +# in a given array whose sum is zero + +# function to print triplets with 0 sum + + +def findTriplets(arr, n): + found = False + for i in range(n - 1): + + # Find all pairs with sum + # equals to ""-arr[i]"" + s = set() + for j in range(i + 1, n): + x = -(arr[i] + arr[j]) + if x in s: + print(x, arr[i], arr[j]) + found = True + else: + s.add(arr[j]) + if found == False: + print(""No Triplet Found"") + + +# Driver Code +arr = [0, -1, 2, -3, 1] +n = len(arr) +findTriplets(arr, n) + +# This code is contributed by Shrikant13",linear,quadratic +"# python program to find triplets in a given +# array whose sum is zero + +# function to print triplets with 0 sum + + +def findTriplets(arr, n): + + found = False + + # sort array elements + arr.sort() + + for i in range(0, n-1): + + # initialize left and right + l = i + 1 + r = n - 1 + x = arr[i] + while (l < r): + + if (x + arr[l] + arr[r] == 0): + # print elements if it's sum is zero + print(x, arr[l], arr[r]) + l += 1 + r -= 1 + found = True + + # If sum of three elements is less + # than zero then increment in left + elif (x + arr[l] + arr[r] < 0): + l += 1 + + # if sum is greater than zero then + # decrement in right side + else: + r -= 1 + + if (found == False): + print("" No Triplet Found"") + + +# Driven source +arr = [0, -1, 2, -3, 1] +n = len(arr) +findTriplets(arr, n) + +# This code is contributed by Smitha Dinesh Semwal",constant,quadratic +"# Python3 program to count +# triplets with given product m + +# Method to count such triplets +def countTriplets(arr, n, m): + + count = 0 + + # Consider all triplets and count if + # their product is equal to m + for i in range (n - 2): + for j in range (i + 1, n - 1): + for k in range (j + 1, n): + if (arr[i] * arr[j] * arr[k] == m): + count += 1 + return count + +# Driver code +if __name__ == ""__main__"": + + arr = [1, 4, 6, 2, 3, 8] + m = 24 + print(countTriplets(arr, + len(arr), m)) + +# This code is contributed by Chitranayal",constant,cubic +"# Python3 program for the above approach + +# Function to find the triplet +def countTriplets(li,product): + flag = 0 + count = 0 + + # Consider all pairs and check + # for a third number so their + # product is equal to product + for i in range(len(li)): + + # Check if current pair + # divides product or not + # If yes, then search for + # (product / li[i]*li[j]) + if li[i]!= 0 and product % li[i] == 0: + + for j in range(i+1, len(li)): + + # Check if the third number is present + # in the map and it is not equal to any + # other two elements and also check if + # this triplet is not counted already + # using their indexes + if li[j]!= 0 and product % (li[j]*li[i]) == 0: + if product // (li[j]*li[i]) in li: + + n = li.index(product//(li[j]*li[i])) + + if n > i and n > j: + flag = 1 + count+=1 + print(count) + +# Driver code +li = [ 1, 4, 6, 2, 3, 8 ] +product = 24 + +# Function call +countTriplets(li,product)",linear,quadratic +"# Python3 program to +# count of pairs with equal +# elements in an array. + +# Return the number of +# pairs with equal values. +def countPairs(arr, n): + + ans = 0 + + # for each index i and j + for i in range(0 , n): + for j in range(i + 1, n): + + # finding the index + # with same value but + # different index. + if (arr[i] == arr[j]): + ans += 1 + return ans + +# Driven Code +arr = [1, 1, 2 ] +n = len(arr) +print(countPairs(arr, n)) + +# This code is contributed +# by Smitha",constant,quadratic +"# Python3 program to count of index pairs +# with equal elements in an array. +import math as mt + +# Return the number of pairs with +# equal values. +def countPairs(arr, n): + + mp = dict() + + # Finding frequency of each number. + for i in range(n): + if arr[i] in mp.keys(): + mp[arr[i]] += 1 + else: + mp[arr[i]] = 1 + + # Calculating pairs of each value. + ans = 0 + for it in mp: + count = mp[it] + ans += (count * (count - 1)) // 2 + return ans + +# Driver Code +arr = [1, 1, 2] +n = len(arr) +print(countPairs(arr, n)) + +# This code is contributed by mohit kumar 29",linear,linear +"# 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.",constant,linear +"# python program for above implementation + +# Function to count numbers to be added +def countNum(arr, n): + + count = 0 + + # Sort the array + arr.sort() + + # Check if elements are consecutive + # or not. If not, update count + for i in range(0, n-1): + if (arr[i] != arr[i+1] and + arr[i] != arr[i + 1] - 1): + count += arr[i + 1] - arr[i] - 1; + + return count + +# Drivers code +arr = [ 3, 5, 8, 6 ] +n = len(arr) +print(countNum(arr, n)) + +# This code is contributed by Sam007",constant,nlogn +"# Function to count numbers to be added +def countNum(arr, n): + + s = dict() + count, maxm, minm = 0, -10**9, 10**9 + + # Make a hash of elements and store + # minimum and maximum element + for i in range(n): + s[arr[i]] = 1 + if (arr[i] < minm): + minm = arr[i] + if (arr[i] > maxm): + maxm = arr[i] + + # Traverse all elements from minimum + # to maximum and count if it is not + # in the hash + for i in range(minm, maxm + 1): + if i not in s.keys(): + count += 1 + return count + +# Driver code +arr = [3, 5, 8, 6 ] +n = len(arr) +print(countNum(arr, n)) + +# This code is contributed by mohit kumar",constant,linear +"# Python 3 program to calculate sum of +# lengths of subarrays of distinct elements. + +# Returns sum of lengths of all subarrays +# with distinct elements. +def sumoflength(arr, n): + + # For maintaining distinct elements. + s = [] + + # Initialize ending point and result + j = 0 + ans = 0 + + # Fix starting point + for i in range(n): + + # Find ending point for current + # subarray with distinct elements. + while (j < n and (arr[j] not in s)): + s.append(arr[j]) + j += 1 + + # Calculating and adding all possible + # length subarrays in arr[i..j] + ans += ((j - i) * (j - i + 1)) // 2 + + # Remove arr[i] as we pick new + # starting point from next + s.remove(arr[i]) + + return ans + +# Driven Code +if __name__==""__main__"": + + arr = [1, 2, 3, 4] + n = len(arr) + print(sumoflength(arr, n)) + +# This code is contributed by ita_c",linear,linear +"# Python3 program Count total number of +# sub-arrays having total distinct elements +# same as that original array. + +# Function to calculate distinct sub-array +def countDistictSubarray(arr, n): + + # Count distinct elements in whole array + vis = dict() + for i in range(n): + vis[arr[i]] = 1 + k = len(vis) + + # Reset the container by removing + # all elements + vid = dict() + + # Use sliding window concept to find + # count of subarrays having k distinct + # elements. + ans = 0 + right = 0 + window = 0 + for left in range(n): + + while (right < n and window < k): + + if arr[right] in vid.keys(): + vid[ arr[right] ] += 1 + else: + vid[ arr[right] ] = 1 + + if (vid[ arr[right] ] == 1): + window += 1 + + right += 1 + + # If window size equals to array distinct + # element size, then update answer + if (window == k): + ans += (n - right + 1) + + # Decrease the frequency of previous + # element for next sliding window + vid[ arr[left] ] -= 1 + + # If frequency is zero then decrease + # the window size + if (vid[ arr[left] ] == 0): + window -= 1 + + return ans + +# Driver code +arr = [2, 1, 3, 2, 3] +n = len(arr) + +print(countDistictSubarray(arr, n)) + +# This code is contributed by +# mohit kumar 29",linear,linear +"# Python3 program to find largest consecutive +# numbers present in arr. + +def findLongestConseqSubseq(arr, n): + '''We insert all the array elements into unordered set.''' + + S = set(); + for i in range(n): + S.add(arr[i]); + + # check each possible sequence from the start + # then update optimal length + ans = 0; + for i in range(n): + + # if current element is the starting + # element of a sequence + if S.__contains__(arr[i]): + + # Then check for next elements in the + # sequence + j = arr[i]; + + # increment the value of array element + # and repeat search in the set + while(S.__contains__(j)): + j += 1; + + # Update optimal length if this length + # is more. To get the length as it is + # incremented one by one + ans = max(ans, j - arr[i]); + return ans; + +# Driver code +if __name__ == '__main__': + arr = [ 1, 94, 93, 1000, 5, 92, 78 ]; + n = len(arr); + print(findLongestConseqSubseq(arr, n)); + +# This code is contributed by 29AjayKumar",linear,quadratic +"# Python3 program to implement the +# above approach +# Make a set of maximum elements +# from two arrays A[] and B[] +from collections import defaultdict + +def maximizeTheFirstArray(A, B, n): + + # Create copies of A[] and B[] + # and sort the copies in + # descending order. + temp1 = A.copy() + temp2 = B.copy() + temp1.sort(reverse = True) + temp2.sort(reverse = True) + + # Put maximum n distinct + # elements of both sorted + # arrays in a map. + m = defaultdict(int) + i = 0 + j = 0; + + while (len(m) < n): + if (temp1[i] >= temp2[j]): + m[temp1[i]] += 1 + i += 1 + else: + m[temp2[j]] += 1 + j += 1 + + # Copy elements of A[] to that + # are present in hash m. + res = [] + + for i in range (n): + if (A[i] in m): + res.append(A[i]) + + # Copy elements of B[] to that + # are present in hash m. This time + # we also check if the element did + # not appear twice. + for i in range (n): + if (B[i] in m and + m[B[i]] == 1): + res.append(B[i]) + + # Print result + for i in range (n): + print (res[i], end = "" "") + +# Driver code +if __name__ == ""__main__"": + + A = [9, 7, 2, 3, 6] + B = [7, 4, 8, 0, 1] + n = len(A) + maximizeTheFirstArray(A, B, n); + +# This code is contributed by Chitranayal",linear,nlogn +"# Python3 implementation to +# find the maximum number +# of chocolates to be +# distributed equally +# among k students + +# function to find the +# maximum number of chocolates +# to be distributed equally +# among k students +def maxNumOfChocolates(arr, n, k): + + um, curr_rem, maxSum = {}, 0, 0 + + # 'sm[]' to store cumulative sm, + # where sm[i] = sm(arr[0]+..arr[i]) + sm = [0]*n + sm[0] = arr[0] + + # building up 'sm[]' + for i in range(1, n): + sm[i] = sm[i - 1] + arr[i] + + # traversing 'sm[]' + for i in range(n): + + # finding current remainder + curr_rem = sm[i] % k + + if (not curr_rem and maxSum < sm[i]) : + maxSum = sm[i] + elif (not curr_rem in um) : + um[curr_rem] = i + elif (maxSum < (sm[i] - sm[um[curr_rem]])): + maxSum = sm[i] - sm[um[curr_rem]] + + return maxSum//k + +# Driver program to test above +arr = [ 2, 7, 6, 1, 4, 5 ] +n, k = len(arr), 3 + +print(""Maximum number of chocolates: "" + + str(maxNumOfChocolates(arr, n, k))) + +# This code is contributed by Ansu Kumari",linear,linear +"# Python 3 program to print n-th +# number in Recaman's sequence + +# Prints first n terms of Recaman +# sequence +def recaman(n): + + # Create an array to store terms + arr = [0] * n + + # First term of the sequence + # is always 0 + arr[0] = 0 + print(arr[0], end="", "") + + # Fill remaining terms using + # recursive formula. + for i in range(1, n): + + curr = arr[i-1] - i + for j in range(0, i): + + # If arr[i-1] - i is + # negative or already + # exists. + if ((arr[j] == curr) or curr < 0): + curr = arr[i-1] + i + break + + arr[i] = curr + print(arr[i], end="", "") + +# Driver code +n = 17 + +recaman(n) + +# This code is contributed by Smitha.",linear,quadratic +"# Python3 program to print n-th number in +# Recaman's sequence + +# Prints first n terms of Recaman sequence +def recaman(n): + + if(n <= 0): + return + + # Print first term and store it in a hash + print(0, "","", end='') + s = set([]) + s.add(0) + + # Print remaining terms using recursive + # formula. + prev = 0 + for i in range(1, n): + + curr = prev - i + + # If arr[i-1] - i is negative or + # already exists. + if(curr < 0 or curr in s): + curr = prev + i + + s.add(curr) + + print(curr, "","", end='') + prev = curr + +# Driver code +if __name__=='__main__': + n = 17 + recaman(n) + +# This code is contributed by +# Sanjit_Prasad",linear,linear +"# python3 program to find largest Fibonacci subset +# Prints largest subset of an array whose +# all elements are fibonacci numbers +def findFibSubset(arr, n): + #Now iterate through all elements of the array.. + for i in range(n): + #we are using the property of fibonacci series to check arr[i] is a + # fib number or not by checking whether any one out of 5(n^2)+4 and 5(n^2)-4 + # is a perfect square or not. + fact1=5*(arr[i]**2)+4 + fact2=5*(arr[i]**2)-4 + if int(fact1**(.5))**2==fact1 or int(fact2**(.5))**2==fact2: + print(arr[i],end="" "") + return None + + + # Driver code +if __name__ == ""__main__"": + + arr = [4, 2, 8, 5, 20, 1, 40, 13, 23] + n = len(arr) + findFibSubset(arr, n) + # This code is contributed by Rajat Kumar (GLA University)",constant,linear +"# python3 program to find largest Fibonacci subset + +# Prints largest subset of an array whose +# all elements are fibonacci numbers +def findFibSubset(arr, n): + + # Find maximum element in arr[] + m= max(arr) + + # Generate all Fibonacci numbers till + # max and store them in hash. + a = 0 + b = 1 + hash = [] + hash.append(a) + hash.append(b) + while (b < m): + + c = a + b + a = b + b = c + hash.append(b) + + + # Npw iterate through all numbers and + # quickly check for Fibonacci using + # hash. + for i in range (n): + if arr[i] in hash : + print( arr[i],end="" "") + +# Driver code +if __name__ == ""__main__"": + + arr = [4, 2, 8, 5, 20, 1, 40, 13, 23] + n = len(arr) + findFibSubset(arr, n)",linear,linear +"# Python3 program to find averages of +# all levels in a binary tree. + +# Helper function that allocates a +# new node with the given data and +# None left and right pointers. +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +def inorder(node, m): + if (not node): + return """" + + Str = ""("" + Str += inorder(node.left, m) + Str += str(node.data) + Str += inorder(node.right, m) + Str += "")"" + + # Subtree already present (Note that + # we use unordered_map instead of + # unordered_set because we want to print + # multiple duplicates only once, consider + # example of 4 in above subtree, it + # should be printed only once. + if (Str in m and m[Str] == 1): + print(node.data, end = "" "") + if Str in m: + m[Str] += 1 + else: + m[Str] = 1 + + return Str + +# Wrapper over inorder() +def printAllDups(root): + m = {} + inorder(root, m) + +# Driver code +if __name__ == '__main__': + root = None + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.right.left = newNode(2) + root.right.left.left = newNode(4) + root.right.right = newNode(4) + printAllDups(root) + +# This code is contributed by PranchalK",quadratic,quadratic +"# A brute force approach based Python3 program to +# find if there is a rectangle with 1 as corners. + +# Returns true if there is a rectangle +# with 1 as corners. +def isRectangle(m): + + # finding row and column size + rows = len(m) + if (rows == 0): + return False + columns = len(m[0]) + + # scanning the matrix + for y1 in range(rows): + + for x1 in range(columns): + + # if any index found 1 then + # try for all rectangles + if (m[y1][x1] == 1): + for y2 in range(y1 + 1, rows): + for x2 in range(x1 + 1, columns): + if (m[y1][x2] == 1 and + m[y2][x1] == 1 and + m[y2][x2] == 1): + return True + return False + +# Driver code +mat = [[1, 0, 0, 1, 0], + [0, 0, 1, 0, 1], + [0, 0, 0, 1, 0], + [1, 0, 1, 0, 1]] + +if (isRectangle(mat)): + print(""Yes"") +else: + print(""No"") + +# This code is contributed +# by mohit kumar 29",constant,quadratic +"# An efficient approach based Python program +# to find if there is a rectangle with 1 as +# corners. + +# Returns true if there is a rectangle +# with 1 as corners. +def isRectangle(matrix): + + # finding row and column size + rows = len(matrix) + if (rows == 0): + return False + + columns = len(matrix[0]) + + # map for storing the index of + # combination of 2 1's + table = {} + + # scanning from top to bottom + # line by line + for i in range(rows): + for j in range(columns - 1): + for k in range(j + 1, columns): + + # if found two 1's in a column + if (matrix[i][j] == 1 and + matrix[i][k] == 1): + + # check if there exists 1's in same + # row previously then return true + if (j in table and k in table[j]): + return True + + if (k in table and j in table[k]): + return True + + # store the indexes in hashset + if j not in table: + table[j] = set() + if k not in table: + table[k] = set() + table[j].add(k) + table[k].add(j) + return False + +# Driver Code +if __name__ == '__main__': + mat = [[ 1, 0, 0, 1, 0 ], + [ 0, 0, 1, 0, 1 ], + [ 0, 0, 0, 1, 0 ], + [ 1, 0, 1, 0, 1 ]] + if (isRectangle(mat)): + print(""Yes"") + else: + print(""No"") + +# This code is contributed +# by SHUBHAMSINGH10",quadratic,quadratic +"# Python3 implementation comes from: +# https:#github.com/MichaelWehar/FourCornersProblem +# Written by Niteesh Kumar and Michael Wehar +# References: +# [1] F. Mráz, D. Prusa, and M. Wehar. +# Two-dimensional Pattern Matching against +# Basic Picture Languages. CIAA 2019. +# [2] D. Prusa and M. Wehar. Complexity of +# Searching for 2 by 2 Submatrices in Boolean +# Matrices. DLT 2020. +def searchForRectangle( rows, cols, mat) : + + # Make sure that matrix is non-trivial + if (rows < 2 or cols < 2) : + + return False; + + # Create map + adjsList = dict(); + if (rows >= cols): + + # Row-wise + num_of_keys = rows; + + # Convert each row into vector of col indexes + for i in range(rows): + + for j in range(cols): + + if (mat[i][j]): + + if i not in adjsList: + adjsList[i] = [] + adjsList[i].append(j); + else : + + # Col-wise + num_of_keys = cols; + + # Convert each col into vector of row indexes + for i in range(rows): + + for j in range(cols): + + if (mat[i][j] == 1) : + + if j not in adjsList: + adjsList[j] = [] + adjsList[j].append(i); + + # Search for a rectangle whose four corners are 1's + pairs = dict(); + + for i in range(num_of_keys): + + values = adjsList[i]; + size = len(values) + + for j in range(size - 1): + + for k in range(j + 1, size): + + temp = (values[j], values[k]); + + if temp in pairs: + return True; + + else: + pairs[temp] = i; + return False; + +# Driver code +mat = [[ 1, 0, 0, 1, 0 ], [ 0, 1, 1, 1, 1 ], [ 0, 0, 0, 1, 0 ], [ 1, 1, 1, 1, 0 ]]; +if (searchForRectangle(4, 5, mat)): + print(""Yes""); +else: + print(""No"") + +# This code is contributed by phasing17.",quadratic,quadratic +"# Python3 program for finding +# maximum area possible of +# a rectangle + +# function for finding +# max area +def findArea(arr, n): + + # sort array in + # non-increasing order + arr.sort(reverse = True) + + # Initialize two + # sides of rectangle + dimension = [0, 0] + + # traverse through array + i = 0 + j = 0 + while(i < n - 1 and j < 2): + + # if any element occurs twice + # store that as dimension + if (arr[i] == arr[i + 1]): + dimension[j] = arr[i] + j += 1 + i += 1 + i += 1 + + # return the product + # of dimensions + return (dimension[0] * + dimension[1]) + +# Driver code +arr = [4, 2, 1, 4, 6, 6, 2, 5] +n = len(arr) +print(findArea(arr, n)) + +# This code is contributed +# by Smitha",constant,nlogn +"# Python 3 program for finding maximum +# area possible of a rectangle + +# function for finding max area +def findArea(arr, n): + + s = [] + + # traverse through array + first = 0 + second = 0 + for i in range(n) : + + # If this is first occurrence of + # arr[i], simply insert and continue + if arr[i] not in s: + s.append(arr[i]) + continue + + # If this is second (or more) occurrence, + # update first and second maximum values. + if (arr[i] > first) : + second = first + first = arr[i] + else if (arr[i] > second): + second = arr[i] + + # return the product of dimensions + return (first * second) + +# Driver Code +if __name__ == ""__main__"": + + arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ] + n = len(arr) + print(findArea(arr, n)) + +# This code is contributed by ita_c",linear,linear +"# Python3 implementation to find length of +# longest strict bitonic subsequence + +# function to find length of longest +# strict bitonic subsequence +def longLenStrictBitonicSub(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/first element of that subsequence + inc, dcr = dict(), dict() + + # arrays to store the length of increasing + # and decreasing subsequences which end at + # them or start from them + len_inc, len_dcr = [0] * n, [0] * n + + # to store the length of longest strict + # bitonic subsequence + longLen = 0 + + # traverse the array elements + # from left to right + for i in range(n): + + # initialize current length + # for element arr[i] as 0 + len = 0 + + # if 'arr[i]-1' is in 'inc' + if inc.get(arr[i] - 1) in inc.values(): + len = inc.get(arr[i] - 1) + + # update arr[i] subsequence length in 'inc' + # and in len_inc[] + inc[arr[i]] = len_inc[i] = len + 1 + + # traverse the array elements + # from right to left + for i in range(n - 1, -1, -1): + + # initialize current length + # for element arr[i] as 0 + len = 0 + + # if 'arr[i]-1' is in 'dcr' + if dcr.get(arr[i] - 1) in dcr.values(): + len = dcr.get(arr[i] - 1) + + # update arr[i] subsequence length + # in 'dcr' and in len_dcr[] + dcr[arr[i]] = len_dcr[i] = len + 1 + + # calculating the length of + # all the strict bitonic subsequence + for i in range(n): + if longLen < (len_inc[i] + len_dcr[i] - 1): + longLen = len_inc[i] + len_dcr[i] - 1 + + # required longest length strict + # bitonic subsequence + return longLen + +# Driver Code +if __name__ == ""__main__"": + arr = [1, 5, 2, 3, 4, 5, 3, 2] + n = len(arr) + print(""Longest length strict bitonic subsequence ="", + longLenStrictBitonicSub(arr, n)) + +# This code is contributed by sanjeev2552",linear,linear +"# Python3 program to find last seen +# element in an array. +import sys; + +# Returns last seen element in arr[] +def lastSeenElement(a, n): + + # Store last occurrence index of + # every element + hash = {} + + for i in range(n): + hash[a[i]] = i + + # Find an element in hash with minimum + # index value + res_ind = sys.maxsize + res = 0 + + for x, y in hash.items(): + if y < res_ind: + res_ind = y + res = x + + return res + +# Driver code +if __name__==""__main__"": + + a = [ 2, 1, 2, 2, 4, 1 ] + n = len(a) + + print(lastSeenElement(a,n)) + +# This code is contributed by rutvik_56",linear,linear +"# Python program to delete a node in a linked list +# at a given position + +# Node class + + +class Node: + + # Constructor to initialize the node object + def __init__(self, data): + self.data = data + self.next = None + + +class LinkedList: + + # Constructor to initialize head + def __init__(self): + self.head = None + + # Function to insert a new node at the beginning + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + # Given a reference to the head of a list + # and a position, delete the node at a given position + # This delete function code is contributed by Arabin Islam + def deleteNodeAtGivenPosition(self, position): + if self.head is None: + return + index = 0 + current = self.head + while current.next and index < position: + previous = current + current = current.next + index += 1 + if index < position: + print(""\nIndex is out of range."") + elif index == 0: + self.head = self.head.next + else: + previous.next = current.next + # current = None #Optional statement + + # Utility function to print the LinkedList + + def printList(self): + temp = self.head + while(temp): + print("" %d "" % (temp.data), end="" "") + temp = temp.next + + +# Driver program to test above function +llist = LinkedList() +llist.push(7) +llist.push(1) +llist.push(3) +llist.push(2) +llist.push(8) + +print(""Created Linked List: "") +llist.printList() +llist.deleteNodeAtGivenPosition(4) +print(""\nLinked List after Deletion at position 4: "") +llist.printList() + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",constant,linear +"# Python3 program to delete all +# the nodes of singly linked list + +# Node class + + +class Node: + + # Function to initialise the node object + def __init__(self, data): + self.data = data # Assign data + self.next = None # Initialize next as null + + +# Constructor to initialize the node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + def deleteList(self): + + # initialize the current node + current = self.head + while current: + next_to_current = current.next # move next node + + # delete the current node + del current.data + + # set current equals prev node + current = next_to_current + + # In python garbage collection happens + # therefore, only + # self.head = None + # would also delete the link list + + # push function to add node in front of llist + def push(self, new_data): + + # Allocate the Node & + # Put in the data + new_node = Node(new_data) + + # Make next of new Node as head + new_node.next = self.head + + # Move the head to point to new Node + self.head = new_node + + +# Use push() to construct below +# list 1-> 12-> 1-> 4-> 1 +if __name__ == '__main__': + + llist = LinkedList() + llist.push(1) + llist.push(4) + llist.push(1) + llist.push(12) + llist.push(1) + + print(""Deleting linked list"") + llist.deleteList() + + print(""Linked list deleted"") + + +# This article is provided by Shrikant13",constant,linear +"# A complete working Python program to find length of a +# Linked List iteratively + +# Node class + + +class Node: + # Function to initialise the node object + def __init__(self, data): + self.data = data # Assign data + self.next = None # Initialize next as null + + +# Linked List class contains a Node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # This function is in LinkedList class. It inserts + # a new node at the beginning of Linked List. + + def push(self, new_data): + + # 1 & 2: Allocate the Node & + # Put in the data + new_node = Node(new_data) + + # 3. Make next of new Node as head + new_node.next = self.head + + # 4. Move the head to point to new Node + self.head = new_node + + # This function counts number of nodes in Linked List + # iteratively, given 'node' as starting node. + + def getCount(self): + temp = self.head # Initialise temp + count = 0 # Initialise count + + # Loop while end of linked list is not reached + while (temp): + count += 1 + temp = temp.next + return count + + +# Driver code +if __name__ == '__main__': + llist = LinkedList() + llist.push(1) + llist.push(3) + llist.push(1) + llist.push(2) + llist.push(1) + + # Function call + print(""Count of nodes is :"", llist.getCount())",constant,linear +"# A complete working Python program to find length of a +# Linked List recursively + +# Node class + + +class Node: + # Function to initialise the node object + def __init__(self, data): + self.data = data # Assign data + self.next = None # Initialize next as null + + +# Linked List class contains a Node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # This function is in LinkedList class. It inserts + # a new node at the beginning of Linked List. + + def push(self, new_data): + + # 1 & 2: Allocate the Node & + # Put in the data + new_node = Node(new_data) + + # 3. Make next of new Node as head + new_node.next = self.head + + # 4. Move the head to point to new Node + self.head = new_node + + # This function counts number of nodes in Linked List + # recursively, given 'node' as starting node. + def getCountRec(self, node): + if (not node): # Base case + return 0 + else: + return 1 + self.getCountRec(node.next) + + # A wrapper over getCountRec() + def getCount(self): + return self.getCountRec(self.head) + + +# Code execution starts here +if __name__ == '__main__': + llist = LinkedList() + llist.push(1) + llist.push(3) + llist.push(1) + llist.push(2) + llist.push(1) + print('Count of nodes is :', llist.getCount())",linear,linear +"# A complete working Python3 program to find length of a +# Linked List using Tail recursion. + +# Node class + + +class Node: + # Function to initialise the node object + def __init__(self, data): + self.data = data # Assign data + self.next = None # Initialize next as null + + +# Linked List class contains a Node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # This function is in LinkedList class. It inserts + # a new node at the beginning of Linked List. + + def push(self, new_data): + + # 1 & 2: Allocate the Node & + # Put in the data + new_node = Node(new_data) + + # 3. Make next of new Node as head + new_node.next = self.head + + # 4. Move the head to point to new Node + self.head = new_node + + # This function counts number of nodes in Linked List + # recursively, given 'node' as starting node using Tail Recursion. + def getCountRec(self, node, count=0): + if (not node): # Base case + return count + else: + return self.getCountRec(node.next, count+1) + + # A wrapper over getCountRec() + def getCount(self): + return self.getCountRec(self.head) + + +# Driver code +if __name__ == '__main__': + llist = LinkedList() + llist.push(1) + llist.push(3) + llist.push(1) + llist.push(2) + llist.push(1) + + # Function call + print('Count of nodes is :', llist.getCount()) + + # This code is contributed by garinesrija.",constant,linear +"# Iterative Python3 program to search an element +# in linked list + +# Node class + + +class Node: + + # Function to initialise the node object + def __init__(self, data): + self.data = data # Assign data + self.next = None # Initialize next as null + +# Linked List class + + +class LinkedList: + def __init__(self): + self.head = None # Initialize head as None + + # This function insert a new node at the + # beginning of the linked list + def push(self, new_data): + + # Create a new Node + new_node = Node(new_data) + + # 3. Make next of new Node as head + new_node.next = self.head + + # 4. Move the head to point to new Node + self.head = new_node + + # This Function checks whether the value + # x present in the linked list + def search(self, x): + + # Initialize current to head + current = self.head + + # loop till current not equal to None + while current != None: + if current.data == x: + return True # data found + + current = current.next + + return False # Data Not found + + +# Driver code +if __name__ == '__main__': + + # Start with the empty list + llist = LinkedList() + + ''' Use push() to construct below list + 14->21->11->30->10 ''' + llist.push(10) + llist.push(30) + llist.push(11) + llist.push(21) + llist.push(14) + + # Function call + if llist.search(21): + print(""Yes"") + else: + print(""No"") + +# This code is contributed by Ravi Shankar",constant,linear +"# Recursive Python program to +# search an element in linked list + +# Node class + + +class Node: + + # Function to initialise + # the node object + def __init__(self, data): + self.data = data # Assign data + self.next = None # Initialize next as null + + +class LinkedList: + + def __init__(self): + self.head = None # Initialize head as None + + # This function insert a new node at + # the beginning of the linked list + def push(self, new_data): + + # Create a new Node + new_node = Node(new_data) + + # Make next of new Node as head + new_node.next = self.head + + # Move the head to + # point to new Node + self.head = new_node + + # Checks whether the value key + # is present in linked list + + def search(self, li, key): + + # Base case + if(not li): + return False + + # If key is present in + # current node, return true + if(li.data == key): + return True + + # Recur for remaining list + return self.search(li.next, key) + + +# Driver Code +if __name__ == '__main__': + + li = LinkedList() + + li.push(1) + li.push(2) + li.push(3) + li.push(4) + + key = 4 + + # Function call + if li.search(li.head, key): + print(""Yes"") + else: + print(""No"") + +# This code is contributed +# by Manoj Sharma",linear,linear +"# Python3 program to find middle of linked list +# Node class +class Node: + + # Function to initialise the node object + def __init__(self, data): + self.data = data # Assign data + self.next = None # Initialize next as null + + +# Linked List class contains a Node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # Function to insert a new node at the beginning + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + # Print the linked list + def printList(self): + node = self.head + while node: + print(str(node.data) + ""->"", end="""") + node = node.next + print(""NULL"") + + # Function that returns middle. + def printMiddle(self): + # Initialize two pointers, one will go one step a time (slow), another two at a time (fast) + slow = self.head + fast = self.head + + # Iterate till fast's next is null (fast reaches end) + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + # return the slow's data, which would be the middle element. + print(""The middle element is "", slow.data) + +# Code execution starts here +if __name__=='__main__': + + # Start with the empty list + llist = LinkedList() + + for i in range(5, 0, -1): + llist.push(i) + llist.printList() + llist.printMiddle() + + # Code is contributed by Kumar Shivam (kshivi99)",constant,linear +"# Node class +class Node: + + # Function to initialise the node object + def __init__(self, data): + self.data = data # Assign data + self.next = None # Initialize next as null + +# Linked List class contains a Node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # Function to insert a new node at the beginning + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + # Print the linked list + def printList(self): + node = self.head + while node: + print(str(node.data) + ""->"", end = """") + node = node.next + print(""NULL"") + + # Function to get the middle of + # the linked list + def printMiddle(self): + count = 0 + mid = self.head + heads = self.head + + while(heads != None): + + # Update mid, when 'count' + # is odd number + if count&1: + mid = mid.next + count += 1 + heads = heads.next + + # If empty list is provided + if mid!=None: + print(""The middle element is "", mid.data) + +# Code execution starts here +if __name__=='__main__': + + # Start with the empty list + llist = LinkedList() + + for i in range(5, 0, -1): + llist.push(i) + llist.printList() + llist.printMiddle() + + # This Code is contributed by Manisha_Ediga",constant,linear +"# Python 3 program to find the number +# of nodes in loop in a linked list +# if loop is present + +# Python Code to detect a loop and +# find the length of the loop +# Node defining class + + +class Node: + + # Function to make a node + def __init__(self, val): + self.val = val + self.next = None + +# Linked List defining and loop +# length finding class + + +class LinkedList: + + # Function to initialize the + # head of the linked list + def __init__(self): + self.head = None + + # Function to insert a new + # node at the end + def AddNode(self, val): + if self.head is None: + self.head = Node(val) + else: + curr = self.head + while(curr.next): + curr = curr.next + curr.next = Node(val) + + # Function to create a loop in the + # Linked List. This function creates + # a loop by connecting the last node + # to n^th node of the linked list, + # (counting first node as 1) + def CreateLoop(self, n): + + # LoopNode is the connecting node to + # the last node of linked list + LoopNode = self.head + for _ in range(1, n): + LoopNode = LoopNode.next + + # end is the last node of the Linked List + end = self.head + while(end.next): + end = end.next + + # Creating the loop + end.next = LoopNode + + # Function to detect the loop and return + # the length of the loop if the returned + # value is zero, that means that either + # the linked list is empty or the linked + # list doesn't have any loop + def detectLoop(self): + + # if linked list is empty then there + # is no loop, so return 0 + if self.head is None: + return 0 + + # Using Floyd’s Cycle-Finding + # Algorithm/ Slow-Fast Pointer Method + slow = self.head + fast = self.head + flag = 0 # to show that both slow and fast + # are at start of the Linked List + while(slow and slow.next and fast and + fast.next and fast.next.next): + if slow == fast and flag != 0: + + # Means loop is confirmed in the + # Linked List. Now slow and fast + # are both at the same node which + # is part of the loop + count = 1 + slow = slow.next + while(slow != fast): + slow = slow.next + count += 1 + return count + + slow = slow.next + fast = fast.next.next + flag = 1 + return 0 # No loop + + +# Setting up the code +# Making a Linked List and adding the nodes +myLL = LinkedList() +myLL.AddNode(1) +myLL.AddNode(2) +myLL.AddNode(3) +myLL.AddNode(4) +myLL.AddNode(5) + +# Creating a loop in the linked List +# Loop is created by connecting the +# last node of linked list to n^th node +# 1<= n <= len(LinkedList) +myLL.CreateLoop(2) + +# Checking for Loop in the Linked List +# and printing the length of the loop +loopLength = myLL.detectLoop() +if myLL.head is None: + print(""Linked list is empty"") +else: + print(str(loopLength)) + +# This code is contributed by _Ashutosh",constant,linear +"# Python3 program to check if linked +# list is palindrome using stack + + +class Node: + def __init__(self, data): + + self.data = data + self.ptr = None + +# Function to check if the linked list +# is palindrome or not + + +def ispalindrome(head): + + # Temp pointer + slow = head + + # Declare a stack + stack = [] + + ispalin = True + + # Push all elements of the list + # to the stack + while slow != None: + stack.append(slow.data) + + # Move ahead + slow = slow.ptr + + # Iterate in the list again and + # check by popping from the stack + while head != None: + + # Get the top most element + i = stack.pop() + + # Check if data is not + # same as popped element + if head.data == i: + ispalin = True + else: + ispalin = False + break + + # Move ahead + head = head.ptr + + return ispalin + +# Driver Code + + +# Addition of linked list +one = Node(1) +two = Node(2) +three = Node(3) +four = Node(4) +five = Node(3) +six = Node(2) +seven = Node(1) + +# Initialize the next pointer +# of every current pointer +one.ptr = two +two.ptr = three +three.ptr = four +four.ptr = five +five.ptr = six +six.ptr = seven +seven.ptr = None + +# Call function to check palindrome or not +result = ispalindrome(one) + +print(""isPalindrome:"", result) + +# This code is contributed by Nishtha Goel",linear,linear +"# Python3 program to check if +# linked list is palindrome + +# Node class + + +class Node: + + # Constructor to initialize + # the node object + def __init__(self, data): + + self.data = data + self.next = None + + +class LinkedList: + + # Function to initialize head + def __init__(self): + + self.head = None + + # Function to check if given + # linked list is palindrome or not + def isPalindrome(self, head): + + slow_ptr = head + fast_ptr = head + prev_of_slow_ptr = head + + # To handle odd size list + midnode = None + + # Initialize result + res = True + + if (head != None and head.next != None): + + # Get the middle of the list. + # Move slow_ptr by 1 and + # fast_ptr by 2, slow_ptr + # will have the middle node + while (fast_ptr != None and + fast_ptr.next != None): + + # We need previous of the slow_ptr + # for linked lists with odd + # elements + fast_ptr = fast_ptr.next.next + prev_of_slow_ptr = slow_ptr + slow_ptr = slow_ptr.next + + # fast_ptr would become NULL when + # there are even elements in the + # list and not NULL for odd elements. + # We need to skip the middle node for + # odd case and store it somewhere so + # that we can restore the original list + if (fast_ptr != None): + midnode = slow_ptr + slow_ptr = slow_ptr.next + + # Now reverse the second half + # and compare it with first half + second_half = slow_ptr + + # NULL terminate first half + prev_of_slow_ptr.next = None + + # Reverse the second half + second_half = self.reverse(second_half) + + # Compare + res = self.compareLists(head, second_half) + + # Construct the original list back + # Reverse the second half again + second_half = self.reverse(second_half) + + if (midnode != None): + + # If there was a mid node (odd size + # case) which was not part of either + # first half or second half. + prev_of_slow_ptr.next = midnode + midnode.next = second_half + else: + prev_of_slow_ptr.next = second_half + return res + + # Function to reverse the linked list + # Note that this function may change + # the head + def reverse(self, second_half): + + prev = None + current = second_half + next = None + + while current != None: + next = current.next + current.next = prev + prev = current + current = next + + second_half = prev + return second_half + + # Function to check if two input + # lists have same data + def compareLists(self, head1, head2): + + temp1 = head1 + temp2 = head2 + + while (temp1 and temp2): + if (temp1.data == temp2.data): + temp1 = temp1.next + temp2 = temp2.next + else: + return 0 + + # Both are empty return 1 + if (temp1 == None and temp2 == None): + return 1 + + # Will reach here when one is NULL + # and other is not + return 0 + + # Function to insert a new node + # at the beginning + def push(self, new_data): + + # Allocate the Node & + # Put in the data + new_node = Node(new_data) + + # Link the old list of the new one + new_node.next = self.head + + # Move the head to point to new Node + self.head = new_node + + # A utility function to print + # a given linked list + def printList(self): + + temp = self.head + + while(temp): + print(temp.data, end=""->"") + temp = temp.next + + print(""NULL"") + + +# Driver code +if __name__ == '__main__': + + l = LinkedList() + s = ['a', 'b', 'a', 'c', 'a', 'b', 'a'] + + for i in range(7): + l.push(s[i]) + if (l.isPalindrome(l.head) != False): + print(""Is Palindrome\n"") + else: + print(""Not Palindrome\n"") + +# This code is contributed by MuskanKalra1",constant,linear +"# Python program for the above approach + +# Head of the list +head = None +left = None + + +class Node: + def __init__(self, val): + self.data = val + self.next = None + +# Initial parameters to this function are +# &head and head + + +def isPalindromeUtil(right): + global head, left + + left = head + + # Stop recursion when right becomes null + if (right == None): + return True + + # If sub-list is not palindrome then no need to + # check for the current left and right, return + # false + isp = isPalindromeUtil(right.next) + if (isp == False): + return False + + # Check values at current left and right + isp1 = (right.data == left.data) + + left = left.next + + # Move left to next node; + return isp1 + +# A wrapper over isPalindrome(Node head) + + +def isPalindrome(head): + result = isPalindromeUtil(head) + return result + +# Push a node to linked list. Note that +# this function changes the head + + +def push(new_data): + global head + + # Allocate the node and put in the data + new_node = Node(new_data) + + # Link the old list off the the new one + new_node.next = head + + # Move the head to point to new node + head = new_node + +# A utility function to print a +# given linked list + + +def printList(ptr): + while (ptr != None): + print(ptr.data, end=""->"") + ptr = ptr.next + + print(""Null "") + + +# Driver Code +str = ['a', 'b', 'a', 'c', 'a', 'b', 'a'] + +for i in range(0, 7): + push(str[i]) + +if (isPalindrome(head) and i != 0): + print(""Is Palindrome\n"") +else: + print(""Not Palindrome\n"") + +# This code is contributed by saurabh_jaiswal.",linear,linear +"# Python3 code to move the last item to front + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class LinkedList: + def __init__(self): + self.head = None + + # Function to add a node + # at the beginning of Linked List + def push(self, data): + new_node = Node(data) + new_node.next = self.head + self.head = new_node + + # Function to print nodes in a + # given linked list + def printList(self): + tmp = self.head + while tmp is not None: + print(tmp.data, end="", "") + tmp = tmp.next + print() + + # Function to bring the last node to the front + def moveToFront(self): + tmp = self.head + sec_last = None # To maintain the track of + # the second last node + + # To check whether we have not received + # the empty list or list with a single node + if not tmp or not tmp.next: + return + + # Iterate till the end to get + # the last and second last node + while tmp and tmp.next: + sec_last = tmp + tmp = tmp.next + + # point the next of the second + # last node to None + sec_last.next = None + + # Make the last node as the first Node + tmp.next = self.head + self.head = tmp + + +# Driver's Code +if __name__ == '__main__': + llist = LinkedList() + + # swap the 2 nodes + llist.push(5) + llist.push(4) + llist.push(3) + llist.push(2) + llist.push(1) + print(""Linked List before moving last to front "") + llist.printList() + + # Function call + llist.moveToFront() + print(""Linked List after moving last to front "") + llist.printList()",constant,linear +"''' Link list node ''' +class Node: + def __init__(self): + self.data = 0 + self.next = None + +'''This solution uses the temporary + dummy to build up the result list ''' +def sortedIntersect(a, b): + dummy = Node() + tail = dummy; + dummy.next = None; + + ''' Once one or the other + list runs out -- we're done ''' + while (a != None and b != None): + if (a.data == b.data): + tail.next = push((tail.next), a.data); + tail = tail.next; + a = a.next; + b = b.next; + + # advance the smaller list + elif(a.data < b.data): + a = a.next; + else: + b = b.next; + return (dummy.next); + +''' UTILITY FUNCTIONS ''' +''' Function to insert a node at +the beginning of the linked list ''' +def push(head_ref, new_data): + + ''' allocate node ''' + new_node = Node() + + ''' put in the data ''' + new_node.data = new_data; + + ''' link the old list off the new node ''' + new_node.next = (head_ref); + + ''' move the head to point to the new node ''' + (head_ref) = new_node; + return head_ref + +''' Function to print nodes in + a given linked list ''' +def printList(node): + while (node != None): + print(node.data, end=' ') + node = node.next; + +''' Driver code''' +if __name__=='__main__': + + ''' Start with the empty lists ''' + a = None; + b = None; + intersect = None; + + ''' Let us create the first sorted + linked list to test the functions + Created linked list will be + 1.2.3.4.5.6 ''' + a = push(a, 6); + a = push(a, 5); + a = push(a, 4); + a = push(a, 3); + a = push(a, 2); + a = push(a, 1); + + ''' Let us create the second sorted linked list + Created linked list will be 2.4.6.8 ''' + b = push(b, 8); + b = push(b, 6); + b = push(b, 4); + b = push(b, 2); + + ''' Find the intersection two linked lists ''' + intersect = sortedIntersect(a, b); + + print(""Linked list containing common items of a & b ""); + printList(intersect); + +# This code is contributed by rutvik_56.",linear,linear +"# Python3 program to implement above approach + +# Link list node +class Node: + def __init__(self, d): + self.data = d + self.next = None + + +def sortedIntersect(a, b): + + result = Node(0) + curr = result + + # Advance comparing the first + # nodes in both lists. + # When one or the other list runs + # out, we're done. + while (a != None and b != None): + if (a.data == b.data): + # found a node for the intersection + curr.next = Node(a.data) + curr = curr.next + + a = a.next + b = b.next + elif (a.data < b.data): + a = a.next # advance the smaller list + else: + b = b.next + result = result.next + return result + + +# UTILITY FUNCTIONS +# Function to insert a node at the beginning of the linked list +def push(head_ref, new_data): + + # Allocate node + new_node = Node(new_data) + + # Link the old list of the new node + new_node.next = head_ref + + # Move the head to point to the new node + head_ref = new_node + return head_ref + + # Function to print nodes in a given linked list + + +def printList(node): + while (node != None): + print(node.data, end="" "") + node = node.next + + +# Driver code + +# Start with the empty lists +a = None +b = None +intersect = None + +# Let us create the first sorted linked list to test the functions Created +# linked list will be 1.2.3.4.5.6 + +a = push(a, 6) +a = push(a, 5) +a = push(a, 4) +a = push(a, 3) +a = push(a, 2) +a = push(a, 1) + +# Let us create the second sorted linked list Created linked list will be +# 2.4.6.8 + +b = push(b, 8) +b = push(b, 6) +b = push(b, 4) +b = push(b, 2) + +# Find the intersection two linked lists +intersect = sortedIntersect(a, b) + +print(""Linked list containing "" + ""common items of a & b"") +printList(intersect) + +# This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear +"# Link list node +class Node: + def __init__(self): + self.data = 0 + self.next = None + + +def sortedIntersect(a, b): + + # base case + if (a == None or b == None): + return None + + # If both lists are non-empty + # Advance the smaller list and call recursively + if (a.data < b.data): + return sortedIntersect(a.next, b); + + if (a.data > b.data): + return sortedIntersect(a, b.next); + + # Below lines are executed only + # when a.data == b.data + temp = Node(); + temp.data = a.data; + + # Advance both lists and call recursively + temp.next = sortedIntersect(a.next, b.next); + return temp; + + # UTILITY FUNCTIONS + # Function to insert a node at the beginning of the linked list + +def push(head_ref, new_data): + + # Allocate node + new_node = Node() + + # Put in the data + new_node.data = new_data; + + # Link the old list of the new node + new_node.next = head_ref; + + # Move the head to point to the new node + head_ref = new_node; + return head_ref; + + # Function to print nodes in a given linked list + +def printList(node): + while (node != None): + print(node.data, end="" "") + node = node.next; + + +# Driver code + +# Start with the empty lists +a = None +b = None +intersect = None + +# Let us create the first sorted linked list to test the functions Created +# linked list will be 1.2.3.4.5.6 + +a = push(a, 6) +a = push(a, 5) +a = push(a, 4) +a = push(a, 3) +a = push(a, 2) +a = push(a, 1) + +# Let us create the second sorted linked list Created linked list will be +# 2.4.6.8 + +b = push(b, 8) +b = push(b, 6) +b = push(b, 4) +b = push(b, 2) + +# Find the intersection two linked lists +intersect = sortedIntersect(a, b) + +print(""\n Linked list containing "" + ""common items of a & b""); +printList(intersect) + +# This code is contributed by Saurabh Jaiswal",linear,linear +"# Python3 program to implement above approach + +# Link list node +class Node: + def __init__(self): + self.data = 0 + self.next = None + + +def printList(node): + while (node != None): + print(node.data, end="" "") + node = node.next; + + +def append(head_ref, new_data): + + new_node = Node() + + new_node.data = new_data; + + new_node.next = head_ref; + + head_ref = new_node; + return head_ref; + + +def intersection(tmp1,tmp2,k): + res = [0]*k + + set1 = set() + while (tmp1 != None): + set1.add(tmp1.data) + tmp1 = tmp1.next + + cnt = 0 + while (tmp2 != None): + if tmp2.data in set1: + res[cnt] = tmp2.data; + cnt += 1 + + tmp2 = tmp2.next + + return res + +def printList(node): + while (node != None): + print(node.data, end="" "") + node = node.next; + + +# Driver code + +# Start with the empty lists +ll = None +ll1 = None + +ll = append(ll , 7) +ll = append(ll , 6) +ll = append(ll , 5) +ll = append(ll , 4) +ll = append(ll , 3) +ll = append(ll , 2) +ll = append(ll , 1) +ll = append(ll , 0) + +ll1 = append(ll1 , 7) +ll1 = append(ll1 , 6) +ll1 = append(ll1 , 5) +ll1 = append(ll1 , 4) +ll1 = append(ll1 , 3) +ll1 = append(ll1 , 12) +ll1 = append(ll1 , 0) +ll1 = append(ll1 , 9) + + +arr = intersection(ll , ll1 , 6) + +for i in range(6): + print(arr[i]) + + +# This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear +"''' + +sort a linked list using quick sort + +''' + + +class Node: + def __init__(self, val): + self.data = val + self.next = None + + +class QuickSortLinkedList: + + def __init__(self): + self.head = None + + def addNode(self, data): + if (self.head == None): + self.head = Node(data) + return + + curr = self.head + while (curr.next != None): + curr = curr.next + + newNode = Node(data) + curr.next = newNode + + def printList(self, n): + while (n != None): + print(n.data, end="" "") + n = n.next + + ''' takes first and last node,but do not + break any links in the whole linked list''' + + def paritionLast(self, start, end): + if (start == end or start == None or end == None): + return start + + pivot_prev = start + curr = start + pivot = end.data + + '''iterate till one before the end, + no need to iterate till the end because end is pivot''' + + while (start != end): + if (start.data < pivot): + + # keep tracks of last modified item + pivot_prev = curr + temp = curr.data + curr.data = start.data + start.data = temp + curr = curr.next + start = start.next + + '''swap the position of curr i.e. + next suitable index and pivot''' + + temp = curr.data + curr.data = pivot + end.data = temp + + ''' return one previous to current because + current is now pointing to pivot ''' + return pivot_prev + + def sort(self, start, end): + if(start == None or start == end or start == end.next): + return + + # split list and partition recurse + pivot_prev = self.paritionLast(start, end) + self.sort(start, pivot_prev) + + ''' + if pivot is picked and moved to the start, + that means start and pivot is same + so pick from next of pivot + ''' + if(pivot_prev != None and pivot_prev == start): + self.sort(pivot_prev.next, end) + + # if pivot is in between of the list,start from next of pivot, + # since we have pivot_prev, so we move two nodes + elif (pivot_prev != None and pivot_prev.next != None): + self.sort(pivot_prev.next.next, end) + + +if __name__ == ""__main__"": + ll = QuickSortLinkedList() + ll.addNode(30) + ll.addNode(3) + ll.addNode(4) + ll.addNode(20) + ll.addNode(5) + + N = ll.head + while (N.next != None): + N = N.next + + print(""\nLinked List before sorting"") + ll.printList(ll.head) + + # Function call + ll.sort(ll.head, N) + + print(""\nLinked List after sorting"") + ll.printList(ll.head) + + # This code is contributed by humpheykibet.",linear,nlogn +"# Python3 program to check if a linked list is circular + +# Node class + + +class Node: + + # Function to initialise the node object + def __init__(self, data): + self.data = data # Assign data + self.next = None # Initialize next as null + + +# Linked List class contains a Node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + +def Circular(head): + if head == None: + return True + + # Next of head + node = head.next + i = 0 + + # This loop would stop in both cases (1) If + # Circular (2) Not circular + while((node is not None) and (node is not head)): + i = i + 1 + node = node.next + + return(node == head) + + +# Driver's code +if __name__ == '__main__': + llist = LinkedList() + llist.head = Node(1) + second = Node(2) + third = Node(3) + fourth = Node(4) + + llist.head.next = second + second.next = third + third.next = fourth + + if (Circular(llist.head)): + print('Yes') + else: + print('No') + + fourth.next = llist.head + + if (Circular(llist.head)): + print('Yes') + else: + print('No') + +# This code is contributed by Sanket Badhe",constant,linear +"// C Program to convert a Binary Tree +// to a Circular Doubly Linked List +#include +#include + +// To represents a node of a Binary Tree +typedef struct Node { + struct Node *left, *right; + int data; +} Node; + +// A function that appends rightList at the end +// of leftList. +Node* concatenate(Node* leftList, Node* rightList) +{ + // If either of the list is empty + // then return the other list + if (leftList == NULL) + return rightList; + if (rightList == NULL) + return leftList; + + // Store the last Node of left List + Node* leftLast = leftList->left; + + // Store the last Node of right List + Node* rightLast = rightList->left; + + // Connect the last node of Left List + // with the first Node of the right List + leftLast->right = rightList; + rightList->left = leftLast; + + // Left of first node points to + // the last node in the list + leftList->left = rightLast; + + // Right of last node refers to the first + // node of the List + rightLast->right = leftList; + + return leftList; +} + +// Function converts a tree to a circular Linked List +// and then returns the head of the Linked List +Node* bTreeToCList(Node* root) +{ + if (root == NULL) + return NULL; + + // Recursively convert left and right subtrees + Node* left = bTreeToCList(root->left); + Node* right = bTreeToCList(root->right); + + // Make a circular linked list of single node + // (or root). To do so, make the right and + // left pointers of this node point to itself + root->left = root->right = root; + + // Step 1 (concatenate the left list with the list + // with single node, i.e., current node) + // Step 2 (concatenate the returned list with the + // right List) + return concatenate(concatenate(left, root), right); +} + +// Display Circular Link List +void displayCList(Node* head) +{ + printf(""Circular Linked List is :\n""); + Node* itr = head; + do { + printf(""%d "", itr->data); + itr = itr->right; + } while (head != itr); + printf(""\n""); +} + +// Create a new Node and return its address +Node* newNode(int data) +{ + Node* temp = (Node*)malloc(sizeof(Node)); + temp->data = data; + temp->left = temp->right = NULL; + return temp; +} + +// Driver Program to test above function +int main() +{ + Node* root = newNode(10); + root->left = newNode(12); + root->right = newNode(15); + root->left->left = newNode(25); + root->left->right = newNode(30); + root->right->left = newNode(36); + + Node* head = bTreeToCList(root); + displayCList(head); + + return 0; +} + +// This code is contributed by Aditya Kumar (adityakumar129)",logn,linear +"# Python3 Program to convert a Binary +# Tree to a Circular Doubly Linked List + + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# A function that appends rightList +# at the end of leftList. + + +def concatenate(leftList, rightList): + + # If either of the list is empty + # then return the other list + if (leftList == None): + return rightList + if (rightList == None): + return leftList + + # Store the last Node of left List + leftLast = leftList.left + + # Store the last Node of right List + rightLast = rightList.left + + # Connect the last node of Left List + # with the first Node of the right List + leftLast.right = rightList + rightList.left = leftLast + + # Left of first node points to + # the last node in the list + leftList.left = rightLast + + # Right of last node refers to + # the first node of the List + rightLast.right = leftList + + return leftList + +# Function converts a tree to a circular +# Linked List and then returns the head +# of the Linked List + + +def bTreeToCList(root): + if (root == None): + return None + + # Recursively convert left and + # right subtrees + left = bTreeToCList(root.left) + right = bTreeToCList(root.right) + + # Make a circular linked list of single + # node (or root). To do so, make the + # right and left pointers of this node + # point to itself + root.left = root.right = root + + # Step 1 (concatenate the left list + # with the list with single + # node, i.e., current node) + # Step 2 (concatenate the returned list + # with the right List) + return concatenate(concatenate(left, + root), right) + +# Display Circular Link List + + +def displayCList(head): + print(""Circular Linked List is :"") + itr = head + first = 1 + while (head != itr or first): + print(itr.data, end="" "") + itr = itr.right + first = 0 + print() + + +# Driver Code +if __name__ == '__main__': + root = newNode(10) + root.left = newNode(12) + root.right = newNode(15) + root.left.left = newNode(25) + root.left.right = newNode(30) + root.right.left = newNode(36) + + head = bTreeToCList(root) + displayCList(head) + +# This code is contributed by PranchalK",logn,linear +"# Python3 program to find last man standing + +# /* structure for a node in circular +# linked list */ +class Node: + def __init__(self, x): + self.data = x + self.next = None + +# /* Function to find the only person left +# after one in every m-th node is killed +# in a circle of n nodes */ +def getJosephusPosition(m, n): + + # Create a circular linked list of + # size N. + head = Node(1) + prev = head + for i in range(2, n + 1): + prev.next = Node(i) + prev = prev.next + prev.next = head # Connect last + #node to first + + #/* while only one node is left in the + #linked list*/ + ptr1 = head + ptr2 = head + while (ptr1.next != ptr1): + # Find m-th node + count = 1 + while (count != m): + ptr2 = ptr1 + ptr1 = ptr1.next + count += 1 + + # /* Remove the m-th node */ + ptr2.next = ptr1.next + # free(ptr1) + ptr1 = ptr2.next + + print(""Last person left standing (Josephus Position) is "", ptr1.data) + +# /* Driver program to test above functions */ +if __name__ == '__main__': + n = 14 + m = 2 + getJosephusPosition(m, n) + +# This code is contributed by mohit kumar 29",linear,quadratic +"# Python3 program for converting +# singly linked list into +# circular linked list. +import sys + +# Linked list node +class Node: + def __init__(self,data): + self.data = data + self.next = None + +def push(head, data): + if not head: + return Node(data) + + # Allocate dynamic memory + # for newNode. + # Assign the data into newNode. + newNode = Node(data) + + # newNode.next assign the + # address of head node. + newNode.next = head + + # newNode become the headNode. + head = newNode + return head + +# Function that convert +# singly linked list into +# circular linked list. +def circular(head): + + # declare a node variable + # start and assign head + # node into start node. + start = head + + # check that while head.next + # not equal to null then head + # points to next node. + while(head.next is not None): + head = head.next + + # if head.next points to null + # then start assign to the + # head.next node. + head.next = start + return start + +# Function that display the elements +# of circular linked list. +def displayList(node): + start = node + while(node.next is not start): + print(""{} "".format(node.data),end="""") + node=node.next + + # Display the last node of + # circular linked list. + print(""{} "".format(node.data),end="""") + +# Driver Code +if __name__=='__main__': + + # Start with empty list + head=None + + # Using push() function to + # convert singly linked list + # 17.22.13.14.15 + head=push(head,15) + head=push(head,14) + head=push(head,13) + head=push(head,22) + head=push(head,17) + + # Call the circular_list function + # that convert singly linked + # list to circular linked list. + circular(head) + print(""Display List:"") + displayList(head) + +# This Code is Contributed By Vikash Kumar 37",constant,linear +"# Python implementation of De-queue using circular +# array + +# A structure to represent a Deque +MAX = 100 + + +class Deque: + def __init__(self, size): + self.arr = [0] * MAX + self.front = -1 + self.rear = 0 + self.size = size + + ''' Operations on Deque: + void insertfront(int key); + void insertrear(int key); + void deletefront(); + void deleterear(); + bool isFull(); + bool isEmpty(); + int getFront(); + int getRear(); ''' + + # Checks whether Deque is full or not. + def isFull(self): + return ((self.front == 0 and self.rear == self.size-1) or self.front == self.rear + 1) + + # Checks whether Deque is empty or not. + + def isEmpty(self): + return (self.front == -1) + + # Inserts an element at front + def insertfront(self, key): + + # check whether Deque if full or not + if (self.isFull()): + print(""Overflow"") + return + + # If queue is initially empty + if (self.front == -1): + self.front = 0 + self.rear = 0 + + # front is at first position of queue + elif (self.front == 0): + self.front = self.size - 1 + + else: # decrement front end by '1' + self.front = self.front-1 + + # insert current element into Deque + self.arr[self.front] = key + + # function to inset element at rear end + # of Deque. + + def insertrear(self, key): + if (self.isFull()): + print("" Overflow"") + return + + # If queue is initially empty + if (self.front == -1): + self.front = 0 + self.rear = 0 + + # rear is at last position of queue + elif (self.rear == self.size-1): + self.rear = 0 + + # increment rear end by '1' + else: + self.rear = self.rear+1 + + # insert current element into Deque + self.arr[self.rear] = key + + # Deletes element at front end of Deque + + def deletefront(self): + # check whether Deque is empty or not + if (self.isEmpty()): + print(""Queue Underflow"") + return + + # Deque has only one element + if (self.front == self.rear): + self.front = -1 + self.rear = -1 + + else: + # back to initial position + if (self.front == self.size - 1): + self.front = 0 + + else: # increment front by '1' to remove current + # front value from Deque + self.front = self.front+1 + + # Delete element at rear end of Deque + + def deleterear(self): + if (self.isEmpty()): + print("" Underflow"") + return + + # Deque has only one element + if (self.front == self.rear): + self.front = -1 + self.rear = -1 + + elif (self.rear == 0): + self.rear = self.size-1 + else: + self.rear = self.rear-1 + + # Returns front element of Deque + + def getFront(self): + # check whether Deque is empty or not + if (self.isEmpty()): + print("" Underflow"") + return -1 + + return self.arr[self.front] + + # function return rear element of Deque + + def getRear(self): + # check whether Deque is empty or not + if(self.isEmpty() or self.rear < 0): + print("" Underflow"") + return -1 + + return self.arr[self.rear] + + +# Driver code +if __name__ == ""__main__"": + dq = Deque(5) + + # Function calls + print(""Insert element at rear end : 5 "") + dq.insertrear(5) + + print(""insert element at rear end : 10 "") + dq.insertrear(10) + + print(f""get rear element : {dq.getRear()}"") + + dq.deleterear() + print(f""After delete rear element new rear become : {dq.getRear()}"") + + print(""inserting element at front end"") + dq.insertfront(15) + + print(f""get front element: {dq.getFront()}"") + + dq.deletefront() + + print(f""After delete front element new front become : {dq.getFront()}"") + +# This code is contributed by _saurabh_jaiswal",linear,linear +"# Python program to exchange first and +# last node in circular linked list class Node { +class Node: + def __init__(self): + self.data = 0 + self.next = None + +def addToEmpty(head, data): + + # This function is only for empty list + if (head != None): + return head + + # Creating a node dynamically. + temp = Node() + + # Assigning the data. + temp.data = data + head = temp + + # Creating the link. + head.next = head + + return head + +def addBegin(head, data): + if (head == None): + return addToEmpty(head, data) + + temp = Node() + + temp.data = data + temp.next = head.next + head.next = temp + + return head + +# function for traversing the list +def traverse(head): + + # If list is empty, return. + if (head == None): + print(""List is empty."") + return + + # Pointing to first Node of the list. + p = head + + # Traversing the list. + while (True): + print(p.data, end="" "") + p = p.next + if(p == head): + break + +# Function to exchange first and last node +def exchangeNodes(head): + + # If list is of length less than 2 + if (head == None or head.next == None): + return head + + tail = head + + # Find pointer to the last node + while (tail.next != head): + tail = tail.next + + # Exchange first and last nodes using head and p + + # temporary variable to store + # head data + temp = tail.data + tail.data = head.data + head.data = temp + return head + +# Driven Program +head = None +head = addToEmpty(head, 6) + +for i in range(5, 0, -1): + head = addBegin(head, i) + +print(""List Before: "") +traverse(head) +print("""") + +print(""List After: "") +head = exchangeNodes(head) +traverse(head) + +# This code is contributed by Saurabh Jaiswal",constant,linear +"# Program to delete a node in a doubly-linked list + +# for Garbage collection +import gc + +# A node of the doubly linked list +class Node: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.next = None + self.prev = None + +class DoublyLinkedList: + # Constructor for empty Doubly Linked List + def __init__(self): + self.head = None + + # Function to delete a node in a Doubly Linked List. + # head_ref --> pointer to head node pointer. + # dele --> pointer to node to be deleted + + def deleteNode(self, dele): + + # Base Case + if self.head is None or dele is None: + return + + # If node to be deleted is head node + if self.head == dele: + self.head = dele.next + + # Change next only if node to be deleted is NOT + # the last node + if dele.next is not None: + dele.next.prev = dele.prev + + # Change prev only if node to be deleted is NOT + # the first node + if dele.prev is not None: + dele.prev.next = dele.next + # Finally, free the memory occupied by dele + # Call python garbage collector + gc.collect() + + + # Given a reference to the head of a list and an + # integer, inserts a new node on the front of list + def push(self, new_data): + + # 1. Allocates node + # 2. Put the data in it + new_node = Node(new_data) + + # 3. Make next of new node as head and + # previous as None (already None) + new_node.next = self.head + + # 4. change prev of head node to new_node + if self.head is not None: + self.head.prev = new_node + + # 5. move the head to point to the new node + self.head = new_node + + + def printList(self, node): + while(node is not None): + print(node.data,end=' ') + node = node.next + + +# Driver program to test the above functions + +# Start with empty list +dll = DoublyLinkedList() + +# Let us create the doubly linked list 10<->8<->4<->2 +dll.push(2); +dll.push(4); +dll.push(8); +dll.push(10); + +print (""\n Original Linked List"",end=' ') +dll.printList(dll.head) + +# delete nodes from doubly linked list +dll.deleteNode(dll.head) +dll.deleteNode(dll.head.next) +dll.deleteNode(dll.head.next) +# Modified linked list will be NULL<-8->NULL +print(""\n Modified Linked List"",end=' ') +dll.printList(dll.head) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",constant,constant +"# Python3 Program to reverse a doubly linked list + +# A node of the doubly linked list + +class Node: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.next = None + self.prev = None + + +class DoublyLinkedList: + # Constructor for empty Doubly Linked List + def __init__(self): + self.head = None + + # Function reverse a Doubly Linked List + def reverse(self): + temp = None + current = self.head + + # Swap next and prev for all nodes of + # doubly linked list + while current is not None: + temp = current.prev + current.prev = current.next + current.next = temp + current = current.prev + + # Before changing head, check for the cases like + # empty list and list with only one node + if temp is not None: + self.head = temp.prev + + # Given a reference to the head of a list and an + # integer,inserts a new node on the front of list + def push(self, new_data): + + # 1. Allocates node + # 2. Put the data in it + new_node = Node(new_data) + + # 3. Make next of new node as head and + # previous as None (already None) + new_node.next = self.head + + # 4. change prev of head node to new_node + if self.head is not None: + self.head.prev = new_node + + # 5. move the head to point to the new node + self.head = new_node + + def printList(self, node): + while(node is not None): + print(node.data, end=' ') + node = node.next + + +# Driver's code +if __name__ == ""__main__"": + dll = DoublyLinkedList() + dll.push(2) + dll.push(4) + dll.push(8) + dll.push(10) + + print(""\nOriginal Linked List"") + dll.printList(dll.head) + + # Function call + dll.reverse() + + print(""\nReversed Linked List"") + dll.printList(dll.head) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",constant,linear +"# Python3 code for the above approach + +class Node: + def __init__(self, data): + self.data = data + self.next = None + self.prev = None + + +class DoublyLinkedList: + def __init__(self): + self.head = None + + """""" + method to reverse a Doubly-Linked List using Stacks + """""" + + def reverseUsingStacks(self): + + stack = [] + temp = self.head + while temp is not None: + stack.append(temp.data) + temp = temp.next + + # Add all the elements in the stack + # in a sequence to the stack + temp = self.head + while temp is not None: + temp.data = stack.pop() + temp = temp.next + + # Popped all the elements and the + # added in the linked list, + # in a reversed order. + + """""" + method to push a new item before the head + """""" + + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + + if self.head is not None: + self.head.prev = new_node + + self.head = new_node + + """""" + method to traverse the doubly-linked + list and print every node in the list + """""" + + def printList(self, node): + while(node is not None): + print(node.data) + node = node. next + + +# driver's code +if __name__ == ""__main__"": + dll = DoublyLinkedList() + dll.push(2) + dll.push(4) + dll.push(8) + dll.push(10) + + print(""original doubly-linked list"") + dll.printList(dll.head) + + # Function call + dll.reverseUsingStacks() + + print("" reversed doubly-linked list"") + dll.printList(dll.head)",linear,linear +"# Program for merge sort on doubly linked list + +# A node of the doubly linked list +class Node: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.next = None + self.prev = None + +class DoublyLinkedList: + + # Constructor for empty Doubly Linked List + def __init__(self): + self.head = None + + # Function to merge two linked list + def merge(self, first, second): + + # If first linked list is empty + if first is None: + return second + + # If second linked list is empty + if second is None: + return first + + # Pick the smaller value + if first.data < second.data: + first.next = self.merge(first.next, second) + first.next.prev = first + first.prev = None + return first + else: + second.next = self.merge(first, second.next) + second.next.prev = second + second.prev = None + return second + + # Function to do merge sort + def mergeSort(self, tempHead): + if tempHead is None: + return tempHead + if tempHead.next is None: + return tempHead + + second = self.split(tempHead) + + # Recur for left and right halves + tempHead = self.mergeSort(tempHead) + second = self.mergeSort(second) + + # Merge the two sorted halves + return self.merge(tempHead, second) + + # Split the doubly linked list (DLL) into two DLLs + # of half sizes + def split(self, tempHead): + fast = slow = tempHead + while(True): + if fast.next is None: + break + if fast.next.next is None: + break + fast = fast.next.next + slow = slow.next + + temp = slow.next + slow.next = None + return temp + + + # Given a reference to the head of a list and an + # integer,inserts a new node on the front of list + def push(self, new_data): + + # 1. Allocates node + # 2. Put the data in it + new_node = Node(new_data) + + # 3. Make next of new node as head and + # previous as None (already None) + new_node.next = self.head + + # 4. change prev of head node to new_node + if self.head is not None: + self.head.prev = new_node + + # 5. move the head to point to the new node + self.head = new_node + + + def printList(self, node): + temp = node + print (""Forward Traversal using next pointer"") + while(node is not None): + print (node.data,end="" "") + temp = node + node = node.next + print (""\nBackward Traversal using prev pointer"") + while(temp): + print (temp.data,end="" "") + temp = temp.prev + +# Driver program to test the above functions +dll = DoublyLinkedList() +dll.push(5) +dll.push(20); +dll.push(4); +dll.push(3); +dll.push(30) +dll.push(10); +dll.head = dll.mergeSort(dll.head) +print (""Linked List after sorting"") +dll.printList(dll.head) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",constant,nlogn +"# Python3 program to create a doubly linked +# list out of given a ternary tree. + +# Custom node class. +class newNode: + + def __init__(self, data): + + self.data = data + self.left = None + self.right = None + self.middle = None + +class GFG: + + def __init__(self): + + # Tail of the linked list. + self.tail = None + + # Function to push the node to the tail. + def push(self, node): + + # To put the node at the end of + # the already existing tail. + self.tail.right = node + + # To point to the previous node. + node.left = self.tail + + # Middle pointer should point to + # nothing so null. initiate right + # pointer to null. + node.middle = node.right = None + + # Update the tail position. + self.tail = node + + # Create a doubly linked list out of given + # a ternary tree By traversing the tree in + # preorder fashion. + def ternaryTree(self, node, head): + + if node == None: + return + + left = node.left + middle = node.middle + right = node.right + + if self.tail != node: + + # Already root is in the tail so dont push + # the node when it was root.In the first + # case both node and tail have root in them. + self.push(node) + + # First the left child is to be taken. + # Then middle and then right child. + self.ternaryTree(left, head) + self.ternaryTree(middle, head) + self.ternaryTree(right, head) + + def startTree(self, root): + + # Initiate the head and tail with root. + head = root + self.tail = root + self.ternaryTree(root, head) + + # Since the head,root are passed + # with reference the changes in + # root will be reflected in head. + return head + + # Utility function for printing double linked list. + def printList(self, head): + + print(""Created Double Linked list is:"") + + while head: + print(head.data, end = "" "") + head = head.right + +# Driver code +if __name__ == '__main__': + + # Constructing ternary tree as shown + # in above figure + root = newNode(30) + root.left = newNode(5) + root.middle = newNode(11) + root.right = newNode(63) + root.left.left = newNode(1) + root.left.middle = newNode(4) + root.left.right = newNode(8) + root.middle.left = newNode(6) + root.middle.middle = newNode(7) + root.middle.right = newNode(15) + root.right.left = newNode(31) + root.right.middle = newNode(55) + root.right.right = newNode(65) + + # The function which initiates the list + # process returns the head. + head = None + gfg = GFG() + head = gfg.startTree(root) + + gfg.printList(head) + +# This code is contributed by Winston Sebastian Pais",linear,linear +"# Python3 program to find a pair with +# given sum x. + +# Structure of node of doubly linked list +class Node: + + def __init__(self, x): + + self.data = x + self.next = None + self.prev = None + +# Function to find pair whose sum +# equal to given value x. +def pairSum(head, x): + + # Set two pointers, first to the + # beginning of DLL and second to + # the end of DLL. + first = head + second = head + + while (second.next != None): + second = second.next + + # To track if we find a pair or not + found = False + + # The loop terminates when they + # cross each other (second.next == + # first), or they become same + # (first == second) + while (first != second and second.next != first): + + # Pair found + if ((first.data + second.data) == x): + found = True + print(""("", first.data, "","", + second.data, "")"") + + # Move first in forward direction + first = first.next + + # Move second in backward direction + second = second.prev + else: + if ((first.data + second.data) < x): + first = first.next + else: + second = second.prev + + # If pair is not present + if (found == False): + print(""No pair found"") + +# A utility function to insert a new node +# at the beginning of doubly linked list +def insert(head, data): + + temp = Node(data) + + if not head: + head = temp + else: + temp.next = head + head.prev = temp + head = temp + + return head + +# Driver code +if __name__ == '__main__': + + head = None + head = insert(head, 9) + head = insert(head, 8) + head = insert(head, 6) + head = insert(head, 5) + head = insert(head, 4) + head = insert(head, 2) + head = insert(head, 1) + x = 7 + + pairSum(head, x) + +# This code is contributed by mohit kumar 29",constant,linear +"# Python3 implementation to insert +# value in sorted way in a sorted +# doubly linked list + +# Node of a doubly linked list +class Node: + + # Constructor to initialize + # the node object + def __init__(self, data): + + self.data = data + self.next = None + self.prev = None + +class DoublyLinkedList: + + # Function to initialize head + def __init__(self): + + self.head = None + + # Function to create and return a + # new node of a doubly linked list + def getNode(self, data): + + return Node(data) + + # Function to insert a new node in + # sorted way in a sorted doubly linked list + def sortedInsert(self, data): + + new_node = self.getNode(data) + + # If the list is empty + if self.head is None: + self.head = new_node + + # If the node is to be inserted at + # the beginning of the doubly linked list + elif self.head.data >= new_node.data: + new_node.next = self.head + new_node.next.prev = new_node + self.head = new_node + else: + current = self.head + + # Locate the node after which + # the new node is to be inserted + while ((current.next is not None) and + (current.next.data < new_node.data)): + current = current.next + + # Make the appropriate links + new_node.next = current.next + + # If the new node is not inserted + # at the end of the list + if current.next is not None: + new_node.next.prev = new_node + + current.next = new_node + new_node.prev = current + + # Function to print the doubly linked list + def printList(self): + + node = self.head + while node: + print(str(node.data), end = "" "") + node = node.next + +# Driver code +if __name__ == '__main__': + + # Insert the following nodes + # in sorted way + llist = DoublyLinkedList() + llist.sortedInsert(8) + llist.sortedInsert(5) + llist.sortedInsert(3) + llist.sortedInsert(10) + llist.sortedInsert(12) + llist.sortedInsert(9) + + print(""Created Doubly Linked List"") + llist.printList() + +# This code is contributed by Siddhartha Pramanik",linear,linear +"# Python3 implementation to count triplets +# in a sorted doubly linked list +# whose sum is equal to a given value 'x' + +# structure of node of doubly linked list +class Node: + def __init__(self): + self.data = None + self.prev = None + self.next = None + +# function to count triplets in a sorted doubly linked list +# whose sum is equal to a given value 'x' +def countTriplets( head, x): + + ptr1 = head + ptr2 = None + ptr3 = None + count = 0 + + # generate all possible triplets + while (ptr1 != None ): + ptr2 = ptr1.next + while ( ptr2 != None ): + ptr3 = ptr2.next + while ( ptr3 != None ): + + # if elements in the current triplet sum up to 'x' + if ((ptr1.data + ptr2.data + ptr3.data) == x): + + # increment count + count = count + 1 + ptr3 = ptr3.next + ptr2 = ptr2.next + ptr1 = ptr1.next + + # required count of triplets + return count + +# A utility function to insert a new node at the +# beginning of doubly linked list +def insert(head, data): + + # allocate node + temp = Node() + + # put in the data + temp.data = data + temp.next = temp.prev = None + + if ((head) == None): + (head) = temp + else : + temp.next = head + (head).prev = temp + (head) = temp + return head + +# Driver code + +# start with an empty doubly linked list +head = None + +# insert values in sorted order +head = insert(head, 9) +head = insert(head, 8) +head = insert(head, 6) +head = insert(head, 5) +head = insert(head, 4) +head = insert(head, 2) +head = insert(head, 1) + +x = 17 + +print( ""Count = "", countTriplets(head, x)) + +# This code is contributed by Arnab Kundu",constant,cubic +"# Python3 implementation to count triplets in a sorted doubly linked list +# whose sum is equal to a given value 'x' + +# structure of node of doubly linked list +class Node: + + def __init__(self, data): + + self.data=data + self.next=None + self.prev=None + + +# function to count triplets in a sorted doubly linked list +# whose sum is equal to a given value 'x' +def countTriplets(head, x): + + ptr2=head + count = 0; + + # unordered_map 'um' implemented as hash table + um = dict() + + ptr = head + # insert the tuple in 'um' + while ptr!=None: + um[ptr.data] = ptr; + ptr = ptr.next + + # generate all possible pairs + ptr1=head + + while ptr1!=None: + + ptr2 = ptr1.next + + while ptr2!=None: + + # p_sum - sum of elements in the current pair + p_sum = ptr1.data + ptr2.data; + + # if 'x-p_sum' is present in 'um' and either of the two nodes + # are not equal to the 'um[x-p_sum]' node + if ((x-p_sum) in um) and um[x - p_sum] != ptr1 and um[x - p_sum] != ptr2: + + # increment count + count+=1 + ptr2 = ptr2.next + ptr1 = ptr1.next + + + # required count of triplets + # division by 3 as each triplet is counted 3 times + return (count // 3); + + +# A utility function to insert a new node at the +# beginning of doubly linked list +def insert(head, data): + + # allocate node + temp = Node(data); + + if ((head) == None): + (head) = temp; + else: + temp.next = head; + (head).prev = temp; + (head) = temp; + return head + + +# Driver program to test above +if __name__=='__main__': + + # start with an empty doubly linked list + head = None; + + # insert values in sorted order + head = insert(head, 9); + head = insert(head, 8); + head = insert(head, 6); + head = insert(head, 5); + head = insert(head, 4); + head = insert(head, 2); + head = insert( head, 1); + + x = 17; + + print(""Count = ""+ str(countTriplets(head, x))) + +# This code is contributed by rutvik_56",linear,quadratic +"# Python3 implementation to count triplets +# in a sorted doubly linked list whose sum +# is equal to a given value 'x' + +# Structure of node of doubly linked list +class Node: + + def __init__(self, x): + + self.data = x + self.next = None + self.prev = None + +# Function to count pairs whose sum +# equal to given 'value' +def countPairs(first, second, value): + + count = 0 + + # The loop terminates when either of two pointers + # become None, or they cross each other (second.next + # == first), or they become same (first == second) + while (first != None and second != None and + first != second and second.next != first): + + # Pair found + if ((first.data + second.data) == value): + + # Increment count + count += 1 + + # Move first in forward direction + first = first.next + + # Move second in backward direction + second = second.prev + + # If sum is greater than 'value' + # move second in backward direction + elif ((first.data + second.data) > value): + second = second.prev + + # Else move first in forward direction + else: + first = first.next + + # Required count of pairs + return count + +# Function to count triplets in a sorted +# doubly linked list whose sum is equal +# to a given value 'x' +def countTriplets(head, x): + + # If list is empty + if (head == None): + return 0 + + current, first, last = head, None, None + count = 0 + + # Get pointer to the last node of + # the doubly linked list + last = head + + while (last.next != None): + last = last.next + + # Traversing the doubly linked list + while current != None: + + # For each current node + first = current.next + + # count pairs with sum(x - current.data) in + # the range first to last and add it to the + # 'count' of triplets + count, current = count + countPairs( + first, last, x - current.data), current.next + + # Required count of triplets + return count + +# A utility function to insert a new node +# at the beginning of doubly linked list +def insert(head, data): + + # Allocate node + temp = Node(data) + + # Put in the data + # temp.next = temp.prev = None + if (head == None): + head = temp + else: + temp.next = head + head.prev = temp + head = temp + + return head + +# Driver code +if __name__ == '__main__': + + # Start with an empty doubly linked list + head = None + + # Insert values in sorted order + head = insert(head, 9) + head = insert(head, 8) + head = insert(head, 6) + head = insert(head, 5) + head = insert(head, 4) + head = insert(head, 2) + head = insert(head, 1) + + x = 17 + + print(""Count = "", countTriplets(head, x)) + +# This code is contributed by mohit kumar 29",constant,quadratic +"# Python implementation to remove duplicates from a +# sorted doubly linked list + +# A linked list node +class Node: + def __init__(self, new_data): + self.data = new_data + self.next = None + self.prev = None + +# Function to _delete a node in a Doubly Linked List. +# head_ref -. pointer to head node pointer. +# _del -. pointer to node to be _deleted. +def _deleteNode(head_ref, _del): + + # base case + if (head_ref == None or _del == None): + return + + # If node to be _deleted is head node + if (head_ref == _del): + head_ref = _del.next + + # Change next only if node to be _deleted + # is NOT the last node + if (_del.next != None): + _del.next.prev = _del.prev + + # Change prev only if node to be _deleted + # is NOT the first node + if (_del.prev != None): + _del.prev.next = _del.next + + return head_ref + +# function to remove duplicates from a +# sorted doubly linked list +def removeDuplicates(head_ref): + + # if list is empty + if ((head_ref) == None): + return None + + current = head_ref + next = None + + # traverse the list till the last node + while (current.next != None) : + + # Compare current node with next node + if (current.data == current.next.data): + + # _delete the node pointed to by + # 'current.next' + _deleteNode(head_ref, current.next) + + # else simply move to the next node + else: + current = current.next + + return head_ref + +# Function to insert a node at the beginning +# of the Doubly Linked List +def push(head_ref, new_data): + + # allocate node + new_node = Node(0) + + # put in the data + new_node.data = new_data + + # since we are adding at the beginning, + # prev is always None + new_node.prev = None + + # link the old list off the new node + new_node.next = (head_ref) + + # change prev of head node to new node + if ((head_ref) != None): + (head_ref).prev = new_node + + # move the head to point to the new node + (head_ref) = new_node + + return head_ref + +# Function to print nodes in a given doubly linked list +def printList(head): + + # if list is empty + if (head == None): + print(""Doubly Linked list empty"") + + while (head != None) : + print(head.data, end = "" "") + head = head.next + +# Driver program to test above functions + +# Start with the empty list +head = None + +# Create the doubly linked list: +# 4<->4<->4<->4<->6<->8<->8<->10<->12<->12 +head = push(head, 12) +head = push(head, 12) +head = push(head, 10) +head = push(head, 8) +head = push(head, 8) +head = push(head, 6) +head = push(head, 4) +head = push(head, 4) +head = push(head, 4) +head = push(head, 4) + +print( ""Original Doubly linked list:\n"") +printList(head) + +# remove duplicate nodes +head = removeDuplicates(head) + +print(""\nDoubly linked list after removing duplicates:"") +printList(head) + +# This code is contributed by Arnab Kundu",constant,linear +"# Python3 implementation to delete all occurrences +# of a given key in a doubly linked list +import math + +# a node of the doubly linked list +class Node: + def __init__(self,data): + self.data = data + self.next = None + self.prev = None + +# Function to delete a node in a Doubly Linked List. +# head_ref --> pointer to head node pointer. +# del --> pointer to node to be deleted. +def deleteNode(head, delete): + # base case + if (head == None or delete == None): + return None + + # If node to be deleted is head node + if (head == delete): + head = delete.next + + # Change next only if node to be deleted + # is NOT the last node + if (delete.next != None): + delete.next.prev = delete.prev + + # Change prev only if node to be deleted + # is NOT the first node + if (delete.prev != None): + delete.prev.next = delete.next + + # Finally, free the memory occupied by del + # free(del) + delete = None + return head + +# function to delete all occurrences of the given +# key 'x' +def deleteAllOccurOfX(head, x): + # if list is empty + if (head == None): + return + + current = head + + # traverse the list up to the end + while (current != None): + + # if node found with the value 'x' + if (current.data == x): + + # save current's next node in the + #pointer 'next' + next = current.next + + # delete the node pointed to by + # 'current' + head = deleteNode(head, current) + + # update current + current = next + + # else simply move to the next node + else: + current = current.next + + return head + +# Function to insert a node at the beginning +# of the Doubly Linked List +def push(head,new_data): + # allocate node + new_node = Node(new_data) + + # put in the data + new_node.data = new_data + + # since we are adding at the beginning, + #prev is always None + new_node.prev = None + + # link the old list off the new node + new_node.next = head + + # change prev of head node to new node + if (head != None): + head.prev = new_node + + # move the head to point to the new node + head = new_node + return head + +# Function to print nodes in a given doubly +# linked list +def printList(head): + # if list is empty + if (head == None): + print(""Doubly Linked list empty"") + + while (head != None) : + print(head.data,end="" "") + head = head.next + +# Driver functions +if __name__=='__main__': + # Start with the empty list + head = None + + # Create the doubly linked list: + # 2<->2<->10<->8<->4<->2<->5<->2 + head = push(head, 2) + head = push(head, 5) + head = push(head, 2) + head = push(head, 4) + head = push(head, 8) + head = push(head, 10) + head = push(head, 2) + head = push(head, 2) + + print(""Original Doubly linked list:"") + printList(head) + + x = 2 + + # delete all occurrences of 'x' + head = deleteAllOccurOfX(head, x) + + print(""\nDoubly linked list after deletion of "",x,"":"") + printList(head) + +# This article contributed by Srathore",constant,linear +"# Python implementation to remove duplicates +# from an unsorted doubly linked list + +# Node of a linked list +class Node: + def __init__(self, data = None, next = None): + self.next = next + self.data = data + +# Function to delete a node in a Doubly Linked List. +# head_ref -. pointer to head node pointer. +# del -. pointer to node to be deleted. +def deleteNode(head_ref,del_): + + # base case + if (head_ref == None or del_ == None): + return head_ref + + # If node to be deleted is head node + if (head_ref == del_): + head_ref = del_.next + + # Change next only if node to be deleted + # is NOT the last node + if (del_.next != None): + del_.next.prev = del_.prev + + # Change prev only if node to be deleted + # is NOT the first node + if (del_.prev != None): + del_.prev.next = del_.next + return head_ref + +# function to remove duplicates from +# an unsorted doubly linked list +def removeDuplicates( head_ref): + + # if DLL is empty or if it contains only + # a single node + if ((head_ref) == None or (head_ref).next == None): + return head_ref + + ptr1 = head_ref + ptr2 = None + + # pick elements one by one + while(ptr1 != None) : + ptr2 = ptr1.next + + # Compare the picked element with the + # rest of the elements + while (ptr2 != None): + + # if duplicate, then delete it + if (ptr1.data == ptr2.data): + + # store pointer to the node next to 'ptr2' + next = ptr2.next + + # delete node pointed to by 'ptr2' + head_ref = deleteNode(head_ref, ptr2) + + # update 'ptr2' + ptr2 = next + + # else simply move to the next node + else: + ptr2 = ptr2.next + ptr1 = ptr1.next + return head_ref + +# Function to insert a node at the beginning +# of the Doubly Linked List +def push( head_ref, new_data): + + # allocate node + new_node = Node() + + # put in the data + new_node.data = new_data + + # since we are adding at the beginning, + # prev is always None + new_node.prev = None + + # link the old list off the new node + new_node.next = (head_ref) + + # change prev of head node to new node + if ((head_ref) != None): + (head_ref).prev = new_node + + # move the head to point to the new node + (head_ref) = new_node + return head_ref + +# Function to print nodes in a +# given doubly linked list +def printList( head): + + # if list is empty + if (head == None): + print(""Doubly Linked list empty"") + + while (head != None): + print( head.data ,end= "" "") + head = head.next + +# Driver Code +head = None + +# Create the doubly linked list: +# 8<.4<.4<.6<.4<.8<.4<.10<.12<.12 +head = push(head, 12) +head = push(head, 12) +head = push(head, 10) +head = push(head, 4) +head = push(head, 8) +head = push(head, 4) +head = push(head, 6) +head = push(head, 4) +head = push(head, 4) +head = push(head, 8) + +print(""Original Doubly linked list:"") +printList(head) + +# remove duplicate nodes */ +head=removeDuplicates(head) + +print(""\nDoubly linked list after removing duplicates:"") +printList(head) + +# This code is contributed by Arnab Kundu",constant,quadratic +"# Python3 implementation to remove duplicates +# from an unsorted doubly linked list + +# a node of the doubly linked list +class Node: + def __init__(self): + self.data = 0 + self.next = None + self.prev = None + +# Function to delete a node in a Doubly Linked List. +# head_ref --> pointer to head node pointer. +# del --> pointer to node to be deleted. +def deleteNode( head_ref, del_): + + # base case + if (head_ref == None or del_ == None): + return None + + # If node to be deleted is head node + if (head_ref == del_): + head_ref = del_.next + + # Change next only if node to be deleted + # is NOT the last node + if (del_.next != None): + del_.next.prev = del_.prev + + # Change prev only if node to be deleted + # is NOT the first node + if (del_.prev != None): + del_.prev.next = del_.next + + return head_ref + +# function to remove duplicates from +# an unsorted doubly linked list +def removeDuplicates(head_ref): + + # if doubly linked list is empty + if ((head_ref) == None): + return None + + # unordered_set 'us' implemented as hash table + us = set() + + current = head_ref + next = None + + # traverse up to the end of the list + while (current != None): + + # if current data is seen before + if ((current.data) in us): + + # store pointer to the node next to + # 'current' node + next = current.next + + # delete the node pointed to by 'current' + head_ref = deleteNode(head_ref, current) + + # update 'current' + current = next + + else: + + # insert the current data in 'us' + us.add(current.data) + + # move to the next node + current = current.next + + return head_ref + +# Function to insert a node at the +# beginning of the Doubly Linked List +def push(head_ref,new_data): + + # allocate node + new_node = Node() + + # put in the data + new_node.data = new_data + + # since we are adding at the beginning, + # prev is always None + new_node.prev = None + + # link the old list off the new node + new_node.next = (head_ref) + + # change prev of head node to new node + if ((head_ref) != None): + (head_ref).prev = new_node + + # move the head to point to the new node + (head_ref) = new_node + return head_ref + +# Function to print nodes in a given doubly +# linked list +def printList( head): + + # if list is empty + if (head == None): + print(""Doubly Linked list empty"") + + while (head != None): + + print(head.data , end="" "") + head = head.next + +# Driver Code + +head = None + +# Create the doubly linked list: +# 8<->4<->4<->6<->4<->8<->4<->10<->12<->12 +head = push(head, 12) +head = push(head, 12) +head = push(head, 10) +head = push(head, 4) +head = push(head, 8) +head = push(head, 4) +head = push(head, 6) +head = push(head, 4) +head = push(head, 4) +head = push(head, 8) + +print(""Original Doubly linked list:"") +printList(head) + +# remove duplicate nodes +head = removeDuplicates(head) + +print(""\nDoubly linked list after removing duplicates:"") +printList(head) + +# This code is contributed by Arnab Kundu",linear,linear +"# Python implementation to sort a k sorted doublyclass DoublyLinkedList { +head = None + +class Node: + def __init__(self, val): + self.data = val + self.prev = None + self.next = None + +# function to sort a k sorted doubly linked list +# Using Insertion Sort +# Time Complexity: O(n*k) +# Space Complexity: O(1) +def sortAKSortedDLL(head , k): + if (head == None or head.next == None): + return head + + # perform on all the nodes in list + i = head.next + while(i != None): + j = i + + # There will be atmost k swaps for each element in the list + # since each node is k steps away from its correct position + while (j.prev != None and j.data < j.prev.data): + + # swap j and j.prev node + temp = j.prev.prev + temp2 = j.prev + temp3 = j.next + j.prev.next = temp3 + j.prev.prev = j + j.prev = temp + j.next = temp2 + if (temp != None): + temp.next = j + if (temp3 != None): + temp3.prev = temp2 + + # if j is now the new head + # then reset head + if (j.prev == None): + head = j + i = i.next + + return head + +# UTILITY FUNCTIONS +# +# Function to insert a node at the beginning of the Doubly Linked List +def push(new_data): + + global head + + # allocate node + new_node = Node(new_data) + + # + # since we are adding at the beginning, prev is always NULL + # + new_node.prev = None + + # link the old list of the new node + new_node.next = head + + # change prev of head node to new node + if (head != None): + head.prev = new_node + + # move the head to point to the new node + head = new_node + +# Function to print nodes in a given doubly linked list This function is same +# as printList() of singly linked list +def printList(node): + while (node != None): + print(node.data,end = "" "") + node = node.next + +# Driver code + +# Let us create a k sorted doubly linked list to test the functions Created +# doubly linked list will be 3<->6<->2<->12<->56<->8 +push(8) +push(56) +push(12) +push(2) +push(6) +push(3) + +k = 2 + +print(""Original Doubly linked list:"") +printList(head) + +sortedDLL = sortAKSortedDLL(head, k) +print("""") +print(""Doubly Linked List after sorting:"") +printList(sortedDLL) + +# This codeis contributed by shinjanpatra",constant,quadratic +"# Python implementation to sort a k sorted doubly linked list +import heapq +head = None + +# a node of the doubly linked list +class Node: + def __init__(self, data): + self.data = data + self.next = None + self.prev = None + +# function to sort a k sorted doubly linked list +def sortAKSortedDLL(head, k): + # if list is empty + if head == None: + return head + + pq = [] + + newHead = None + last = None + + for i in range(k+1): + # push the node + heapq.heappush(pq, (head.data, head)) + # move to the next node + head = head.next + + # loop till there are elements in 'pq' + while len(pq) > 0: + + if newHead == None: + newHead = heapq.heappop(pq)[1] + newHead.prev = None + + # 'last' points to the last node of the result sorted list so far + last = newHead + else: + last.next = heapq.heappop(pq)[1] + last.next.prev = last + last = last.next + + # if there are more nodes left in the input list + if head != None: + # push the node + heapq.heappush(pq, (head.data, head)) + + # move to the next node + head = head.next + + # making 'next' of last node point to NULL + last.next = None + + # new head of the required sorted DLL + return newHead + +# Function to insert a node at the beginning of the Doubly Linked List +def push(new_data): + + global head + + # allocate node + new_node = Node(new_data) + + # since we are adding at the beginning, prev is always NULL + new_node.prev = None + + # link the old list off the new node + new_node.next = head + + # change prev of head node to new node + if (head != None): + head.prev = new_node + + # move the head to point to the new node + head = new_node + + +# Function to print nodes in a given doubly linked list +def printList(head): + # if list is empty + if head is None: + print(""Doubly Linked list empty"") + + while head is not None: + print(head.data, end="" "") + head = head.next + + +# Driver code +if __name__ == '__main__': + + # Create the doubly linked list: + # 3<->6<->2<->12<->56<->8 + push(8) + push(56) + push(12) + push(2) + push(6) + push(3) + + k = 2 + + print(""Original Doubly linked list:"") + printList(head) + + sortedDLL = sortAKSortedDLL(head, k) + + print(""\nDoubly Linked List after sorting:"") + printList(sortedDLL) + +# This code is contributed by Tapesh(tapeshdua420)",constant,nlogn +"# Python3 program to convert a given Binary Tree to Doubly Linked List +class Node: + def __init__(self, data): + self.data = data + self.left = self.right = None + +class BinaryTree: + # A simple recursive function to convert a given + # Binary tree to Doubly Linked List + # root --> Root of Binary Tree + # head --> Pointer to head node of created doubly linked list + root, head = None, None + + def BToDll(self, root: Node): + if root is None: + return + + # Recursively convert right subtree + self.BToDll(root.right) + + # Insert root into doubly linked list + root.right = self.head + + # Change left pointer of previous head + if self.head is not None: + self.head.left = root + + # Change head of doubly linked list + self.head = root + + # Recursively convert left subtree + self.BToDll(root.left) + + @staticmethod + def print_list(head: Node): + print('Extracted Double Linked list is:') + while head is not None: + print(head.data, end = ' ') + head = head.right + +# Driver program to test above function +if __name__ == '__main__': + + """""" + Constructing below tree + 5 + // \\ + 3 6 + // \\ \\ + 1 4 8 + // \\ // \\ + 0 2 7 9 + """""" + tree = BinaryTree() + tree.root = Node(5) + tree.root.left = Node(3) + tree.root.right = Node(6) + tree.root.left.left = Node(1) + tree.root.left.right = Node(4) + tree.root.right.right = Node(8) + tree.root.left.left.left = Node(0) + tree.root.left.left.right = Node(2) + tree.root.right.right.left = Node(7) + tree.root.right.right.right = Node(9) + + tree.BToDll(tree.root) + tree.print_list(tree.head) + +# This code is contributed by Rajat Srivastava",linear,linear +"# Python program to insetail nodes in doubly +# linked list such that list remains in +# ascending order on printing from left +# to right + +# Linked List node +class Node: + def __init__(self, data): + self.info = data + self.next = None + self.prev = None + +head = None +tail = None + +# Function to insetail new node +def nodeInsetail( key) : + + global head + global tail + + p = Node(0) + p.info = key + p.next = None + + # If first node to be insetailed in doubly + # linked list + if ((head) == None) : + (head) = p + (tail) = p + (head).prev = None + return + + # If node to be insetailed has value less + # than first node + if ((p.info) < ((head).info)) : + p.prev = None + (head).prev = p + p.next = (head) + (head) = p + return + + # If node to be insetailed has value more + # than last node + if ((p.info) > ((tail).info)) : + + p.prev = (tail) + (tail).next = p + (tail) = p + return + + # Find the node before which we need to + # insert p. + temp = (head).next + while ((temp.info) < (p.info)) : + temp = temp.next + + # Insert new node before temp + (temp.prev).next = p + p.prev = temp.prev + temp.prev = p + p.next = temp + +# Function to print nodes in from left to right +def printList(temp) : + + while (temp != None) : + + print( temp.info, end = "" "") + temp = temp.next + +# Driver program to test above functions +nodeInsetail( 30) +nodeInsetail( 50) +nodeInsetail( 90) +nodeInsetail( 10) +nodeInsetail( 40) +nodeInsetail( 110) +nodeInsetail( 60) +nodeInsetail( 95) +nodeInsetail( 23) + +print(""Doubly linked list on printing from left to right\n"" ) + +printList(head) + +# This code is contributed by Arnab Kundu",constant,linear +"# Python code to rotate doubly linked list by N nodes. +class Node: + def __init__(self, data): + self.data = data + self.pre = None + self.next = None + +class GFG: + def __init__(self): + self.head = None + + # Function to insert nodes at the start of the linked list. + def insertAtHead(self, data): + n = Node(data) + if self.head == None: + self.head = n + return + + n.next = self.head + self.head.pre = n + self.head = n + return + + # Function to insert nodes at the tail of the linked list. + def insertAtTail(self, data): + if self.head == None: + self.insertAtHead(data) + return + temp = self.head + while temp.next != None: + temp = temp.next + n = Node(data) + temp.next = n + n.pre = temp + return + + # Function to print the list. + def display(self): + temp = self.head + while temp != None: + print(temp.data, ""-->"", sep="""", end="""") + temp = temp.next + print(""NULL"") + + # Function to rotate doubly linked list by N nodes. + def rotateByN(self, pos): + if pos == 0: + return + curr = self.head + while pos: + curr = curr.next + pos -= 1 + tail = curr.pre + NewHead = curr + tail.next = None + curr.pre = None + + while curr.next != None: + curr = curr.next + + curr.next = self.head + self.head.pre = curr + self.head = NewHead + + +# Driver Code +if __name__ == ""__main__"": + list = GFG() + list.insertAtTail('a') + list.insertAtTail('b') + list.insertAtTail('c') + list.insertAtTail('d') + list.insertAtTail('e') + + n = 2 + print(""Before Rotation : "") + list.display() + list.rotateByN(n) + print(""\nAfter Rotation : "") + list.display() + print() + +# This code is contributed by Tapesh(tapeshdua420)",constant,linear +"class Node: + def __init__(self): + self.data = 0; + self.next = None; + self.next = None; + +# Function to add Node at the end of a +# Doubly LinkedList +def insertAtEnd(head, data): + new_Node = Node(); + new_Node.data = data; + new_Node.next = None; + temp = head; + + if (head == None): + new_Node.prev = None; + head = new_Node; + return head; + + + while (temp.next != None): + temp = temp.next; + + temp.next = new_Node; + new_Node.prev = temp; + return head; + + +# Function to print Doubly LinkedList +def printDLL(head): + while (head != None): + print(head.data, end="" ""); + head = head.next; + + print(); + + +# Function to Reverse a doubly linked list +# in groups of given size +def reverseByN(head, k): + if (head == None): + return None; + + head.prev = None; + temp=None; + curr = head; + newHead = None; + count = 0; + + while (curr != None and count < k): + newHead = curr; + temp = curr.prev; + curr.prev = curr.next; + curr.next = temp; + curr = curr.prev; + count += 1; + + # Checking if the reversed LinkedList size is + # equal to K or not. If it is not equal to k + # that means we have reversed the last set of + # size K and we don't need to call the + # recursive function + if (count >= k): + rest = reverseByN(curr, k); + head.next = rest; + if (rest != None): + + # it is required for prev link otherwise u + # wont be backtrack list due to broken + # links + rest.prev = head; + + return newHead; + + +# Driver code +if __name__ == '__main__': + head = None; + for i in range(1,11): + head = insertAtEnd(head, i); + + printDLL(head); + n = 4; + + head = reverseByN(head, n); + printDLL(head); + +# This code contributed by umadevi9616",constant,linear +"# Python implementation to reverse a doubly +# linked list in groups of given size without recursion +# Iterative method. + +# Represents a node of doubly linked list. +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +# Function to get a new Node. +def getNode(data): + # allocating node + new_node = Node(0) + new_node.data = data + new_node.next = new_node.prev = None + return new_node + +# Function to insert a node at the beginning of the doubly linked list. + + +def push(head, new_node): + # since we are adding at the beginning, prev is always null. + new_node.prev = None + # link the old list off the new node. + new_node.next = head + # change prev of head node to new node. + if ((head) != None): + head.prev = new_node + # move the head to point to the new node. + head = new_node + return head + +# Function to print nodes in given doubly linked list. + + +def printList(head): + while (head): + print(head.data, end="" "") + head = head.next + +# Function to reverse a doubly linked list in groups of given size. + + +def revListInGroupOfGivenSize(head, k): + if head is None: + return head + st = head + globprev, ans = None, None + while (st != None): + # Count the number of nodes. + count = 1 + curr = st + prev, next_node = None, None + while (curr != None and count <= k): + # Reversing k nodes. + next_node = curr.next + curr.prev = next_node + curr.next = prev + prev = curr + curr = next_node + count += 1 + + if ans is None: + ans = prev + ans.prev = None + + if globprev is None: + globprev = st + + else: + globprev.next = prev + prev.prev = globprev + globprev = st + + st = curr + + return ans + + +# Start with the empty list. +head = None + +# Create a doubly linked list: 10<->8<->4<->2 +head = push(head, getNode(2)) +head = push(head, getNode(4)) +head = push(head, getNode(8)) +head = push(head, getNode(10)) + +print(""Original list:"", end="" "") +printList(head) + +k = 2 + +# Reverse doubly linked list in groups of size 'k' +head = revListInGroupOfGivenSize(head, k) + +print(""\nModified list:"", end="" "") +printList(head) + +# This code is contributed by lokesh (lokeshmvs21).",constant,linear +"# Python3 program to implement Stack +# using linked list so that reverse +# can be done with O(1) extra space. +class StackNode: + + def __init__(self, data): + + self.data = data + self.next = None + +class Stack: + + def __init__(self): + + self.top = None + + # Push and pop operations + def push(self, data): + + if (self.top == None): + self.top = StackNode(data) + return + + s = StackNode(data) + s.next = self.top + self.top = s + + def pop(self): + + s = self.top + self.top = self.top.next + return s + + # Prints contents of stack + def display(self): + + s = self.top + + while (s != None): + print(s.data, end = ' ') + s = s.next + + # Reverses the stack using simple + # linked list reversal logic. + def reverse(self): + + prev = self.top + cur = self.top + cur = cur.next + succ = None + prev.next = None + + while (cur != None): + succ = cur.next + cur.next = prev + prev = cur + cur = succ + + self.top = prev + +# Driver code +if __name__=='__main__': + + s = Stack() + s.push(1) + s.push(2) + s.push(3) + s.push(4) + + print(""Original Stack"") + s.display() + print() + + # Reverse + s.reverse() + + print(""Reversed Stack"") + s.display() + +# This code is contributed by rutvik_56",constant,linear +"# Python3 program to find a list in second list +class Node: + def __init__(self, value = 0): + + self.value = value + self.next = None + +# Returns true if first list is +# present in second list +def findList(first, second): + + # If both linked lists are empty/None, + # return True + if not first and not second: + return True + + # If ONLY one of them is empty, + # return False + if not first or not second: + return False + + ptr1 = first + ptr2 = second + + # Traverse the second LL by + # picking nodes one by one + while ptr2: + + # Initialize 'ptr2' with current + # node of 'second' + ptr2 = second + + # Start matching first LL + # with second LL + while ptr1: + + # If second LL become empty and + # first not, return False, + # since first LL has not been + # traversed completely + if not ptr2: + return False + + # If value of both nodes from both + # LLs are equal, increment pointers + # for both LLs so that next value + # can be matched + else if ptr1.value == ptr2.value: + ptr1 = ptr1.next + ptr2 = ptr2.next + + # If a single mismatch is found + # OR ptr1 is None/empty,break out + # of the while loop and do some checks + else: + break + + # check 1 : + # If 'ptr1' is None/empty,that means + # the 'first LL' has been completely + # traversed and matched so return True + if not ptr1: + return True + + # If check 1 fails, that means, some + # items for 'first' LL are still yet + # to be matched, so start again by + # bringing back the 'ptr1' to point + # to 1st node of 'first' LL + ptr1 = first + + # And increment second node element to next + second = second.next + + return False + +# Driver Code + +# Let us create two linked lists to +# test the above functions. +# Created lists would be be +# node_a: 1->2->3->4 +# node_b: 1->2->1->2->3->4 +node_a = Node(1) +node_a.next = Node(2) +node_a.next.next = Node(3) +node_a.next.next.next = Node(4) + +node_b = Node(1) +node_b.next = Node(2) +node_b.next.next = Node(1) +node_b.next.next.next = Node(2) +node_b.next.next.next.next = Node(3) +node_b.next.next.next.next.next = Node(4) + +if findList(node_a, node_b): + print(""LIST FOUND"") +else: + print(""LIST NOT FOUND"") + +# This code is contributed by GauriShankarBadola",constant,quadratic +"# Python3 program to implement unrolled +# linked list and traversing it. +maxElements = 4 + +# Unrolled Linked List Node +class Node: + + def __init__(self): + + self.numElements = 0 + self.array = [0 for i in range(maxElements)] + self.next = None + +# Function to traverse an unrolled linked list +# and print all the elements +def printUnrolledList(n): + + while (n != None): + + # Print elements in current node + for i in range(n.numElements): + print(n.array[i], end = ' ') + + # Move to next node + n = n.next + +# Driver Code +if __name__=='__main__': + + head = None + second = None + third = None + + # Allocate 3 Nodes + head = Node() + second = Node() + third = Node() + + # Let us put some values in second + # node (Number of values must be + # less than or equal to + # maxElement) + head.numElements = 3 + head.array[0] = 1 + head.array[1] = 2 + head.array[2] = 3 + + # Link first Node with the second Node + head.next = second + + # Let us put some values in second node + # (Number of values must be less than + # or equal to maxElement) + second.numElements = 3 + second.array[0] = 4 + second.array[1] = 5 + second.array[2] = 6 + + # Link second Node with the third Node + second.next = third + + # Let us put some values in third node + # (Number of values must be less than + # or equal to maxElement) + third.numElements = 3 + third.array[0] = 7 + third.array[1] = 8 + third.array[2] = 9 + third.next = None + + printUnrolledList(head) + +# This code is contributed by rutvik_56",linear,linear +"# Python program to construct a Maximum Sum Linked List out of +# two Sorted Linked Lists having some Common nodes +class LinkedList(object): + def __init__(self): + # head of list + self.head = None + + # Linked list Node + class Node(object): + def __init__(self, d): + self.data = d + self.next = None + + # Method to adjust pointers and print final list + def finalMaxSumList(self, a, b): + result = None + # assigning pre and cur to head + # of the linked list + pre1 = a + curr1 = a + pre2 = b + curr2 = b + # Till either of current pointers is not null + # execute the loop + while curr1 != None or curr2 != None: + # Keeping 2 local variables at the start of every + # loop run to keep track of the sum between pre + # and cur reference elements. + sum1 = 0 + sum2 = 0 + # Calculating sum by traversing the nodes of linked + # list as the merging of two linked list. The loop + # stops at a common node + while curr1 != None and curr2 != None and curr1.data != curr2.data: + if curr1.data < curr2.data: + sum1 += curr1.data + curr1 = curr1.next + else: + sum2 += curr2.data + curr2 = curr2.next + # If either of current pointers becomes null + # carry on the sum calculation for other one. + if curr1 == None: + while curr2 != None: + sum2 += curr2.data + curr2 = curr2.next + if curr2 == None: + while curr1 != None: + sum1 += curr1.data + curr1 = curr1.next + # First time adjustment of resultant head based on + # the maximum sum. + if pre1 == a and pre2 == b: + result = pre1 if (sum1 > sum2) else pre2 + else: + # If pre1 and pre2 don't contain the head references of + # lists adjust the next pointers of previous pointers. + if sum1 > sum2: + pre2.next = pre1.next + else: + pre1.next = pre2.next + # Adjusting previous pointers + pre1 = curr1 + pre2 = curr2 + # If curr1 is not NULL move to the next. + if curr1 != None: + curr1 = curr1.next + # If curr2 is not NULL move to the next. + if curr2 != None: + curr2 = curr2.next + + while result != None: + print (str(result.data),end="" "") + result = result.next + print () + + # Utility functions + # Inserts a new Node at front of the list. + def push(self, new_data): + # 1 & 2: Allocate the Node & + # Put in the data + new_node = self.Node(new_data) + # 3. Make next of new Node as head + new_node.next = self.head + # 4. Move the head to point to new Node + self.head = new_node + +# Driver program +llist1 = LinkedList() +llist2 = LinkedList() + +# Linked List 1 : 1->3->30->90->110->120->NULL +# Linked List 2 : 0->3->12->32->90->100->120->130->NULL + +llist1.push(120) +llist1.push(110) +llist1.push(90) +llist1.push(30) +llist1.push(3) +llist1.push(1) + +llist2.push(130) +llist2.push(120) +llist2.push(100) +llist2.push(90) +llist2.push(32) +llist2.push(12) +llist2.push(3) +llist2.push(0) + +llist1.finalMaxSumList(llist1.head, llist2.head) + +# This code is contributed by BHAVYA JAIN",constant,linear +"# Python3 program to find fractional node +# in a linked list +import math + +# Linked list node +class Node: + def __init__(self, data): + self.data = data + self.next = None + +# Function to create a new node +# with given data +def newNode(data): + new_node = Node(data) + new_node.data = data + new_node.next = None + return new_node + +# Function to find fractional node +# in the linked list +def fractionalNodes(head, k): + + # Corner cases + if (k <= 0 or head == None): + return None + + fractionalNode = None + + # Traverse the given list + i = 0 + temp = head + while (temp != None): + + # For every k nodes, we move + # fractionalNode one step ahead. + if (i % k == 0): + + # First time we see a multiple of k + if (fractionalNode == None): + fractionalNode = head + + else: + fractionalNode = fractionalNode.next + + i = i + 1 + temp = temp.next + + return fractionalNode + +# A utility function to print a linked list +def printList(node): + while (node != None): + print(node.data, end = ' ') + node = node.next + +# Driver Code +if __name__ == '__main__': + head = newNode(1) + head.next = newNode(2) + head.next.next = newNode(3) + head.next.next.next = newNode(4) + head.next.next.next.next = newNode(5) + k = 2 + + print(""List is"", end = ' ') + printList(head) + + answer = fractionalNodes(head, k) + print(""\nFractional node is"", end = ' ') + print(answer.data) + +# This code is contributed by Srathore",constant,linear +"# Python3 program to find modular node +# in a linked list +import math + +# Linked list node +class Node: + def __init__(self, data): + self.data = data + self.next = None + +# Function to create a new node +# with given data +def newNode(data): + new_node = Node(data) + new_node.data = data + new_node.next = None + return new_node + +# Function to find modular node +# in the linked list +def modularNode(head, k): + + # Corner cases + if (k <= 0 or head == None): + return None + + # Traverse the given list + i = 1 + modularNode = None + temp = head + while (temp != None): + if (i % k == 0): + modularNode = temp + + i = i + 1 + temp = temp.next + return modularNode + +# Driver Code +if __name__ == '__main__': + head = newNode(1) + head.next = newNode(2) + head.next.next = newNode(3) + head.next.next.next = newNode(4) + head.next.next.next.next = newNode(5) + k = 2 + answer = modularNode(head, k) + print(""Modular node is"", end = ' ') + if (answer != None): + print(answer.data, end = ' ') + else: + print(""None"") + +# This code is contributed by Srathore",constant,linear +"# Python3 program to find smallest and largest +# elements in singly linked list. + +# Linked list node +class Node: + + def __init__(self): + self.data = None + self.next = None + +head = None + +# Function that returns the largest element +# from the linked list. +def largestElement(head): + + # Declare a max variable and initialize + # it with INT_MIN value. + # INT_MIN is integer type and its value + # is -32767 or less. + max = -32767 + + # Check loop while head not equal to None + while (head != None): + + # If max is less than head.data then + # assign value of head.data to max + # otherwise node point to next node. + if (max < head.data) : + max = head.data + head = head.next + + return max + +# Function that returns smallest element +# from the linked list. +def smallestElement(head): + + # Declare a min variable and initialize + # it with INT_MAX value. + # INT_MAX is integer type and its value + # is 32767 or greater. + min = 32767 + + # Check loop while head not equal to None + while (head != None) : + + # If min is greater than head.data then + # assign value of head.data to min + # otherwise node point to next node. + if (min > head.data) : + min = head.data + head = head.next + + return min + +# Function that push the element in linked list. +def push( data) : + + global head + + # Allocate dynamic memory for newNode. + newNode = Node() + + # Assign the data into newNode. + newNode.data = data + + # newNode.next assign the address of + # head node. + newNode.next = (head) + + # newNode become the headNode. + (head) = newNode + +# Display linked list. +def printList( head) : + + while (head != None) : + print(head.data ,end= "" -> "") + head = head.next + + print(""None"") + +# Driver code + +# Start with empty list +# head = new Node() + +# Using push() function to construct +# singly linked list +# 17.22.13.14.15 +push( 15) +push( 14) +push( 13) +push( 22) +push( 17) +print(""Linked list is : "") + +# Call printList() function to +# display the linked list. +printList(head) +print(""Maximum element in linked list: "",end="""") + +# Call largestElement() function to get +# largest element in linked list. +print(largestElement(head)) +print(""Minimum element in linked list: "",end="""") + +# Call smallestElement() function to get +# smallest element in linked list. +print(smallestElement(head),end="""") + +# This code is contributed by Arnab Kundu",constant,linear +"# Python3 program to remove vowels +# Nodes in a linked list + +# A linked list node +class Node: + def __init__(self, x): + self.data = x + self.next = None + +# Utility function to print the +# linked list +def printlist(head): + if (not head): + print(""Empty List"") + return + + while (head != None): + print(head.data, end = "" "") + if (head.next): + print(end = ""-> "") + head = head.next + print() + +# Utility function for checking vowel +def isVowel(x): + return (x == 'a' or x == 'e' or x == 'i' + or x == 'o' or x == 'u' or x == 'A' + or x == 'E' or x == 'I' or x == 'O' + or x == 'U') + +#/* function to arrange consonants and +# vowels nodes */ +def arrange(head): + newHead = head + + # for keep track of vowel + latestVowel = None + + curr = head + + # list is empty + if (head == None): + return None + + # We need to discover the first vowel + # in the list. It is going to be the + # returned head, and also the initial + # latestVowel. + if (isVowel(head.data)): + + # first element is a vowel. It will + # also be the new head and the initial + # latestVowel + latestVowel = head + + else: + + # First element is not a vowel. Iterate + # through the list until we find a vowel. + # Note that curr points to the element + # *before* the element with the vowel. + while (curr.next != None and + not isVowel(curr.next.data)): + curr = curr.next + + + # This is an edge case where there are + # only consonants in the list. + if (curr.next == None): + return head + + # Set the initial latestVowel and the + # new head to the vowel item that we found. + # Relink the chain of consonants after + # that vowel item: + # old_head_consonant.consonant1.consonant2. + # vowel.rest_of_list becomes + # vowel.old_head_consonant.consonant1. + # consonant2.rest_of_list + latestVowel = newHead = curr.next + curr.next = curr.next.next + latestVowel.next = head + + # Now traverse the list. Curr is always the item + # *before* the one we are checking, so that we + # can use it to re-link. + while (curr != None and curr.next != None): + if (isVowel(curr.next.data)): + + # The next discovered item is a vowel + if (curr == latestVowel): + # If it comes directly after the + # previous vowel, we don't need to + # move items around, just mark the + # new latestVowel and advance curr. + latestVowel = curr = curr.next + else: + + # But if it comes after an intervening + # chain of consonants, we need to chain + # the newly discovered vowel right after + # the old vowel. Curr is not changed as + # after the re-linking it will have a + # new next, that has not been checked yet, + # and we always keep curr at one before + # the next to check. + temp = latestVowel.next + + # Chain in new vowel + latestVowel.next = curr.next + + # Advance latestVowel + latestVowel = latestVowel.next + + # Remove found vowel from previous place + curr.next = curr.next.next + + # Re-link chain of consonants after latestVowel + latestVowel.next = temp + + else: + + # No vowel in the next element, advance curr. + curr = curr.next + + return newHead + +# Driver code +if __name__ == '__main__': + + # Initialise the Linked List + head = Node('a') + head.next = Node('b') + head.next.next = Node('c') + head.next.next.next = Node('e') + head.next.next.next.next = Node('d') + head.next.next.next.next.next = Node('o') + head.next.next.next.next.next.next = Node('x') + head.next.next.next.next.next.next.next = Node('i') + + # Print the given Linked List + print(""Linked list before :"") + printlist(head) + + head = arrange(head) + + # Print the Linked List after + # removing vowels + print(""Linked list after :"") + printlist(head) + +# This code is contributed by mohit kumar 29",constant,linear +"''' Python program to arrange consonants and +vowels Nodes in a linked list ''' + +''' A linked list Node ''' +class Node: + def __init__(self, data): + self.data = data; + self.next = None; + +''' Function to add new Node to the List ''' +def append(headRef, data): + new_Node = Node(data); + last = headRef; + if (headRef == None): + headRef = new_Node; + return headRef; + + while (last.next != None): + last = last.next; + last.next = new_Node; + return headRef; + +# utility function to print linked list +def printlist(head): + if (head == None): + print(""Empty List""); + return; + + while (head != None): + print(head.data, end=""""); + if (head.next != None): + print(""-> "",end=""""); + head = head.next; + + print(); + + +''' + * function to arrange consonants and vowels Nodes + ''' +def arrange(head): + vowel = None; + consonant = None; + start = None; + end = None; + while (head != None): + x = head.data; + + # Checking the current Node data is vowel or + # not + if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'): + if (vowel == None): + vowel = Node(x); + start = vowel; + else: + vowel.next = Node(x); + vowel = vowel.next; + + else: + if (consonant == None): + consonant = Node(x); + end = consonant; + else: + consonant.next = Node(x); + consonant = consonant.next; + + + head = head.next; + + # In case when there is no vowel in the incoming LL + # then we have to return the head of the consonant LL + if (start == None): + return end; + + # Connecting the vowel and consonant LL + vowel.next = end; + return start; + +# Driver code +if __name__ == '__main__': + head = None; + head = append(head, 'a'); + head = append(head, 'b'); + head = append(head, 'c'); + head = append(head, 'e'); + head = append(head, 'd'); + head = append(head, 'o'); + head = append(head, 'x'); + head = append(head, 'i'); + + print(""Linked list before :""); + printlist(head); + + head = arrange(head); + + print(""Linked list after :""); + printlist(head); + +# This code is contributed by Rajput-Ji",linear,linear +"# Python3 program to partition a +# linked list around a given value. +import math + +# Link list Node +class Node: + def __init__(self, data): + self.data = data + self.next = None + +# A utility function to create a new node +def newNode(data): + new_node = Node(data) + new_node.data = data + new_node.next = None + return new_node + +# Function to make a new list +# (using the existing nodes) +# and return head of new list. +def partition(head, x): + + # Let us initialize start and + # tail nodes of new list + tail = head + + # Now iterate original list + # and connect nodes + curr = head + while (curr != None): + next = curr.next + if (curr.data < x): + + # Insert node at head. + curr.next = head + head = curr + + else: + + # Append to the list of greater values + # Insert node at tail. + tail.next = curr + tail = curr + + curr = next + + tail.next = None + + # The head has changed, so we need + # to return it to the user. + return head + +# Function to print linked list +def printList(head): + temp = head + while (temp != None): + print(temp.data, end = "" "") + temp = temp.next + +# Driver Code +if __name__=='__main__': + + # Start with the empty list + head = newNode(3) + head.next = newNode(5) + head.next.next = newNode(8) + head.next.next.next = newNode(2) + head.next.next.next.next = newNode(10) + head.next.next.next.next.next = newNode(2) + head.next.next.next.next.next.next = newNode(1) + + x = 5 + head = partition(head, x) + printList(head) + +# This code is contributed by AbhiThakur",constant,linear +"# Python3 implementation to modify the contents +# of the linked list + +# Linked list node +class Node: + + def __init__(self, data): + self.data = data + self.next = None + +# Function to insert a node at the beginning +# of the linked list +def push(head_ref, new_data): + + # allocate node + new_node =Node(0) + + # put in the data + new_node.data = new_data + + # link the old list at the end + #of the new node + new_node.next = head_ref + + # move the head to point to the new node + head_ref = new_node + + return head_ref + +front = None +back = None + +# Split the nodes of the given list +# into front and back halves, +# and return the two lists +# using the reference parameters. +# Uses the fast/slow pointer strategy. +def frontAndBackSplit( head): + + global front + global back + slow = None + fast = None + + slow = head + fast = head.next + + # Advance 'fast' two nodes, and + # advance 'slow' one node + while (fast != None): + + fast = fast.next + if (fast != None): + slow = slow.next + fast = fast.next + + # 'slow' is before the midpoint in the list, + # so split it in two at that point. + front = head + back = slow.next + slow.next = None + return head + +# Function to reverse the linked list +def reverseList( head_ref): + + current = None + prev = None + next = None + current = head_ref + prev = None + while (current != None): + + next = current.next + current.next = prev + prev = current + current = next + + head_ref = prev + return head_ref + +# perform the required subtraction operation +# on the 1st half of the linked list +def modifyTheContentsOf1stHalf(): + + global front + global back + front1 = front + back1 = back + + # traversing both the lists simultaneously + while (back1 != None): + + # subtraction operation and node data + # modification + front1.data = front1.data - back1.data + + front1 = front1.next + back1 = back1.next + +# function to concatenate the 2nd(back) list +# at the end of the 1st(front) list and +# returns the head of the new list +def concatFrontAndBackList( front, back): + + head = front + + if(front == None): + return back + + while (front.next != None): + front = front.next + + front.next = back + return head + +# function to modify the contents of the linked list +def modifyTheList( head): + + global front + global back + + # if list is empty or contains only single node + if (head == None or head.next == None): + return head + front = None + back = None + + # split the list into two halves + # front and back lists + frontAndBackSplit(head) + + # reverse the 2nd(back) list + back = reverseList(back) + + # modify the contents of 1st half + modifyTheContentsOf1stHalf() + + # agains reverse the 2nd(back) list + back = reverseList(back) + + # concatenating the 2nd list back to the + # end of the 1st list + head = concatFrontAndBackList(front, back) + + # pointer to the modified list + return head + +# function to print the linked list +def printList( head): + + if (head == None): + return + + while (head.next != None): + + print(head.data , "" -> "",end="""") + head = head.next + + print(head.data ) + +# Driver Code + +head = None + +# creating the linked list +head = push(head, 10) +head = push(head, 7) +head = push(head, 12) +head = push(head, 8) +head = push(head, 9) +head = push(head, 2) + +# modify the linked list +head = modifyTheList(head) + +# print the modified linked list +print( ""Modified List:"" ) +printList(head) + +# This code is contributed by Arnab Kundu",constant,linear +"# Python3 implementation to modify the +# contents of the linked list + +# Linked list node +class Node: + + def __init__(self): + + self.data = 0 + self.next = None + +# Function to insert a node at the +# beginning of the linked list +def append(head_ref, new_data): + + # Allocate node + new_node = Node() + + # Put in the data + new_node.data = new_data + + # Link the old list at the end + # of the new node + new_node.next = head_ref + + # Move the head to point to the new node + head_ref = new_node + + return head_ref + +# Function to print the linked list +def printList(head): + + if (not head): + return; + + while (head.next != None): + print(head.data, end = ' -> ') + head = head.next + + print(head.data) + +# Function to middle node of list. +def find_mid(head): + + temp = head + slow = head + fast = head + + while (fast and fast.next): + + # Advance 'fast' two nodes, and + # advance 'slow' one node + slow = slow.next + fast = fast.next.next + + # If number of nodes are odd then + # update slow by slow.next; + if (fast): + slow = slow.next + + return slow + +# Function to modify the contents of +# the linked list. +def modifyTheList(head, slow): + + # Create Stack. + s = [] + temp = head + + while (slow): + s.append(slow.data) + slow = slow.next + + # Traverse the list by using + # temp until stack is empty. + while (len(s) != 0): + temp.data = temp.data - s[-1] + temp = temp.next + s.pop() + +# Driver code +if __name__=='__main__': + + head = None + + # creating the linked list + head = append(head, 10) + head = append(head, 7) + head = append(head, 12) + head = append(head, 8) + head = append(head, 9) + head = append(head, 2) + + # Call Function to Find the + # starting point of second half of list. + mid = find_mid(head) + + # Call function to modify the + # contents of the linked list. + modifyTheList( head, mid) + + # Print the modified linked list + print(""Modified List:"") + printList(head) + +# This code is contributed by rutvik_56",linear,linear +"# Python3 program to rotate a matrix by 90 degrees +N = 4 + +# An Inplace function to rotate +# N x N matrix by 90 degrees in +# anti-clockwise direction + + +def rotateMatrix(mat): + + # Consider all squares one by one + for x in range(0, int(N / 2)): + + # Consider elements in group + # of 4 in current square + for y in range(x, N-x-1): + + # store current cell in temp variable + temp = mat[x][y] + + # move values from right to top + mat[x][y] = mat[y][N-1-x] + + # move values from bottom to right + mat[y][N-1-x] = mat[N-1-x][N-1-y] + + # move values from left to bottom + mat[N-1-x][N-1-y] = mat[N-1-y][x] + + # assign temp to left + mat[N-1-y][x] = temp + + +# Function to print the matrix +def displayMatrix(mat): + + for i in range(0, N): + + for j in range(0, N): + + print(mat[i][j], end=' ') + print("""") + + +# Driver Code +if __name__ == ""__main__"": + mat = [[0 for x in range(N)] for y in range(N)] + + mat = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + + # Function call + rotateMatrix(mat) + + # Print rotated matrix + displayMatrix(mat) + + +# This code is contributed by saloni1297",constant,quadratic +"# Python program to rotate +# a matrix by 90 degrees + + +def rotateMatrix(mat): + + # reversing the matrix + for i in range(len(mat)): + mat[i].reverse() + + # make transpose of the matrix + for i in range(len(mat)): + for j in range(i, len(mat)): + + # swapping mat[i][j] and mat[j][i] + mat[i][j], mat[j][i] = mat[j][i], mat[i][j] + + +# Function to print the matrix +def displayMatrix(mat): + + for i in range(0, len(mat)): + for j in range(0, len(mat)): + print(mat[i][j], end=' ') + print() + + +# Driver code +if __name__ == ""__main__"": + mat = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + + # Function call + rotateMatrix(mat) + + # Print rotated matrix + displayMatrix(mat) + +# This code is contributed by shivambhagat02(CC).",constant,quadratic +"# Python3 program to +# rotate a matrix by +# 180 degrees +N = 3; + +# Function to Rotate +# the matrix by 180 degree +def rotateMatrix(mat): + + # Simply print from + # last cell to first cell. + i = N - 1; + while(i >= 0): + j = N - 1; + while(j >= 0): + print(mat[i][j], end = "" ""); + j = j - 1; + print(); + i = i - 1; + +# Driven code +mat = [[1, 2, 3], + [ 4, 5, 6 ], + [ 7, 8, 9 ]]; +rotateMatrix(mat); + +# This code is contributed +# by mits",constant,quadratic +"# Python3 program for left rotation of matrix by 180 + +R = 4 +C = 4 + +# Function to rotate the matrix by 180 degree +def reverseColumns(arr): + for i in range(C): + j = 0 + k = C-1 + while j < k: + t = arr[j][i] + arr[j][i] = arr[k][i] + arr[k][i] = t + j += 1 + k -= 1 + +# Function for transpose of matrix +def transpose(arr): + for i in range(R): + for j in range(i, C): + t = arr[i][j] + arr[i][j] = arr[j][i] + arr[j][i] = t + +# Function for display the matrix +def printMatrix(arr): + for i in range(R): + for j in range(C): + print(arr[i][j], end = "" ""); + print(); + +# Function to anticlockwise rotate matrix +# by 180 degree +def rotate180(arr): + transpose(arr); + reverseColumns(arr); + transpose(arr); + reverseColumns(arr); + +# Driven code +arr = [ [ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ], + [9, 10, 11, 12 ], + [13, 14, 15, 16 ] ]; +rotate180(arr); +printMatrix(arr);",constant,quadratic +"# Reverse Row at specified index in the matrix +def reverseRow(data, index): + + cols = len(data[index]) + for i in range(cols // 2): + temp = data[index][i] + data[index][i] = data[index][cols - i - 1] + data[index][cols - i - 1] = temp + + return data + +# Print Matrix data +def printMatrix(data): + + for i in range(len(data)): + for j in range(len(data[0])): + print(data[i][j], end = ' ') + + print() + +# Rotate Matrix by 180 degrees +def rotateMatrix(data): + + rows = len(data) + cols = len(data[0]) + + if (rows % 2): + + # If N is odd reverse the middle + # row in the matrix + data = reverseRow(data, len(data) // 2) + + # Swap the value of matrix [i][j] with + # [rows - i - 1][cols - j - 1] for half + # the rows size. + for i in range(rows // 2): + for j in range(cols): + temp = data[i][j] + data[i][j] = data[rows - i - 1][cols - j - 1] + data[rows - i - 1][cols - j - 1] = temp + + return data + +# Driver Code +data = [ [ 1, 2, 3, 4, 5 ], + [ 6, 7, 8, 9, 10 ], + [ 11, 12, 13, 14, 15 ], + [ 16, 17, 18, 19, 20 ], + [ 21, 22, 23, 24, 25 ] ] + +# Rotate Matrix +data = rotateMatrix(data) + +# Print Matrix +printMatrix(data) + +# This code is contributed by rohitsingh07052",constant,quadratic +"# Python3 program to check if all rows +# of a matrix are rotations of each other + +MAX = 1000 + +# Returns true if all rows of mat[0..n-1][0..n-1] +# are rotations of each other. +def isPermutedMatrix(mat, n) : + + # Creating a string that contains + # elements of first row. + str_cat = """" + for i in range(n) : + str_cat = str_cat + ""-"" + str(mat[0][i]) + + # Concatenating the string with itself + # so that substring search operations + # can be performed on this + str_cat = str_cat + str_cat + + # Start traversing remaining rows + for i in range(1, n) : + + # Store the matrix into vector + # in the form of strings + curr_str = """" + + for j in range(n) : + curr_str = curr_str + ""-"" + str(mat[i][j]) + + # Check if the current string is present + # in the concatenated string or not + if (str_cat.find(curr_str)) : + return True + + return False + +# Driver code +if __name__ == ""__main__"" : + n = 4 + mat = [[1, 2, 3, 4], + [4, 1, 2, 3], + [3, 4, 1, 2], + [2, 3, 4, 1]] + + if (isPermutedMatrix(mat, n)): + print(""Yes"") + else : + print(""No"") + +# This code is contributed by Ryuga",linear,cubic +"# Python3 implementation to sort +# the given matrix + +SIZE = 10 + +# Function to sort the given matrix +def sortMat(mat, n) : + + # Temporary matrix of size n^2 + temp = [0] * (n * n) + k = 0 + + # Copy the elements of matrix + # one by one into temp[] + for i in range(0, n) : + + for j in range(0, n) : + + temp[k] = mat[i][j] + k += 1 + + # sort temp[] + temp.sort() + + # copy the elements of temp[] + # one by one in mat[][] + k = 0 + + for i in range(0, n) : + + for j in range(0, n) : + mat[i][j] = temp[k] + k += 1 + + +# Function to print the given matrix +def printMat(mat, n) : + + for i in range(0, n) : + + for j in range( 0, n ) : + + print(mat[i][j] , end = "" "") + + print() + + +# Driver program to test above +mat = [ [ 5, 4, 7 ], + [ 1, 3, 8 ], + [ 2, 9, 6 ] ] +n = 3 + +print( ""Original Matrix:"") +printMat(mat, n) + +sortMat(mat, n) + +print(""\nMatrix After Sorting:"") +printMat(mat, n) + + +# This code is contributed by Nikita Tiwari.",quadratic,quadratic +"# Python program to find median of matrix +# sorted row wise + +from bisect import bisect_right as upper_bound + +MAX = 100; + +# Function to find median in the matrix +def binaryMedian(m, r, d): + mi = m[0][0] + mx = 0 + for i in range(r): + if m[i][0] < mi: + mi = m[i][0] + if m[i][d-1] > mx : + mx = m[i][d-1] + + desired = (r * d + 1) // 2 + + while (mi < mx): + mid = mi + (mx - mi) // 2 + place = [0]; + + # Find count of elements smaller than or equal to mid + for i in range(r): + j = upper_bound(m[i], mid) + place[0] = place[0] + j + if place[0] < desired: + mi = mid + 1 + else: + mx = mid + print (""Median is"", mi) + return + +# Driver code +r, d = 3, 3 + +m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]] +binaryMedian(m, r, d) + +# This code is contributed by Sachin BIsht",constant,nlogn +"# Recursive code for Matrix Multiplication +MAX = 100 +i = 0 +j = 0 +k = 0 + +def multiplyMatrixRec(row1, col1, A, + row2, col2, B, C): + + # Note that below variables are static + # i and j are used to know current cell of + # result matrix C[][]. k is used to know + # current column number of A[][] and row + # number of B[][] to be multiplied + global i + global j + global k + + # If all rows traversed. + if (i >= row1): + return + + # If i < row1 + if (j < col2): + if (k < col1): + C[i][j] += A[i][k] * B[k][j] + k += 1 + multiplyMatrixRec(row1, col1, A, + row2, col2,B, C) + + k = 0 + j += 1 + multiplyMatrixRec(row1, col1, A, + row2, col2, B, C) + + j = 0 + i += 1 + multiplyMatrixRec(row1, col1, A, + row2, col2, B, C) + +# Function to multiply two matrices +# A[][] and B[][] +def multiplyMatrix(row1, col1, A, row2, col2, B): + if (row2 != col1): + print(""Not Possible"") + return + + C = [[0 for i in range(MAX)] + for i in range(MAX)] + multiplyMatrixRec(row1, col1, A, + row2, col2, B, C) + + # Print the result + for i in range(row1): + for j in range(col2): + print( C[i][j], end = "" "") + print() + +# Driver Code +A = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] +B = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + +row1 = 3 +col1 = 3 +row2 = 3 +col2 = 3 +multiplyMatrix(row1, col1, A, row2, col2, B) + +# This code is contributed by sahilshelangia",logn,quadratic +"# Python3 program to print Lower +# triangular and Upper triangular +# matrix of an array + +# Function to form lower triangular +# matrix +def lower(matrix, row, col): + + + for i in range(0, row): + + for j in range(0, col): + + if (i < j): + + print(""0"", end = "" ""); + + else: + print(matrix[i][j], + end = "" "" ); + + print("" ""); + +# Function to form upper triangular matrix +def upper(matrix, row, col): + + for i in range(0, row): + + for j in range(0, col): + + if (i > j): + print(""0"", end = "" ""); + + else: + print(matrix[i][j], + end = "" "" ); + + print("" ""); + +# Driver Code +matrix = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]; +row = 3; +col = 3; + +print(""Lower triangular matrix: ""); +lower(matrix, row, col); + +print(""Upper triangular matrix: ""); +upper(matrix, row, col); + +# This code is contributed by +# Shivi_Aggarwal",constant,quadratic +"# python3 program for the above approach + + +def spiralOrder(matrix): + ans = [] + + if (len(matrix) == 0): + return ans + + m = len(matrix) + n = len(matrix[0]) + seen = [[0 for i in range(n)] for j in range(m)] + dr = [0, 1, 0, -1] + dc = [1, 0, -1, 0] + x = 0 + y = 0 + di = 0 + + # Iterate from 0 to R * C - 1 + for i in range(m * n): + ans.append(matrix[x][y]) + seen[x][y] = True + cr = x + dr[di] + cc = y + dc[di] + + if (0 <= cr and cr < m and 0 <= cc and cc < n and not(seen[cr][cc])): + x = cr + y = cc + else: + di = (di + 1) % 4 + x += dr[di] + y += dc[di] + return ans + + +# Driver code +if __name__ == ""__main__"": + a = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + + # Function call + for x in spiralOrder(a): + print(x, end="" "") + print()",linear,linear +"# Python3 program to print +# given matrix in spiral form + + +def spiralPrint(m, n, a): + k = 0 + l = 0 + + ''' k - starting row index + m - ending row index + l - starting column index + n - ending column index + i - iterator ''' + + while (k < m and l < n): + + # Print the first row from + # the remaining rows + for i in range(l, n): + print(a[k][i], end="" "") + + k += 1 + + # Print the last column from + # the remaining columns + for i in range(k, m): + print(a[i][n - 1], end="" "") + + n -= 1 + + # Print the last row from + # the remaining rows + if (k < m): + + for i in range(n - 1, (l - 1), -1): + print(a[m - 1][i], end="" "") + + m -= 1 + + # Print the first column from + # the remaining columns + if (l < n): + for i in range(m - 1, k - 1, -1): + print(a[i][l], end="" "") + + l += 1 + + +# Driver Code +a = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + +R = 4 +C = 4 + +# Function Call +spiralPrint(R, C, a) + +# This code is contributed by Nikita Tiwari.",constant,quadratic +"# Python3 program for the above approach + +# Function for printing matrix in spiral +# form i, j: Start index of matrix, row +# and column respectively m, n: End index +# of matrix row and column respectively + + +def printdata(arr, i, j, m, n): + + # If i or j lies outside the matrix + if (i >= m or j >= n): + return + + # Print First Row + for p in range(i, n): + print(arr[i][p], end="" "") + + # Print Last Column + for p in range(i + 1, m): + print(arr[p][n - 1], end="" "") + + # Print Last Row, if Last and + # First Row are not same + if ((m - 1) != i): + for p in range(n - 2, j - 1, -1): + print(arr[m - 1][p], end="" "") + + # Print First Column, if Last and + # First Column are not same + if ((n - 1) != j): + for p in range(m - 2, i, -1): + print(arr[p][j], end="" "") + + printdata(arr, i + 1, j + 1, m - 1, n - 1) + + +# Driver code +if __name__ == ""__main__"": + R = 4 + C = 4 + arr = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] + + # Function Call + printdata(arr, 0, 0, R, C) + +# This code is contributed by avsadityavardhan",constant,quadratic +"# Python3 program for the above approach + +R = 4 +C = 4 + + +def isInBounds(i, j): + global R + global C + if (i < 0 or i >= R or j < 0 or j >= C): + return False + return True + +# Check if the position is blocked + + +def isBlocked(matrix, i, j): + if (not isInBounds(i, j)): + return True + if (matrix[i][j] == -1): + return True + + return False + +# DFS code to traverse spirally + + +def spirallyDFSTravserse(matrix, i, j, Dir, res): + if (isBlocked(matrix, i, j)): + return + + allBlocked = True + for k in range(-1, 2, 2): + allBlocked = allBlocked and isBlocked( + matrix, k + i, j) and isBlocked(matrix, i, j + k) + + res.append(matrix[i][j]) + matrix[i][j] = -1 + if (allBlocked): + return + + # dir: 0 - right, 1 - down, 2 - left, 3 - up + nxt_i = i + nxt_j = j + nxt_dir = Dir + if (Dir == 0): + if (not isBlocked(matrix, i, j + 1)): + nxt_j += 1 + else: + nxt_dir = 1 + nxt_i += 1 + + elif(Dir == 1): + if (not isBlocked(matrix, i + 1, j)): + nxt_i += 1 + else: + nxt_dir = 2 + nxt_j -= 1 + + elif(Dir == 2): + if (not isBlocked(matrix, i, j - 1)): + nxt_j -= 1 + else: + nxt_dir = 3 + nxt_i -= 1 + + elif(Dir == 3): + if (not isBlocked(matrix, i - 1, j)): + nxt_i -= 1 + else: + nxt_dir = 0 + nxt_j += 1 + + spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res) + +# To traverse spirally + + +def spirallyTraverse(matrix): + res = [] + spirallyDFSTravserse(matrix, 0, 0, 0, res) + return res + + +# Driver code +if __name__ == ""__main__"": + a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] + + # Function Call + res = spirallyTraverse(a) + print(*res) + +# This code is contributed by rag2127",constant,quadratic +"# Python program to find unique element in matrix + +# function that calculate unique element +def unique(mat, r, c) -> int: + + # declare map for hashing + mp = {} + for i in range(r): + for j in range(c): + + # increase freq of mat[i][j] in map + if mat[i][j] not in mp: + mp[mat[i][j]] = 1 + else: + mp[mat[i][j]] += 1 + flag = False + + # print unique element + for p in mp: + if mp[p] == 1: + print(p, end="" "") + flag = True + if flag == False: + print(""No unique element in the matrix"") + + +# Driver program +if __name__ == ""__main__"": + mat = [[1, 2, 3, 20], [5, 6, 20, 25], [1, 3, 5, 6], [6, 7, 8, 15]] + + # function that calculate unique element + unique(mat, 4, 4) + + # This code is contributed by ajaymakvana",quadratic,quadratic +"# Python3 program to shift k +# elements in a matrix. + +N = 4 +# Function to shift first k +# elements of each row of +# matrix. +def shiftMatrixByK(mat, k): + if (k > N) : + print (""shifting is"" + "" not possible"") + return + + j = 0 + while (j < N) : + + # Print elements from + # index k + for i in range(k, N): + print (""{} "" . + format(mat[j][i]), end="""") + + # Print elements before + # index k + for i in range(0, k): + print (""{} "" . + format(mat[j][i]), end="""") + + print ("""") + j = j + 1 + +# Driver code +mat = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]] +k = 2 + +# Function call +shiftMatrixByK(mat, k) + +# This code is contributed by +# Manish Shaw (manishshaw1)",constant,quadratic +"# Python3 Program to swap diagonal of a matrix + +# size of square matrix +N = 3 + +# Function to swap diagonal of matrix +def swapDiagonal(matrix): + + for i in range(N): + + matrix[i][i], matrix[i][N-i-1] = \ + matrix[i][N-i-1], matrix[i][i] + + +# Driver Code +matrix = [[0, 1, 2], + [3, 4, 5], + [6, 7, 8]] + +# swap diagonals of matrix +swapDiagonal(matrix); + +# Displaying modified matrix +for i in range(N): + for j in range(N): + print(matrix[i][j], end = ' ') + print()",constant,quadratic +"# Python 3 program for finding max path in matrix +# To calculate max path in matrix + +def findMaxPath(mat): + + for i in range(1, N): + + res = -1 + for j in range(M): + + # When all paths are possible + if (j > 0 and j < M - 1): + mat[i][j] += max(mat[i - 1][j], + max(mat[i - 1][j - 1], + mat[i - 1][j + 1])) + + # When diagonal right is not possible + else if (j > 0): + mat[i][j] += max(mat[i - 1][j], + mat[i - 1][j - 1]) + + # When diagonal left is not possible + else if (j < M - 1): + mat[i][j] += max(mat[i - 1][j], + mat[i - 1][j + 1]) + + # Store max path sum + res = max(mat[i][j], res) + return res + +# Driver program to check findMaxPath +N=4 +M=6 +mat = ([[ 10, 10, 2, 0, 20, 4 ], + [ 1, 0, 0, 30, 2, 5 ], + [ 0, 10, 4, 0, 2, 0 ], + [ 1, 0, 2, 20, 0, 4 ]]) + +print(findMaxPath(mat)) + +# This code is contributed by Azkia Anam.",constant,quadratic +"# Python3 code to move matrix elements +# in given direction with add +# element with same value +MAX = 50 + +# Function to shift the matrix +# in the given direction +def moveMatrix(d, n, a): + + # For right shift move. + if (d[0] == 'r'): + + # For each row from + # top to bottom + for i in range(n): + v = [] + w = [] + + # For each element of + # row from right to left + for j in range(n - 1, -1, -1): + + # if not 0 + if (a[i][j]): + v.append(a[i][j]) + + # For each temporary array + j = 0 + while (j < len(v)): + + # If two element have same + # value at consecutive position. + if (j < len(v) - 1 and + v[j] == v[j + 1]): + + # Insert only one element + # as sum of two same element. + w.append(2 * v[j]) + j += 1 + + else: + w.append(v[j]) + + j += 1 + + # Filling the each row element to 0. + for j in range(n): + a[i][j] = 0 + + j = n - 1 + + # Copying the temporary + # array to the current row. + for it in w: + a[i][j] = it + j -= 1 + + # For left shift move + elif (d[0] == 'l'): + + # For each row + for i in range(n): + v = [] + w = [] + + # For each element of the + # row from left to right + for j in range(n): + + # If not 0 + if (a[i][j]): + v.append(a[i][j]) + + # For each temporary array + j = 0 + while(j < len(v)): + + # If two element have same + # value at consecutive position. + if (j < len(v) - 1 and + v[j] == v[j + 1]): + + # Insert only one element + # as sum of two same element. + w.append(2 * v[j]) + j += 1 + + else: + w.append(v[j]) + + j += 1 + + # Filling the each row element to 0. + for j in range(n): + a[i][j] = 0 + + j = 0 + + for it in w: + a[i][j] = it + j += 1 + + # For down shift move. + elif (d[0] == 'd'): + + # For each column + for i in range(n): + v = [] + w = [] + + # For each element of + # column from bottom to top + for j in range(n - 1, -1, -1): + + # If not 0 + if (a[j][i]): + v.append(a[j][i]) + + # For each temporary array + j = 0 + while(j < len(v)): + + # If two element have same + # value at consecutive position. + if (j m[i][k + 1]): + + # swapping of elements + t = m[i][k] + m[i][k] = m[i][k + 1] + m[i][k + 1] = t + + # printing the sorted matrix + for i in range(len(m)): + for j in range(len(m[i])): + print(m[i][j], end="" "") + print() + +# Driver code +m = [[9, 8, 7, 1 ],[7, 3, 0, 2],[9, 5, 3, 2],[ 6, 3, 1, 2 ]] +sortRowWise(m) + +# This code is contributed by shubhamsingh10",constant,quadratic +"# Python3 code to sort 2D matrix row-wise +def sortRowWise(m): + + # One by one sort individual rows. + for i in range(len(m)): + m[i].sort() + + # printing the sorted matrix + for i in range(len(m)): + for j in range(len(m[i])): + print(m[i][j], end="" "") + print() + + return 0 + +# Driver code +m = [[9, 8, 7, 1 ],[7, 3, 0, 2],[9, 5, 3, 2 ],[ 6, 3, 1, 2]] + +sortRowWise(m) + +# This code is contributed by shubhamsingh10",constant,quadratic +"# Python 3 code to check Markov Matrix + +def checkMarkov(m) : + + # Outer loop to access rows + # and inner to access columns + for i in range(0, len(m)) : + + # Find sum of current row + sm = 0 + for j in range(0, len(m[i])) : + sm = sm + m[i][j] + + if (sm != 1) : + return False + + return True + +# Matrix to check +m = [ [ 0, 0, 1 ], + [ 0.5, 0, 0.5 ], + [ 1, 0, 0 ] ] + +# Calls the function check() +if (checkMarkov(m)) : + print("" yes "") +else : + print("" no "") + + +# This code is contributed by Nikita Tiwari.",constant,quadratic +"# Python3 Program to check if matrix +# is diagonal matrix or not. + +N = 4 + +# Function to check matrix +# is diagonal matrix +# or not. +def isDiagonalMatrix(mat) : + for i in range(0, N): + for j in range(0, N) : + + # condition to check + # other elements + # except main diagonal + # are zero or not. + if ((i != j) and + (mat[i][j] != 0)) : + return False + + return True + + +# Driver function +mat = [[ 4, 0, 0, 0 ], + [ 0, 7, 0, 0 ], + [ 0, 0, 5, 0 ], + [ 0, 0, 0, 1 ]] + +if (isDiagonalMatrix(mat)) : + print(""Yes"") +else : + print(""No"") + + +# This code is contributed by Nikita Tiwari.",constant,quadratic +"# Program to check matrix +# is scalar matrix or not. + + +N = 4 + +# Function to check matrix is +# scalar matrix or not. +def isScalarMatrix(mat) : + + # Check all elements + # except main diagonal are + # zero or not. + for i in range(0,N) : + for j in range(0,N) : + if ((i != j) + and (mat[i][j] != 0)) : + return False + + # Check all diagonal + # elements are same or not. + for i in range(0,N-1) : + if (mat[i][i] != + mat[i + 1][i + 1]) : + return False + + return True + + +# Driver function +mat = [[ 2, 0, 0, 0 ], + [ 0, 2, 0, 0 ], + [ 0, 0, 2, 0 ], + [ 0, 0, 0, 2 ]] + +# Function call +if (isScalarMatrix(mat)): + print(""Yes"") +else : + print(""No"") + + +# This code is contributed by +# Nikita tiwari.",constant,quadratic +"# Python 3 implementation to +# sort the matrix row-wise +# and column-wise +MAX_SIZE = 10 + +# function to sort each +# row of the matrix +def sortByRow(mat, n): + for i in range (n): + + # sorting row number 'i' + for j in range(n-1): + if mat[i][j] > mat[i][j + 1]: + temp = mat[i][j] + mat[i][j] = mat[i][j + 1] + mat[i][j + 1] = temp + +# function to find +# transpose of the matrix +def transpose(mat, n): + for i in range (n): + for j in range(i + 1, n): + + # swapping element at + # index (i, j) by element + # at index (j, i) + t = mat[i][j] + mat[i][j] = mat[j][i] + mat[j][i] = t + +# function to sort +# the matrix row-wise +# and column-wise +def sortMatRowAndColWise(mat, n): + + # sort rows of mat[][] + sortByRow(mat, n) + + # get transpose of mat[][] + transpose(mat, n) + + # again sort rows of mat[][] + sortByRow(mat, n) + + # again get transpose of mat[][] + transpose(mat, n) + +# function to print the matrix +def printMat(mat, n): + for i in range(n): + for j in range(n): + print(str(mat[i][j] ), end = "" "") + print(); + +# Driver Code +mat = [[ 4, 1, 3 ], + [ 9, 6, 8 ], + [ 5, 2, 7 ]] +n = 3 + +print(""Original Matrix:"") +printMat(mat, n) + +sortMatRowAndColWise(mat, n) + +print(""\nMatrix After Sorting:"") +printMat(mat, n) + +# This code is contributed +# by ChitraNayal",constant,quadratic +"# Program to count islands in boolean 2D matrix +class Graph: + + def __init__(self, row, col, g): + self.ROW = row + self.COL = col + self.graph = g + + # A function to check if a given cell + # (row, col) can be included in DFS + def isSafe(self, i, j, visited): + # row number is in range, column number + # is in range and value is 1 + # and not yet visited + return (i >= 0 and i < self.ROW and + j >= 0 and j < self.COL and + not visited[i][j] and self.graph[i][j]) + + # A utility function to do DFS for a 2D + # boolean matrix. It only considers + # the 8 neighbours as adjacent vertices + + def DFS(self, i, j, visited): + + # These arrays are used to get row and + # column numbers of 8 neighbours + # of a given cell + rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] + colNbr = [-1, 0, 1, -1, 1, -1, 0, 1] + + # Mark this cell as visited + visited[i][j] = True + + # Recur for all connected neighbours + for k in range(8): + if self.isSafe(i + rowNbr[k], j + colNbr[k], visited): + self.DFS(i + rowNbr[k], j + colNbr[k], visited) + + # The main function that returns + # count of islands in a given boolean + # 2D matrix + + def countIslands(self): + # Make a bool array to mark visited cells. + # Initially all cells are unvisited + visited = [[False for j in range(self.COL)]for i in range(self.ROW)] + + # Initialize count as 0 and traverse + # through the all cells of + # given matrix + count = 0 + for i in range(self.ROW): + for j in range(self.COL): + # If a cell with value 1 is not visited yet, + # then new island found + if visited[i][j] == False and self.graph[i][j] == 1: + # Visit all cells in this island + # and increment island count + self.DFS(i, j, visited) + count += 1 + + return count + + +graph = [[1, 1, 0, 0, 0], + [0, 1, 0, 0, 1], + [1, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 1]] + + +row = len(graph) +col = len(graph[0]) + +g = Graph(row, col, graph) + +print(""Number of islands is:"") +print(g.countIslands()) + +# This code is contributed by Neelam Yadav",quadratic,quadratic +"# Program to count islands in boolean 2D matrix +class Graph: + + def __init__(self, row, col, graph): + self.ROW = row + self.COL = col + self.graph = graph + + # A utility function to do DFS for a 2D + # boolean matrix. It only considers + # the 8 neighbours as adjacent vertices + def DFS(self, i, j): + if i < 0 or i >= len(self.graph) or j < 0 or j >= len(self.graph[0]) or self.graph[i][j] != 1: + return + + # mark it as visited + self.graph[i][j] = -1 + + # Recur for 8 neighbours + self.DFS(i - 1, j - 1) + self.DFS(i - 1, j) + self.DFS(i - 1, j + 1) + self.DFS(i, j - 1) + self.DFS(i, j + 1) + self.DFS(i + 1, j - 1) + self.DFS(i + 1, j) + self.DFS(i + 1, j + 1) + + # The main function that returns + # count of islands in a given boolean + # 2D matrix + def countIslands(self): + # Initialize count as 0 and traverse + # through the all cells of + # given matrix + count = 0 + for i in range(self.ROW): + for j in range(self.COL): + # If a cell with value 1 is not visited yet, + # then new island found + if self.graph[i][j] == 1: + # Visit all cells in this island + # and increment island count + self.DFS(i, j) + count += 1 + + return count + + +graph = [ + [1, 1, 0, 0, 0], + [0, 1, 0, 0, 1], + [1, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 1] +] + + +row = len(graph) +col = len(graph[0]) + +g = Graph(row, col, graph) + +print(""Number of islands is:"", g.countIslands()) + +# This code is contributed by Shivam Shrey",quadratic,quadratic +"# Python program to print magic square of double order + +def DoublyEven(n): + + # 2-D matrix with all entries as 0 + arr = [[(n*y)+x+1 for x in range(n)]for y in range(n)] + + # Change value of array elements at fix location + # as per the rule (n*n+1)-arr[i][[j] + + # Corners of order (n/4)*(n/4) + # Top left corner + for i in range(0,n//4): + for j in range(0,n//4): + arr[i][j] = (n*n + 1) - arr[i][j]; + + # Top right corner + for i in range(0,n//4): + for j in range(3 * (n//4),n): + arr[i][j] = (n*n + 1) - arr[i][j]; + + # Bottom Left corner + for i in range(3 * (n//4),n): + for j in range(0,n//4): + arr[i][j] = (n*n + 1) - arr[i][j]; + + # Bottom Right corner + for i in range(3 * (n//4),n): + for j in range(3 * (n//4),n): + arr[i][j] = (n*n + 1) - arr[i][j]; + + # Centre of matrix,order (n/2)*(n/2) + for i in range(n//4,3 * (n//4)): + for j in range(n//4,3 * (n//4)): + arr[i][j] = (n*n + 1) - arr[i][j]; + + # Printing the square + for i in range(n): + for j in range(n): + print ('%2d ' %(arr[i][j]),end="" "") + print() + +# Driver Program +n = 8 +DoublyEven(n) + +# Contributed by Harshit Agrawal ",quadratic,quadratic +"# Python program to generate +# odd sized magic squares +# A function to generate odd +# sized magic squares + + +def generateSquare(n): + + # 2-D array with all + # slots set to 0 + magicSquare = [[0 for x in range(n)] + for y in range(n)] + + # initialize position of 1 + i = n // 2 + j = n - 1 + + # Fill the magic square + # by placing values + num = 1 + while num <= (n * n): + if i == -1 and j == n: # 3rd condition + j = n - 2 + i = 0 + else: + + # next number goes out of + # right side of square + if j == n: + j = 0 + + # next number goes + # out of upper side + if i < 0: + i = n - 1 + + if magicSquare[int(i)][int(j)]: # 2nd condition + j = j - 2 + i = i + 1 + continue + else: + magicSquare[int(i)][int(j)] = num + num = num + 1 + + j = j + 1 + i = i - 1 # 1st condition + + # Printing magic square + print(""Magic Square for n ="", n) + print(""Sum of each row or column"", + n * (n * n + 1) // 2, ""\n"") + + for i in range(0, n): + for j in range(0, n): + print('%2d ' % (magicSquare[i][j]), + end='') + + # To display output + # in matrix form + if j == n - 1: + print() + +# Driver Code + + +# Works only when n is odd +n = 7 +generateSquare(n) + +# This code is contributed +# by Harshit Agrawal",quadratic,quadratic +"# Python3 program to check whether a given +# matrix is magic matrix or not +# Returns true if mat[][] is magic +# square, else returns false. +def isMagicSquare( mat) : + n = len(mat) + # sumd1 and sumd2 are the sum of the two diagonals + sumd1=0 + sumd2=0 + for i in range(n): + # (i, i) is the diagonal from top-left -> bottom-right + # (i, n - i - 1) is the diagonal from top-right -> bottom-left + sumd1+=mat[i][i] + sumd2+=mat[i][n-i-1] + # if the two diagonal sums are unequal then it is not a magic square + if not(sumd1==sumd2): + return False + for i in range(n): + #sumr is rowsum and sumc is colsum + sumr=0 + sumc=0 + for j in range(n): + sumr+=mat[i][j] + sumc+=mat[j][i] + if not(sumr==sumc==sumd1): + return False + #if all the conditions are satisfied then it is a magic square + return True + + + + + +# Driver Code +mat = [ [ 2, 7, 6 ], + [ 9, 5, 1 ], + [ 4, 3, 8 ] ] + +if (isMagicSquare(mat)) : + print( ""Magic Square"") +else : + print( ""Not a magic Square"") + ",constant,quadratic +"# Python3 program to check whether a given +# matrix is magic matrix or not +# Returns true if mat[][] is magic +# square, else returns false. +def isMagicSquare( mat) : + n = len(mat) + # sumd1 and sumd2 are the sum of the two diagonals + sumd1=0 + sumd2=0 + for i in range(n): + # (i, i) is the diagonal from top-left -> bottom-right + # (i, n - i - 1) is the diagonal from top-right -> bottom-left + sumd1+=mat[i][i] + sumd2+=mat[i][n-i-1] + # if the two diagonal sums are unequal then it is not a magic square + if not(sumd1==sumd2): + return False + for i in range(n): + #sumr is rowsum and sumc is colsum + sumr=0 + sumc=0 + for j in range(n): + sumr+=mat[i][j] + sumc+=mat[j][i] + if not(sumr==sumc==sumd1): + return False + #if all the conditions are satisfied then it is a magic square + return True + + + + + +# Driver Code +mat = [ [ 2, 7, 6 ], + [ 9, 5, 1 ], + [ 4, 3, 8 ] ] + +if (isMagicSquare(mat)) : + print( ""Magic Square"") +else : + print( ""Not a magic Square"") + ",constant,quadratic +"# Python implementation to +# count sub-matrices having +# sum divisible by the +# value 'k' + +# function to count all +# sub-arrays divisible by k +def subCount(arr, n, k) : + + # create auxiliary hash + # array to count frequency + # of remainders + mod = [0] * k; + + # Traverse original array + # and compute cumulative + # sum take remainder of + # this current cumulative + # sum and increase count + # by 1 for this remainder + # in mod array + cumSum = 0; + for i in range(0, n) : + + cumSum = cumSum + arr[i]; + + # as the sum can be + # negative, taking + # modulo twice + mod[((cumSum % k) + k) % k] = mod[ + ((cumSum % k) + k) % k] + 1; + + result = 0; # Initialize result + + # Traverse mod + for i in range(0, k) : + + # If there are more than + # one prefix subarrays + # with a particular mod value. + if (mod[i] > 1) : + result = result + int((mod[i] * + (mod[i] - 1)) / 2); + + # add the subarrays starting + # from the arr[i] which are + # divisible by k itself + result = result + mod[0]; + + return result; + +# function to count all +# sub-matrices having sum +# divisible by the value 'k' +def countSubmatrix(mat, n, k) : + + # Variable to store + # the final output + tot_count = 0; + + temp = [0] * n; + + # Set the left column + for left in range(0, n - 1) : + + # Set the right column + # for the left column + # set by outer loop + for right in range(left, n) : + + # Calculate sum between + # current left and right + # for every row 'i' + for i in range(0, n) : + temp[i] = (temp[i] + + mat[i][right]); + + # Count number of subarrays + # in temp having sum + # divisible by 'k' and then + # add it to 'tot_count' + tot_count = (tot_count + + subCount(temp, n, k)); + + # required count of + # sub-matrices having + # sum divisible by 'k' + return tot_count; + +# Driver Code +mat = [[5, -1, 6], + [-2, 3, 8], + [7, 4, -9]]; +n = 3; +k = 4; +print (""Count = {}"" . format( + countSubmatrix(mat, n, k))); + +# This code is contributed by +# Manish Shaw(manishshaw1)",linear,cubic +"# Python Program to check +# whether given matrix is +# Diagonally Dominant Matrix. + +# check the given +# matrix is Diagonally +# Dominant Matrix or not. +def isDDM(m, n) : + + # for each row + for i in range(0, n) : + + # for each column, finding + # sum of each row. + sum = 0 + for j in range(0, n) : + sum = sum + abs(m[i][j]) + + # removing the + # diagonal element. + sum = sum - abs(m[i][i]) + + # checking if diagonal + # element is less than + # sum of non-diagonal + # element. + if (abs(m[i][i]) < sum) : + return False + + return True + +# Driver Code +n = 3 +m = [[ 3, -2, 1 ], + [ 1, -3, 2 ], + [ -1, 2, 4 ]] + +if((isDDM(m, n))) : + print (""YES"") +else : + print (""NO"") + +# This code is contributed by +# Manish Shaw(manishshaw1)",constant,quadratic +"# Python 3 Program to Find minimum +# number of operation required such +# that sum of elements on each row +# and column becomes same + +# Function to find minimum operation +# required to make sum of each row +# and column equals + + +def findMinOpeartion(matrix, n): + + # Initialize the sumRow[] and sumCol[] + # array to 0 + sumRow = [0] * n + sumCol = [0] * n + + # Calculate sumRow[] and sumCol[] array + for i in range(n): + for j in range(n): + sumRow[i] += matrix[i][j] + sumCol[j] += matrix[i][j] + + # Find maximum sum value in + # either row or in column + maxSum = 0 + for i in range(n): + maxSum = max(maxSum, sumRow[i]) + maxSum = max(maxSum, sumCol[i]) + + count = 0 + i = 0 + j = 0 + while i < n and j < n: + + # Find minimum increment required + # in either row or column + diff = min(maxSum - sumRow[i], + maxSum - sumCol[j]) + + # Add difference in corresponding + # cell, sumRow[] and sumCol[] array + matrix[i][j] += diff + sumRow[i] += diff + sumCol[j] += diff + + # Update the count variable + count += diff + + # If ith row satisfied, increment + # ith value for next iteration + if (sumRow[i] == maxSum): + i += 1 + + # If jth column satisfied, increment + # jth value for next iteration + if (sumCol[j] == maxSum): + j += 1 + + return count + +# Utility function to print matrix + + +def printMatrix(matrix, n): + for i in range(n): + for j in range(n): + print(matrix[i][j], end="" "") + print() + + +# Driver code +if __name__ == ""__main__"": + matrix = [[1, 2], + [3, 4]] + print(findMinOpeartion(matrix, 2)) + printMatrix(matrix, 2) + +# This code is contributed +# by ChitraNayal",linear,quadratic +"# Python program to find +# the frequency of k +# in matrix where +# m(i, j)=i+j + +import math + +def find( n, k): + + if (n + 1 >= k): + return (k - 1) + else: + return (2 * n + 1 - k) + + +# Driver Code +n = 4 +k = 7 + +freq = find(n, k) + +if (freq < 0): + print ( "" element not exist"") +else: + print("" Frequency of "" , k ,"" is "" , freq ) + +# This code is contributed +# by Gitanjali.",constant,constant +"# Python3 program to print given number of 1's, +# 2's, 3's ....k's in zig-zag way. + +# function that prints given number of 1's, +# 2's, 3's ....k's in zig-zag way. +def ZigZag(rows, columns, numbers): + k = 0 + + # two-dimensional array to store numbers. + arr = [[0 for i in range(columns)] for j in range(rows)] + for i in range(rows): + + # for even row. + if (i % 2 == 0): + + # for each column. + j = 0 + while j < columns and numbers[k] > 0: + + # storing element. + arr[i][j] = k + 1 + + # decrement element at + # kth index. + numbers[k] -= 1 + + # if array contains zero + # then increment index to + # make this next index + if numbers[k] == 0: + k += 1 + j += 1 + # for odd row. + else: + + # for each column. + j = columns-1 + while j>=0 and numbers[k]>0: + + # storing element. + arr[i][j] = k+1 + + # decrement element + # at kth index. + numbers[k] -= 1 + + # if array contains zero then + # increment index to make this + # next index. + if numbers[k] == 0: + k += 1 + j -= 1 + + # printing the stored elements. + for i in arr: + for j in i: + print(j, end ="" "") + print() + +# Driver code +rows = 4; +columns = 5; +Numbers = [3, 4, 2, 2, 3, 1, 5] +ZigZag(rows, columns, Numbers) + +# This code is contributed by +# Rajnis09",quadratic,quadratic +"# Python3 program to find out the maximum +# product in the matrix which four elements +# are adjacent to each other in one direction +n = 5 + +# function to find max product +def FindMaxProduct(arr, n): + + max = 0 + + # iterate the rows. + for i in range(n): + + # iterate the columns. + for j in range( n): + + # check the maximum product + # in horizontal row. + if ((j - 3) >= 0): + result = (arr[i][j] * arr[i][j - 1] * + arr[i][j - 2] * arr[i][j - 3]) + + if (max < result): + max = result + + # check the maximum product + # in vertical row. + if ((i - 3) >= 0) : + result = (arr[i][j] * arr[i - 1][j] * + arr[i - 2][j] * arr[i - 3][j]) + + if (max < result): + max = result + + # check the maximum product in + # diagonal going through down - right + if ((i - 3) >= 0 and (j - 3) >= 0): + result = (arr[i][j] * arr[i - 1][j - 1] * + arr[i - 2][j - 2] * arr[i - 3][j - 3]) + + if (max < result): + max = result + + # check the maximum product in + # diagonal going through up - right + if ((i - 3) >= 0 and (j - 3) <= 0): + result = (arr[i][j] * arr[i - 1][j + 1] * + arr[i - 2][j + 2] * arr[i - 3][j + 3]) + + if (max < result): + max = result + + return max + +# Driver code +if __name__ == ""__main__"": + + + # int arr[][4] = {{6, 2, 3, 4}, + # {5, 4, 3, 1}, + # {7, 4, 5, 6}, + # {8, 3, 1, 0}}; + # int arr[][5] = {{1, 2, 1, 3, 4}, + # {5, 6, 3, 9, 2}, + # {7, 8, 8, 1, 2}, + # {1, 0, 7, 9, 3}, + # {3, 0, 8, 4, 9}}; + + arr = [[1, 2, 3, 4, 5], + [6, 7, 8, 9, 1], + [2, 3, 4, 5, 6], + [7, 8, 9, 1, 0], + [9, 6, 4, 2, 3]] + + print(FindMaxProduct(arr, n)) + +# This code is contributed by ita_c",constant,quadratic +"# Python implementation of the above approach +def maxPro(a,n,m,k): + maxi = 1 + mp = 1 + for i in range(n): + + # Window Product for each row. + wp = 1 + + for l in range(k): + wp *= a[i][l] + + # Maximum window product for each row + mp = wp + + for j in range(k,m): + wp = wp * a[i][j] / a[i][j - k] + + # Global maximum + # window product + maxi = max( + maxi, + max(mp, wp)) + + return maxi + +# Driver Code +n = 6 +m = 5 +k = 4 +a=[[1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 1 ], + [ 2, 3, 4, 5, 6 ], [ 7, 8, 9, 1, 0 ], + [ 9, 6, 4, 2, 3 ], [ 1, 1, 2, 1, 1 ]] + +# Function call +maxpro = maxPro(a, n, m, k) +print(maxpro) + +# This code is contributed by ab2127",constant,quadratic +"# Python3 Program to check +# lower triangular matrix. + +# Function to check matrix +# is in lower triangular +def islowertriangular(M): + for i in range(0, len(M)): + for j in range(i + 1, len(M)): + if(M[i][j] != 0): + return False + return True + +# Driver function. +M = [[1,0,0,0], + [1,4,0,0], + [4,6,2,0], + [0,4,7,6]] + +if islowertriangular(M): + print (""Yes"") +else: + print (""No"") + +# This code is contributed by Anurag Rawat",constant,quadratic +"# Python3 Program to check upper +# triangular matrix. + +# Function to check matrix +# is in upper triangular +def isuppertriangular(M): + for i in range(1, len(M)): + for j in range(0, i): + if(M[i][j] != 0): + return False + return True + +# Driver function. +M = [[1,3,5,3], + [0,4,6,2], + [0,0,2,5], + [0,0,0,6]] + +if isuppertriangular(M): + print (""Yes"") +else: + print (""No"") + +# This code is contributed by Anurag Rawat",constant,quadratic +"# Python Program to Find the frequency +# of even and odd numbers in a matrix + +MAX=100 + +# Function for calculating frequency +def freq(ar, m, n): + even = 0 + odd = 0 + + for i in range(m): + for j in range(n): + + # modulo by 2 to check + # even and odd + if ((ar[i][j] % 2) == 0): + even += 1 + else: + odd += 1 + + # print Frequency of numbers + print("" Frequency of odd number ="", odd) + print("" Frequency of even number ="", even) + + +# Driver code +m = 3 +n = 3 + +array = [ [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] ] + +freq(array, m, n) + +# This code is contributed +# by Anant Agarwal.",constant,quadratic +"# Python 3 Program to check if the center +# element is equal to the individual +# sum of all the half diagonals + +MAX = 100 + +# Function to Check center element +# is equal to the individual +# sum of all the half diagonals +def HalfDiagonalSums( mat, n): + + # Find sums of half diagonals + diag1_left = 0 + diag1_right = 0 + diag2_left = 0 + diag2_right = 0 + i = 0 + j = n - 1 + while i < n: + + if (i < n//2) : + diag1_left += mat[i][i] + diag2_left += mat[j][i] + + elif (i > n//2) : + diag1_right += mat[i][i] + diag2_right += mat[j][i] + i += 1 + j -= 1 + + return (diag1_left == diag2_right and + diag2_right == diag2_left and + diag1_right == diag2_left and + diag2_right == mat[n//2][n//2]) + +# Driver code +if __name__ == ""__main__"": + + a = [[2, 9, 1, 4, -2], + [6, 7, 2, 11, 4], + [ 4, 2, 9, 2, 4], + [1, 9, 2, 4, 4 ], + [ 0, 2, 4, 2, 5]] + + print(""Yes"") if (HalfDiagonalSums(a, 5)) else print(""No"" )",constant,linear +"# Python code to print identity matrix + +# Function to print identity matrix +def Identity(size): + for row in range(0, size): + for col in range(0, size): + + # Here end is used to stay in same line + if (row == col): + print(""1 "", end="" "") + else: + print(""0 "", end="" "") + print() + +# Driver Code +size = 5 +Identity(size)",constant,quadratic +"# Python3 program to check +# if a given matrix is identity +MAX = 100; +def isIdentity(mat, N): + for row in range(N): + for col in range(N): + if (row == col and + mat[row][col] != 1): + return False; + elif (row != col and + mat[row][col] != 0): + return False; + return True; + +# Driver Code +N = 4; +mat = [[1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1]]; +if (isIdentity(mat, N)): + print(""Yes ""); +else: + print(""No ""); + +# This code is contributed +# by mits",constant,quadratic +"# Python Program to implement matrix +# for swapping the upper diagonal +# elements with lower diagonal +# elements of matrix. + +# Function to swap the diagonal +# elements in a matrix. +def swapUpperToLower(arr): + n = 4; + + # Loop for swap the elements + # of matrix. + for i in range(0, n): + for j in range(i + 1, n): + temp = arr[i][j]; + arr[i][j] = arr[j][i]; + arr[j][i] = temp; + + # Loop for print the matrix elements. + for i in range(0, n): + for j in range(0, n): + print(arr[i][j], end = "" ""); + print("" ""); + +# Driver Code + +arr = [[2, 3, 5, 6 ],[ 4, 5, 7, 9 ], + [8, 6, 4, 9 ],[ 1, 3, 5, 6 ]]; + +# Function call +swapUpperToLower(arr); + +# This code is contributed +# by Shivi_Aggarwal",constant,quadratic +"# Simple Python3 program to find mirror of +# matrix across diagonal. +MAX = 100 + +def imageSwap(mat, n): + + # for diagonal which start from at + # first row of matrix + row = 0 + + # traverse all top right diagonal + for j in range(n): + + # here we use stack for reversing + # the element of diagonal + s = [] + i = row + k = j + while (i < n and k >= 0): + s.append(mat[i][k]) + i += 1 + k -= 1 + + # push all element back to matrix + # in reverse order + i = row + k = j + while (i < n and k >= 0): + mat[i][k] = s[-1] + k -= 1 + i += 1 + s.pop() + + # do the same process for all the + # diagonal which start from last + # column + column = n - 1 + for j in range(1, n): + + # here we use stack for reversing + # the elements of diagonal + s = [] + i = j + k = column + while (i < n and k >= 0): + s.append(mat[i][k]) + i += 1 + k -= 1 + + # push all element back to matrix + # in reverse order + i = j + k = column + while (i < n and k >= 0): + mat[i][k] = s[-1] + i += 1 + k -= 1 + s.pop() + +# Utility function to print a matrix +def printMatrix(mat, n): + for i in range(n): + for j in range(n): + print(mat[i][j], end="" "") + print() + +# Driver code +mat = [[1, 2, 3, 4],[5, 6, 7, 8], + [9, 10, 11, 12],[13, 14, 15, 16]] +n = 4 +imageSwap(mat, n) +printMatrix(mat, n) + +# This code is contributed by shubhamsingh10",linear,quadratic +"# Efficient Python3 program to find mirror of +# matrix across diagonal. +from builtins import range +MAX = 100; + +def imageSwap(mat, n): + + # traverse a matrix and swap + # mat[i][j] with mat[j][i] + for i in range(n): + for j in range(i + 1): + t = mat[i][j]; + mat[i][j] = mat[j][i] + mat[j][i] = t + +# Utility function to print a matrix +def printMatrix(mat, n): + for i in range(n): + for j in range(n): + print(mat[i][j], end="" ""); + print(); + +# Driver code +if __name__ == '__main__': + mat = [1, 2, 3, 4], \ + [5, 6, 7, 8], \ + [9, 10, 11, 12], \ + [13, 14, 15, 16]; + n = 4; + imageSwap(mat, n); + printMatrix(mat, n); + +# This code is contributed by Rajput-Ji",constant,quadratic +"# A brute force approach based Python3 program to +# find if there is a rectangle with 1 as corners. + +# Returns true if there is a rectangle +# with 1 as corners. +def isRectangle(m): + + # finding row and column size + rows = len(m) + if (rows == 0): + return False + columns = len(m[0]) + + # scanning the matrix + for y1 in range(rows): + + for x1 in range(columns): + + # if any index found 1 then + # try for all rectangles + if (m[y1][x1] == 1): + for y2 in range(y1 + 1, rows): + for x2 in range(x1 + 1, columns): + if (m[y1][x2] == 1 and + m[y2][x1] == 1 and + m[y2][x2] == 1): + return True + return False + +# Driver code +mat = [[1, 0, 0, 1, 0], + [0, 0, 1, 0, 1], + [0, 0, 0, 1, 0], + [1, 0, 1, 0, 1]] + +if (isRectangle(mat)): + print(""Yes"") +else: + print(""No"") + +# This code is contributed +# by mohit kumar 29",constant,quadratic +"# An efficient approach based Python program +# to find if there is a rectangle with 1 as +# corners. + +# Returns true if there is a rectangle +# with 1 as corners. +def isRectangle(matrix): + + # finding row and column size + rows = len(matrix) + if (rows == 0): + return False + + columns = len(matrix[0]) + + # map for storing the index of + # combination of 2 1's + table = {} + + # scanning from top to bottom + # line by line + for i in range(rows): + for j in range(columns - 1): + for k in range(j + 1, columns): + + # if found two 1's in a column + if (matrix[i][j] == 1 and + matrix[i][k] == 1): + + # check if there exists 1's in same + # row previously then return true + if (j in table and k in table[j]): + return True + + if (k in table and j in table[k]): + return True + + # store the indexes in hashset + if j not in table: + table[j] = set() + if k not in table: + table[k] = set() + table[j].add(k) + table[k].add(j) + return False + +# Driver Code +if __name__ == '__main__': + mat = [[ 1, 0, 0, 1, 0 ], + [ 0, 0, 1, 0, 1 ], + [ 0, 0, 0, 1, 0 ], + [ 1, 0, 1, 0, 1 ]] + if (isRectangle(mat)): + print(""Yes"") + else: + print(""No"") + +# This code is contributed +# by SHUBHAMSINGH10",quadratic,quadratic +"# Python3 implementation comes from: +# https:#github.com/MichaelWehar/FourCornersProblem +# Written by Niteesh Kumar and Michael Wehar +# References: +# [1] F. Mráz, D. Prusa, and M. Wehar. +# Two-dimensional Pattern Matching against +# Basic Picture Languages. CIAA 2019. +# [2] D. Prusa and M. Wehar. Complexity of +# Searching for 2 by 2 Submatrices in Boolean +# Matrices. DLT 2020. +def searchForRectangle( rows, cols, mat) : + + # Make sure that matrix is non-trivial + if (rows < 2 or cols < 2) : + + return False; + + # Create map + adjsList = dict(); + if (rows >= cols): + + # Row-wise + num_of_keys = rows; + + # Convert each row into vector of col indexes + for i in range(rows): + + for j in range(cols): + + if (mat[i][j]): + + if i not in adjsList: + adjsList[i] = [] + adjsList[i].append(j); + else : + + # Col-wise + num_of_keys = cols; + + # Convert each col into vector of row indexes + for i in range(rows): + + for j in range(cols): + + if (mat[i][j] == 1) : + + if j not in adjsList: + adjsList[j] = [] + adjsList[j].append(i); + + # Search for a rectangle whose four corners are 1's + pairs = dict(); + + for i in range(num_of_keys): + + values = adjsList[i]; + size = len(values) + + for j in range(size - 1): + + for k in range(j + 1, size): + + temp = (values[j], values[k]); + + if temp in pairs: + return True; + + else: + pairs[temp] = i; + return False; + +# Driver code +mat = [[ 1, 0, 0, 1, 0 ], [ 0, 1, 1, 1, 1 ], [ 0, 0, 0, 1, 0 ], [ 1, 1, 1, 1, 0 ]]; +if (searchForRectangle(4, 5, mat)): + print(""Yes""); +else: + print(""No"") + +# This code is contributed by phasing17.",quadratic,quadratic +"# Python program to find all +# rectangles filled with 0 + +def findend(i,j,a,output,index): + x = len(a) + y = len(a[0]) + + # flag to check column edge case, + # initializing with 0 + flagc = 0 + + # flag to check row edge case, + # initializing with 0 + flagr = 0 + + for m in range(i,x): + + # loop breaks where first 1 encounters + if a[m][j] == 1: + flagr = 1 # set the flag + break + + # pass because already processed + if a[m][j] == 5: + pass + + for n in range(j, y): + + # loop breaks where first 1 encounters + if a[m][n] == 1: + flagc = 1 # set the flag + break + + # fill rectangle elements with any + # number so that we can exclude + # next time + a[m][n] = 5 + + if flagr == 1: + output[index].append( m-1) + else: + # when end point touch the boundary + output[index].append(m) + + if flagc == 1: + output[index].append(n-1) + else: + # when end point touch the boundary + output[index].append(n) + + +def get_rectangle_coordinates(a): + + # retrieving the column size of array + size_of_array = len(a) + + # output array where we are going + # to store our output + output = [] + + # It will be used for storing start + # and end location in the same index + index = -1 + + for i in range(0,size_of_array): + for j in range(0, len(a[0])): + if a[i][j] == 0: + + # storing initial position + # of rectangle + output.append([i, j]) + + # will be used for the + # last position + index = index + 1 + findend(i, j, a, output, index) + + + print (output) + +# driver code +tests = [ + + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 0, 0, 0, 1], + [1, 0, 1, 0, 0, 0, 1], + [1, 0, 1, 1, 1, 1, 1], + [1, 0, 1, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1] + + ] + + +get_rectangle_coordinates(tests)",quadratic,quadratic +"# Python3 Code implementation for above problem + +# QItem for current location and distance +# from source location +class QItem: + def __init__(self, row, col, dist): + self.row = row + self.col = col + self.dist = dist + + def __repr__(self): + return f""QItem({self.row}, {self.col}, {self.dist})"" + +def minDistance(grid): + source = QItem(0, 0, 0) + + # Finding the source to start from + for row in range(len(grid)): + for col in range(len(grid[row])): + if grid[row][col] == 's': + source.row = row + source.col = col + break + + # To maintain location visit status + visited = [[False for _ in range(len(grid[0]))] + for _ in range(len(grid))] + + # applying BFS on matrix cells starting from source + queue = [] + queue.append(source) + visited[source.row][source.col] = True + while len(queue) != 0: + source = queue.pop(0) + + # Destination found; + if (grid[source.row][source.col] == 'd'): + return source.dist + + # moving up + if isValid(source.row - 1, source.col, grid, visited): + queue.append(QItem(source.row - 1, source.col, source.dist + 1)) + visited[source.row - 1][source.col] = True + + # moving down + if isValid(source.row + 1, source.col, grid, visited): + queue.append(QItem(source.row + 1, source.col, source.dist + 1)) + visited[source.row + 1][source.col] = True + + # moving left + if isValid(source.row, source.col - 1, grid, visited): + queue.append(QItem(source.row, source.col - 1, source.dist + 1)) + visited[source.row][source.col - 1] = True + + # moving right + if isValid(source.row, source.col + 1, grid, visited): + queue.append(QItem(source.row, source.col + 1, source.dist + 1)) + visited[source.row][source.col + 1] = True + + return -1 + + +# checking where move is valid or not +def isValid(x, y, grid, visited): + if ((x >= 0 and y >= 0) and + (x < len(grid) and y < len(grid[0])) and + (grid[x][y] != '0') and (visited[x][y] == False)): + return True + return False + +# Driver code +if __name__ == '__main__': + grid = [['0', '*', '0', 's'], + ['*', '0', '*', '*'], + ['0', '*', '*', '*'], + ['d', '*', '*', '*']] + + print(minDistance(grid)) + + # This code is contributed by sajalmittaldei.",quadratic,quadratic +"# Python3 program to compute number of sets +# in a binary matrix. +m = 3 # no of columns +n = 2 # no of rows + +# function to calculate the number of +# non empty sets of cell +def countSets(a): + + # stores the final answer + res = 0 + + # traverses row-wise + for i in range(n): + u = 0 + v = 0 + for j in range(m): + if a[i][j]: + u += 1 + else: + v += 1 + res += pow(2, u) - 1 + pow(2, v) - 1 + + # traverses column wise + for i in range(m): + + u = 0 + v = 0 + for j in range(n): + if a[j][i]: + u += 1 + else: + v += 1 + res += pow(2, u) - 1 + pow(2, v) - 1 + + # at the end subtract n*m as no of + # single sets have been added twice. + return res - (n*m) + +# Driver program to test the above function. +a = [[1, 0, 1],[0, 1, 0]] + +print(countSets(a)) + +# This code is contributed by shubhamsingh10",constant,quadratic +"# Python program to search an element in row-wise +# and column-wise sorted matrix + +# Searches the element x in mat[][]. If the +# element is found, then prints its position +# and returns true, otherwise prints ""not found"" +# and returns false + + +def search(mat, n, x): + if(n == 0): + return -1 + + # Traverse through the matrix + for i in range(n): + for j in range(n): + + # If the element is found + if(mat[i][j] == x): + print(""Element found at ("", i, "","", j, "")"") + return 1 + + print("" Element not found"") + return 0 + + +# Driver code +if __name__ == ""__main__"": + mat = [[10, 20, 30, 40], [15, 25, 35, 45], + [27, 29, 37, 48], [32, 33, 39, 50]] + + # Function call + search(mat, 4, 29) + +# This code is contributed by rag2127",constant,quadratic +"# Python3 program to search an element +# in row-wise and column-wise sorted matrix + +# Searches the element x in mat[][]. If the +# element is found, then prints its position +# and returns true, otherwise prints ""not found"" +# and returns false + + +def search(mat, n, x): + + i = 0 + + # set indexes for top right element + j = n - 1 + while (i < n and j >= 0): + + if (mat[i][j] == x): + + print(""Element found at "", i, "", "", j) + return 1 + + if (mat[i][j] > x): + j -= 1 + + # if mat[i][j] < x + else: + i += 1 + + print(""Element not found"") + return 0 # if (i == n || j == -1 ) + + +# Driver Code +if __name__ == ""__main__"": + mat = [[10, 20, 30, 40], + [15, 25, 35, 45], + [27, 29, 37, 48], + [32, 33, 39, 50]] + + # Function call + search(mat, 4, 29) + +# This code is contributed by Anant Agarwal.",constant,linear +"# Python3 program to Create a matrix with +# alternating rectangles of O and X + +# Function to print alternating rectangles +# of 0 and X +def fill0X(m, n): + + # k - starting row index + # m - ending row index + # l - starting column index + # n - ending column index + # i - iterator + i, k, l = 0, 0, 0 + + # Store given number of rows and + # columns for later use + r = m + c = n + + # A 2D array to store the output + # to be printed + a = [[None] * n for i in range(m)] + x = 'X' # Initialize the character to + # be stored in a[][] + + # Fill characters in a[][] in spiral form. + # Every iteration fills one rectangle of + # either Xs or Os + while k < m and l < n: + + # Fill the first row from the + # remaining rows + for i in range(l, n): + a[k][i] = x + k += 1 + + # Fill the last column from + # the remaining columns + for i in range(k, m): + a[i][n - 1] = x + n -= 1 + + # Fill the last row from the + # remaining rows + if k < m: + for i in range(n - 1, l - 1, -1): + a[m - 1][i] = x + m -= 1 + + # Print the first column from + # the remaining columns + if l < n: + for i in range(m - 1, k - 1, -1): + a[i][l] = x + l += 1 + + # Flip character for next iteration + x = 'X' if x == '0' else '0' + + # Print the filled matrix + for i in range(r): + for j in range(c): + print(a[i][j], end = "" "") + print() + +# Driver Code +if __name__ == '__main__': + + print(""Output for m = 5, n = 6"") + fill0X(5, 6) + + print(""Output for m = 4, n = 4"") + fill0X(4, 4) + + print(""Output for m = 3, n = 4"") + fill0X(3, 4) + +# This code is contributed by pranchalK",quadratic,quadratic +"# Python3 program to print all elements +# of given matrix in diagonal order +ROW = 5 +COL = 4 + +# Main function that prints given +# matrix in diagonal order + + +def diagonalOrder(matrix): + + # There will be ROW+COL-1 lines in the output + for line in range(1, (ROW + COL)): + # Get column index of the first element + # in this line of output. The index is 0 + # for first ROW lines and line - ROW for + # remaining lines + start_col = max(0, line - ROW) + + # Get count of elements in this line. + # The count of elements is equal to + # minimum of line number, COL-start_col and ROW + count = min(line, (COL - start_col), ROW) + + # Print elements of this line + for j in range(0, count): + print(matrix[min(ROW, line) - j - 1] + [start_col + j], end=""\t"") + + print() + + +# Utility function to print a matrix +def printMatrix(matrix): + for i in range(0, ROW): + for j in range(0, COL): + print(matrix[i][j], end=""\t"") + + print() + + +# Driver Code +M = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16], + [17, 18, 19, 20]] +print(""Given matrix is "") +printMatrix(M) + +print(""\nDiagonal printing of matrix is "") +diagonalOrder(M) + +# This code is contributed by Nikita Tiwari.",constant,quadratic +"# Python3 program to print all elements +# of given matrix in diagonal order +R = 5 +C = 4 + + +def isValid(i, j): + if (i < 0 or i >= R or j >= C or j < 0): + return False + return True + + +def diagonalOrder(arr): + + # through this for loop we choose each element + # of first column as starting point and print + # diagonal starting at it. + # arr[0][0], arr[1][0]....arr[R-1][0] + # are all starting points + for k in range(0, R): + print(arr[k][0], end="" "") + + # set row index for next point in diagonal + i = k - 1 + + # set column index for next point in diagonal + j = 1 + + # Print Diagonally upward + while (isValid(i, j)): + print(arr[i][j], end="" "") + i -= 1 + j += 1 # move in upright direction + + print() + + # Through this for loop we choose each + # element of last row as starting point + # (except the [0][c-1] it has already been + # processed in previous for loop) and print + # diagonal starting at it. + # arr[R-1][0], arr[R-1][1]....arr[R-1][c-1] + # are all starting points + + # Note : we start from k = 1 to C-1; + for k in range(1, C): + print(arr[R-1][k], end="" "") + + # set row index for next point in diagonal + i = R - 2 + + # set column index for next point in diagonal + j = k + 1 + + # Print Diagonally upward + while (isValid(i, j)): + print(arr[i][j], end="" "") + i -= 1 + j += 1 # move in upright direction + + print() + + +# Driver Code +arr = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16], + [17, 18, 19, 20]] + +# Function call +diagonalOrder(arr) + +# This code is contributed by Nikita Tiwari.",constant,quadratic +"R = 5 +C = 5 +def diagonalOrder(arr, n, m): + + # we will use a 2D vector to + # store the diagonals of our array + # the 2D vector will have (n+m-1) + # rows that is equal to the number of + # diagonals + ans = [[] for i in range(n + m - 1)] + + for i in range(m): + for j in range(n): + ans[i + j].append(arr[j][i]) + + for i in range(len(ans)): + for j in range(len(ans[i])): + print(ans[i][j], end = "" "") + print() + +# Driver Code +# we have a matrix of n rows +# and m columns +n = 5 +m = 4 + +# Function call +arr = [[1, 2, 3, 4],[ 5, 6, 7, 8],[9, 10, 11, 12 ],[13, 14, 15, 16 ],[ 17, 18, 19, 20]] +diagonalOrder(arr, n, m) + +# This code is contributed by rag2127",linear,quadratic +"# implementation to find the total +# energy required to rearrange the +# numbers +n = 4 + +# function to find the total energy +# required to rearrange the numbers +def calculateEnergy(mat,n): + + tot_energy = 0 + + # nested loops to access the + # elements of the given matrix + for i in range(n): + for j in range(n): + + #store quotient + q = mat[i][j]//n + + # final destination location + # (i_des, j_des) of the + # element mat[i][j] is being + # calculated + i_des = q + j_des = mat[i][j]- (n*q) + + # energy required for the + # movement of the element + # mat[i][j] is calculated + # and then accumulated in + # the 'tot_energy' + tot_energy += (abs(i_des-i) + + abs(j_des-j)) + + # required total energy + return tot_energy + + +# Driver Program +mat = [[4, 7, 0, 3], + [8, 5, 6, 1], + [9, 11, 10, 2], + [15, 13, 14, 12]] +print(""Total energy required = "", + calculateEnergy(mat,n), ""units"") + +# This code is contributed by Shrikant13.",constant,quadratic +"# Python3 program to count unique cells in +# a matrix + +MAX = 100 + +# Returns true if mat[i][j] is unique +def isUnique(mat, i, j, n, m): + + # checking in row calculating sumrow + # will be moving column wise + sumrow = 0 + for k in range(m): + sumrow += mat[i][k] + if (sumrow > 1): + return False + + # checking in column calculating sumcol + # will be moving row wise + sumcol = 0 + for k in range(n): + sumcol += mat[k][j] + if (sumcol > 1): + return False + + return True + +def countUnique(mat, n, m): + uniquecount = 0 + for i in range(n): + for j in range(m): + if (mat[i][j] and isUnique(mat, i, j, n, m)): + uniquecount += 1 + return uniquecount + +# Driver code + +mat = [[0, 1, 0, 0], + [0, 0, 1, 0], + [1, 0, 0, 1]] +print(countUnique(mat, 3, 4)) + +# This code is contributed by mohit kumar 29",constant,quadratic +"# Efficient Python3 program to count unique +# cells in a binary matrix +MAX = 100; + +def countUnique(mat, n, m): + rowsum = [0] * n; + colsum = [0] * m; + + # Count number of 1s in each row + # and in each column + for i in range(n): + for j in range(m): + if (mat[i][j] != 0): + rowsum[i] += 1; + colsum[j] += 1; + + # Using above count arrays, + # find cells + uniquecount = 0; + for i in range(n): + for j in range(m): + if (mat[i][j] != 0 and + rowsum[i] == 1 and + colsum[j] == 1): + uniquecount += 1; + return uniquecount; + +# Driver code +if __name__ == '__main__': + mat = [ 0, 1, 0, 0 ], + [ 0, 0, 1, 0 ], + [ 1, 0, 0, 1 ]; + print(countUnique(mat, 3, 4)); + +# This code is contributed by 29AjayKumar",linear,quadratic +"# Python 3 program for counting +# number of cell equals to given x + +# function to count factors +# as number of cell +def count(n, x): + cnt = 0 + + # traverse and find the factors + for i in range(1, n + 1): + + # // x%i == 0 means i is factor of x + # x/i <= n means i and j are <= n (for i*j=x) + if i <= x: + if x // i <= n and x % i == 0: + cnt += 1 + return cnt + +# Driver code +n = 8 +x = 24 +print(count(n, x)) + +# This code is contributed by Shrikant13",constant,linear +"# Python 3 code to check +# if a matrix is +# sparse. + +MAX = 100 + +def isSparse(array,m, n) : + + counter = 0 + + # Count number of zeros + # in the matrix + for i in range(0,m) : + for j in range(0,n) : + if (array[i][j] == 0) : + counter = counter + 1 + + return (counter > + ((m * n) // 2)) + +# Driver Function +array = [ [ 1, 0, 3 ], + [ 0, 0, 4 ], + [ 6, 0, 0 ] ] +m = 3 +n = 3 + +if (isSparse(array, m, n)) : + print(""Yes"") +else : + print(""No"") + + +# this code is contributed by +# Nikita tiwari",constant,quadratic +"# Python3 program to find common +# elements in two diagonals. + +Max = 100 + +# Returns count of row wise same +# elements in two diagonals of +# mat[n][n] +def countCommon(mat, n): + res = 0 + + for i in range(n): + + if mat[i][i] == mat[i][n-i-1] : + res = res + 1 + return res + +# Driver Code +mat = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + +print(countCommon(mat, 3)) + +# This code is contributed by Anant Agarwal.",constant,linear +"# Python3 program to check the if +# sum of a row is same as +# corresponding column +MAX = 100; + +# Function to check the if sum +# of a row is same as +# corresponding column +def areSumSame(a, n, m): + sum1 = 0 + sum2 = 0 + for i in range(0, n): + sum1 = 0 + sum2 = 0 + for j in range(0, m): + sum1 += a[i][j] + sum2 += a[j][i] + + if (sum1 == sum2): + return 1 + + return 0 + +# Driver Code +n = 4; # number of rows +m = 4; # number of columns +M = [ [ 1, 2, 3, 4 ], + [ 9, 5, 3, 1 ], + [ 0, 3, 5, 6 ], + [ 0, 4, 5, 6 ] ] + +print(areSumSame(M, n, m)) + +# This code is contributed by Sam007.",constant,linear +"# python program to find row with +# maximum 1 in row sorted binary +# matrix + +N = 4 + +# function for finding row with +# maximum 1 +def findMax (arr): + row = 0 + j = N - 1 + for i in range(0, N): + # find left most position + # of 1 in a row find 1st + # zero in a row + while (arr[i][j] == 1 + and j >= 0): + row = i + j -= 1 + + print(""Row number = "" , row + 1, + "", MaxCount = "", N - 1 - j) + +# driver program +arr = [ [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 0], + [0, 1, 1, 1] ] + +findMax(arr) + +# This code is contributed by Sam007",constant,linear +"# Simple Python code for check a matrix is +# symmetric or not. + +# Fills transpose of mat[N][N] in tr[N][N] +def transpose(mat, tr, N): + for i in range(N): + for j in range(N): + tr[i][j] = mat[j][i] + +# Returns true if mat[N][N] is symmetric, else false +def isSymmetric(mat, N): + + tr = [ [0 for j in range(len(mat[0])) ] for i in range(len(mat)) ] + transpose(mat, tr, N) + for i in range(N): + for j in range(N): + if (mat[i][j] != tr[i][j]): + return False + return True + +# Driver code +mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ] +if (isSymmetric(mat, 3)): + print ""Yes"" +else: + print ""No"" + +# This code is contributed by Sachin Bisht",quadratic,quadratic +"# Efficient Python code for check a matrix is +# symmetric or not. + +# Returns true if mat[N][N] is symmetric, else false +def isSymmetric(mat, N): + for i in range(N): + for j in range(N): + if (mat[i][j] != mat[j][i]): + return False + return True + +# Driver code +mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ] +if (isSymmetric(mat, 3)): + print ""Yes"" +else: + print ""No"" + +# This code is contributed by Sachin Bisht",constant,quadratic +"# Python3 program for the above approach + +# function which tells all cells are visited or not +def isAllCellTraversed(grid, n, m): + + visited = [[True for j in range(m)] for i in range(n)]; + total = n*m; + + # starting cell values + startx = grid[0][0][0]; + starty = grid[0][0][1]; + + for i in range(total-2): + + # if we get {0,0} before the end of loop + # then returns False. Because it means we + # didn't traverse all the cells + if (grid[startx][starty][0] == -1 and + grid[startx][starty][1] == -1): + return False; + + # If found cycle then return False + if (visited[startx][starty] == True): + return False; + + visited[startx][starty] = True; + x = grid[startx][starty][0]; + y = grid[startx][starty][1]; + + # Update startx and starty values to next + # cell values + startx = x; + starty = y; + + # finally if we reach our goal then returns True + if (grid[startx][starty][0] == -1 and + grid[startx][starty][1] == -1): + return True; + + return False; + +# Driver code +cell = [[[] for j in range(3)] for i in range(3)] +cell[0][0] = [0, 1]; +cell[0][1] = [2, 0]; +cell[1][0] = [-1,-1]; +cell[1][1] = [1, 0]; +cell[2][0] = [2, 1]; +cell[2][1] = [1, 1]; + +if(not isAllCellTraversed(cell, 3, 2)): + print(""True""); +else: + print(""False""); + + # This code is contributed by rrrtnx.",quadratic,linear +"# Python3 program to find number +# of possible moves of knight +n = 4; +m = 4; + +# To calculate possible moves +def findPossibleMoves(mat, p, q): + global n, m; + + # All possible moves of a knight + X = [2, 1, -1, -2, -2, -1, 1, 2]; + Y = [1, 2, 2, 1, -1, -2, -2, -1]; + + count = 0; + + # Check if each possible move + # is valid or not + for i in range(8): + + # Position of knight after move + x = p + X[i]; + y = q + Y[i]; + + # count valid moves + if(x >= 0 and y >= 0 and x < n and + y < m and mat[x][y] == 0): + count += 1; + + # Return number of possible moves + return count; + +# Driver code +if __name__ == '__main__': + mat = [[1, 0, 1, 0], [0, 1, 1, 1], + [1, 1, 0, 1], [0, 1, 1, 1]]; + + p, q = 2, 2; + + print(findPossibleMoves(mat, p, q)); + +# This code is contributed by 29AjayKumar",constant,constant +"# A simple Python program to +# find sum of diagonals +MAX = 100 + +def printDiagonalSums(mat, n): + + principal = 0 + secondary = 0; + for i in range(0, n): + for j in range(0, n): + + # Condition for principal diagonal + if (i == j): + principal += mat[i][j] + + # Condition for secondary diagonal + if ((i + j) == (n - 1)): + secondary += mat[i][j] + + print(""Principal Diagonal:"", principal) + print(""Secondary Diagonal:"", secondary) + +# Driver code +a = [[ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ], + [ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ]] +printDiagonalSums(a, 4) + +# This code is contributed +# by ihritik",constant,quadratic +"# A simple Python3 program to find +# sum of diagonals +MAX = 100 + +def printDiagonalSums(mat, n): + + principal = 0 + secondary = 0 + for i in range(0, n): + principal += mat[i][i] + secondary += mat[i][n - i - 1] + + print(""Principal Diagonal:"", principal) + print(""Secondary Diagonal:"", secondary) + +# Driver code +a = [[ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ], + [ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ]] +printDiagonalSums(a, 4) + +# This code is contributed +# by ihritik",constant,linear +"# Python program to print boundary element +# of the matrix. + +MAX = 100 + + +def printBoundary(a, m, n): + for i in range(m): + for j in range(n): + if (i == 0): + print a[i][j], + elif (i == m-1): + print a[i][j], + elif (j == 0): + print a[i][j], + elif (j == n-1): + print a[i][j], + else: + print "" "", + print + + +# Driver code +if __name__ == ""__main__"": + a = [[1, 2, 3, 4], [5, 6, 7, 8], + [1, 2, 3, 4], [5, 6, 7, 8]] + + # Function call + printBoundary(a, 4, 4) + +# This code is contributed by Sachin Bisht",constant,quadratic +"# Python program to print boundary element +# of the matrix. + +MAX = 100 + + +def printBoundary(a, m, n): + sum = 0 + for i in range(m): + for j in range(n): + if (i == 0): + sum += a[i][j] + elif (i == m-1): + sum += a[i][j] + elif (j == 0): + sum += a[i][j] + elif (j == n-1): + sum += a[i][j] + return sum + + +# Driver code +if __name__ == ""__main__"": + a = [[1, 2, 3, 4], [5, 6, 7, 8], + [1, 2, 3, 4], [5, 6, 7, 8]] + + # Function call + sum = printBoundary(a, 4, 4) + print ""Sum of boundary elements is"", sum + +# This code is contributed by Sachin Bisht",constant,quadratic +"# Python3 program to print a matrix +# in spiral form. +MAX = 100 + +def printSpiral(mat, r, c): + + a = 0 + b = 2 + + low_row = 0 if (0 > a) else a + low_column = 0 if (0 > b) else b - 1 + high_row = r-1 if ((a + 1) >= r) else a + 1 + high_column = c-1 if ((b + 1) >= c) else b + 1 + + while ((low_row > 0 - r and low_column > 0 - c)): + + i = low_column + 1 + while (i <= high_column and + i < c and low_row >= 0): + print( mat[low_row][i], end = "" "") + i += 1 + low_row -= 1 + + i = low_row + 2 + while (i <= high_row and + i < r and high_column < c): + print(mat[i][high_column], end = "" "") + i += 1 + high_column += 1 + + i = high_column - 2 + while (i >= low_column and + i >= 0 and high_row < r): + print(mat[high_row][i], end = "" "") + i -= 1 + high_row += 1 + + i = high_row - 2 + while (i > low_row and + i >= 0 and low_column >= 0): + print(mat[i][low_column], end = "" "") + i -= 1 + low_column -= 1 + + print() + +# Driver code +if __name__ == ""__main__"": + + mat = [[ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ]] + r = 3 + c = 3 + printSpiral(mat, r, c) + +# This code is contributed by ita_c",constant,quadratic +"# Python 3 program to print +# matrix in snake order +M = 4 +N = 4 + + +def printf(mat): + global M, N + + # Traverse through all rows + for i in range(M): + + # If current row is + # even, print from + # left to right + if i % 2 == 0: + for j in range(N): + print(str(mat[i][j]), + end="" "") + + # If current row is + # odd, print from + # right to left + else: + for j in range(N - 1, -1, -1): + print(str(mat[i][j]), + end="" "") + + +# Driver code +mat = [[10, 20, 30, 40], + [15, 25, 35, 45], + [27, 29, 37, 48], + [32, 33, 39, 50]] + +printf(mat) + +# This code is contributed +# by ChitraNayal",constant,quadratic +"# Python program to interchange +# the diagonals of matrix +N = 3; + +# Function to interchange diagonals +def interchangeDiagonals(array): + + # swap elements of diagonal + for i in range(N): + if (i != N / 2): + temp = array[i][i]; + array[i][i] = array[i][N - i - 1]; + array[i][N - i - 1] = temp; + + for i in range(N): + for j in range(N): + print(array[i][j], end = "" ""); + print(); + +# Driver Code +if __name__ == '__main__': + array = [ 4, 5, 6 ],[ 1, 2, 3 ],[ 7, 8, 9 ]; + interchangeDiagonals(array); + +# This code is contributed by Rajput-Ji",constant,quadratic +"# Python3 program to find the difference +# between the sum of diagonal. +def difference(arr, n): + + # Initialize sums of diagonals + d1 = 0 + d2 = 0 + + for i in range(0, n): + + for j in range(0, n): + + # finding sum of primary diagonal + if (i == j): + d1 += arr[i][j] + + # finding sum of secondary diagonal + if (i == n - j - 1): + d2 += arr[i][j] + + # Absolute difference of the sums + # across the diagonals + return abs(d1 - d2); + +# Driver Code +n = 3 + +arr = [[11, 2, 4], + [4 , 5, 6], + [10, 8, -12]] + +print(difference(arr, n)) + +# This code is contributed +# by ihritik",constant,quadratic +"# Python3 program to find the difference +# between the sum of diagonal. +def difference(arr, n): + + # Initialize sums of diagonals + d1 = 0 + d2 = 0 + + for i in range(0, n): + d1 = d1 + arr[i][i] + d2 = d2 + arr[i][n - i - 1] + + # Absolute difference of the sums + # across the diagonals + return abs(d1 - d2) + +# Driver Code +n = 3 + +arr = [[11, 2, 4], + [4 , 5, 6], + [10, 8, -12]] + +print(difference(arr, n)) + +# This code is contributed +# by ihritik",constant,linear +"# Python3 program to construct ancestor +# matrix for given tree. + +class newnode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# anc[] stores all ancestors of current node. +# This function fills ancestors for all nodes. +# It also returns size of tree. Size of tree +# is used to print ancestor matrix. +def ancestorMatrixRec(root, anc): + global mat, MAX + + # base case + if root == None: + return 0 + + # Update all ancestors of current node + data = root.data + for i in range(len(anc)): + mat[anc[i]][data] = 1 + + # Push data to list of ancestors + anc.append(data) + + # Traverse left and right subtrees + l = ancestorMatrixRec(root.left, anc) + r = ancestorMatrixRec(root.right, anc) + + # Remove data from list the list of ancestors + # as all descendants of it are processed now. + anc.pop(-1) + + return l + r + 1 + +# This function mainly calls ancestorMatrixRec() +def ancestorMatrix(root): + + # Create an empty ancestor array + anc = [] + + # Fill ancestor matrix and find + # size of tree. + n = ancestorMatrixRec(root, anc) + + # Print the filled values + for i in range(n): + for j in range(n): + print(mat[i][j], end = "" "") + print() + +# Driver Code +MAX = 100 +mat = [[0] * MAX for i in range(MAX)] + +# Construct the following binary tree +# 5 +# / \ +# 1 2 +# / \ / +# 0 4 3 +root = newnode(5) +root.left = newnode(1) +root.right = newnode(2) +root.left.left = newnode(0) +root.left.right = newnode(4) +root.right.left = newnode(3) + +ancestorMatrix(root) + +# This code is contributed by PranchalK",quadratic,quadratic +"# Python3 program to construct ancestor +# matrix for given tree. +size = 6 + +M = [[0 for j in range(size)] + for i in range(size)] + +# A binary tree node +class Node: + + def __init__(self, data): + + self.left = None + self.right = None + self.data = data + +# Helper function to create a new node +def newnode(data): + + temp = Node(data) + + return temp + +def printMatrix(): + + for i in range(size): + for j in range(size): + print(M[i][j], end = ' ') + + print() + +# First PreOrder Traversal +def MatrixUtil(root, index): + + if (root == None): + return + + preData = root.data + + # Since there is no ancestor for + # root node, so we doesn't assign + # it's value as 1 + if (index == -1): + index = root.data + else: + M[index][preData] = 1 + + MatrixUtil(root.left, preData) + MatrixUtil(root.right, preData) + +def Matrix(root): + + # Call Func MatrixUtil + MatrixUtil(root, -1) + + # Applying Transitive Closure + # for the given Matrix + for i in range(size): + for j in range(size): + for k in range(size): + M[j][k] = (M[j][k] or + (M[j][i] and + M[i][k])) + + # Printing Matrix + printMatrix() + +# Driver code +if __name__==""__main__"": + + root = newnode(5) + root.left = newnode(1) + root.right = newnode(2) + root.left.left = newnode(0) + root.left.right = newnode(4) + root.right.left = newnode(3) + + Matrix(root) + +# This code is contributed by rutvik_56",quadratic,quadratic +"# key structure to store a binary tree node +class Node: + def __init__(self, key, left = None, right = None): + self.key = key + self.left = left + self.right = right + +# Utility function to print binary tree nodes in-order fashion +def inorder(node): + if node: + inorder(node.left) + print(node.key, end = ' ') + inorder(node.right) + +# Function to construct a binary tree +# from specified ancestor matrix +def constructBT(mat): + + # get number of rows in the matrix + N = len(mat) + + # create an empty multi-dict + dict = {} + + # Use sum as key and row numbers as values in the multi-dict + for i in range(N): + + # find the sum of the current row + total = sum(mat[i]) + + # insert the sum and row number into the dict + dict.setdefault(total, []).append(i) + + # node[i] will store node for i in constructed tree + node = [Node(-1)] * N + last = 0 + + # the value of parent[i] is true if parent is set for i'th node + parent = [False] * N + + # Traverse the dictionary in sorted order (default behavior) + for key in dict.keys(): + for row in dict.get(key): + last = row + + # create a new node + node[row] = Node(row) + + # if leaf node, do nothing + if key == 0: + continue + + # traverse row + for i in range(N): + + # do if parent is not set and ancestor exits + if not parent[i] and mat[row][i] == 1: + + # check for the unoccupied node + if node[row].left is None: + node[row].left = node[i] + else: + node[row].right = node[i] + + # set parent for i'th node + parent[i] = True + + # last processed node is the root + return node[last] + +# Construct a Binary Tree from Ancestor Matrix +if __name__ == '__main__': + + mat = [[0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 1, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 0, 0]] + + root = constructBT(mat) + inorder(root) + +# This code is contributed by Priyadarshini Kumari",quadratic,quadratic +"# Python program to fill a matrix with +# values from 1 to n*n in spiral fashion. + +# Fills a[m][n] with values +# from 1 to m*n in spiral fashion. +def spiralFill(m, n, a): + + # Initialize value to be filled in matrix. + val = 1 + + # k - starting row index + # m - ending row index + # l - starting column index + # n - ending column index + k, l = 0, 0 + while (k < m and l < n): + + # Print the first row from the remaining rows. + for i in range(l, n): + a[k][i] = val + val += 1 + k += 1 + + # Print the last column from the remaining columns. + for i in range(k, m): + a[i][n - 1] = val + val += 1 + n -= 1 + + # Print the last row from the remaining rows. + if (k < m): + for i in range(n - 1, l - 1, -1): + a[m - 1][i] = val + val += 1 + m -= 1 + + # Print the first column from the remaining columns. + if (l < n): + for i in range(m - 1, k - 1, -1): + a[i][l] = val + val += 1 + l += 1 + +# Driver program +if __name__ == '__main__': + m, n = 4, 4 + a = [[0 for j in range(n)] for i in range(m)] + spiralFill(m, n, a) + for i in range(m): + for j in range(n): + print(a[i][j], end=' ') + print('') + +# This code is contributed by Parin Shah",quadratic,quadratic +"# A simple Python program to implement Game of Life + +# driver program + +# Function to print next generation +def nextGeneration(grid, M, N): + future = [[0 for i in range(N)] for j in range(M)] + + # Loop through every cell + for l in range(M): + for m in range(N): + + # finding no Of Neighbours that are alive + aliveNeighbours = 0 + for i in range(-1,2): + for j in range(-1,2): + if ((l+i>=0 and l+i=0 and m+j 3)): + future[l][m] = 0 + + # A new cell is born + elif ((grid[l][m] == 0) and (aliveNeighbours == 3)): + future[l][m] = 1 + + # Remains the same + else: + future[l][m] = grid[l][m] + + + print(""Next Generation"") + for i in range(M): + for j in range(N): + if (future[i][j] == 0): + print(""."",end="""") + else: + print(""*"",end="""") + print() + +M,N = 10,10 + +# Initializing the grid. +grid = [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ], + [ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ], + [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] +] + +# Displaying the grid +print(""Original Generation"") +for i in range(M): + for j in range(N): + + if(grid[i][j] == 0): + print(""."",end = """") + else: + print(""*"",end = """") + print() +print() +nextGeneration(grid, M, N) + +# This code is contributed by shinjanpatra",quadratic,quadratic +"# Python 3 program to find the maximum +# sum of hour glass in a Matrix + +# Fixing the size of the Matrix. +# Here it is of order 6 x 6 +R = 5 +C = 5 + +# Function to find the maximum sum of hour glass +def MaxSum(arr): + + # Considering the matrix also contains + max_sum = -50000 + + # Negative values , so initialized with + # -50000. It can be any value but very + # smaller. + # max_sum=0 -> Initialize with 0 only if your + # matrix elements are positive + + if(R < 3 or C < 3): + print(""Not possible"") + exit() + + # Here loop runs (R-2)*(C-2) times considering + # different top left cells of hour glasses. + for i in range(0, R-2): + for j in range(0, C-2): + + # Considering arr[i][j] as top + # left cell of hour glass. + SUM = (arr[i][j] + arr[i][j + 1] + arr[i][j + 2]) + (arr[i + 1][j + 1]) + (arr[i + 2][j] + + arr[i + 2][j + 1] + arr[i + 2][j + 2]) + + # If previous sum is less + # then current sum then + # update new sum in max_sum + if(SUM > max_sum): + max_sum = SUM + else: + continue + + return max_sum + + +# Driver Code +arr = [[1, 2, 3, 0, 0], + [0, 0, 0, 0, 0], + [2, 1, 4, 0, 0], + [0, 0, 0, 0, 0], + [1, 1, 0, 1, 0]] +res = MaxSum(arr) + +print(f""Maximum sum of hour glass = {res}"") + +# This code is written by Akshay Prakash +# Code is modified by Susobhan Akhuli",constant,quadratic +"# Python3 program for finding +# MAXimum and MINimum in a matrix. +MAX = 100 + +# Finds MAXimum and MINimum in arr[0..n-1][0..n-1] +# using pair wise comparisons +def MAXMIN(arr, n): + + MIN = 10**9 + MAX = -10**9 + + # Traverses rows one by one + for i in range(n): + for j in range(n // 2 + 1): + + # Compare elements from beginning + # and end of current row + if (arr[i][j] > arr[i][n - j - 1]): + if (MIN > arr[i][n - j - 1]): + MIN = arr[i][n - j - 1] + if (MAX< arr[i][j]): + MAX = arr[i][j] + else: + if (MIN > arr[i][j]): + MIN = arr[i][j] + if (MAX< arr[i][n - j - 1]): + MAX = arr[i][n - j - 1] + + print(""MAXimum ="", MAX, "", MINimum ="", MIN) + +# Driver Code +arr = [[5, 9, 11], + [25, 0, 14], + [21, 6, 4]] + +MAXMIN(arr, 3) + +# This code is contributed by Mohit Kumar",constant,quadratic +"# Python 3 program to print +# matrix in anti-spiral form +R = 4 +C = 5 + +def antiSpiralTraversal(m, n, a): + k = 0 + l = 0 + + # k - starting row index + # m - ending row index + # l - starting column index + # n - ending column index + # i - iterator + stk = [] + + while (k <= m and l <= n): + + # Print the first row + # from the remaining rows + for i in range(l, n + 1): + stk.append(a[k][i]) + k += 1 + + # Print the last column + # from the remaining columns + for i in range(k, m + 1): + stk.append(a[i][n]) + n -= 1 + + # Print the last row + # from the remaining rows + if ( k <= m): + for i in range(n, l - 1, -1): + stk.append(a[m][i]) + m -= 1 + + # Print the first column + # from the remaining columns + if (l <= n): + for i in range(m, k - 1, -1): + stk.append(a[i][l]) + l += 1 + + while len(stk) != 0: + print(str(stk[-1]), end = "" "") + stk.pop() + +# Driver Code +mat = [[1, 2, 3, 4, 5], + [6, 7, 8, 9, 10], + [11, 12, 13, 14, 15], + [16, 17, 18, 19, 20]]; + +antiSpiralTraversal(R - 1, C - 1, mat) + +# This code is contributed +# by ChitraNayal",quadratic,quadratic +"# Python3 program to find trace and +# normal of given matrix +import math + +# Size of given matrix +MAX = 100; + +# Returns Normal of a matrix +# of size n x n +def findNormal(mat, n): + + sum = 0; + for i in range(n): + for j in range(n): + sum += mat[i][j] * mat[i][j]; + return math.floor(math.sqrt(sum)); + +# Returns trace of a matrix of +# size n x n +def findTrace(mat, n): + + sum = 0; + for i in range(n): + sum += mat[i][i]; + return sum; + +# Driver Code +mat = [[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5]]; + +print(""Trace of Matrix ="", findTrace(mat, 5)); + +print(""Normal of Matrix ="", findNormal(mat, 5)); + +# This code is contributed by mits",constant,quadratic +"# Python 3 program to find +# minimum operations required +# to set all the element of +# binary matrix + +# Return minimum operation +# required to make all 1s. +def minOperation(arr): + ans = 0 + for i in range(N - 1, -1, -1): + for j in range(M - 1, -1, -1): + + # check if this + # cell equals 0 + if(arr[i][j] == 0): + + # increase the + # number of moves + ans += 1 + + # flip from this cell + # to the start point + for k in range(i + 1): + for h in range(j + 1): + + # flip the cell + if (arr[k][h] == 1): + arr[k][h] = 0 + else: + arr[k][h] = 1 + + return ans + +# Driver Code +mat = [[ 0, 0, 1, 1, 1], + [0, 0, 0, 1, 1], + [0, 0, 0, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1]] +M = 5 +N = 5 + +print(minOperation(mat)) + +# This code is contributed +# by ChitraNayal",quadratic,quadratic +"# Python3 Code to Print a given +# matrix in reverse spiral form + +# This is a modified code of +# https:#www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/ +R, C = 3, 6 + +def ReversespiralPrint(m, n, a): + + # Large array to initialize it + # with elements of matrix + b = [0 for i in range(100)] + + #/* k - starting row index + #l - starting column index*/ + i, k, l = 0, 0, 0 + + # Counter for single dimension array + # in which elements will be stored + z = 0 + + # Total elements in matrix + size = m * n + + while (k < m and l < n): + + # Variable to store value of matrix. + val = 0 + + # Print the first row + # from the remaining rows + for i in range(l, n): + + # printf(""%d "", a[k][i]) + val = a[k][i] + b[z] = val + z += 1 + k += 1 + + # Print the last column + # from the remaining columns + for i in range(k, m): + + # printf(""%d "", a[i][n-1]) + val = a[i][n - 1] + b[z] = val + z += 1 + + n -= 1 + + # Print the last row + # from the remaining rows + if (k < m): + for i in range(n - 1, l - 1, -1): + + # printf(""%d "", a[m-1][i]) + val = a[m - 1][i] + b[z] = val + z += 1 + + m -= 1 + + # Print the first column + # from the remaining columns + if (l < n): + for i in range(m - 1, k - 1, -1): + + # printf(""%d "", a[i][l]) + val = a[i][l] + b[z] = val + z += 1 + l += 1 + + for i in range(size - 1, -1, -1): + print(b[i], end = "" "") + +# Driver Code +a = [[1, 2, 3, 4, 5, 6], + [7, 8, 9, 10, 11, 12], + [13, 14, 15, 16, 17, 18]] + +ReversespiralPrint(R, C, a) + +# This code is contributed by mohit kumar",constant,quadratic +"# Python 3 program to check +# whether given matrix +# is skew-symmetric or not +ROW=3 +COL=3 + +# Utility function to +# create transpose matrix +def transpose(transpose_matrix,matrix): + for i in range (ROW): + for j in range(COL): + transpose_matrix[j][i] = matrix[i][j] + +# Utility function to +# check skew - symmetric +# matrix condition +def check(transpose_matrix,matrix): + for i in range(ROW): + for j in range(COL): + if (matrix[i][j] != -transpose_matrix[i][j]): + return False + return True + +# Utility function to print a matrix +def printMatrix(matrix): + for i in range (ROW): + for j in range(COL): + print(matrix[i][j],"" "",end="""") + print() + +# Driver program to test above functions +matrix= [ + [0, 5, -4], + [-5, 0, 1], + [4, -1, 0], + ] +transpose_matrix=[[0 for i in range(3)] for j in range(3)] + +# Function create transpose matrix +transpose(transpose_matrix, matrix) +print(""Transpose matrix:"") +printMatrix(transpose_matrix) + +# Check whether matrix is +# skew-symmetric or not +if (check(transpose_matrix, matrix)): + print(""Skew Symmetric Matrix"") +else: + print(""Not Skew Symmetric Matrix"") + +# This code is contributed +# by Azkia Anam.",quadratic,quadratic +"# Python 3 program to find sum of +# matrix element where each element +# is integer division of row and column. + +# Return sum of matrix element +# where each element is division +# of its corresponding row and column. +def findSum(N): + ans = 0 + for i in range(1, N + 1): + for j in range(1, N + 1): + ans += i // j + return ans + +# Driver code +N = 2 +print(findSum(N)) + +# This code is contributed +# by Shrikant13",constant,quadratic +"# Program to find sum of matrix element +# where each element is integer division +# of row and column. + +# Return sum of matrix element where each +# element is division of its corresponding +# row and column. +def findSum(n): + ans = 0; temp = 0; + + for i in range(1, n + 1): + + # count the number of elements of + # each column. Initialize to i -1 + # because number of zeroes are i - 1. + if temp < n: + temp = i - 1 + + # For multiply + num = 1 + while temp < n: + if temp + i <= n: + ans += i * num + else: + ans += (n - temp) * num + temp += i + num += 1 + return ans + +# Driver Code +N = 2 +print(findSum(N)) + +# This code is contributed by Shrikant13",constant,quadratic +"# Python3 program to find number of +# countOpsation to make two matrix +# equals +def countOps(A, B, m, n): + + # Update matrix A[][] so that only + # A[][] has to be countOpsed + for i in range(n): + for j in range(m): + A[i][j] -= B[i][j]; + + # Check necessary condition for + # condition for existence of full + # countOpsation + for i in range(1, n): + for j in range(1, n): + if (A[i][j] - A[i][0] - + A[0][j] + A[0][0] != 0): + return -1; + + # If countOpsation is possible + # calculate total countOpsation + result = 0; + + for i in range(n): + result += abs(A[i][0]); + + for j in range(m): + result += abs(A[0][j] - A[0][0]); + + return (result); + +# Driver code +if __name__ == '__main__': + A = [[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]; + + B = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]; + + print(countOps(A, B, 3, 3)); + +# This code is contributed by Rajput-Ji",constant,quadratic +"# Python3 program to print 2 coils of a +# 4n x 4n matrix. + +# Print coils in a matrix of size 4n x 4n +def printCoils(n): + + # Number of elements in each coil + m = 8*n*n + + # Let us fill elements in coil 1. + coil1 = [0]*m + + # First element of coil1 + # 4*n*2*n + 2*n + coil1[0] = 8*n*n + 2*n + + curr = coil1[0] + + nflg = 1 + step = 2 + + # Fill remaining m-1 elements in coil1[] + index = 1 + while (index < m): + + # Fill elements of current step from + # down to up + for i in range(step): + + # Next element from current element + curr = coil1[index] = (curr - 4*n*nflg) + index += 1 + if (index >= m): + break + if (index >= m): + break + + # Fill elements of current step from + # up to down. + for i in range(step): + + curr = coil1[index] = curr + nflg + index += 1 + if (index >= m): + break + nflg = nflg*(-1) + step += 2 + + #get coil2 from coil1 */ + + coil2 = [0]*m + i = 0 + while(i < 8*n*n): + coil2[i] = 16*n*n + 1 -coil1[i] + i += 1 + # Print both coils + print(""Coil 1 :"", end = "" "") + i = 0 + while(i < 8*n*n): + print(coil1[i], end = "" "") + i += 1 + print(""\nCoil 2 :"", end = "" "") + i = 0 + while(i < 8*n*n): + print(coil2[i], end = "" "") + i += 1 + +# Driver code + +n = 1 +printCoils(n) + +# This code is contributed by shubhamsingh10",quadratic,quadratic +"# Python3 program to find sum of matrix +# in which each element is absolute +# difference of its corresponding +# row and column number row. + +# Return the sum of matrix in which each +# element is absolute difference of its +# corresponding row and column number row +def findSum(n): + + # Generate matrix + arr = [[0 for x in range(n)] + for y in range (n)] + for i in range (n): + for j in range (n): + arr[i][j] = abs(i - j) + + # Compute sum + sum = 0 + for i in range (n): + for j in range(n): + sum += arr[i][j] + + return sum + +# Driver Code +if __name__ == ""__main__"": + + n = 3 + print (findSum(n)) + +# This code is contributed by ita_c",quadratic,quadratic +"# Python 3 program to find sum +# of matrix in which each element +# is absolute difference of its +# corresponding row and column +# number row. + +# Return the sum of matrix in +# which each element is absolute +# difference of its corresponding +# row and column number row +def findSum(n): + sum = 0 + for i in range(n): + sum += i * (n - i) + return 2 * sum + +# Driver code +n = 3 +print(findSum(n)) + +# This code is contributed by Shrikant13",constant,linear +"# Python 3 program to find sum of matrix +# in which each element is absolute +# difference of its corresponding row +# and column number row. + +# Return the sum of matrix in which +# each element is absolute difference +# of its corresponding row and column +# number row +def findSum(n): + n -= 1 + sum = 0 + sum += (n * (n + 1)) / 2 + sum += (n * (n + 1) * (2 * n + 1)) / 6 + return int(sum) + +# Driver Code +n = 3 +print(findSum(n)) + +# This code contributed by Rajput-Ji",constant,constant +"# Python3 program to find if a matrix is symmetric. +MAX = 1000 + + +def checkHV(arr, N, M): + + # Initializing as both horizontal and vertical + # symmetric. + horizontal = True + vertical = True + + # Checking for Horizontal Symmetry. We compare + # first row with last row, second row with second + # last row and so on. + i = 0 + k = N - 1 + while(i < N // 2): + + # Checking each cell of a column. + for j in range(M): + + # check if every cell is identical + if (arr[i][j] != arr[k][j]): + horizontal = False + break + i += 1 + k -= 1 + + # Checking for Vertical Symmetry. We compare + # first column with last column, second column + # with second last column and so on. + i = 0 + k = M - 1 + while(j < M // 2): + + # Checking each cell of a row. + for i in range(N): + + # check if every cell is identical + if (arr[i][j] != arr[i][k]): + vertical = False + break + j += 1 + k -= 1 + + if (not horizontal and not vertical): + print(""NO"") + elif (horizontal and not vertical): + print(""HORIZONTAL"") + elif (vertical and not horizontal): + print(""VERTICAL"") + else: + print(""BOTH"") + + +# Driver code +mat = [[1, 0, 1], [0, 0, 0], [1, 0, 1]] + +checkHV(mat, 3, 3) + +# This code is contributed by shubhamsingh10",constant,quadratic +"# Python 3 program to find maximum +# possible determinant of 0/n matrix. +# Function for maximum determinant +def maxDet(n): + return 2 * n * n * n + +# Function to print resultant matrix +def resMatrix(n): + for i in range(3): + for j in range(3): + + # three position where 0 appears + if i == 0 and j == 2: + print(""0"", end = "" "") + else if i == 1 and j == 0: + print(""0"", end = "" "") + else if i == 2 and j == 1: + print(""0"", end = "" "") + + # position where n appears + else: + print(n, end = "" "") + print(""\n"") + +# Driver code +n = 15 +print(""Maximum Detrminat="", maxDet(n)) +print(""Resultant Matrix:"") +resMatrix(n) + +# This code is contributed by Shrikant13",constant,constant +"# Python3 program to find sum of +# diagonals of spiral matrix + +# function returns sum of diagonals +def spiralDiaSum(n): + + if n == 1: + return 1 + + # as order should be only odd + # we should pass only odd + # integers + return (4 * n*n - 6 * n + 6 + + spiralDiaSum(n-2)) + +# Driver program +n = 7; +print(spiralDiaSum(n)) + +# This code is contributed by Anant Agarwal.",linear,linear +"# Python program to find all +# permutations of a given row + +# Function to find all +# permuted rows of a given row r +def permutatedRows(mat, m, n, r): + + + # Creating an empty set + s=set() + + # Count frequencies of + # elements in given row r + for j in range(n): + s.add(mat[r][j]) + + # Traverse through all remaining rows + for i in range(m): + + # we do not need to check + # for given row r + if i == r: + continue + + # initialize hash i.e + # count frequencies + # of elements in row i + for j in range(n): + if mat[i][j] not in s: + + # to avoid the case when last + # element does not match + j = j - 2 + break; + if j + 1 != n: + continue + print(i) + + + +# Driver program to run the case +m = 4 +n = 4 +r = 3 +mat = [[3, 1, 4, 2], + [1, 6, 9, 3], + [1, 2, 3, 4], + [4, 3, 2, 1]] + +permutatedRows(mat, m, n, r) + +# This code is contributed +# by Upendra Singh Bartwal.",linear,quadratic +"# Python3 program to find perimeter of area +# covered by 1 in 2D matrix consists of 0's and 1's. + +R = 3 +C = 5 + +# Find the number of covered side for mat[i][j]. +def numofneighbour(mat, i, j): + + count = 0; + + # UP + if (i > 0 and mat[i - 1][j]): + count+= 1; + + # LEFT + if (j > 0 and mat[i][j - 1]): + count+= 1; + + # DOWN + if (i < R-1 and mat[i + 1][j]): + count+= 1 + + # RIGHT + if (j < C-1 and mat[i][j + 1]): + count+= 1; + + return count; + +# Returns sum of perimeter of shapes formed with 1s +def findperimeter(mat): + + perimeter = 0; + + # Traversing the matrix and finding ones to + # calculate their contribution. + for i in range(0, R): + for j in range(0, C): + if (mat[i][j]): + perimeter += (4 - numofneighbour(mat, i, j)); + + return perimeter; + +# Driver Code +mat = [ [0, 1, 0, 0, 0], + [1, 1, 1, 0, 0], + [1, 0, 0, 0, 0] ] + +print(findperimeter(mat), end=""\n""); + +# This code is contributed by Akanksha Rai",constant,quadratic +"# Python program to print cells with same rectangular +# sum diagonally +# R 4 +# C 4 + +# Method prints cell index at which rectangular sum is +# same at prime diagonal and other diagonal +def printCellWithSameRectangularArea(mat, m, n): + # sum[i][j] denotes sum of sub-matrix, mat[0][0] + # to mat[i][j] + # sumr[i][j] denotes sum of sub-matrix, mat[i][j] + # to mat[m - 1][n - 1] + sum = [[0 for i in range(m)]for j in range(n)] + sumr = [[0 for i in range(m)]for j in range(n)] + + # Initialize both sum matrices by mat + totalSum = 0 + for i in range(m): + for j in range(n): + sumr[i][j] = sum[i][j] = mat[i][j]; + totalSum += mat[i][j] + + # updating first and last row separately + for i in range(1,m): + sum[i][0] += sum[i-1][0] + sumr[m-i-1][n-1] += sumr[m-i][n-1] + + # updating first and last column separately + for j in range(1,n): + sum[0][j] += sum[0][j-1]; + sumr[m-1][n-j-1] += sumr[m-1][n-j] + + # updating sum and sumr indices by nearby indices + for i in range(1,m): + for j in range(1,n): + sum[i][j] += sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + sumr[m-i-1][n-j-1] += sumr[m-i][n-j-1] + sumr[m-i-1][n-j] - sumr[m-i][n-j] + + # Uncomment below code to print sum and reverse sum + # matrix + + # print all those indices at which sum of prime diagonal + # rectangles is half of the total sum of matrix + for i in range(m): + for j in range(n): + mainDiagRectangleSum = sum[i][j] + sumr[i][j] - mat[i][j] + if (totalSum == 2 * mainDiagRectangleSum): + print (""("",i,"","",j,"")"") + +# Driver code to test above methods +mat =[[1, 2, 3, 5,], + [4, 1, 0, 2,], + [0, 1, 2, 0], + [7, 1, 1, 0]] +printCellWithSameRectangularArea(mat, 4, 4) + +# Contributed by Afzal",quadratic,quadratic +"# Python 3 program to print matrix in diagonal order +MAX = 100 + +def printMatrixDiagonal(mat, n): + # Initialize indexes of element to be printed next + i = 0 + j = 0 + k = 0 + # Direction is initially from down to up + isUp = True + + # Traverse the matrix till all elements get traversed + while k= 0 and j= 0 and i= n): + mode += 1 + t1 = n - 1 + it -= 1 + lower += 1 + else: + lower = 0 + it += 1 + + for i in range(t1, lower - 1, -1): + if ((t1 + mode) % 2 == 0): + print((mat[i][t1 + lower - i])) + else: + print(mat[t1 + lower - i][i]) + +# This code is contributed by princiraj1992",constant,quadratic +"# Python3 program to find maximum difference +# of sum of elements of two rows + +# Function to find maximum difference of +# sum of elements of two rows such that +# second row appears before first row. +def maxRowDiff(mat, m, n): + + # auxiliary array to store sum of + # all elements of each row + rowSum = [0] * m + + # calculate sum of each row and + # store it in rowSum array + for i in range(0, m): + sum = 0 + for j in range(0, n): + sum += mat[i][j] + rowSum[i] = sum + + # calculating maximum difference of + # two elements such that + # rowSum[i] max_diff): + max_diff = rowSum[i] - min_element + + # if new element is less than previous + # minimum element then update it so + # that we may get maximum difference + # in remaining array + if (rowSum[i] < min_element): + min_element = rowSum[i] + return max_diff + +# Driver program to run the case +m = 5 +n = 4 +mat = [[-1, 2, 3, 4], + [5, 3, -2, 1], + [6, 7, 2, -3], + [2, 9, 1, 4], + [2, 1, -2, 0]] + +print( maxRowDiff(mat, m, n)) + +# This code is contributed by Swetank Modi",linear,quadratic +"# Python 3 program to find a pair with +# given sum such that every element of +# pair is in different rows. +MAX = 100 + +# Function to find pair for given +# sum in matrix mat[][] --> given matrix +# n --> order of matrix +# sum --> given sum for which we +# need to find pair +def pairSum(mat, n, sum): + + # First sort all the rows + # in ascending order + for i in range(n): + mat[i].sort() + + # Select i'th row and find pair for + # element in i'th row in j'th row + # whose summation is equal to given sum + for i in range(n - 1): + for j in range(i + 1, n): + left = 0 + right = n - 1 + while (left < n and right >= 0): + if ((mat[i][left] + mat[j][right]) == sum): + print( ""("", mat[i][left], + "", "", mat[j][right], ""), "", + end = "" "") + left += 1 + right -= 1 + + else: + if ((mat[i][left] + + mat[j][right]) < sum): + left += 1 + else: + right -= 1 + +# Driver Code +if __name__ == ""__main__"": + n = 4 + sum = 11 + mat = [[1, 3, 2, 4], + [5, 8, 7, 6], + [9, 10, 13, 11], + [12, 0, 14, 15]] + pairSum(mat, n, sum) + +# This code is contributed +# by ChitraNayal",constant,cubic +"# Python3 program to get total coverage of all zeros in +# a binary matrix +R = 4 +C = 4 + +# Returns total coverage of all zeros in mat[][] +def getTotalCoverageOfMatrix(mat): + res = 0 + + # looping for all rows of matrix + for i in range(R): + + isOne = False # 1 is not seen yet + + # looping in columns from left to right + # direction to get left ones + for j in range(C): + + # If one is found from left + if (mat[i][j] == 1): + isOne = True + + # If 0 is found and we have found + # a 1 before. + else if (isOne): + res += 1 + + # Repeat the above process for right to + # left direction. + isOne = False + for j in range(C - 1, -1, -1): + if (mat[i][j] == 1): + isOne = True + else if (isOne): + res += 1 + + # Traversing across columns for up and down + # directions. + for j in range(C): + isOne = False # 1 is not seen yet + for i in range(R): + + if (mat[i][j] == 1): + isOne = True + else if (isOne): + res += 1 + + isOne = False + for i in range(R - 1, -1, -1): + if (mat[i][j] == 1): + isOne = True + else if (isOne): + res += 1 + + return res + +# Driver code +mat = [[0, 0, 0, 0],[1, 0, 0, 1],[0, 1, 1, 0],[0, 1, 0, 0]] +print(getTotalCoverageOfMatrix(mat)) + +# This code is contributed by shubhamsingh10",constant,quadratic +"# Python3 program to find number +# of sorted rows +def sortedCount(mat, r, c): + + result = 0 + + # Start from left side of matrix to + # count increasing order rows + for i in range(r): + + # Check if there is any pair ofs element + # that are not in increasing order. + j = 0 + for j in range(c - 1): + if mat[i][j + 1] <= mat[i][j]: + break + + # If the loop didn't break (All elements + # of current row were in increasing order) + if j == c - 2: + result += 1 + + # Start from right side of matrix to + # count increasing order rows ( reference + # to left these are in decreasing order ) + for i in range(0, r): + + # Check if there is any pair ofs element + # that are not in decreasing order. + j = 0 + for j in range(c - 1, 0, -1): + if mat[i][j - 1] <= mat[i][j]: + break + + # Note c > 1 condition is required to + # make sure that a single column row + # is not counted twice (Note that a + # single column row is sorted both + # in increasing and decreasing order) + if c > 1 and j == 1: + result += 1 + + return result + +# Driver code +m, n = 4, 5 + +mat = [[1, 2, 3, 4, 5], + [4, 3, 1, 2, 6], + [8, 7, 6, 5, 4], + [5, 7, 8, 9, 10]] + +print(sortedCount(mat, m, n)) + +# This code is contributed by +# Mohit kumar 29 (IIIT gwalior)",constant,quadratic +"# Python3 program to Find maximum +# XOR value in matrix either row / column wise + +# maximum number of row and column +MAX = 1000 + +# Function return the maximum +# xor value that is either row +# or column wise +def maxXOR(mat, N): + + # For row xor and column xor + max_xor = 0 + + # Traverse matrix + for i in range(N): + + r_xor = 0 + c_xor = 0 + for j in range(N): + + # xor row element + r_xor = r_xor ^ mat[i][j] + + # for each column : j is act as row & i + # act as column xor column element + c_xor = c_xor ^ mat[j][i] + + + # update maximum between r_xor , c_xor + if (max_xor < max(r_xor, c_xor)): + max_xor = max(r_xor, c_xor) + + # return maximum xor value + return max_xor + +# Driver Code +N = 3 + +mat= [[1 , 5, 4], + [3 , 7, 2 ], + [5 , 9, 10]] + +print(""maximum XOR value : "", + maxXOR(mat, N)) + +# This code is contributed by Anant Agarwal.",constant,quadratic +"# Python3 program to find how many mirror can transfer +# light from bottom to right + +# method returns number of mirror which can transfer +# light from bottom to right +def maximumMirrorInMatrix(mat, N): + + # To store first obstacles horizontally (from right) + # and vertically (from bottom) + horizontal = [-1 for i in range(N)] + vertical = [-1 for i in range(N)]; + + # looping matrix to mark column for obstacles + for i in range(N): + for j in range(N - 1, -1, -1): + + if (mat[i][j] == 'B'): + continue; + + # mark rightmost column with obstacle + horizontal[i] = j; + break; + + + # looping matrix to mark rows for obstacles + for j in range(N): + + for i in range(N - 1, -1, -1): + + if (mat[i][j] == 'B'): + continue; + + # mark leftmost row with obstacle + vertical[j] = i; + break; + + res = 0; # Initialize result + + # if there is not obstacle on right or below, + # then mirror can be placed to transfer light + for i in range(N): + for j in range(N): + + ''' if i > vertical[j] then light can from bottom + if j > horizontal[i] then light can go to right ''' + if (i > vertical[j] and j > horizontal[i]): + + ''' uncomment this code to print actual mirror + position also''' + res+=1; + + return res; + + +# Driver code to test above method +N = 5; + +# B - Blank O - Obstacle +mat = [""BBOBB"", + ""BBBBO"", + ""BBBBB"", + ""BOOBO"", + ""BBBOB"" + ]; + +print(maximumMirrorInMatrix(mat, N)); + +# This code is contributed by rutvik_56.",linear,quadratic +"# Python3 program to check whether given +# matrix is a Toeplitz matrix or not +N = 5 +M = 4 + +# Function to check if all elements present in +# descending diagonal starting from position +# (i, j) in the matrix are all same or not + + +def checkDiagonal(mat, i, j): + res = mat[i][j] + i += 1 + j += 1 + + while (i < N and j < M): + + # mismatch found + if (mat[i][j] != res): + return False + + i += 1 + j += 1 + + # we only reach here when all elements + # in given diagonal are same + return True + +# Function to check whether given +# matrix is a Toeplitz matrix or not + + +def isToeplitz(mat): + + # do for each element in first row + for j in range(M): + + # check descending diagonal starting from + # position (0, j) in the matrix + if not(checkDiagonal(mat, 0, j)): + return False + + # do for each element in first column + for i in range(1, N): + + # check descending diagonal starting + # from position (i, 0) in the matrix + if not(checkDiagonal(mat, i, 0)): + return False + + return True + + +# Driver Code +if __name__ == ""__main__"": + + mat = [[6, 7, 8, 9], + [4, 6, 7, 8], + [1, 4, 6, 7], + [0, 1, 4, 6], + [2, 0, 1, 4]] + + # Function call + if(isToeplitz(mat)): + print(""Matrix is a Toeplitz"") + else: + print(""Matrix is not a Toeplitz"") + +# This code is contributed by Jasmine K Grewal",constant,quadratic +"# Python3 program to check whether given matrix +# is a Toeplitz matrix or not + +def isToeplitz(matrix): + + # row = number of rows + # col = number of columns + row = len(matrix) + col = len(matrix[0]) + + # dictionary to store key,value pairs + map = {} + for i in range(row): + for j in range(col): + key = i-j + + # if key value exists in the map, + if (key in map): + + # we check whether the current value stored + # in this key matches to element at current + # index or not. If not, return false + if (map[key] != matrix[i][j]): + return False + + # else we put key,value pair in map + else: + map[key] = matrix[i][j] + return True + +# Driver Code +if __name__ == ""__main__"": + matrix = [[12, 23, -32], [-20, 12, 23], [56, -20, 12], [38, 56, -20]] + + # Function call + if (isToeplitz(matrix)): + print(""Yes"") + else: + print(""No"")",linear,quadratic +"# Python program to count number +# of 0s in the given row-wise +# and column-wise sorted +# binary matrix. + +# Function to count number +# of 0s in the given +# row-wise and column-wise +# sorted binary matrix. +def countZeroes(mat): + + # start from bottom-left + # corner of the matrix + N = 5; + row = N - 1; + col = 0; + + # stores number of + # zeroes in the matrix + count = 0; + + while (col < N): + + # move up until + # you find a 0 + while (mat[row][col]): + + # if zero is not found + # in current column, we + # are done + if (row < 0): + return count; + row = row - 1; + + # add 0s present in + # current column to result + count = count + (row + 1); + + # move right to + # next column + col = col + 1; + + return count; + +# Driver Code +mat = [[0, 0, 0, 0, 1], + [0, 0, 0, 1, 1], + [0, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1]]; + +print( countZeroes(mat)); + +# This code is contributed +# by chandan_jnu",constant,linear +"# Python3 Program to return previous element +# in an expanding matrix. + +# Returns left of str in an +# expanding matrix of a, b, c, and d. +def findLeft(str): + n = len(str) - 1; + + # Start from rightmost position + while (n > 0): + + # If the current character is ‘b’ or ‘d’, + # change to ‘a’ or ‘c’ respectively and + # break the loop + if (str[n] == 'd'): + str = str[0:n] + 'c' + str[n + 1:]; + break; + + if (str[n] == 'b'): + str = str[0:n] + 'a' + str[n + 1:]; + break; + + # If the current character is ‘a’ or ‘c’, + # change it to ‘b’ or ‘d’ respectively + if (str[n] == 'a'): + str = str[0:n] + 'b' + str[n + 1:]; + else if (str[n] == 'c'): + str = str[0:n] + 'd' + str[n + 1:]; + n-=1; + + return str; + +# Driver Code +if __name__ == '__main__': + str = ""aacbddc""; + print(""Left of"", str, ""is"", findLeft(str)); + +# This code is contributed by PrinciRaj1992",constant,linear +"# Python3 program to print a n x n spiral matrix +# in clockwise direction using O(1) space + +# Prints spiral matrix of size n x n +# containing numbers from 1 to n x n +def printSpiral(n) : + + for i in range(0, n) : + for j in range(0, n) : + + # Finds minimum of four inputs + x = min(min(i, j), min(n - 1 - i, n - 1 - j)) + + # For upper right half + if (i <= j) : + print((n - 2 * x) * (n - 2 * x) - + (i - x)- (j - x), end = ""\t"") + + # For lower left half + else : + print(((n - 2 * x - 2) * + (n - 2 * x - 2) + + (i - x) + (j - x)), end = ""\t"") + print() + +# Driver code +n = 5 + +# print a n x n spiral matrix +# in O(1) space +printSpiral(n) + +# This code is contributed by Nikita Tiwari.",constant,quadratic +"# Python3 code to implement the approach +import sys + +# User defined Pair class +class Pair: + def __init__(self, x, y): + self.first = x + self.second = y + +# Check if it is possible to go to (x, y) from the current +# position. The function returns false if the cell has +# value 0 or already visited +def isSafe(mat, visited, x, y): + return (x >= 0 and x < len(mat) and y >= 0 and y < len(mat[0]) and mat[x][y] == 1 and (not visited[x][y])) + +def findShortestPath(mat, visited, i, j, x, y, min_dist, dist): + if (i == x and j == y): + min_dist = min(dist, min_dist) + return min_dist + + # set (i, j) cell as visited + visited[i][j] = True + + # go to the bottom cell + if (isSafe(mat, visited, i + 1, j)): + min_dist = findShortestPath( + mat, visited, i + 1, j, x, y, min_dist, dist + 1) + + # go to the right cell + if (isSafe(mat, visited, i, j + 1)): + min_dist = findShortestPath( + mat, visited, i, j + 1, x, y, min_dist, dist + 1) + + # go to the top cell + if (isSafe(mat, visited, i - 1, j)): + min_dist = findShortestPath( + mat, visited, i - 1, j, x, y, min_dist, dist + 1) + + # go to the left cell + if (isSafe(mat, visited, i, j - 1)): + min_dist = findShortestPath( + mat, visited, i, j - 1, x, y, min_dist, dist + 1) + + # backtrack: remove (i, j) from the visited matrix + visited[i][j] = False + return min_dist + +# Wrapper over findShortestPath() function +def findShortestPathLength(mat, src, dest): + if (len(mat) == 0 or mat[src.first][src.second] == 0 + or mat[dest.first][dest.second] == 0): + return -1 + + row = len(mat) + col = len(mat[0]) + + # construct an `M × N` matrix to keep track of visited + # cells + visited = [] + for i in range(row): + visited.append([None for _ in range(col)]) + + dist = sys.maxsize + dist = findShortestPath(mat, visited, src.first, + src.second, dest.first, dest.second, dist, 0) + + if (dist != sys.maxsize): + return dist + return -1 + +# Driver code +mat = [[1, 0, 1, 1, 1, 1, 0, 1, 1, 1], + [1, 0, 1, 0, 1, 1, 1, 0, 1, 1], + [1, 1, 1, 0, 1, 1, 0, 1, 0, 1], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 1], + [1, 1, 1, 0, 1, 1, 1, 0, 1, 0], + [1, 0, 1, 1, 1, 1, 0, 1, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 1, 1, 1, 1, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 0, 1, 0, 0, 1] + ] + +src = Pair(0, 0) +dest = Pair(3, 4) +dist = findShortestPathLength(mat, src, dest) +if (dist != -1): + print(""Shortest Path is"", dist) + +else: + print(""Shortest Path doesn't exist"") + +# This code is contributed by phasing17",quadratic,np +"# Python program to find the shortest +# path between a given source cell +# to a destination cell. + +from collections import deque +ROW = 9 +COL = 10 + +# To store matrix cell coordinates +class Point: + def __init__(self,x: int, y: int): + self.x = x + self.y = y + +# A data structure for queue used in BFS +class queueNode: + def __init__(self,pt: Point, dist: int): + self.pt = pt # The coordinates of the cell + self.dist = dist # Cell's distance from the source + +# Check whether given cell(row,col) +# is a valid cell or not +def isValid(row: int, col: int): + return (row >= 0) and (row < ROW) and + (col >= 0) and (col < COL) + +# These arrays are used to get row and column +# numbers of 4 neighbours of a given cell +rowNum = [-1, 0, 0, 1] +colNum = [0, -1, 1, 0] + +# Function to find the shortest path between +# a given source cell to a destination cell. +def BFS(mat, src: Point, dest: Point): + + # check source and destination cell + # of the matrix have value 1 + if mat[src.x][src.y]!=1 or mat[dest.x][dest.y]!=1: + return -1 + + visited = [[False for i in range(COL)] + for j in range(ROW)] + + # Mark the source cell as visited + visited[src.x][src.y] = True + + # Create a queue for BFS + q = deque() + + # Distance of source cell is 0 + s = queueNode(src,0) + q.append(s) # Enqueue source cell + + # Do a BFS starting from source cell + while q: + + curr = q.popleft() # Dequeue the front cell + + # If we have reached the destination cell, + # we are done + pt = curr.pt + if pt.x == dest.x and pt.y == dest.y: + return curr.dist + + # Otherwise enqueue its adjacent cells + for i in range(4): + row = pt.x + rowNum[i] + col = pt.y + colNum[i] + + # if adjacent cell is valid, has path + # and not visited yet, enqueue it. + if (isValid(row,col) and + mat[row][col] == 1 and + not visited[row][col]): + visited[row][col] = True + Adjcell = queueNode(Point(row,col), + curr.dist+1) + q.append(Adjcell) + + # Return -1 if destination cannot be reached + return -1 + +# Driver code +def main(): + mat = [[ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], + [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ], + [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 ], + [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ], + [ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 ], + [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ], + [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], + [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], + [ 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 ]] + source = Point(0,0) + dest = Point(3,4) + + dist = BFS(mat,source,dest) + + if dist!=-1: + print(""Shortest Path is"",dist) + else: + print(""Shortest Path doesn't exist"") +main() + +# This code is contributed by stutipathak31jan",quadratic,quadratic +"# Python3 program for finding orientation of the pattern +# using KMP pattern searching algorithm +N = 5 + +# Used in KMP Search for preprocessing the pattern +def computeLPSArray(pat, M, lps): + + # length of the previous longest prefix suffix + lenl = 0 + i = 1 + + lps[0] = 0 # lps[0] is always 0 + + # the loop calculates lps[i] for i = 1 to M-1 + while (i < M): + if (pat[i] == pat[lenl]): + lenl += 1 + lps[i] = lenl + i += 1 + else: # (pat[i] != pat[lenl]) + if (lenl != 0) : + + # This is tricky. Consider the example + # AAACAAAA and i = 7. + lenl = lps[lenl - 1] + + # Also, note that we do not increment i here + + # if (lenl == 0) + else: + lps[i] = 0 + i += 1 + +def KMPSearch(pat, txt): + M = len(pat) + + # create lps[] that will hold the longest + # prefix suffix values for pattern + lps = [0] * M + j = 0 # index for pat[] + + # Preprocess the pattern (calculate lps[] array) + computeLPSArray(pat, M, lps) + + # index for txt[] + i = 0 + while (i < N): + if (pat[j] == txt[i]): + j += 1 + i += 1 + if (j == M): + + # return 1 is pattern is found + return 1 + + # mismatch after j matches + elif (i < N and pat[j] != txt[i]): + + # Do not match lps[0..lps[j-1]] characters, + # they will match anyway + if (j != 0): + j = lps[j - 1] + else: + i = i + 1 + + # to amemory leak + + # return 0 is pattern is not found + return 0 + +# Function to find orientation of pattern in the matrix +# It uses KMP pattern searching algorithm +def findOrientation(mat, pat): + + # allocate memory for string containing cols + col = ['a'] * (N) + + for i in range(N): + + # search in row i + if (KMPSearch(pat, mat[i])): + print(""Horizontal"") + return + + # Construct an array to store i'th column + for j in range(N): + col[j] = mat[j][i] + + # Search in column i + if (KMPSearch(pat, col)): + print(""Vertical"") + +# Driver Code +mat=[['a', 'b', 'c', 'd', 'e'], + ['f', 'g', 'h', 'i', 'j'], + ['k', 'l', 'm', 'n', 'o'], + ['p', 'q', 'r', 's', 't'], + ['u', 'v', 'w', 'x', 'y']] +pat= ""pqrs"" + +findOrientation(mat, pat) + +# This code is contributed by Mohit kumar 29",linear,quadratic +"# A Naive method to find maximum +# value of mat[d][e] - mat[a][b] +# such that d > a and e > b +N = 5 + +# The function returns maximum +# value A(d,e) - A(a,b) over +# all choices of indexes such +# that both d > a and e > b. +def findMaxValue(mat): + + # stores maximum value + maxValue = 0 + + # Consider all possible pairs + # mat[a][b] and mat[d][e] + for a in range(N - 1): + for b in range(N - 1): + for d in range(a + 1, N): + for e in range(b + 1, N): + if maxValue < int (mat[d][e] - + mat[a][b]): + maxValue = int(mat[d][e] - + mat[a][b]); + + return maxValue; + +# Driver Code +mat = [[ 1, 2, -1, -4, -20 ], + [ -8, -3, 4, 2, 1 ], + [ 3, 8, 6, 1, 3 ], + [ -4, -1, 1, 7, -6 ], + [ 0, -4, 10, -5, 1 ]]; + +print(""Maximum Value is "" + + str(findMaxValue(mat))) + +# This code is contributed +# by ChitraNayal",constant,np +"# An efficient method to find maximum value +# of mat[d] - ma[a][b] such that c > a and d > b + +import sys +N = 5 + +# The function returns maximum value +# A(c,d) - A(a,b) over all choices of +# indexes such that both c > a and d > b. +def findMaxValue(mat): + + # stores maximum value + maxValue = -sys.maxsize -1 + + # maxArr[i][j] stores max of elements + # in matrix from (i, j) to (N-1, N-1) + maxArr = [[0 for x in range(N)] + for y in range(N)] + + # last element of maxArr will be + # same's as of the input matrix + maxArr[N - 1][N - 1] = mat[N - 1][N - 1] + + # preprocess last row + maxv = mat[N - 1][N - 1]; # Initialize max + for j in range (N - 2, -1, -1): + + if (mat[N - 1][j] > maxv): + maxv = mat[N - 1][j] + maxArr[N - 1][j] = maxv + + # preprocess last column + maxv = mat[N - 1][N - 1] # Initialize max + for i in range (N - 2, -1, -1): + + if (mat[i][N - 1] > maxv): + maxv = mat[i][N - 1] + maxArr[i][N - 1] = maxv + + # preprocess rest of the matrix + # from bottom + for i in range (N - 2, -1, -1): + + for j in range (N - 2, -1, -1): + + # Update maxValue + if (maxArr[i + 1][j + 1] - + mat[i][j] > maxValue): + maxValue = (maxArr[i + 1][j + 1] - + mat[i][j]) + + # set maxArr (i, j) + maxArr[i][j] = max(mat[i][j], + max(maxArr[i][j + 1], + maxArr[i + 1][j])) + + return maxValue + +# Driver Code +mat = [[ 1, 2, -1, -4, -20 ], + [-8, -3, 4, 2, 1 ], + [ 3, 8, 6, 1, 3 ], + [ -4, -1, 1, 7, -6] , + [0, -4, 10, -5, 1 ]] + +print (""Maximum Value is"", + findMaxValue(mat)) + +# This code is contributed by iAyushRaj",quadratic,quadratic +"# An efficient Python3 program to find maximum sum +# sub-square matrix + +# Size of given matrix +N = 5 + +# A O(n^2) function to the maximum sum sub- +# squares of size k x k in a given square +# matrix of size n x n +def printMaxSumSub(mat, k): + + # k must be smaller than or equal to n + if (k > N): + return; + + # 1: PREPROCESSING + # To store sums of all strips of size k x 1 + stripSum = [[0 for j in range(N)] for i in range(N)]; + + # Go column by column + for j in range(N): + + # Calculate sum of first k x 1 rectangle + # in this column + sum = 0; + for i in range(k): + sum += mat[i][j]; + stripSum[0][j] = sum; + + # Calculate sum of remaining rectangles + for i in range(1,N-k+1): + sum += (mat[i+k-1][j] - mat[i-1][j]); + stripSum[i][j] = sum; + + # max_sum stores maximum sum and its + # position in matrix + max_sum = -1000000000 + i_ind = 0 + j_ind = 0 + + # 2: CALCULATE SUM of Sub-Squares using stripSum[][] + for i in range(N-k+1): + + # Calculate and print sum of first subsquare + # in this row + sum = 0; + for j in range(k): + sum += stripSum[i][j]; + + # Update max_sum and position of result + if (sum > max_sum): + max_sum = sum; + i_ind = i + j_ind = 0 + + + # Calculate sum of remaining squares in + # current row by removing the leftmost + # strip of previous sub-square and adding + # a new strip + for j in range(1,N-k+1): + sum += (stripSum[i][j+k-1] - stripSum[i][j-1]); + + # Update max_sum and position of result + if (sum > max_sum): + max_sum = sum; + i_ind = i + j_ind = j + + # Print the result matrix + for i in range(k): + for j in range(k): + print(mat[i+i_ind][j+j_ind], end = ' ') + print() + +# Driver program to test above function +mat = [[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 8, 6, 7, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5], + ]; +k = 3; +print(""Maximum sum 3 x 3 matrix is""); +printMaxSumSub(mat, k); + +# This code is contributed by rutvik_56.",quadratic,quadratic +"# A Program to prints common element +# in all rows of matrix + +# Specify number of rows and columns +M = 4 +N = 5 + +# prints common element in all +# rows of matrix +def printCommonElements(mat): + + mp = dict() + + # initialize 1st row elements + # with value 1 + for j in range(N): + mp[mat[0][j]] = 1 + + # traverse the matrix + for i in range(1, M): + for j in range(N): + + # If element is present in the + # map and is not duplicated in + # current row. + if (mat[i][j] in mp.keys() and + mp[mat[i][j]] == i): + + # we increment count of the + # element in map by 1 + mp[mat[i][j]] = i + 1 + + # If this is last row + if i == M - 1: + print(mat[i][j], end = "" "") + +# Driver Code +mat = [[1, 2, 1, 4, 8], + [3, 7, 8, 5, 1], + [8, 7, 7, 3, 1], + [8, 1, 2, 7, 9]] + +printCommonElements(mat) + +# This code is contributed +# by mohit kumar 29",linear,quadratic +"# Python3 Code For A Boolean Matrix Question +R = 3 +C = 4 + + +def modifyMatrix(mat): + row = [0] * R + col = [0] * C + + # Initialize all values of row[] as 0 + for i in range(0, R): + row[i] = 0 + + # Initialize all values of col[] as 0 + for i in range(0, C): + col[i] = 0 + + # Store the rows and columns to be marked + # as 1 in row[] and col[] arrays respectively + for i in range(0, R): + + for j in range(0, C): + if (mat[i][j] == 1): + row[i] = 1 + col[j] = 1 + + # Modify the input matrix mat[] using the + # above constructed row[] and col[] arrays + for i in range(0, R): + + for j in range(0, C): + if (row[i] == 1 or col[j] == 1): + mat[i][j] = 1 + +# A utility function to print a 2D matrix + + +def printMatrix(mat): + for i in range(0, R): + + for j in range(0, C): + print(mat[i][j], end="" "") + print() + + +# Driver Code +mat = [[1, 0, 0, 1], + [0, 0, 1, 0], + [0, 0, 0, 0]] + +print(""Input Matrix"") +printMatrix(mat) + +modifyMatrix(mat) + +print(""Matrix after modification"") +printMatrix(mat) + +# This code is contributed by Nikita Tiwari.",linear,quadratic +"# Python3 Code For A Boolean Matrix Question +def modifyMatrix(mat): + + # variables to check if there are any 1 + # in first row and column + row_flag = False + col_flag = False + + # updating the first row and col + # if 1 is encountered + for i in range(0, len(mat)): + + for j in range(0, len(mat)): + if (i == 0 and mat[i][j] == 1): + row_flag = True + + if (j == 0 and mat[i][j] == 1): + col_flag = True + + if (mat[i][j] == 1): + mat[0][j] = 1 + mat[i][0] = 1 + + # Modify the input matrix mat[] using the + # first row and first column of Matrix mat + for i in range(1, len(mat)): + + for j in range(1, len(mat) + 1): + if (mat[0][j] == 1 or mat[i][0] == 1): + mat[i][j] = 1 + + # modify first row if there was any 1 + if (row_flag == True): + for i in range(0, len(mat)): + mat[0][i] = 1 + + # modify first col if there was any 1 + if (col_flag == True): + for i in range(0, len(mat)): + mat[i][0] = 1 + +# A utility function to print a 2D matrix + + +def printMatrix(mat): + + for i in range(0, len(mat)): + for j in range(0, len(mat) + 1): + print(mat[i][j], end="""") + + print() + + +# Driver Code +mat = [[1, 0, 0, 1], + [0, 0, 1, 0], + [0, 0, 0, 0]] + +print(""Input Matrix :"") +printMatrix(mat) + +modifyMatrix(mat) + +print(""Matrix After Modification :"") +printMatrix(mat) + +# This code is contributed by Nikita tiwari.",constant,quadratic +"''' Python program to find k such that all elements in k'th row + are 0 and k'th column are 1''' + +def find(arr): + + # store length of the array + n = len(arr) + + # start from top right-most corner + i = 0 + j = n - 1 + + # initialise result + res = -1 + + # find the index (This loop runs at most 2n times, we + # either increment row number or decrement column number) + while i < n and j >= 0: + + # if the current element is 0, then this row may be a solution + if arr[i][j] == 0: + + # check for all the elements in this row + while j >= 0 and (arr[i][j] == 0 or i == j): + j -= 1 + + # if all values are 0, update result as row number + if j == -1: + res = i + break + + # if found a 1 in current row, the row can't be a + # solution, increment row number + else: i += 1 + + # if the current element is 1 + else: + + #check for all the elements in this column + while i < n and (arr[i][j] == 1 or i == j): + i +=1 + + # if all elements are 1, update result as col number + if i == n: + res = j + break + + # if found a 0 in current column, the column can't be a + # solution, decrement column number + else: j -= 1 + + # if we couldn't find result in above loop, result doesn't exist + if res == -1: + return res + + # check if the above computed res value is valid + for i in range(0, n): + if res != i and arr[i][res] != 1: + return -1 + for j in range(0, j): + if res != j and arr[res][j] != 0: + return -1; + + return res; + +# test find(arr) function +arr = [ [0,0,1,1,0], + [0,0,0,1,0], + [1,1,1,1,0], + [0,0,0,0,0], + [1,1,1,1,1] ] + +print (find(arr))",constant,linear +"# Python3 program to check whether a given tic tac toe +# board is valid or not + +# Returns true if char wins. Char can be either +# 'X' or 'O' +def win_check(arr, char): + # Check all possible winning combinations + matches = [[0, 1, 2], [3, 4, 5], + [6, 7, 8], [0, 3, 6], + [1, 4, 7], [2, 5, 8], + [0, 4, 8], [2, 4, 6]] + + for i in range(8): + if(arr[matches[i][0]] == char and + arr[matches[i][1]] == char and + arr[matches[i][2]] == char): + return True + return False + +def is_valid(arr): + # Count number of 'X' and 'O' in the given board + xcount = arr.count('X') + ocount = arr.count('O') + + # Board can be valid only if either xcount and ocount + # is same or count is one more than oCount + if(xcount == ocount+1 or xcount == ocount): + # Check if O wins + if win_check(arr, 'O'): + # Check if X wins, At a given point only one can win, + # if X also wins then return Invalid + if win_check(arr, 'X'): + return ""Invalid"" + + # O can only win if xcount == ocount in case where whole + # board has values in each position. + if xcount == ocount: + return ""Valid"" + + # If X wins then it should be xc == oc + 1, + # If not return Invalid + if win_check(arr, 'X') and xcount != ocount+1: + return ""Invalid"" + + # if O is not the winner return Valid + if not win_check(arr, 'O'): + return ""Valid"" + + # If nothing above matches return invalid + return ""Invalid"" + + +# Driver Code +arr = ['X', 'X', 'O', + 'O', 'O', 'X', + 'X', 'O', 'X'] +print(""Given board is "" + is_valid(arr))",constant,constant +"# Python 3 program to compute submatrix +# query sum in O(1) time + +M = 4 +N = 5 + +# Function to preprocess input mat[M][N]. +# This function mainly fills aux[M][N] +# such that aux[i][j] stores sum +# of elements from (0,0) to (i,j) +def preProcess(mat, aux): + + # Copy first row of mat[][] to aux[][] + for i in range(0, N, 1): + aux[0][i] = mat[0][i] + + # Do column wise sum + for i in range(1, M, 1): + for j in range(0, N, 1): + aux[i][j] = mat[i][j] + aux[i - 1][j] + + # Do row wise sum + for i in range(0, M, 1): + for j in range(1, N, 1): + aux[i][j] += aux[i][j - 1] + +# A O(1) time function to compute sum of submatrix +# between (tli, tlj) and (rbi, rbj) using aux[][] +# which is built by the preprocess function +def sumQuery(aux, tli, tlj, rbi, rbj): + + # result is now sum of elements + # between (0, 0) and (rbi, rbj) + res = aux[rbi][rbj] + + # Remove elements between (0, 0) + # and (tli-1, rbj) + if (tli > 0): + res = res - aux[tli - 1][rbj] + + # Remove elements between (0, 0) + # and (rbi, tlj-1) + if (tlj > 0): + res = res - aux[rbi][tlj - 1] + + # Add aux[tli-1][tlj-1] as elements + # between (0, 0) and (tli-1, tlj-1) + # are subtracted twice + if (tli > 0 and tlj > 0): + res = res + aux[tli - 1][tlj - 1] + + return res + +# Driver Code +if __name__ == '__main__': + mat = [[1, 2, 3, 4, 6], + [5, 3, 8, 1, 2], + [4, 6, 7, 5, 5], + [2, 4, 8, 9, 4]] +aux = [[0 for i in range(N)] + for j in range(M)] + +preProcess(mat, aux) + +tli = 2 +tlj = 2 +rbi = 3 +rbj = 4 +print(""Query1:"", sumQuery(aux, tli, tlj, rbi, rbj)) + +tli = 0 +tlj = 0 +rbi = 1 +rbj = 1 +print(""Query2:"", sumQuery(aux, tli, tlj, rbi, rbj)) + +tli = 1 +tlj = 2 +rbi = 3 +rbj = 3 +print(""Query3:"", sumQuery(aux, tli, tlj, rbi, rbj)) + +# This code is contributed by +# Shashank_Sharma",quadratic,quadratic +"# Python 3 program to find rank of a matrix +class rankMatrix(object): + def __init__(self, Matrix): + self.R = len(Matrix) + self.C = len(Matrix[0]) + + # Function for exchanging two rows of a matrix + def swap(self, Matrix, row1, row2, col): + for i in range(col): + temp = Matrix[row1][i] + Matrix[row1][i] = Matrix[row2][i] + Matrix[row2][i] = temp + + # Function to Display a matrix + def Display(self, Matrix, row, col): + for i in range(row): + for j in range(col): + print ("" "" + str(Matrix[i][j])) + print ('\n') + + # Find rank of a matrix + def rankOfMatrix(self, Matrix): + rank = self.C + for row in range(0, rank, 1): + + # Before we visit current row + # 'row', we make sure that + # mat[row][0],....mat[row][row-1] + # are 0. + + # Diagonal element is not zero + if Matrix[row][row] != 0: + for col in range(0, self.R, 1): + if col != row: + + # This makes all entries of current + # column as 0 except entry 'mat[row][row]' + multiplier = (Matrix[col][row] / + Matrix[row][row]) + for i in range(rank): + Matrix[col][i] -= (multiplier * + Matrix[row][i]) + + # Diagonal element is already zero. + # Two cases arise: + # 1) If there is a row below it + # with non-zero entry, then swap + # this row with that row and process + # that row + # 2) If all elements in current + # column below mat[r][row] are 0, + # then remove this column by + # swapping it with last column and + # reducing number of columns by 1. + else: + reduce = True + + # Find the non-zero element + # in current column + for i in range(row + 1, self.R, 1): + + # Swap the row with non-zero + # element with this row. + if Matrix[i][row] != 0: + self.swap(Matrix, row, i, rank) + reduce = False + break + + # If we did not find any row with + # non-zero element in current + # column, then all values in + # this column are 0. + if reduce: + + # Reduce number of columns + rank -= 1 + + # copy the last column here + for i in range(0, self.R, 1): + Matrix[i][row] = Matrix[i][rank] + + # process this row again + row -= 1 + + # self.Display(Matrix, self.R,self.C) + return (rank) + +# Driver Code +if __name__ == '__main__': + Matrix = [[10, 20, 10], + [-20, -30, 10], + [30, 50, 0]] + RankMatrix = rankMatrix(Matrix) + print (""Rank of the Matrix is:"", + (RankMatrix.rankOfMatrix(Matrix))) + +# This code is contributed by Vikas Chitturi",constant,quadratic +"# Python3 program to find largest rectangle +# with all 1s in a binary matrix + +# Finds the maximum area under the +# histogram represented +# by histogram. See below article for details. + + +class Solution(): + def maxHist(self, row): + # Create an empty stack. The stack holds + # indexes of hist array / The bars stored + # in stack are always in increasing order + # of their heights. + result = [] + + # Top of stack + top_val = 0 + + # Initialize max area in current + max_area = 0 + # row (or histogram) + + area = 0 # Initialize area with current top + + # Run through all bars of given + # histogram (or row) + i = 0 + while (i < len(row)): + + # If this bar is higher than the + # bar on top stack, push it to stack + if (len(result) == 0) or (row[result[-1]] <= row[i]): + result.append(i) + i += 1 + else: + + # If this bar is lower than top of stack, + # then calculate area of rectangle with + # stack top as the smallest (or minimum + # height) bar. 'i' is 'right index' for + # the top and element before top in stack + # is 'left index' + top_val = row[result.pop()] + area = top_val * i + + if (len(result)): + area = top_val * (i - result[-1] - 1) + max_area = max(area, max_area) + + # Now pop the remaining bars from stack + # and calculate area with every popped + # bar as the smallest bar + while (len(result)): + top_val = row[result.pop()] + area = top_val * i + if (len(result)): + area = top_val * (i - result[-1] - 1) + + max_area = max(area, max_area) + + return max_area + + # Returns area of the largest rectangle + # with all 1s in A + def maxRectangle(self, A): + + # Calculate area for first row and + # initialize it as result + result = self.maxHist(A[0]) + + # iterate over row to find maximum rectangular + # area considering each row as histogram + for i in range(1, len(A)): + + for j in range(len(A[i])): + + # if A[i][j] is 1 then add A[i -1][j] + if (A[i][j]): + A[i][j] += A[i - 1][j] + + # Update result if area with current + # row (as last row) of rectangle) is more + result = max(result, self.maxHist(A[i])) + + return result + + +# Driver Code +if __name__ == '__main__': + A = [[0, 1, 1, 0], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 0, 0]] + ans = Solution() + + print(""Area of maximum rectangle is"", + ans.maxRectangle(A)) + +# This code is contributed +# by Aaryaman Sharma",linear,quadratic +"# Python3 code for Maximum size +# square sub-matrix with all 1s + +def printMaxSubSquare(M): + R = len(M) # no. of rows in M[][] + C = len(M[0]) # no. of columns in M[][] + + S = [] + for i in range(R): + temp = [] + for j in range(C): + if i == 0 or j == 0: + temp += M[i][j], + else: + temp += 0, + S += temp, + # here we have set the first row and first column of S same as input matrix, other entries are set to 0 + + # Update other entries + for i in range(1, R): + for j in range(1, C): + if (M[i][j] == 1): + S[i][j] = min(S[i][j-1], S[i-1][j], + S[i-1][j-1]) + 1 + else: + S[i][j] = 0 + + # Find the maximum entry and + # indices of maximum entry in S[][] + max_of_s = S[0][0] + max_i = 0 + max_j = 0 + for i in range(R): + for j in range(C): + if (max_of_s < S[i][j]): + max_of_s = S[i][j] + max_i = i + max_j = j + + print(""Maximum size sub-matrix is: "") + for i in range(max_i, max_i - max_of_s, -1): + for j in range(max_j, max_j - max_of_s, -1): + print(M[i][j], end="" "") + print("""") + + +# Driver Program +M = [[0, 1, 1, 0, 1], + [1, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [0, 0, 0, 0, 0]] + +printMaxSubSquare(M) + +# This code is contributed by Soumen Ghosh",quadratic,quadratic +"# Python code for Maximum size square +# sub-matrix with all 1s +# (space optimized solution) + +R = 6 +C = 5 + + +def printMaxSubSquare(M): + + global R, C + Max = 0 + + # set all elements of S to 0 first + S = [[0 for col in range(C)]for row in range(2)] + + # Construct the entries + for i in range(R): + for j in range(C): + + # Compute the entrie at the current position + Entrie = M[i][j] + if(Entrie): + if(j): + Entrie = 1 + min(S[1][j - 1], min(S[0][j - 1], S[1][j])) + + # Save the last entrie and add the new one + S[0][j] = S[1][j] + S[1][j] = Entrie + + # Keep track of the max square length + Max = max(Max, Entrie) + + # Print the square + print(""Maximum size sub-matrix is: "") + for i in range(Max): + for j in range(Max): + print(""1"", end="" "") + print() + + +# Driver code +M = [[0, 1, 1, 0, 1], + [1, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [0, 0, 0, 0, 0]] + +printMaxSubSquare(M) + +# This code is contributed by shinjanpatra",linear,quadratic +"# Python3 implementation of the approach + +# A structure to represent a cell index +class Cell: + + def __init__(self, r, c): + self.r = r # r is row, varies from 0 to R-1 + self.c = c # c is column, varies from 0 to C-1 + +# A simple solution to find sums +# for a given array of cell indexes +def printSums(mat, arr, n): + + # Iterate through all cell indexes + for i in range(0, n): + + Sum = 0; r = arr[i].r; c = arr[i].c + + # Compute sum for current cell index + for j in range(0, R): + for k in range(0, C): + if j != r and k != c: + Sum += mat[j][k] + print(Sum) + +# Driver Code +if __name__ == ""__main__"": + + mat = [[1, 1, 2], [3, 4, 6], [5, 3, 2]] + R = C = 3 + arr = [Cell(0, 0), Cell(1, 1), Cell(0, 1)] + n = len(arr) + printSums(mat, arr, n) + +# This code is contributed by Rituraj Jain",constant,cubic +"# Python3 implementation of the approach + +# A structure to represent a cell index +class Cell: + + def __init__(self, r, c): + self.r = r # r is row, varies from 0 to R-1 + self.c = c # c is column, varies from 0 to C-1 + +# A simple solution to find sums +# for a given array of cell indexes +def printSums(mat, arr, n): + + Sum = 0 + row, col = [0] * R, [0] * C + + # Compute sum of all elements, + # sum of every row and sum every column + for i in range(0, R): + for j in range(0, C): + Sum += mat[i][j] + row[i] += mat[i][j] + col[j] += mat[i][j] + + # Compute the desired sum + # for all given cell indexes + for i in range(0, n): + r0, c0 = arr[i].r, arr[i].c + print(Sum - row[r0] - col[c0] + mat[r0][c0]) + +# Driver Code +if __name__ == ""__main__"": + + mat = [[1, 1, 2], [3, 4, 6], [5, 3, 2]] + R = C = 3 + arr = [Cell(0, 0), Cell(1, 1), Cell(0, 1)] + n = len(arr) + printSums(mat, arr, n) + +# This code is contributed by Rituraj Jain",linear,quadratic +"# A Python3 program to count the number +# of rectangular islands where every +# island is separated by a line + +# Size of given matrix is M X N +M = 6 +N = 3 + +# This function takes a matrix of 'X' and 'O' +# and returns the number of rectangular +# islands of 'X' where no two islands are +# row-wise or column-wise adjacent, the islands +# may be diagonally adjacent +def countIslands(mat): + + count = 0; # Initialize result + + # Traverse the input matrix + for i in range (0, M): + + for j in range(0, N): + + # If current cell is 'X', then check + # whether this is top-leftmost of a + # rectangle. If yes, then increment count + if (mat[i][j] == 'X'): + + if ((i == 0 or mat[i - 1][j] == 'O') and + (j == 0 or mat[i][j - 1] == 'O')): + count = count + 1 + + return count + +# Driver Code +mat = [['O', 'O', 'O'], + ['X', 'X', 'O'], + ['X', 'X', 'O'], + ['O', 'O', 'X'], + ['O', 'O', 'X'], + ['X', 'X', 'O']] + +print(""Number of rectangular islands is"", + countIslands(mat)) + +# This code is contributed by iAyushRaj",constant,quadratic +"# Python 3 program to find a common element +# in all rows of a row wise sorted array + +# Specify number of rows +# and columns +M = 4 +N = 5 + +# Returns common element in all rows +# of mat[M][N]. If there is no common +# element, then -1 is returned +def findCommon(mat): + + # An array to store indexes of + # current last column + column = [N - 1] * M + + min_row = 0 # Initialize min_row as first row + + # Keep finding min_row in current last + # column, till either all elements of + # last column become same or we hit first column. + while (column[min_row] >= 0): + + # Find minimum in current last column + for i in range(M): + if (mat[i][column[i]] < + mat[min_row][column[min_row]]): + min_row = i + + # eq_count is count of elements equal + # to minimum in current last column. + eq_count = 0 + + # Traverse current last column elements + # again to update it + for i in range(M): + + # Decrease last column index of a row + # whose value is more than minimum. + if (mat[i][column[i]] > + mat[min_row][column[min_row]]): + if (column[i] == 0): + return -1 + + column[i] -= 1 # Reduce last column + # index by 1 + + else: + eq_count += 1 + + # If equal count becomes M, return the value + if (eq_count == M): + return mat[min_row][column[min_row]] + return -1 + +# Driver Code +if __name__ == ""__main__"": + + mat = [[1, 2, 3, 4, 5], + [2, 4, 5, 8, 10], + [3, 5, 7, 9, 11], + [1, 3, 5, 7, 9]] + + result = findCommon(mat) + if (result == -1): + print(""No common element"") + else: + print(""Common element is"", result) + +# This code is contributed by ita_c",linear,quadratic +"# Python3 program to replace all 'O's with +# 'X's if surrounded by 'X' + +# Size of given matrix is M x N +M = 6 +N = 6 + +# A recursive function to replace previous +# value 'prevV' at '(x, y)' and all surrounding +# values of (x, y) with new value 'newV'. +def floodFillUtil(mat, x, y, prevV, newV): + + # Base Cases + if (x < 0 or x >= M or y < 0 or y >= N): + return + + if (mat[x][y] != prevV): + return + + # Replace the color at (x, y) + mat[x][y] = newV + + # Recur for north, east, south and west + floodFillUtil(mat, x + 1, y, prevV, newV) + floodFillUtil(mat, x - 1, y, prevV, newV) + floodFillUtil(mat, x, y + 1, prevV, newV) + floodFillUtil(mat, x, y - 1, prevV, newV) + +# Returns size of maximum size subsquare +# matrix surrounded by 'X' +def replaceSurrounded(mat): + + # Step 1: Replace all 'O's with '-' + for i in range(M): + for j in range(N): + if (mat[i][j] == 'O'): + mat[i][j] = '-' + + # Call floodFill for all '-' + # lying on edges + # Left Side + for i in range(M): + if (mat[i][0] == '-'): + floodFillUtil(mat, i, 0, '-', 'O') + + # Right side + for i in range(M): + if (mat[i][N - 1] == '-'): + floodFillUtil(mat, i, N - 1, '-', 'O') + + # Top side + for i in range(N): + if (mat[0][i] == '-'): + floodFillUtil(mat, 0, i, '-', 'O') + + # Bottom side + for i in range(N): + if (mat[M - 1][i] == '-'): + floodFillUtil(mat, M - 1, i, '-', 'O') + + # Step 3: Replace all '-' with 'X' + for i in range(M): + for j in range(N): + if (mat[i][j] == '-'): + mat[i][j] = 'X' + +# Driver code +if __name__ == '__main__': + + mat = [ [ 'X', 'O', 'X', 'O', 'X', 'X' ], + [ 'X', 'O', 'X', 'X', 'O', 'X' ], + [ 'X', 'X', 'X', 'O', 'X', 'X' ], + [ 'O', 'X', 'X', 'X', 'X', 'X' ], + [ 'X', 'X', 'X', 'O', 'X', 'O' ], + [ 'O', 'O', 'X', 'O', 'O', 'O' ] ]; + + replaceSurrounded(mat) + + for i in range(M): + print(*mat[i]) + +# This code is contributed by himanshu77",quadratic,quadratic +"# A Python3 program to find the largest +# subsquare surrounded by 'X' in a given +# matrix of 'O' and 'X' +import math as mt + +# Size of given matrix is N X N +N = 6 + +# A utility function to find minimum +# of two numbers + + +def getMin(x, y): + if x < y: + return x + else: + return y + +# Returns size of Maximum size +# subsquare matrix surrounded by 'X' + + +def findSubSquare(mat): + + Max = 0 # Initialize result + + # Initialize the left-top value + # in hor[][] and ver[][] + hor = [[0 for i in range(N)] + for i in range(N)] + ver = [[0 for i in range(N)] + for i in range(N)] + + if mat[0][0] == 'X': + hor[0][0] = 1 + ver[0][0] = 1 + + # Fill values in hor[][] and ver[][] + for i in range(N): + + for j in range(N): + + if (mat[i][j] == 'O'): + ver[i][j], hor[i][j] = 0, 0 + else: + if j == 0: + ver[i][j], hor[i][j] = 1, 1 + else: + (ver[i][j], + hor[i][j]) = (ver[i - 1][j] + 1, + hor[i][j - 1] + 1) + + # Start from the rightmost-bottommost corner + # element and find the largest ssubsquare + # with the help of hor[][] and ver[][] + for i in range(N - 1, 0, -1): + + for j in range(N - 1, 0, -1): + + # Find smaller of values in hor[][] and + # ver[][]. A Square can only be made by + # taking smaller value + small = getMin(hor[i][j], ver[i][j]) + + # At this point, we are sure that there + # is a right vertical line and bottom + # horizontal line of length at least 'small'. + + # We found a bigger square if following + # conditions are met: + # 1)If side of square is greater than Max. + # 2)There is a left vertical line + # of length >= 'small' + # 3)There is a top horizontal line + # of length >= 'small' + while (small > Max): + + if (ver[i][j - small + 1] >= small and + hor[i - small + 1][j] >= small): + + Max = small + + small -= 1 + + return Max + + +# Driver Code +mat = [['X', 'O', 'X', 'X', 'X', 'X'], + ['X', 'O', 'X', 'X', 'O', 'X'], + ['X', 'X', 'X', 'O', 'O', 'X'], + ['O', 'X', 'X', 'X', 'X', 'X'], + ['X', 'X', 'X', 'O', 'X', 'O'], + ['O', 'O', 'X', 'O', 'O', 'O']] + +# Function call +print(findSubSquare(mat)) + +# This code is contributed by +# Mohit kumar 29",quadratic,quadratic +"# Python3 program to find the largest +# subsquare surrounded by 'X' in a given +# matrix of 'O' and 'X' + +# Size of given matrix is N X N +N = 6 + +def maximumSubSquare(arr): + + dp = [[[-1, -1] for i in range(51)] + for j in range(51)] + + # Initialize maxside with 0 + maxside = [[0 for i in range(51)] + for j in range(51)] + + x = 0 + y = 0 + + # Fill the dp matrix horizontally. + # for contiguous 'X' increment the + # value of x, otherwise make it 0 + for i in range(N): + x = 0 + + for j in range(N): + if (arr[i][j] == 'X'): + x += 1 + else: + x = 0 + + dp[i][j][0] = x + + # Fill the dp matrix vertically. + # For contiguous 'X' increment + # the value of y, otherwise + # make it 0 + for i in range(N): + y = 0 + for j in range(N): + if (arr[j][i] == 'X'): + y += 1 + else: + y = 0 + + dp[j][i][1] = y + + # Now check , for every value of (i, j) if sub-square + # is possible, + # traverse back horizontally by value val, and check if + # vertical contiguous + # 'X'enfing at (i , j-val+1) is greater than equal to + # val. + # Similarly, check if traversing back vertically, the + # horizontal contiguous + # 'X'ending at (i-val+1, j) is greater than equal to + # val. + maxval = 0 + val = 0 + + for i in range(N): + for j in range(N): + val = min(dp[i][j][0], + dp[i][j][1]) + + if (dp[i][j - val + 1][1] >= val and + dp[i - val + 1][j][0] >= val): + maxside[i][j] = val + else: + maxside[i][j] = 0 + + # Store the final answer in maxval + maxval = max(maxval, maxside[i][j]) + + # Return the final answe. + return maxval + +# Driver code +mat = [ [ 'X', 'O', 'X', 'X', 'X', 'X' ], + [ 'X', 'O', 'X', 'X', 'O', 'X' ], + [ 'X', 'X', 'X', 'O', 'O', 'X' ], + [ 'O', 'X', 'X', 'X', 'X', 'X' ], + [ 'X', 'X', 'X', 'O', 'X', 'O' ], + [ 'O', 'O', 'X', 'O', 'O', 'O' ] ] + +# Function call +print(maximumSubSquare(mat)) + +# This code is contributed by avanitrachhadiya2155",quadratic,quadratic +"# Python3 program to implement +# flood fill algorithm + +# Dimensions of paint screen +M = 8 +N = 8 + +# A recursive function to replace +# previous color 'prevC' at '(x, y)' +# and all surrounding pixels of (x, y) +# with new color 'newC' and +def floodFillUtil(screen, x, y, prevC, newC): + + # Base cases + if (x < 0 or x >= M or y < 0 or + y >= N or screen[x][y] != prevC or + screen[x][y] == newC): + return + + # Replace the color at (x, y) + screen[x][y] = newC + + # Recur for north, east, south and west + floodFillUtil(screen, x + 1, y, prevC, newC) + floodFillUtil(screen, x - 1, y, prevC, newC) + floodFillUtil(screen, x, y + 1, prevC, newC) + floodFillUtil(screen, x, y - 1, prevC, newC) + +# It mainly finds the previous color on (x, y) and +# calls floodFillUtil() +def floodFill(screen, x, y, newC): + prevC = screen[x][y] + if(prevC==newC): + return + floodFillUtil(screen, x, y, prevC, newC) + +# Driver Code +screen = [[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 0, 0], + [1, 0, 0, 1, 1, 0, 1, 1], + [1, 2, 2, 2, 2, 0, 1, 0], + [1, 1, 1, 2, 2, 0, 1, 0], + [1, 1, 1, 2, 2, 2, 2, 0], + [1, 1, 1, 1, 1, 2, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 1]] + +x = 4 +y = 4 +newC = 3 +floodFill(screen, x, y, newC) + +print (""Updated screen after call to floodFill:"") +for i in range(M): + for j in range(N): + print(screen[i][j], end = ' ') + print() + +# This code is contributed by Ashutosh450 +# Updated by Arun Pandey",quadratic,quadratic +"# Python3 program for above approach + +# Function to check valid coordinate +def validCoord(x, y, n, m): + if x < 0 or y < 0: + return 0 + if x >= n or y >= m: + return 0 + return 1 + +# Function to run bfs +def bfs(n, m, data, X, Y, color): + + # Visiting array + vis = [[0 for i in range(101)] for j in range(101)] + + # Creating queue for bfs + obj = [] + + # Pushing pair of {x, y} + obj.append([X, Y]) + + # Marking {x, y} as visited + vis[X][Y] = 1 + + # Until queue is empty + while len(obj) > 0: + + # Extracting front pair + coord = obj[0] + x = coord[0] + y = coord[1] + preColor = data[x][y] + + data[x][y] = color + + # Popping front pair of queue + obj.pop(0) + + # For Upside Pixel or Cell + if validCoord(x + 1, y, n, m) == 1 and vis[x + 1][y] == 0 and data[x + 1][y] == preColor: + obj.append([x + 1, y]) + vis[x + 1][y] = 1 + + # For Downside Pixel or Cell + if validCoord(x - 1, y, n, m) == 1 and vis[x - 1][y] == 0 and data[x - 1][y] == preColor: + obj.append([x - 1, y]) + vis[x - 1][y] = 1 + + # For Right side Pixel or Cell + if validCoord(x, y + 1, n, m) == 1 and vis[x][y + 1] == 0 and data[x][y + 1] == preColor: + obj.append([x, y + 1]) + vis[x][y + 1] = 1 + + # For Left side Pixel or Cell + if validCoord(x, y - 1, n, m) == 1 and vis[x][y - 1] == 0 and data[x][y - 1] == preColor: + obj.append([x, y - 1]) + vis[x][y - 1] = 1 + + # Printing The Changed Matrix Of Pixels + for i in range(n): + for j in range(m): + print(data[i][j], end = "" "") + print() + print() + +n = 8 +m = 8 + +data = [ + [ 1, 1, 1, 1, 1, 1, 1, 1 ], + [ 1, 1, 1, 1, 1, 1, 0, 0 ], + [ 1, 0, 0, 1, 1, 0, 1, 1 ], + [ 1, 2, 2, 2, 2, 0, 1, 0 ], + [ 1, 1, 1, 2, 2, 0, 1, 0 ], + [ 1, 1, 1, 2, 2, 2, 2, 0 ], + [ 1, 1, 1, 1, 1, 2, 1, 1 ], + [ 1, 1, 1, 1, 1, 2, 2, 1 ], +] + +x, y, color = 4, 4, 3 + +# Function Call +bfs(n, m, data, x, y, color) + +# This code is contributed by decode2207.",quadratic,quadratic +"# A simple Python 3 program to find sum +# of all subsquares of size k x k + +# Size of given matrix +n = 5 + +# A simple function to find sum of all +# sub-squares of size k x k in a given +# square matrix of size n x n +def printSumSimple(mat, k): + + # k must be smaller than or equal to n + if (k > n): + return + + # row number of first cell in current + # sub-square of size k x k + for i in range(n - k + 1): + + # column of first cell in current + # sub-square of size k x k + for j in range(n - k + 1): + + # Calculate and print sum of + # current sub-square + sum = 0 + for p in range(i, k + i): + for q in range(j, k + j): + sum += mat[p][q] + print(sum, end = "" "") + + # Line separator for sub-squares + # starting with next row + print() + +# Driver Code +if __name__ == ""__main__"": + + mat = [[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5]] + k = 3 + printSumSimple(mat, k) + +# This code is contributed by ita_c",constant,quadratic +"# An efficient Python3 program to find sum +# of all subsquares of size k x k + +# A O(n^2) function to find sum of all +# sub-squares of size k x k in a given +# square matrix of size n x n +def printSumTricky(mat, k): + global n + + # k must be smaller than or + # equal to n + if k > n: + return + + # 1: PREPROCESSING + # To store sums of all strips of size k x 1 + stripSum = [[None] * n for i in range(n)] + + # Go column by column + for j in range(n): + + # Calculate sum of first k x 1 + # rectangle in this column + Sum = 0 + for i in range(k): + Sum += mat[i][j] + stripSum[0][j] = Sum + + # Calculate sum of remaining rectangles + for i in range(1, n - k + 1): + Sum += (mat[i + k - 1][j] - + mat[i - 1][j]) + stripSum[i][j] = Sum + + # 2: CALCULATE SUM of Sub-Squares + # using stripSum[][] + for i in range(n - k + 1): + + # Calculate and print sum of first + # subsquare in this row + Sum = 0 + for j in range(k): + Sum += stripSum[i][j] + print(Sum, end = "" "") + + # Calculate sum of remaining squares + # in current row by removing the leftmost + # strip of previous sub-square and adding + # a new strip + for j in range(1, n - k + 1): + Sum += (stripSum[i][j + k - 1] - + stripSum[i][j - 1]) + print(Sum, end = "" "") + + print() + +# Driver Code +n = 5 +mat = [[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5]] +k = 3 +printSumTricky(mat, k) + +# This code is contributed by PranchalK",quadratic,quadratic +"# Python3 Program to find +# transpose of a matrix + +N = 4 + +# This function stores +# transpose of A[][] in B[][] + + +def transpose(A, B): + + for i in range(N): + for j in range(N): + B[i][j] = A[j][i] + + +# Driver code +if __name__ == '__main__': + A = [[1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4]] + + + # To store result + B = [[0 for x in range(N)] for y in range(N)] + + # Function call + transpose(A, B) + + print(""Result matrix is"") + for i in range(N): + for j in range(N): + print(B[i][j], "" "", end='') + print()",quadratic,quadratic +"# Python3 Program to find +# transpose of a matrix + +N = 4 + +# Finds transpose of A[][] in-place + + +def transpose(A): + + for i in range(N): + for j in range(i+1, N): + A[i][j], A[j][i] = A[j][i], A[i][j] + + +# driver code +A = [[1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4]] + +transpose(A) + +print(""Modified matrix is"") +for i in range(N): + for j in range(N): + print(A[i][j], "" "", end='') + print() + +# This code is contributed +# by Anant Agarwal.",constant,quadratic +"# Python3 program for addition +# of two matrices + +N = 4 + +# This function adds A[][] +# and B[][], and stores +# the result in C[][] + + +def add(A, B, C): + + for i in range(N): + for j in range(N): + C[i][j] = A[i][j] + B[i][j] + + +# driver code +A = [[1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4]] + +B = [[1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4]] + +C = A[:][:] # To store result + +add(A, B, C) + +print(""Result matrix is"") +for i in range(N): + for j in range(N): + print(C[i][j], "" "", end='') + print() + +# This code is contributed +# by Anant Agarwal.",quadratic,quadratic +"# A Memoization based program to find maximum collection +# using two traversals of a grid + +R=5 +C=4 +intmin=-10000000 +intmax=10000000 + +# checks whether a given input is valid or not +def isValid(x,y1,y2): + return ((x >= 0 and x < R and y1 >=0 + and y1 < C and y2 >=0 and y2 < C)) + +# Driver function to collect max value +def getMaxUtil(arr,mem,x,y1,y2): + # ---------- BASE CASES ----------- + if isValid(x, y1, y2)==False: + return intmin + + # if both traversals reach their destinations + if x == R-1 and y1 == 0 and y2 == C-1: + if y1==y2: + return arr[x][y1] + else: + return arr[x][y1]+arr[x][y2] + + # If both traversals are at last row + # but not at their destination + if x==R-1: + return intmin + + # If subproblem is already solved + if mem[x][y1][y2] != -1: + return mem[x][y1][y2] + + # Initialize answer for this subproblem + ans=intmin + + # this variable is used to store gain of current cell(s) + temp=0 + if y1==y2: + temp=arr[x][y1] + else: + temp=arr[x][y1]+arr[x][y2] + + # Recur for all possible cases, then store and return the + # one with max value + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)) + + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)) + + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)) + + mem[x][y1][y2] = ans + return ans + +# This is mainly a wrapper over recursive +# function getMaxUtil(). +# This function creates a table for memoization and calls +# getMaxUtil() + +def geMaxCollection(arr): + + # Create a memoization table and + # initialize all entries as -1 + mem=[[[-1 for i in range(C)] for i in range(C)] for i in range(R)] + + # Calculation maximum value using + # memoization based function + # getMaxUtil() + return getMaxUtil(arr, mem, 0, 0, C-1) + +# Driver program to test above functions +if __name__=='__main__': + arr=[[3, 6, 8, 2], + [5, 2, 4, 3], + [1, 1, 20, 10], + [1, 1, 20, 10], + [1, 1, 20, 10], + ] + print('Maximum collection is ', geMaxCollection(arr)) + +#this code is contributed by sahilshelangia",quadratic,cubic +"# A Naive Recursive Python program to +# count paths with exactly 'k' coins + +R = 3 +C = 3 + +# Recursive function to count paths +# with sum k from (0, 0) to (m, n) +def pathCountRec(mat, m, n, k): + + # Base cases + if m < 0 or n < 0 or k < 0: + return 0 + elif m == 0 and n == 0: + return k == mat[m][n] + + # #(m, n) can be reached either + # through (m-1, n) or through + # (m, n-1) + return (pathCountRec(mat, m-1, n, k-mat[m][n]) + + pathCountRec(mat, m, n-1, k-mat[m][n])) + +# A wrapper over pathCountRec() +def pathCount(mat, k): + return pathCountRec(mat, R-1, C-1, k) + +# Driver Program +k = 12 +mat = [[1, 2, 3], + [4, 6, 5], + [3, 2, 1]] + +print(pathCount(mat, k)) + +# This code is contributed by Shrikant13.",quadratic,linear +"# A Dynamic Programming based Python3 program to +# count paths with exactly 'k' coins +R = 3 +C = 3 +MAX_K = 1000 + +def pathCountDPRecDP(mat, m, n, k): + + # Base cases + if m < 0 or n < 0 or k < 0: + return 0 + elif m == 0 and n == 0: + return k == mat[m][n] + + # If this subproblem is already solved + if (dp[m][n][k] != -1): + return dp[m][n][k] + + # #(m, n) can be reached either + # through (m-1, n) or through + # (m, n-1) + dp[m][n][k] = (pathCountDPRecDP(mat, m - 1, n, k - mat[m][n]) + + pathCountDPRecDP(mat, m, n - 1, k - mat[m][n])) + + return dp[m][n][k] + +# A wrapper over pathCountDPRecDP() +def pathCountDP(mat, k): + return pathCountDPRecDP(mat, R - 1, C - 1, k) + +# Driver Code +k = 12 + +# Initialising dp[][][] +dp = [[ [-1 for col in range(MAX_K)] + for col in range(C)] + for row in range(R)] + +mat = [[1, 2, 3], + [4, 6, 5], + [3, 2, 1]] + +print(pathCountDP(mat, k)) + +# This code is contributed by ashutosh450",quadratic,quadratic +"# Python3 program to find the longest path in a matrix +# with given constraints + +n = 3 +# Returns length of the longest path beginning with mat[i][j]. +# This function mainly uses lookup table dp[n][n] + + +def findLongestFromACell(i, j, mat, dp): + # Base case + if (i < 0 or i >= n or j < 0 or j >= n): + return 0 + + # If this subproblem is already solved + if (dp[i][j] != -1): + return dp[i][j] + + # To store the path lengths in all the four directions + x, y, z, w = -1, -1, -1, -1 + + # Since all numbers are unique and in range from 1 to n * n, + # there is atmost one possible direction from any cell + if (j < n-1 and ((mat[i][j] + 1) == mat[i][j + 1])): + x = 1 + findLongestFromACell(i, j + 1, mat, dp) + + if (j > 0 and (mat[i][j] + 1 == mat[i][j-1])): + y = 1 + findLongestFromACell(i, j-1, mat, dp) + + if (i > 0 and (mat[i][j] + 1 == mat[i-1][j])): + z = 1 + findLongestFromACell(i-1, j, mat, dp) + + if (i < n-1 and (mat[i][j] + 1 == mat[i + 1][j])): + w = 1 + findLongestFromACell(i + 1, j, mat, dp) + + # If none of the adjacent fours is one greater we will take 1 + # otherwise we will pick maximum from all the four directions + dp[i][j] = max(x, max(y, max(z, max(w, 1)))) + return dp[i][j] + + +# Returns length of the longest path beginning with any cell +def finLongestOverAll(mat): + result = 1 # Initialize result + + # Create a lookup table and fill all entries in it as -1 + dp = [[-1 for i in range(n)]for i in range(n)] + + # Compute longest path beginning from all cells + for i in range(n): + for j in range(n): + if (dp[i][j] == -1): + findLongestFromACell(i, j, mat, dp) + # Update result if needed + result = max(result, dp[i][j]) + return result + + +# Driver program +mat = [[1, 2, 9], + [5, 3, 8], + [4, 6, 7]] +print(""Length of the longest path is "", finLongestOverAll(mat)) + +# this code is improved by sahilshelangia",quadratic,quadratic +"# Python3 program to find minimum initial +# points to reach destination +import math as mt +R = 3 +C = 3 + + +def minInitialPoints(points): + ''' + dp[i][j] represents the minimum initial + points player should have so that when + starts with cell(i, j) successfully + reaches the destination cell(m-1, n-1) + ''' + dp = [[0 for x in range(C + 1)] + for y in range(R + 1)] + m, n = R, C + + if points[m - 1][n - 1] > 0: + dp[m - 1][n - 1] = 1 + else: + dp[m - 1][n - 1] = abs(points[m - 1][n - 1]) + 1 + ''' + Fill last row and last column as base + to fill entire table + ''' + for i in range(m - 2, -1, -1): + dp[i][n - 1] = max(dp[i + 1][n - 1] - + points[i][n - 1], 1) + for i in range(n - 2, -1, -1): + dp[m - 1][i] = max(dp[m - 1][i + 1] - + points[m - 1][i], 1) + ''' + fill the table in bottom-up fashion + ''' + for i in range(m - 2, -1, -1): + for j in range(n - 2, -1, -1): + min_points_on_exit = min(dp[i + 1][j], + dp[i][j + 1]) + dp[i][j] = max(min_points_on_exit - + points[i][j], 1) + + return dp[0][0] + + +# Driver code +points = [[-2, -3, 3], + [-5, -10, 1], + [10, 30, -5]] + +print(""Minimum Initial Points Required:"", + minInitialPoints(points)) + + +# This code is contributed by +# Mohit kumar 29 (IIIT gwalior)",quadratic,quadratic +"# Python3 program to find maximum sum +# subarray in a given 2D array + +# Implementation of Kadane's algorithm +# for 1D array. The function returns the +# maximum sum and stores starting and +# ending indexes of the maximum sum subarray +# at addresses pointed by start and finish +# pointers respectively. + + +def kadane(arr, start, finish, n): + + # initialize sum, maxSum and + Sum = 0 + maxSum = -999999999999 + i = None + + # Just some initial value to check + # for all negative values case + finish[0] = -1 + + # local variable + local_start = 0 + + for i in range(n): + Sum += arr[i] + if Sum < 0: + Sum = 0 + local_start = i + 1 + elif Sum > maxSum: + maxSum = Sum + start[0] = local_start + finish[0] = i + + # There is at-least one + # non-negative number + if finish[0] != -1: + return maxSum + + # Special Case: When all numbers + # in arr[] are negative + maxSum = arr[0] + start[0] = finish[0] = 0 + + # Find the maximum element in array + for i in range(1, n): + if arr[i] > maxSum: + maxSum = arr[i] + start[0] = finish[0] = i + return maxSum + +# The main function that finds maximum +# sum rectangle in M[][] + + +def findMaxSum(M): + global ROW, COL + + # Variables to store the final output + maxSum, finalLeft = -999999999999, None + finalRight, finalTop, finalBottom = None, None, None + left, right, i = None, None, None + + temp = [None] * ROW + Sum = 0 + start = [0] + finish = [0] + + # Set the left column + for left in range(COL): + + # Initialize all elements of temp as 0 + temp = [0] * ROW + + # Set the right column for the left + # column set by outer loop + for right in range(left, COL): + + # Calculate sum between current left + # and right for every row 'i' + for i in range(ROW): + temp[i] += M[i][right] + + # Find the maximum sum subarray in + # temp[]. The kadane() function also + # sets values of start and finish. + # So 'sum' is sum of rectangle between + # (start, left) and (finish, right) which + # is the maximum sum with boundary columns + # strictly as left and right. + Sum = kadane(temp, start, finish, ROW) + + # Compare sum with maximum sum so far. + # If sum is more, then update maxSum + # and other output values + if Sum > maxSum: + maxSum = Sum + finalLeft = left + finalRight = right + finalTop = start[0] + finalBottom = finish[0] + + # Prfinal values + print(""(Top, Left)"", ""("", finalTop, + finalLeft, "")"") + print(""(Bottom, Right)"", ""("", finalBottom, + finalRight, "")"") + print(""Max sum is:"", maxSum) + + +# Driver Code +ROW = 4 +COL = 5 +M = [[1, 2, -1, -4, -20], + [-8, -3, 4, 2, 1], + [3, 8, 10, 1, 3], + [-4, -1, 1, 7, -6]] + +# Function call +findMaxSum(M) + +# This code is contributed by PranchalK",linear,cubic +"# Program to implement a stack using +# two queue +from _collections import deque + + +class Stack: + + def __init__(self): + + # Two inbuilt queues + self.q1 = deque() + self.q2 = deque() + + def push(self, x): + + # Push x first in empty q2 + self.q2.append(x) + + # Push all the remaining + # elements in q1 to q2. + while (self.q1): + self.q2.append(self.q1.popleft()) + + # swap the names of two queues + self.q1, self.q2 = self.q2, self.q1 + + def pop(self): + + # if no elements are there in q1 + if self.q1: + self.q1.popleft() + + def top(self): + if (self.q1): + return self.q1[0] + return None + + def size(self): + return len(self.q1) + + +# Driver Code +if __name__ == '__main__': + s = Stack() + s.push(1) + s.push(2) + s.push(3) + + print(""current size: "", s.size()) + print(s.top()) + s.pop() + print(s.top()) + s.pop() + print(s.top()) + + print(""current size: "", s.size()) + +# This code is contributed by PranchalK",linear,linear +"# Program to implement a stack using +# two queue +from _collections import deque + + +class Stack: + + def __init__(self): + + # Two inbuilt queues + self.q1 = deque() + self.q2 = deque() + + def push(self, x): + self.q1.append(x) + + def pop(self): + # if no elements are there in q1 + if (not self.q1): + return + # Leave one element in q1 and push others in q2 + while(len(self.q1) != 1): + self.q2.append(self.q1.popleft()) + + # swap the names of two queues + self.q1, self.q2 = self.q2, self.q1 + + def top(self): + # if no elements are there in q1 + if (not self.q1): + return + # Leave one element in q1 and push others in q2 + while(len(self.q1) != 1): + self.q2.append(self.q1.popleft()) + + # Pop the only left element from q1 to q2 + top = self.q1[0] + self.q2.append(self.q1.popleft()) + + # swap the names of two queues + self.q1, self.q2 = self.q2, self.q1 + + return top + + def size(self): + return len(self.q1) + + +# Driver Code +if __name__ == '__main__': + s = Stack() + s.push(1) + s.push(2) + s.push(3) + + print(""current size: "", s.size()) + print(s.top()) + s.pop() + print(s.top()) + s.pop() + print(s.top()) + + print(""current size: "", s.size()) + +# This code is contributed by jainlovely450",linear,linear +"from _collections import deque + +# Stack Class that acts as a queue + + +class Stack: + def __init__(self): + self.q = deque() + + # Push operation + def push(self, data): + # Get previous size of queue + s = len(self.q) + + # Push the current element + self.q.append(data) + + # Pop all the previous elements and put them after + # current element + for i in range(s): + self.q.append(self.q.popleft()) + + # Removes the top element + def pop(self): + if (not self.q): + print(""No elements"") + else: + self.q.popleft() + + # Returns top of stack + def top(self): + if (not self.q): + return + return self.q[0] + + def size(self): + return len(self.q) + + +if __name__ == '__main__': + st = Stack() + st.push(1) + st.push(2) + st.push(3) + print(""current size: "", st.size()) + print(st.top()) + st.pop() + print(st.top()) + st.pop() + print(st.top()) + print(""current size: "", st.size())",linear,linear +"# Python3 program to demonstrate linked list +# based implementation of queue + +# A linked list (LL) node +# to store a queue entry + + +class Node: + + def __init__(self, data): + self.data = data + self.next = None + +# A class to represent a queue + +# The queue, front stores the front node +# of LL and rear stores the last node of LL + + +class Queue: + + def __init__(self): + self.front = self.rear = None + + def isEmpty(self): + return self.front == None + + # Method to add an item to the queue + def EnQueue(self, item): + temp = Node(item) + + if self.rear == None: + self.front = self.rear = temp + return + self.rear.next = temp + self.rear = temp + + # Method to remove an item from queue + def DeQueue(self): + + if self.isEmpty(): + return + temp = self.front + self.front = temp.next + + if(self.front == None): + self.rear = None + + +# Driver Code +if __name__ == '__main__': + q = Queue() + q.EnQueue(10) + q.EnQueue(20) + q.DeQueue() + q.DeQueue() + q.EnQueue(30) + q.EnQueue(40) + q.EnQueue(50) + q.DeQueue() + print(""Queue Front : "" + str(q.front.data)) + print(""Queue Rear : "" + str(q.rear.data))",constant,constant +"# Python implementation of De-queue using circular +# array + +# A structure to represent a Deque +MAX = 100 + + +class Deque: + def __init__(self, size): + self.arr = [0] * MAX + self.front = -1 + self.rear = 0 + self.size = size + + ''' Operations on Deque: + void insertfront(int key); + void insertrear(int key); + void deletefront(); + void deleterear(); + bool isFull(); + bool isEmpty(); + int getFront(); + int getRear(); ''' + + # Checks whether Deque is full or not. + def isFull(self): + return ((self.front == 0 and self.rear == self.size-1) or self.front == self.rear + 1) + + # Checks whether Deque is empty or not. + + def isEmpty(self): + return (self.front == -1) + + # Inserts an element at front + def insertfront(self, key): + + # check whether Deque if full or not + if (self.isFull()): + print(""Overflow"") + return + + # If queue is initially empty + if (self.front == -1): + self.front = 0 + self.rear = 0 + + # front is at first position of queue + elif (self.front == 0): + self.front = self.size - 1 + + else: # decrement front end by '1' + self.front = self.front-1 + + # insert current element into Deque + self.arr[self.front] = key + + # function to inset element at rear end + # of Deque. + + def insertrear(self, key): + if (self.isFull()): + print("" Overflow"") + return + + # If queue is initially empty + if (self.front == -1): + self.front = 0 + self.rear = 0 + + # rear is at last position of queue + elif (self.rear == self.size-1): + self.rear = 0 + + # increment rear end by '1' + else: + self.rear = self.rear+1 + + # insert current element into Deque + self.arr[self.rear] = key + + # Deletes element at front end of Deque + + def deletefront(self): + # check whether Deque is empty or not + if (self.isEmpty()): + print(""Queue Underflow"") + return + + # Deque has only one element + if (self.front == self.rear): + self.front = -1 + self.rear = -1 + + else: + # back to initial position + if (self.front == self.size - 1): + self.front = 0 + + else: # increment front by '1' to remove current + # front value from Deque + self.front = self.front+1 + + # Delete element at rear end of Deque + + def deleterear(self): + if (self.isEmpty()): + print("" Underflow"") + return + + # Deque has only one element + if (self.front == self.rear): + self.front = -1 + self.rear = -1 + + elif (self.rear == 0): + self.rear = self.size-1 + else: + self.rear = self.rear-1 + + # Returns front element of Deque + + def getFront(self): + # check whether Deque is empty or not + if (self.isEmpty()): + print("" Underflow"") + return -1 + + return self.arr[self.front] + + # function return rear element of Deque + + def getRear(self): + # check whether Deque is empty or not + if(self.isEmpty() or self.rear < 0): + print("" Underflow"") + return -1 + + return self.arr[self.rear] + + +# Driver code +if __name__ == ""__main__"": + dq = Deque(5) + + # Function calls + print(""Insert element at rear end : 5 "") + dq.insertrear(5) + + print(""insert element at rear end : 10 "") + dq.insertrear(10) + + print(f""get rear element : {dq.getRear()}"") + + dq.deleterear() + print(f""After delete rear element new rear become : {dq.getRear()}"") + + print(""inserting element at front end"") + dq.insertfront(15) + + print(f""get front element: {dq.getFront()}"") + + dq.deletefront() + + print(f""After delete front element new front become : {dq.getFront()}"") + +# This code is contributed by _saurabh_jaiswal",linear,linear +"# Recursive Python program for level +# order traversal of Binary Tree + +# A node structure + + +class Node: + + # A utility function to create a new node + def __init__(self, key): + self.data = key + self.left = None + self.right = None + + +# Function to print level order traversal of tree +def printLevelOrder(root): + h = height(root) + for i in range(1, h+1): + printCurrentLevel(root, i) + + +# Print nodes at a current level +def printCurrentLevel(root, level): + if root is None: + return + if level == 1: + print(root.data, end="" "") + elif level > 1: + printCurrentLevel(root.left, level-1) + printCurrentLevel(root.right, level-1) + + +"""""" Compute the height of a tree--the number of nodes + along the longest path from the root node down to + the farthest leaf node +"""""" + + +def height(node): + if node is None: + return 0 + else: + # Compute the height of each subtree + lheight = height(node.left) + rheight = height(node.right) + + # Use the larger one + if lheight > rheight: + return lheight+1 + else: + return rheight+1 + + +# Driver program to test above function +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) + +print(""Level order traversal of binary tree is -"") +printLevelOrder(root) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,quadratic +"# Python program to print level +# order traversal using Queue + +# A node structure + + +class Node: + # A utility function to create a new node + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# Iterative Method to print the +# height of a binary tree + + +def printLevelOrder(root): + # Base Case + if root is None: + return + + # Create an empty queue + # for level order traversal + queue = [] + + # Enqueue Root and initialize height + queue.append(root) + + while(len(queue) > 0): + + # Print front of queue and + # remove it from queue + print(queue[0].data, end = "" "") + node = queue.pop(0) + + # Enqueue left child + if node.left is not None: + queue.append(node.left) + + # Enqueue right child + if node.right is not None: + queue.append(node.right) + + +# Driver Program to test above function +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) + +print(""Level Order Traversal of binary tree is -"") +printLevelOrder(root) +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python program to create a Complete Binary Tree from +# its linked list representation + +# Linked List node +class ListNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.next = None + +# Binary Tree Node structure +class BinaryTreeNode: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Class to convert the linked list to Binary Tree +class Conversion: + + # Constructor for storing head of linked list + # and root for the Binary Tree + def __init__(self, data = None): + self.head = None + self.root = None + + def push(self, new_data): + + # Creating a new linked list node and storing data + new_node = ListNode(new_data) + + # Make next of new node as head + new_node.next = self.head + + # Move the head to point to new node + self.head = new_node + + def convertList2Binary(self): + + # Queue to store the parent nodes + q = [] + + # Base Case + if self.head is None: + self.root = None + return + + # 1.) The first node is always the root node, + # and add it to the queue + self.root = BinaryTreeNode(self.head.data) + q.append(self.root) + + # Advance the pointer to the next node + self.head = self.head.next + + # Until the end of linked list is reached, do: + while(self.head): + + # 2.a) Take the parent node from the q and + # and remove it from q + parent = q.pop(0) # Front of queue + + # 2.c) Take next two nodes from the linked list. + # We will add them as children of the current + # parent node in step 2.b. + # Push them into the queue so that they will be + # parent to the future node + leftChild= None + rightChild = None + + leftChild = BinaryTreeNode(self.head.data) + q.append(leftChild) + self.head = self.head.next + if(self.head): + rightChild = BinaryTreeNode(self.head.data) + q.append(rightChild) + self.head = self.head.next + + #2.b) Assign the left and right children of parent + parent.left = leftChild + parent.right = rightChild + + def inorderTraversal(self, root): + if(root): + self.inorderTraversal(root.left) + print (root.data,end="" "") + self.inorderTraversal(root.right) + +# Driver Program to test above function + +# Object of conversion class +conv = Conversion() +conv.push(36) +conv.push(30) +conv.push(25) +conv.push(15) +conv.push(12) +conv.push(10) + +conv.convertList2Binary() + +print (""Inorder Traversal of the constructed Binary Tree is:"") +conv.inorderTraversal(conv.root) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",np,linear +"# Python Program to print zigzag traversal +# of binary tree + +# Binary tree node +class Node: + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = self.right = None + + +# function to print zigzag traversal of +# binary tree +def zizagtraversal(root): + + # Base Case + if root is None: + return + + # Create two stacks to store current + # and next level + currentLevel = [] + nextLevel = [] + + # if ltr is true push nodes from + # left to right otherwise from + # right to left + ltr = True + + # append root to currentlevel stack + currentLevel.append(root) + + # Check if stack is empty + while len(currentLevel) > 0: + # pop from stack + temp = currentLevel.pop(-1) + # print the data + print(temp.data, "" "", end="""") + + if ltr: + # if ltr is true push left + # before right + if temp.left: + nextLevel.append(temp.left) + if temp.right: + nextLevel.append(temp.right) + else: + # else push right before left + if temp.right: + nextLevel.append(temp.right) + if temp.left: + nextLevel.append(temp.left) + + if len(currentLevel) == 0: + # reverse ltr to push node in + # opposite order + ltr = not ltr + # swapping of stacks + currentLevel, nextLevel = nextLevel, currentLevel + + +# Driver program to check above function +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(7) +root.left.right = Node(6) +root.right.left = Node(5) +root.right.right = Node(4) +print(""Zigzag Order traversal of binary tree is"") +zizagtraversal(root) + +# This code is contributed by Shweta Singh",linear,linear +"# Python3 implementation of a O(n) time method for +# Zigzag order traversal +from collections import deque + +# Binary Tree node +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Function to print the zigzag traversal +def zigZagTraversal(root): + q = deque([]) + v = [] + q.append(root) + v.append(root.data) + + # set initial level as 1, because root is + # already been taken care of. + l = 1 + + while len(q) > 0: + n = len(q) + for i in range(n): + # popping mechanism + if (l % 2 == 0): + temp = q[-1] + q.pop() + else: + temp = q[0] + q.popleft() + + # pushing mechanism + if (l % 2 != 0): + if (temp.right): + q.append(temp.right) + v.append(temp.right.data) + if (temp.left): + q.append(temp.left) + v.append(temp.left.data) + elif (l % 2 == 0): + if (temp.left): + q.appendleft(temp.left) + v.append(temp.left.data) + if (temp.right): + q.appendleft(temp.right) + v.append(temp.right.data) + l+=1 # level plus one + return v + +# vector to store the traversal order. +v = [] + +# create tree +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(7) +root.left.right = Node(6) +root.right.left = Node(5) +root.right.right = Node(4) +print(""ZigZag Order traversal of binary tree is"") + +v = zigZagTraversal(root) + +for i in range(len(v)): + print(v[i], end = "" "") + + # This code is contributed by suresh07.",linear,linear +"# Python Program to print zigzag traversal +# of binary tree + +# Binary tree node +class Node: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = self.right = None + + +# function to print zigzag traversal of +# binary tree +def zigzagtraversal(root): + + # Base Case + if root is None: + return + ans = [] # store the traversal in the ans array + queue = [root] # use list as queue + flag = False + while len(queue) != 0: + + n = len(queue) + level = [] + for i in range(n): + node = queue[0] + queue.pop(0) + level.append(node.data) + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + flag = not flag + if flag == False: + level = level[::-1] + for i in range(n): + + ans.append(level[i]) + + return ans + + +# Driver program to check above function +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(7) +root.left.right = Node(6) +root.right.left = Node(5) +root.right.right = Node(4) +print(""Zigzag Order traversal of binary tree is"") + +v = zigzagtraversal(root) +for i in v: + print(i,end = "" "") +#This Code is Contributed By Vivek Maddeshiya",linear,linear +"# Python3 program to demonstrate working of LIFO + +# Pushing element on the top of the stack +def stack_push(stack): + for i in range(5): + stack.append(i) + return stack + +# Popping element from the top of the stack +def stack_pop(stack): + print(""Pop :"") + + for i in range(5): + y = stack[-1] + stack.pop() + print(y) + return stack + +# Displaying element on the top of the stack +def stack_peek(stack): + element = stack[-1] + print(""Element on stack top :"", element) + +# Searching element in the stack +def stack_search(stack, element): + pos = -1 + co = 0 + while(len(stack) > 0): + co+=1 + if(stack[-1] == element): + pos = co + break + stack.pop() + + if (pos == -1): + print( ""Element not found"") + else: + print(""Element is found at position"", pos) + +stack = [] +stack_push(stack) +stack_pop(stack) +stack_push(stack) +stack_peek(stack) +stack_search(stack, 2) +stack_search(stack, 6) + +# This code is contributed by rameshtravel07.",linear,linear +"from queue import Queue + + +def reverse_queue(queue: Queue): + # Base case + if queue.empty(): + return + + # Dequeue current item (from front) + item = queue.queue[0] + queue.get() + + # Reverse remaining queue + reverse_queue(queue) + + # Enqueue current item (to rear) + queue.put(item) + + +def print_queue(queue: Queue): + while not queue.empty(): + print(queue.queue[0], end="" "") + queue.get() + print() + + +# Driver Code +if __name__ == ""__main__"": + q = Queue() + q.put(56) + q.put(27) + q.put(30) + q.put(45) + q.put(85) + q.put(92) + q.put(58) + q.put(80) + q.put(90) + q.put(100) + + reverse_queue(q) + print_queue(q)",linear,linear +"# Python3 program to reverse first k +# elements of a queue. +from queue import Queue + +# Function to reverse the first K +# elements of the Queue + + +def reverseQueueFirstKElements(k, Queue): + if (Queue.empty() == True or + k > Queue.qsize()): + return + if (k <= 0): + return + + Stack = [] + + # put the first K elements + # into a Stack + for i in range(k): + Stack.append(Queue.queue[0]) + Queue.get() + + # Enqueue the contents of stack + # at the back of the queue + while (len(Stack) != 0): + Queue.put(Stack[-1]) + Stack.pop() + + # Remove the remaining elements and + # enqueue them at the end of the Queue + for i in range(Queue.qsize() - k): + Queue.put(Queue.queue[0]) + Queue.get() + +# Utility Function to print the Queue + + +def Print(Queue): + while (not Queue.empty()): + print(Queue.queue[0], end="" "") + Queue.get() + + +# Driver code +if __name__ == '__main__': + Queue = Queue() + Queue.put(10) + Queue.put(20) + Queue.put(30) + Queue.put(40) + Queue.put(50) + Queue.put(60) + Queue.put(70) + Queue.put(80) + Queue.put(90) + Queue.put(100) + + k = 5 + reverseQueueFirstKElements(k, Queue) + Print(Queue) + +# This code is contributed by PranchalK",linear,linear +"# Python3 program for recursive level order +# traversal in spiral form + + +class newNode: + + # Construct to create a newNode + def __init__(self, key): + self.data = key + self.left = None + self.right = None + + +"""""" Function to print spiral traversal of a tree"""""" + + +def printSpiral(root): + + h = height(root) + + """"""ltr Left to Right. If this variable + is set, then the given level is traversed + from left to right. """""" + ltr = False + for i in range(1, h + 1): + + printGivenLevel(root, i, ltr) + + """"""Revert ltr to traverse next level + in opposite order"""""" + ltr = not ltr + + +"""""" Print nodes at a given level """""" + + +def printGivenLevel(root, level, ltr): + + if(root == None): + return + if(level == 1): + print(root.data, end="" "") + elif (level > 1): + + if(ltr): + printGivenLevel(root.left, level - 1, ltr) + printGivenLevel(root.right, level - 1, ltr) + + else: + printGivenLevel(root.right, level - 1, ltr) + printGivenLevel(root.left, level - 1, ltr) + + +"""""" Compute the ""height"" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node."""""" + + +def height(node): + + if (node == None): + return 0 + else: + + """""" compute the height of each subtree """""" + lheight = height(node.left) + rheight = height(node.right) + + """""" use the larger one """""" + if (lheight > rheight): + return(lheight + 1) + else: + return(rheight + 1) + + +# Driver Code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(7) + root.left.right = newNode(6) + root.right.left = newNode(5) + root.right.right = newNode(4) + print(""Spiral Order traversal of binary tree is"") + printSpiral(root) + +# This code is contributed +# by SHUBHAMSINGH10",linear,quadratic +"# Python3 implementation of a O(n) time +# method for spiral order traversal + +# A class to create a new node + + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def printSpiral(root): + if (root == None): + return # None check + + # Create two stacks to store + # alternate levels + s1 = [] # For levels to be printed + # from right to left + s2 = [] # For levels to be printed + # from left to right + + # append first level to first stack 's1' + s1.append(root) + + # Keep printing while any of the + # stacks has some nodes + while not len(s1) == 0 or not len(s2) == 0: + + # Print nodes of current level from s1 + # and append nodes of next level to s2 + while not len(s1) == 0: + temp = s1[-1] + s1.pop() + print(temp.data, end="" "") + + # Note that is right is appended + # before left + if (temp.right): + s2.append(temp.right) + if (temp.left): + s2.append(temp.left) + + # Print nodes of current level from s2 + # and append nodes of next level to s1 + while (not len(s2) == 0): + temp = s2[-1] + s2.pop() + print(temp.data, end="" "") + + # Note that is left is appended + # before right + if (temp.left): + s1.append(temp.left) + if (temp.right): + s1.append(temp.right) + + +# Driver Code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(7) + root.left.right = newNode(6) + root.right.left = newNode(5) + root.right.right = newNode(4) + print(""Spiral Order traversal of"", + ""binary tree is "") + printSpiral(root) + +# This code is contributed by PranchalK",linear,linear +"# Python3 implementation of above approach + +# A class to create a new node +from collections import deque + + +class newNode: + def __init__(self, data): + self.key = data + self.left = None + self.right = None + + +def spiralPrint(root): + # Declare a deque + dq = deque() + + # Insert the root of the tree into the deque + dq.append(root) + + # Create a variable that will switch in each iteration + reverse = True + + # Start iteration + while (len(dq)): + + # Save the size of the deque here itself, as in further steps the size + # of deque will frequently change + n = len(dq) + + # If we are printing left to right + if(not reverse): + + # Iterate from left to right + while (n > 0): + n -= 1 + + # Insert the child from the back of the deque + # Left child first + if (dq[0].left != None): + dq.append(dq[0].left) + + if (dq[0].right != None): + dq.append(dq[0].right) + + # Print the current processed element + print(dq[0].key, end="" "") + dq.popleft() + + # Switch reverse for next traversal + reverse = not reverse + else: + + # If we are printing right to left + # Iterate the deque in reverse order and insert the children + # from the front + while (n > 0): + n -= 1 + # Insert the child in the front of the deque + # Right child first + if (dq[-1].right != None): + dq.appendleft(dq[-1].right) + + if (dq[-1].left != None): + dq.appendleft(dq[-1].left) + + # Print the current processed element + print(dq[-1].key, end="" "") + dq.pop() + + # Switch reverse for next traversal + reverse = not reverse + + +# Driver Code +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(7) + root.left.right = newNode(6) + root.right.left = newNode(5) + root.right.right = newNode(4) + print(""Spiral Order traversal of"", + ""binary tree is :"") + spiralPrint(root) + +# This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear +"# Python3 program for the above approach + +# Method to find the maximum for each +# and every contiguous subarray +# of size K + +def printMax(arr, N, K): + max = 0 + + for i in range(N - K + 1): + max = arr[i] + for j in range(1, K): + if arr[i + j] > max: + max = arr[i + j] + print(str(max) + "" "", end="""") + + +# Driver's code +if __name__ == ""__main__"": + arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + N = len(arr) + K = 3 + + # Function call + printMax(arr, N, K) + +# This code is contributed by Shiv Shankar",constant,quadratic +"# Python3 program to find the maximum for +# each and every contiguous subarray of +# size K + +from collections import deque + +# A Deque (Double ended queue) based +# method for printing maximum element +# of all subarrays of size K + + +def printMax(arr, N, K): + """""" Create a Double Ended Queue, Qi that + will store indexes of array elements. + The queue will store indexes of useful + elements in every window and it will + maintain decreasing order of values from + front to rear in Qi, i.e., arr[Qi.front[]] + to arr[Qi.rear()] are sorted in decreasing + order"""""" + Qi = deque() + + # Process first k (or first window) + # elements of array + for i in range(K): + + # For every element, the previous + # smaller elements are useless + # so remove them from Qi + while Qi and arr[i] >= arr[Qi[-1]]: + Qi.pop() + + # Add new element at rear of queue + Qi.append(i) + + # Process rest of the elements, i.e. + # from arr[k] to arr[n-1] + for i in range(K, N): + + # The element at the front of the + # queue is the largest element of + # previous window, so print it + print(str(arr[Qi[0]]) + "" "", end="""") + + # Remove the elements which are + # out of this window + while Qi and Qi[0] <= i-K: + + # remove from front of deque + Qi.popleft() + + # Remove all elements smaller than + # the currently being added element + # (Remove useless elements) + while Qi and arr[i] >= arr[Qi[-1]]: + Qi.pop() + + # Add current element at the rear of Qi + Qi.append(i) + + # Print the maximum element of last window + print(str(arr[Qi[0]])) + + +# Driver's code +if __name__ == ""__main__"": + arr = [12, 1, 78, 90, 57, 89, 56] + K = 3 + + # Function call + printMax(arr, len(arr), K) + +# This code is contributed by Shiv Shankar",constant,linear +"node = {""data"":0,""maximum"":0} + +# It is a modification in the way of implementation of +# queue using two stack +def insert( s2, val): + + # inserting the element in s2 + other = node + other[""data""] = val + + if (len(s2)==0): + other[""maximum""] = val + else: + front = node + front[""data""] = s2[0][""data""] + front[""maximum""] = s2[0][""maximum""] + # updating maximum in that stack append it + other[""maximum""] = max(val, front[""maximum""]) + s2.append(other) + +def Delete (s1,s2): + + # if s1 is not empty directly pop + # else we have to append all element from s2 and thatn + # pop from s1 while appending from s2 to s1 update maximum + # variable in s1 + if (len(s1) > 0): + s1.pop() + else: + while (len(s2) > 0): + val = node + val = s2[0] + insert(s1, val[""data""]) + s2.pop() + s1.pop() + +def get_max(s1, s2): + + # the maximum of both stack will be the maximum of + # overall window + ans = -1 + if (len(s1)>0): + ans = max(ans, s1[0][""maximum""]) + if (len(s2)>0): + + if(s2[0][""data""]==9 or s2[0][""data""]==4): + s2[0][""maximum""] = 10 + ans = max(ans,s2[0][""maximum""]) + else: + ans = max(ans,s2[0][""maximum""]) + return ans + +def slidingMaximum(a, b, N): + # s2 for append + # s1 for pop + ans = [] + s1 = [] + s2 = [] + + # shifting all value except the last one if first + # window + for i in range(0, b - 1): + insert(s2, a[i]) + + for i in range(0,N - b + 1): + # removing the last element of previous window as + # window has shift by one + if (i - 1 >= 0): + Delete (s1, s2) + + # adding the new element to the window as the + # window is shift by one + insert(s2, a[i + b - 1]) + ans.append(get_max(s1, s2)) + return ans + +# Driver's code +arr = [ 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 ] +N = len(arr) +K = 4 + +# Function call +ans = slidingMaximum(arr, K, N) +print(ans) + +# This code is contributed by akashish__",constant,linear +"# Python program to find circular tour for a truck +# In this approach we will start the tour from the first petrol pump +# then while moving to the next pumps in the loop we will store the cumulative +# information that whether we have a deficit of petrol at the current pump or not +# If there is a deficit then we will add it to the deficit value calculated +# till the previous petrol pump and then update the starting point to the next pump +# and reset the petrol available in the truck as 0 + +# This function return starting point if there is a possible +# solution otherwise returns -1 +def printTour(arr,n): + + # Consider first petrol pump as starting point + start = 0 + # These two variable will keep tracking if there is + # surplus(s) or deficit(d) of petrol in the truck + s = 0 # petrol available the truck till now + d = 0 # deficit of petrol till visiting this petrol pump + + # Start from the first petrol pump and complete one loop + # of visiting all the petrol pumps and keep updating s and d at each pump + for i in range(n): + s += arr[i][0] - arr[i][1] + if s < 0: # the truck has a deficit of petrol + start = i+1 # change the starting point + d += s # storing the deficit of petrol till current petrol pump + s = 0 # starting again from new station + + # when we reach first petrol pump again and sum of the petrol available at the truck + # and the petrol deficit till now is 0 or more petrol then return the starting point + # else return -1 + return start if (s+d)>=0 else -1 + + +# Driver program to test above function +arr = [[6,4], [3,6], [7,3]] +start = printTour(arr,3) +if start == -1: + print(""No Solution Possible !!!"") +else: + print(""start = {}"".format(start)) + +# This code is contributed by Antara Das(anny)",constant,linear +"# Python program to find circular tour for a truck + +# A petrol pump has petrol and distance to next petrol pump +class petrolPump: + def __init__(self, petrol, distance): + self.petrol = petrol + self.distance = distance + +# The function returns starting point if there is a +# possible solution, otherwise returns -1 +def printTour(arr, n): + start = 0 + + for i in range(n): + + # Identify the first petrol pump from where we + # might get a full circular tour + if arr[i].petrol >= arr[i].distance: + start = i + break + + # To store the excess petrol + curr_petrol = 0 + for i in range(start, n): + curr_petrol += (arr[i].petrol - arr[i].distance) + + # If at any point remaining petrol is less than 0, + # it means that we cannot start our journey from + # current start + if(curr_petrol < 0): + + # We move to the next petrol pump + i += 1 + + # We try to identify the next petrol pump from + # where we might get a full circular tour + while(i < n): + if(arr[i].petrol >= arr[i].distance): + start = i + + # Reset rem_petrol + curr_petrol = 0 + break + i += 1 + + else: + # Move to the next petrolpump if curr_petrol is + # >= 0 + i += 1 + + ''' If remaining petrol is less than 0 while we reach the + first petrol pump, it means no circular tour is + possible ''' + if(curr_petrol < 0): + return -1 + + for i in range(start): + curr_petrol += (arr[i].petrol - arr[i].distance) + + ''' If remaining petrol is less than 0 at any point + before we reach initial start, it means no + circular tour is possible ''' + if(curr_petrol < 0): + return -1 + + ''' If we have successfully reached intial_start, it + means can get a circular tour from final_start, hence + return it ''' + return start + +# Driver code +arr = [petrolPump(6, 4), petrolPump(3, 6), petrolPump(7, 3)] +start = printTour(arr, len(arr)) +if start == -1: + print(""No solution"") +else: + print(""Start = {}"".format(start)) + +# This code is contributed by jainlovely450",constant,linear +"# Python program to find circular tour for a truck + +# A petrol pump has petrol and distance to next petrol pump +class petrolPump: + def __init__(self,a, b): + self.petrol = a; + self.distance = b; + +# The function returns starting point if there is a +# possible solution, otherwise returns -1 +def printTour( p, n): + + # deficit is used to store the value of the capacity as + # soon as the value of capacity becomes negative so as + # not to traverse the array twice in order to get the + # solution + start = 0; + deficit = 0; + capacity = 0; + for i in range(n): + capacity += p[i].petrol - p[i].distance; + if (capacity < 0): + # If this particular step is not done then the + # between steps would be redundant + start = i + 1; + deficit += capacity; + capacity = 0; + + if(capacity + deficit >= 0): + return start; + else: + return -1; + +# Driver code +if __name__ == '__main__': + arr = [petrolPump(6, 4),petrolPump(3, 6),petrolPump(7, 3)] ; + + n = len(arr); + start = printTour(arr, n); + + if (start == -1): + print(""No solution""); + else: + print(""Start = "" , start); + + +# This code is contributed by Rajput-Ji",constant,linear +"# Python3 program to find smallest multiple of +# a given number made of digits 0 and 9 only +from queue import Queue + +# Preprocessing function to generate +# all possible numbers formed by 0 and 9 +def generateNumbersUtil(): + global vec + + # Create an empty queue of strings + q = Queue() + + # enqueue the first number + q.put(""9"") + + # This loops is like BFS of a tree + # with 9 as root, 0 as left child + # and 9 as right child and so on + for count in range(MAX_COUNT, -1, -1): + s1 = q.queue[0] + q.get() + + # storing the front of queue + # in the vector + vec.append(s1) + + s2 = s1 + + # Append ""0"" to s1 and enqueue it + s1 += ""0"" + q.put(s1) + + # Append ""9"" to s2 and enqueue it. Note + # that s2 contains the previous front + s2 += ""9"" + q.put(s2) + +# function to find smallest number made +# up of only digits 9’s and 0’s, which +# is a multiple of n. +def findSmallestMultiple(n): + global vec + + # traverse the vector to find + # the smallest multiple of n + for i in range(len(vec)): + + # int is used for string to + # conversion + if (int(vec[i]) % n == 0): + return vec[i] + +# Driver Code + +# Maximum number of numbers +# made of 0 and 9 +MAX_COUNT = 10000 + +# stack to store all numbers that +# can be formed using digits 0 and +# 9 and are less than 10^5 +vec = [] +generateNumbersUtil() +n = 7 +print(findSmallestMultiple(n)) + +# This code is contributed by PranchalK",np,linear +"# Program to find height of tree by Iteration Method + +# A binary tree node +class Node: + + # Constructor to create new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Iterative method to find height of Binary Tree +def treeHeight(root): + + # Base Case + if root is None: + return 0 + + # Create a empty queue for level order traversal + q = [] + + # Enqueue Root and Initialize Height + q.append(root) + height = 0 + + while(True): + + # nodeCount(queue size) indicates number of nodes + # at current level + nodeCount = len(q) + if nodeCount == 0 : + return height + + height += 1 + + # Dequeue all nodes of current level and Enqueue + # all nodes of next level + while(nodeCount > 0): + node = q[0] + q.pop(0) + if node.left is not None: + q.append(node.left) + if node.right is not None: + q.append(node.right) + + nodeCount -= 1 + + +# Driver program to test above function +# Let us create binary tree shown in above diagram +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) + +print (""Height of tree is"", treeHeight(root)) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python3 program to generate binary numbers from +# 1 to n + +# This function uses queue data structure to print binary numbers + + +def generatePrintBinary(n): + + # Create an empty queue + from queue import Queue + q = Queue() + + # Enqueue the first binary number + q.put(""1"") + + # This loop is like BFS of a tree with 1 as root + # 0 as left child and 1 as right child and so on + while(n > 0): + n -= 1 + # Print the front of queue + s1 = q.get() + print(s1) + + s2 = s1 # Store s1 before changing it + + # Append ""0"" to s1 and enqueue it + q.put(s1+""0"") + + # Append ""1"" to s2 and enqueue it. Note that s2 + # contains the previous front + q.put(s2+""1"") + + +# Driver code +if __name__ == ""__main__"": + n = 10 + + # Function call + generatePrintBinary(n) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python3 program to find minimum time required to make all +# oranges rotten +from collections import deque + +# function to check whether a cell is valid / invalid + + +def isvalid(i, j): + return (i >= 0 and j >= 0 and i < 3 and j < 5) + +# Function to check whether the cell is delimiter +# which is (-1, -1) + + +def isdelim(temp): + return (temp[0] == -1 and temp[1] == -1) + +# Function to check whether there is still a fresh +# orange remaining + + +def checkall(arr): + for i in range(3): + for j in range(5): + if (arr[i][j] == 1): + return True + return False + +# This function finds if it is +# possible to rot all oranges or not. +# If possible, then it returns +# minimum time required to rot all, +# otherwise returns -1 + + +def rotOranges(arr): + + # Create a queue of cells + Q = deque() + temp = [0, 0] + ans = 1 + + # Store all the cells having + # rotten orange in first time frame + for i in range(3): + for j in range(5): + if (arr[i][j] == 2): + temp[0] = i + temp[1] = j + Q.append([i, j]) + + # Separate these rotten oranges + # from the oranges which will rotten + # due the oranges in first time + # frame using delimiter which is (-1, -1) + temp[0] = -1 + temp[1] = -1 + Q.append([-1, -1]) + # print(Q) + + # Process the grid while there are + # rotten oranges in the Queue + while False: + + # This flag is used to determine + # whether even a single fresh + # orange gets rotten due to rotten + # oranges in current time + # frame so we can increase + # the count of the required time. + flag = False + print(len(Q)) + + # Process all the rotten + # oranges in current time frame. + while not isdelim(Q[0]): + temp = Q[0] + print(len(Q)) + + # Check right adjacent cell that if it can be rotten + if (isvalid(temp[0] + 1, temp[1]) and arr[temp[0] + 1][temp[1]] == 1): + + # if this is the first orange to get rotten, increase + # count and set the flag. + if (not flag): + ans, flag = ans + 1, True + + # Make the orange rotten + arr[temp[0] + 1][temp[1]] = 2 + + # append the adjacent orange to Queue + temp[0] += 1 + Q.append(temp) + + temp[0] -= 1 # Move back to current cell + + # Check left adjacent cell that if it can be rotten + if (isvalid(temp[0] - 1, temp[1]) and arr[temp[0] - 1][temp[1]] == 1): + if (not flag): + ans, flag = ans + 1, True + arr[temp[0] - 1][temp[1]] = 2 + temp[0] -= 1 + Q.append(temp) # append this cell to Queue + temp[0] += 1 + + # Check top adjacent cell that if it can be rotten + if (isvalid(temp[0], temp[1] + 1) and arr[temp[0]][temp[1] + 1] == 1): + if (not flag): + ans, flag = ans + 1, True + arr[temp[0]][temp[1] + 1] = 2 + temp[1] += 1 + Q.append(temp) # Push this cell to Queue + temp[1] -= 1 + + # Check bottom adjacent cell if it can be rotten + if (isvalid(temp[0], temp[1] - 1) and arr[temp[0]][temp[1] - 1] == 1): + if (not flag): + ans, flag = ans + 1, True + arr[temp[0]][temp[1] - 1] = 2 + temp[1] -= 1 + Q.append(temp) # append this cell to Queue + Q.popleft() + + # Pop the delimiter + Q.popleft() + + # If oranges were rotten in + # current frame than separate the + # rotten oranges using delimiter + # for the next frame for processing. + if (len(Q) == 0): + temp[0] = -1 + temp[1] = -1 + Q.append(temp) + + # If Queue was empty than no rotten oranges left to process so exit + + # Return -1 if all arranges could not rot, otherwise return ans. + return ans + 1 if(checkall(arr)) else -1 + + +# Driver program +if __name__ == '__main__': + arr = [[2, 1, 0, 2, 1], + [1, 0, 1, 2, 1], + [1, 0, 0, 2, 1]] + ans = rotOranges(arr) + if (ans == -1): + print(""All oranges cannot rotn"") + else: + print(""Time required for all oranges to rot => "", ans) + + # This code is contributed by mohit kumar 29",quadratic,quadratic +"# Python3 program to find Sum of all minimum and maximum +# elements Of Sub-array Size k. +from collections import deque + +# Returns Sum of min and max element of all subarrays +# of size k +def SumOfKsubArray(arr, n , k): + + Sum = 0 # Initialize result + + # The queue will store indexes of useful elements + # in every window + # In deque 'G' we maintain decreasing order of + # values from front to rear + # In deque 'S' we maintain increasing order of + # values from front to rear + S = deque() + G = deque() + + + # Process first window of size K + + for i in range(k): + + # Remove all previous greater elements + # that are useless. + while ( len(S) > 0 and arr[S[-1]] >= arr[i]): + S.pop() # Remove from rear + + # Remove all previous smaller that are elements + # are useless. + while ( len(G) > 0 and arr[G[-1]] <= arr[i]): + G.pop() # Remove from rear + + # Add current element at rear of both deque + G.append(i) + S.append(i) + + # Process rest of the Array elements + for i in range(k, n): + + # Element at the front of the deque 'G' & 'S' + # is the largest and smallest + # element of previous window respectively + Sum += arr[S[0]] + arr[G[0]] + + # Remove all elements which are out of this + # window + while ( len(S) > 0 and S[0] <= i - k): + S.popleft() + while ( len(G) > 0 and G[0] <= i - k): + G.popleft() + + # remove all previous greater element that are + # useless + while ( len(S) > 0 and arr[S[-1]] >= arr[i]): + S.pop() # Remove from rear + + # remove all previous smaller that are elements + # are useless + while ( len(G) > 0 and arr[G[-1]] <= arr[i]): + G.pop() # Remove from rear + + # Add current element at rear of both deque + G.append(i) + S.append(i) + + # Sum of minimum and maximum element of last window + Sum += arr[S[0]] + arr[G[0]] + + return Sum + +# Driver program to test above functions +arr=[2, 5, -1, 7, -3, -1, -2] +n = len(arr) +k = 3 +print(SumOfKsubArray(arr, n, k)) + +# This code is contributed by mohit kumar",constant,linear +"# Python3 program to find distance of +# nearest cell having 1 in a binary matrix. + +# Print distance of nearest cell +# having 1 for each cell. + + +def printDistance(mat): + global N, M + ans = [[None] * M for i in range(N)] + + # Initialize the answer matrix + # with INT_MAX. + for i in range(N): + for j in range(M): + ans[i][j] = 999999999999 + + # For each cell + for i in range(N): + for j in range(M): + + # Traversing the whole matrix + # to find the minimum distance. + for k in range(N): + for l in range(M): + + # If cell contain 1, check + # for minimum distance. + if (mat[k][l] == 1): + ans[i][j] = min(ans[i][j], + abs(i - k) + abs(j - l)) + + # Printing the answer. + for i in range(N): + for j in range(M): + print(ans[i][j], end="" "") + print() + + +# Driver Code +if __name__ == '__main__': + N = 3 + M = 4 + mat = [[0, 0, 0, 1], + [0, 0, 1, 1], + [0, 1, 1, 0]] + + # Function call + printDistance(mat) + +# This code is contributed by PranchalK",quadratic,quadratic +"# Python3 program for the above approach + +import sys + + +class matrix_element: + + def __init__(self, row, col): + self.row = row + self.col = col + + +def printDistance(arr): + Row_Count = len(arr) + Col_Count = len(arr[0]) + + q = [] + + # Adding all ones in queue + for i in range(Row_Count): + for j in range(Col_Count): + if (arr[i][j] == 1): + q.append(matrix_element(i, j)) + + # In order to find min distance we will again + # traverse all elements in Matrix. If its zero then + # it will check against all 1's in Queue. Whatever + # will be dequeued from queued, will be enqueued + # back again. + + Queue_Size = len(q) + for i in range(Row_Count): + + for j in range(Col_Count): + + distance = 0 + min_distance = sys.maxsize + + if (arr[i][j] == 0): + + for k in range(Queue_Size): + + One_Pos = q[0] + q = q[1:] + One_Row = One_Pos.row + One_Col = One_Pos.col + distance = abs(One_Row - i) + abs(One_Col - j) + min_distance = min(min_distance, distance) + if (min_distance == 1): + + arr[i][j] = 1 + q.append(matrix_element(One_Row, One_Col)) + break + + q.append(matrix_element(One_Row, One_Col)) + + arr[i][j] = min_distance + + else: + arr[i][j] = 0 + + # print elements + for i in range(Row_Count): + for j in range(Col_Count): + print(arr[i][j], end="" "") + + print() + + +# Driver code +if __name__ == '__main__': + arr = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]] + + # Function call + printDistance(arr) + +# This code is contributed by shinjanpatra",quadratic,quadratic +"# Python3 program to find distance of nearest +# cell having 1 in a binary matrix. +from collections import deque + +MAX = 500 +N = 3 +M = 4 + +# Making a class of graph with bfs function. +g = [[] for i in range(MAX)] +n, m = 0, 0 + +# Function to create graph with N*M nodes +# considering each cell as a node and each +# boundary as an edge. + + +def createGraph(): + + global g, n, m + + # A number to be assigned to a cell + k = 1 + + for i in range(1, n + 1): + for j in range(1, m + 1): + + # If last row, then add edge on right side. + if (i == n): + + # If not bottom right cell. + if (j != m): + g[k].append(k + 1) + g[k + 1].append(k) + + # If last column, then add edge toward down. + elif (j == m): + g[k].append(k+m) + g[k + m].append(k) + + # Else makes an edge in all four directions. + else: + g[k].append(k + 1) + g[k + 1].append(k) + g[k].append(k+m) + g[k + m].append(k) + + k += 1 + +# BFS function to find minimum distance + + +def bfs(visit, dist, q): + + global g + while (len(q) > 0): + temp = q.popleft() + + for i in g[temp]: + if (visit[i] != 1): + dist[i] = min(dist[i], dist[temp] + 1) + q.append(i) + visit[i] = 1 + + return dist + +# Printing the solution. + + +def prt(dist): + + c = 1 + for i in range(1, n * m + 1): + print(dist[i], end="" "") + if (c % m == 0): + print() + + c += 1 + +# Find minimum distance + + +def findMinDistance(mat): + + global g, n, m + + # Creating a graph with nodes values assigned + # from 1 to N x M and matrix adjacent. + n, m = N, M + createGraph() + + # To store minimum distance + dist = [0] * MAX + + # To mark each node as visited or not in BFS + visit = [0] * MAX + + # Initialising the value of distance and visit. + for i in range(1, M * N + 1): + dist[i] = 10**9 + visit[i] = 0 + + # Inserting nodes whose value in matrix + # is 1 in the queue. + k = 1 + q = deque() + for i in range(N): + for j in range(M): + if (mat[i][j] == 1): + dist[k] = 0 + visit[k] = 1 + q.append(k) + + k += 1 + + # Calling for Bfs with given Queue. + dist = bfs(visit, dist, q) + + # Printing the solution. + prt(dist) + + +# Driver code +if __name__ == '__main__': + + mat = [[0, 0, 0, 1], + [0, 0, 1, 1], + [0, 1, 1, 0]] + + # Function call + findMinDistance(mat) + +# This code is contributed by mohit kumar 29",quadratic,quadratic +""""""" +Python program to do level order traversal +line by line using dual queue"""""" +class GFG: + + """"""Constructor to create a new tree node"""""" + def __init__(self,data): + self.val = data + self.left = None + self.right = None + + """"""Prints level order traversal line by + line using two queues."""""" + def levelOrder(self,node): + q1 = [] # Queue 1 + q2 = [] # Queue 2 + q1.append(node) + + """"""Executing loop till both the + queues become empty"""""" + while(len(q1) > 0 or len(q2) > 0): + + """"""Empty string to concatenate + the string for q1"""""" + concat_str_q1 = '' + while(len(q1) > 0): + + """"""Poped node at the first + pos in queue 1 i.e q1"""""" + poped_node = q1.pop(0) + concat_str_q1 += poped_node.val +' ' + + """"""Pushing left child of current + node in first queue into second queue"""""" + if poped_node.left: + q2.append(poped_node.left) + + """"""Pushing right child of current node + in first queue into second queue"""""" + if poped_node.right: + q2.append(poped_node.right) + print( str(concat_str_q1)) + concat_str_q1 = '' + + """"""Empty string to concatenate the + string for q1"""""" + concat_str_q2 = '' + while (len(q2) > 0): + + """"""Poped node at the first pos + in queue 1 i.e q1"""""" + poped_node = q2.pop(0) + concat_str_q2 += poped_node.val + ' ' + + """"""Pushing left child of current node + in first queue into first queue"""""" + if poped_node.left: + q1.append(poped_node.left) + + """"""Pushing right child of current node + in first queue into first queue"""""" + if poped_node.right: + q1.append(poped_node.right) + print(str(concat_str_q2)) + concat_str_q2 = '' + +"""""" Driver program to test above functions"""""" +node = GFG(""1"") +node.left = GFG(""2"") +node.right = GFG(""3"") +node.left.left = GFG(""4"") +node.left.right = GFG(""5"") +node.right.right = GFG(""6"") +node.levelOrder(node) + +# This code is contributed by Vaibhav Kumar 12",linear,linear +"# Python3 program to find min sum of +# squares of characters after k removals +from queue import PriorityQueue + +MAX_CHAR = 26 + +# Main Function to calculate min sum of +# squares of characters after k removals +def minStringValue(str, k): + l = len(str) # find length of string + + # if K is greater than length of string + # so reduced string will become 0 + if(k >= l): + return 0 + + # Else find Frequency of each + # character and store in an array + frequency = [0] * MAX_CHAR + for i in range(0, l): + frequency[ord(str[i]) - 97] += 1 + + # Push each char frequency negative + # into a priority_queue as the queue + # by default is minheap + q = PriorityQueue() + for i in range(0, MAX_CHAR): + q.put(-frequency[i]) + + # Removal of K characters + while(k > 0): + + # Get top element in priority_queue + # multiply it by -1 as temp is negative + # remove it. Increment by 1 and again + # push into priority_queue + temp = q.get() + temp = temp + 1 + q.put(temp, temp) + k = k - 1 + + # After removal of K characters find + # sum of squares of string Value + result = 0; # initialize result + while not q.empty(): + temp = q.get() + temp = temp * (-1) + result += temp * temp + return result + +# Driver Code +if __name__ == ""__main__"": + str = ""abbccc"" + k = 2 + print(minStringValue(str, k)) + + str = ""aaab"" + k = 2 + print(minStringValue(str, k)) + +# This code is contributed +# by Sairahul Jella",constant,nlogn +"# Python program to find min sum of squares +# of characters after k removals +MAX_CHAR = 26 + +# Main Function to calculate min sum of +# squares of characters after k removals + +def minStringValue(str, k): + + alphabetCount =[] + for i in range(MAX_CHAR): + alphabetCount.append(0) + + # Here the array stored frequency the number of + # occurrences in string m[frequency]=number of alphabets + # with frequency i.e, in our example abbccc m[1]=1(1 + # a's occur),m[2]=1(2 b's occur),m[3]=1(3 c'soccur) + m = [] + for i in range(len(str)): + m.append(0) + + for i in range(len(str)): + alphabetCount[ord(str[i]) - ord('a')] += 1 + + # Store the maximum + maximum = 0 + + for i in range(MAX_CHAR): + m[alphabetCount[i]] += 1 + maximum = max(maximum, alphabetCount[i]) + + while (k > 0): + z = m[maximum] + if z <= k: + # Remove one occurrence of alphabet from each + # with frequency as maximum. + # So we will have k-z more remove operations to + # perform as z is number of characters and we + # perform one removal from each of the alphabet + # with that frequency. + k = k - z + # As we removed one occurrence from each the + # alphabets will no longer have the frequency + # of maximum their frequency will be decreased + # by one so add these number of alphabets to + # group with frequency one less than maximum. + # Remove them from maximum count. + m[maximum] = 0 + # Add those to frequency one less. + m[maximum - 1] += z + # new maximum will be one less. + maximum -= 1 + + else: + # if all the elements of that frequency cannot + # be removed we should partially remove them. + m[maximum] -= k + maximum -= 1 + m[maximum] += k + k = 0 + + ans = 0 + for i in range(len(str)): + # (square of frequency)*(number of + # characters corresponding to that frequency) + ans = ans + (i * i) * m[i] + + return ans + +# Driver Code +str = ""abbccc"" # Input 1 +k = 2 + +print(minStringValue(str, k)) + +str = ""aaab"" # Input 2 +k = 2 +print(minStringValue(str, k)) + + +# This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear +"# Python3 program for a Queue based approach +# to find first non-repeating character +from queue import Queue + +# function to find first non +# repeating character of sa Stream +def firstnonrepeating(Str): + global MAX_CHAR + q = Queue() + charCount = [0] * MAX_CHAR + + # traverse whole Stream + for i in range(len(Str)): + + # push each character in queue + q.put(Str[i]) + + # increment the frequency count + charCount[ord(Str[i]) - + ord('a')] += 1 + + # check for the non repeating + # character + while (not q.empty()): + if (charCount[ord(q.queue[0]) - + ord('a')] > 1): + q.get() + else: + print(q.queue[0], end = "" "") + break + + if (q.empty()): + print(-1, end = "" "") + print() + +# Driver Code +MAX_CHAR = 26 +Str = ""aabc"" +firstnonrepeating(Str) + +# This code is contributed by PranchalK",linear,linear +"# Given two arrays, check if one array is +# stack permutation of other. +from queue import Queue + +# function to check if Input queue +# is permutable to output queue +def checkStackPermutation(ip, op, n): + + # Input queue + Input = Queue() + for i in range(n): + Input.put(ip[i]) + + # output queue + output = Queue() + for i in range(n): + output.put(op[i]) + + # stack to be used for permutation + tempStack = [] + while (not Input.empty()): + ele = Input.queue[0] + Input.get() + if (ele == output.queue[0]): + output.get() + while (len(tempStack) != 0): + if (tempStack[-1] == output.queue[0]): + tempStack.pop() + output.get() + else: + break + else: + tempStack.append(ele) + + # If after processing, both Input + # queue and stack are empty then + # the Input queue is permutable + # otherwise not. + return (Input.empty() and + len(tempStack) == 0) + +# Driver Code +if __name__ == '__main__': + + # Input Queue + Input = [1, 2, 3] + + # Output Queue + output = [2, 1, 3] + + n = 3 + + if (checkStackPermutation(Input, + output, n)): + print(""Yes"") + else: + print(""Not Possible"") + +# This code is contributed by PranchalK",linear,linear +"# Given two arrays, check if one array is +# stack permutation of other. + +# function to check if input array is +# permutable to output array +def checkStackPermutation(ip, op, n): + + # we will be appending elements from input array to stack uptill top of our stack + # matches with first element of output array + s = [] + + # will maintain a variable j to iterate on output array + j = 0 + + # will iterate one by one in input array + for i in range(n): + + # appended an element from input array to stack + s.append(ip[i]) + + # if our stack isn't empty and top matches with output array + # then we will keep popping out from stack uptill top matches with + # output array + while(len(s) > 0 and s[- 1] == op[j]): + s.pop() + + # increasing j so next time we can compare next element in output array + j += 1 + + + # if output array was a correct permutation of input array then + # by now our stack should be empty + if(len(s) == 0): + return True + + return False + +# Driver program to test above function + +# Input Array +input = [4,5,6,7,8] + +# Output Array + +output = [8,7,6,5,4] +n = 5 +if (checkStackPermutation(input, output, n)): + print(""Yes"") +else: + print(""Not Possible"") + +# This code is contributed by shinjanpatra",linear,linear +"// C++ program to implement a stack using +// Priority queue(min heap) +#include +using namespace std; + +typedef pair pi; + +// User defined stack class +class Stack{ + + // cnt is used to keep track of the number of + //elements in the stack and also serves as key + //for the priority queue. + int cnt; + priority_queue > pq; +public: + Stack():cnt(0){} + void push(int n); + void pop(); + int top(); + bool isEmpty(); +}; + +// push function increases cnt by 1 and +// inserts this cnt with the original value. +void Stack::push(int n){ + cnt++; + pq.push(pi(cnt, n)); +} + +// pops element and reduces count. +void Stack::pop(){ + if(pq.empty()){ cout<<""Nothing to pop!!!"";} + cnt--; + pq.pop(); +} + +// returns the top element in the stack using +// cnt as key to determine top(highest priority), +// default comparator for pairs works fine in this case +int Stack::top(){ + pi temp=pq.top(); + return temp.second; +} + +// return true if stack is empty +bool Stack::isEmpty(){ + return pq.empty(); +} + +// Driver code +int main() +{ + Stack* s=new Stack(); + s->push(1); + s->push(2); + s->push(3); + while(!s->isEmpty()){ + cout<top()<pop(); + } +}",linear,logn +"# Program to demonstrate customized data structure +# which supports functions in O(1) +import sys + +stack = [] +Min = sys.maxsize + +# Utility function for adding a new element +def addElement(x): + + global Min, stack + if (len(stack) == 0 or x < Min): + Min = x + pair = [x, Min] + stack.append(pair) + print(x, ""inserted successfully"") + +# Utility function for returning last +# element of stack +def getLastElement(): + + global Min, stack + + if (len(stack) == 0): + print(""UnderFlow Error"") + return -1 + else: + return stack[-1][0] + +# Utility function for removing last +# element successfully; +def removeLastElement(): + + global Min, stack + if (len(stack) == 0): + print(""UnderFlow Error"") + elif (len(stack) > 1): + Min = stack[-2][1] + else: + Min = sys.maxsize + stack.pop() + + print(""removed successfully"") + +# Utility function for returning min +# element till now; +def getMin(): + + global Min, stack + if (len(stack) == 0): + print(""UnderFlow Error"") + return -1 + + return stack[-1][1] + +# Driver code +addElement(5) +addElement(7) +addElement(3) +print(""min element ::"", getMin()) +removeLastElement() +addElement(2) +addElement(9) +print(""Last element ::"", getLastElement()) +addElement(0) +print(""min element ::"", getMin()) +removeLastElement() +addElement(11) +print(""min element ::"", getMin()) + +# This code is contributed by mukesh07",linear,constant +"# Python program to convert infix expression to postfix + +# Class to convert the expression + + +class Conversion: + + # Constructor to initialize the class variables + def __init__(self, capacity): + self.top = -1 + self.capacity = capacity + # This array is used a stack + self.array = [] + # Precedence setting + self.output = [] + self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} + + # check if the stack is empty + def isEmpty(self): + return True if self.top == -1 else False + + # Return the value of the top of the stack + def peek(self): + return self.array[-1] + + # Pop the element from the stack + def pop(self): + if not self.isEmpty(): + self.top -= 1 + return self.array.pop() + else: + return ""$"" + + # Push the element to the stack + def push(self, op): + self.top += 1 + self.array.append(op) + + # A utility function to check is the given character + # is operand + def isOperand(self, ch): + return ch.isalpha() + + # Check if the precedence of operator is strictly + # less than top of stack or not + def notGreater(self, i): + try: + a = self.precedence[i] + b = self.precedence[self.peek()] + return True if a <= b else False + except KeyError: + return False + + # The main function that + # converts given infix expression + # to postfix expression + def infixToPostfix(self, exp): + + # Iterate over the expression for conversion + for i in exp: + # If the character is an operand, + # add it to output + if self.isOperand(i): + self.output.append(i) + + # If the character is an '(', push it to stack + elif i == '(': + self.push(i) + + # If the scanned character is an ')', pop and + # output from the stack until and '(' is found + elif i == ')': + while((not self.isEmpty()) and + self.peek() != '('): + a = self.pop() + self.output.append(a) + if (not self.isEmpty() and self.peek() != '('): + return -1 + else: + self.pop() + + # An operator is encountered + else: + while(not self.isEmpty() and self.notGreater(i)): + self.output.append(self.pop()) + self.push(i) + + # pop all the operator from the stack + while not self.isEmpty(): + self.output.append(self.pop()) + + print """".join(self.output) + + +# Driver's code +if __name__ == '__main__': + exp = ""a+b*(c^d-e)^(f+g*h)-i"" + obj = Conversion(len(exp)) + + # Function call + obj.infixToPostfix(exp) + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python Program to convert prefix to Infix +def prefixToInfix(prefix): + stack = [] + + # read prefix in reverse order + i = len(prefix) - 1 + while i >= 0: + if not isOperator(prefix[i]): + + # symbol is operand + stack.append(prefix[i]) + i -= 1 + else: + + # symbol is operator + str = ""("" + stack.pop() + prefix[i] + stack.pop() + "")"" + stack.append(str) + i -= 1 + + return stack.pop() + +def isOperator(c): + if c == ""*"" or c == ""+"" or c == ""-"" or c == ""/"" or c == ""^"" or c == ""("" or c == "")"": + return True + else: + return False + +# Driver code +if __name__==""__main__"": + str = ""*-A/BC-/AKL"" + print(prefixToInfix(str)) + +# This code is contributed by avishekarora",linear,linear +"# Python3 Program to convert postfix to prefix + +# function to check if +# character is operator or not + + +def isOperator(x): + + if x == ""+"": + return True + + if x == ""-"": + return True + + if x == ""/"": + return True + + if x == ""*"": + return True + + return False + +# Convert postfix to Prefix expression + + +def postToPre(post_exp): + + s = [] + + # length of expression + length = len(post_exp) + + # reading from right to left + for i in range(length): + + # check if symbol is operator + if (isOperator(post_exp[i])): + + # pop two operands from stack + op1 = s[-1] + s.pop() + op2 = s[-1] + s.pop() + + # concat the operands and operator + temp = post_exp[i] + op2 + op1 + + # Push string temp back to stack + s.append(temp) + + # if symbol is an operand + else: + + # push the operand to the stack + s.append(post_exp[i]) + + + ans = """" + for i in s: + ans += i + return ans + + +# Driver Code +if __name__ == ""__main__"": + + post_exp = ""AB+CD-"" + + # Function call + print(""Prefix : "", postToPre(post_exp)) + +# This code is contributed by AnkitRai01",linear,linear +"# Python3 program to check for +# balanced brackets. + +# function to check if +# brackets are balanced + + +def areBracketsBalanced(expr): + stack = [] + + # Traversing the Expression + for char in expr: + if char in [""("", ""{"", ""[""]: + + # Push the element in the stack + stack.append(char) + else: + + # IF current character is not opening + # bracket, then it must be closing. + # So stack cannot be empty at this point. + if not stack: + return False + current_char = stack.pop() + if current_char == '(': + if char != "")"": + return False + if current_char == '{': + if char != ""}"": + return False + if current_char == '[': + if char != ""]"": + return False + + # Check Empty Stack + if stack: + return False + return True + + +# Driver Code +if __name__ == ""__main__"": + expr = ""{()}[]"" + + # Function call + if areBracketsBalanced(expr): + print(""Balanced"") + else: + print(""Not Balanced"") + +# This code is contributed by AnkitRai01 and improved +# by Raju Pitta",linear,linear +"'''NFG function to find the next greater frequency + element for each element in the array''' + + +def NFG(a, n): + + if (n <= 0): + print(""List empty"") + return [] + + # stack data structure to store the position + # of array element + stack = [0]*n + + # freq is a dictionary which maintains the + # frequency of each element + freq = {} + for i in a: + freq[a[i]] = 0 + for i in a: + freq[a[i]] += 1 + + # res to store the value of next greater + # frequency element for each element + res = [0]*n + + # initialize top of stack to -1 + top = -1 + + # push the first position of array in the stack + top += 1 + stack[top] = 0 + + # now iterate for the rest of elements + for i in range(1, n): + + ''' If the frequency of the element which is + pointed by the top of stack is greater + than frequency of the current element + then push the current position i in stack''' + if (freq[a[stack[top]]] > freq[a[i]]): + top += 1 + stack[top] = i + + else: + ''' If the frequency of the element which + is pointed by the top of stack is less + than frequency of the current element, then + pop the stack and continuing popping until + the above condition is true while the stack + is not empty''' + + while (top > -1 and freq[a[stack[top]]] < freq[a[i]]): + res[stack[top]] = a[i] + top -= 1 + + # now push the current element + top += 1 + stack[top] = i + + '''After iterating over the loop, the remaining + position of elements in stack do not have the + next greater element, so print -1 for them''' + while (top > -1): + res[stack[top]] = -1 + top -= 1 + + # return the res list containing next + # greater frequency element + return res + + +# Driver Code +print(NFG([1, 1, 2, 3, 4, 2, 1], 7))",linear,linear +"# Python3 program of Next Greater Frequency Element + +mystack = [] +mymap = {} + +""""""NFG function to find the next greater frequency +element for each element and for placing it in the +resultant array """""" +def NGF(arr, res): + n = len(arr) + + # Initially store the frequencies of all elements + # in a hashmap + for i in range(n): + if arr[i] in mymap: + mymap[arr[i]] += 1 + else: + mymap[arr[i]] = 1 + + # Get the frequency of the last element + curr_freq = mymap[arr[n-1]] + + # push it to the stack + mystack.append([arr[n-1],curr_freq]) + + # place -1 as next greater freq for the last + # element as it does not have next greater. + res[n-1] = -1 + + # iterate through array in reverse order + for i in range(n - 2, -1, -1): + curr_freq = mymap[arr[i]] + + """""" If the frequency of the element which is + pointed by the top of stack is greater + than frequency of the current element + then push the current position i in stack"""""" + while len(mystack) > 0 and curr_freq >= mystack[-1][1]: + mystack.pop() + + # If the stack is empty, place -1. If it is not empty + # then we will have next higher freq element at the top of the stack. + if (len(mystack) == 0): + res[i] = -1 + else: + res[i] = mystack[-1][0] + + # push the element at current position + mystack.append([arr[i],mymap[arr[i]]]) + +arr = [1, 1, 1, 2, 2, 2, 2, 11, 3, 3] + +res = [0]*(len(arr)) +NGF(arr, res) +print(res) + +# This code is contributed by rameshtravel07.",linear,linear +"class GFG: + # Function to find number of next greater elements on + # the right of a given element + @staticmethod + def nextGreaterElements(a, index): + count = 0 + N = len(a) + i = index + 1 + while (i < N): + if (a[i] > a[index]): + count += 1 + i += 1 + return count + + @staticmethod + def main(args): + a = [3, 4, 2, 7, 5, 8, 10, 6] + Q = 2 + queries = [0, 5] + i = 0 + while (i < Q): + # Function call + print(str(GFG.nextGreaterElements(a, queries[i])) + "" "", end="""") + i += 1 + + +if __name__ == ""__main__"": + GFG.main([])",constant,linear +"# Python3 program to find celebrity + +# Max # of persons in the party +N = 8 + +# Person with 2 is celebrity +MATRIX = [[0, 0, 1, 0], + [0, 0, 1, 0], + [0, 0, 0, 0], + [0, 0, 1, 0]] + + +def knows(a, b): + + return MATRIX[a][b] + + +def findCelebrity(n): + + # The graph needs not be constructed + # as the edges can be found by + # using knows function + + # degree array; + indegree = [0 for x in range(n)] + outdegree = [0 for x in range(n)] + + # Query for all edges + for i in range(n): + for j in range(n): + x = knows(i, j) + + # Set the degrees + outdegree[i] += x + indegree[j] += x + + # Find a person with indegree n-1 + # and out degree 0 + for i in range(n): + if (indegree[i] == n - 1 and + outdegree[i] == 0): + return i + + return -1 + + +# Driver code +if __name__ == '__main__': + + n = 4 + id_ = findCelebrity(n) + + if id_ == -1: + print(""No celebrity"") + else: + print(""Celebrity ID"", id_) + +# This code is contributed by UnworthyProgrammer",linear,quadratic +"# Python3 program to find celebrity + +# Max # of persons in the party +N = 8 + +# Person with 2 is celebrity +MATRIX = [[0, 0, 1, 0], + [0, 0, 1, 0], + [0, 0, 0, 0], + [0, 0, 1, 0]] + + +def knows(a, b): + + return MATRIX[a][b] + +# Returns -1 if a potential celebrity +# is not present. If present, +# returns id (value from 0 to n-1). + + +def findPotentialCelebrity(n): + + # Base case + if (n == 0): + return 0 + + # Find the celebrity with n-1 + # persons + id_ = findPotentialCelebrity(n - 1) + + # If there are no celebrities + if (id_ == -1): + return n - 1 + # if the id knows the nth person + # then the id cannot be a celebrity, but nth person + # could be on + elif knows(id_, n - 1): + return n - 1 + # if the id knows the nth person + # then the id cannot be a celebrity, but nth person + # could be one + elif knows(n - 1, id_): + return id_ + # If there is no celebrity + return - 1 + +# Returns -1 if celebrity +# is not present. If present, +# returns id (value from 0 to n-1). +# a wrapper over findCelebrity + + +def Celebrity(n): + + # Find the celebrity + id_ = findPotentialCelebrity(n) + + # Check if the celebrity found + # is really the celebrity + if (id_ == -1): + return id_ + else: + c1 = 0 + c2 = 0 + + # Check the id is really the + # celebrity + for i in range(n): + if (i != id_): + c1 += knows(id_, i) + c2 += knows(i, id_) + + # If the person is known to + # everyone. + if (c1 == 0 and c2 == n - 1): + return id_ + + return -1 + + +# Driver code +if __name__ == '__main__': + + n = 4 + id_ = Celebrity(n) + + if id_ == -1: + print(""No celebrity"") + else: + print(""Celebrity ID"", id_) + +# This code is contributed by UnworthyProgrammer",constant,linear +"# Python3 program to find celebrity +# using stack data structure + +# Max # of persons in the party +N = 8 + +# Person with 2 is celebrity +MATRIX = [[0, 0, 1, 0], + [0, 0, 1, 0], + [0, 0, 0, 0], + [0, 0, 1, 0]] + + +def knows(a, b): + + return MATRIX[a][b] + +# Returns -1 if celebrity +# is not present. If present, +# returns id (value from 0 to n-1). + + +def findCelebrity(n): + + # Handle trivial + # case of size = 2 + s = [] + + # Push everybody to stack + for i in range(n): + s.append(i) + + # Find a potential celebrity + while (len(s) > 1): + + # Pop out the first two elements from stack + A = s.pop() + B = s.pop() + + # if A knows B, we find that B might be the celebrity and vice versa + if (knows(A, B)): + s.append(B) + else: + s.append(A) + + # If there are only two people + # and there is no + # potential candidate + if(len(s) == 0): + return -1 + + # Potential candidate? + C = s.pop() + + # Last candidate was not + # examined, it leads one + # excess comparison (optimize) + if (knows(C, B)): + C = B + + if (knows(C, A)): + C = A + + # Check if C is actually + # a celebrity or not + for i in range(n): + + # If any person doesn't + # know 'a' or 'a' doesn't + # know any person, return -1 + if ((i != C) and + (knows(C, i) or + not(knows(i, C)))): + return -1 + + return C + + +# Driver code +if __name__ == '__main__': + + n = 4 + id_ = findCelebrity(n) + + if id_ == -1: + print(""No celebrity"") + else: + print(""Celebrity ID "", id_) + +# This code is contributed by UnworthyProgrammer",linear,linear +"# Python code for the above approach + + +# Function to find if there is a celebrity in the party +# or not. +def celebrity(M, n): + # r=row number + r = 0 + for i in range(1, n): + # checking if r th person knows i th person + if(M[r][i] == 1): + M[r][r] = 1 + r = i + else: + M[i][i] = 1 + + for i in range(n): + # checking if i th person can be a celebrity or + # not + if(M[i][i] == 0): + flag = 0 + # iterating in the i th column to check + # whether everyone knows i th person or not + for j in range(n): + # checking if M[j][i] is not a diagonal + # element and if j th person knows i th + # person + if(j != i and M[j][i] == 0): + flag = 1 + break + if(flag == 0): + return i + + return -1 + + +M = [[0, 0, 1, 0], + [0, 0, 1, 0], + [0, 0, 0, 0], + [0, 0, 1, 0]] +a = celebrity(M, 4) +if(a is -1): + print(""No Celebrity"") +else: + print(""Celebrity ID"", a) + +# This code is contributed by lokeshmvs21.",constant,linear +"# Python3 code +class Solution: + + # Function to find if there is a celebrity in the party or not. + # return index if celebrity else return -1 + def celebrity(self, M, n): + # code here + i = 0 + j = n-1 + candidate = -1 + while(i < j): + if M[j][i] == 1: + j -= 1 + else: + i += 1 + + candidate = i + for k in range(n): + if candidate != k: + if M[candidate][k] == 1 or M[k][candidate] == 0: + return -1 + + return candidate + + +n = 4 +m = [[0, 0, 1, 0], + [0, 0, 1, 0], + [0, 0, 0, 0], + [0, 0, 1, 0]] +ob = Solution() +a = ob.celebrity(m, n) +if a == -1: + print(""No Celebrity"") +else: + print(""Celebrity ID"", a)",constant,linear +"# Python3 program to evaluate a given +# expression where tokens are +# separated by space. + +# Function to find precedence +# of operators. +def precedence(op): + + if op == '+' or op == '-': + return 1 + if op == '*' or op == '/': + return 2 + return 0 + +# Function to perform arithmetic +# operations. +def applyOp(a, b, op): + + if op == '+': return a + b + if op == '-': return a - b + if op == '*': return a * b + if op == '/': return a // b + +# Function that returns value of +# expression after evaluation. +def evaluate(tokens): + + # stack to store integer values. + values = [] + + # stack to store operators. + ops = [] + i = 0 + + while i < len(tokens): + + # Current token is a whitespace, + # skip it. + if tokens[i] == ' ': + i += 1 + continue + + # Current token is an opening + # brace, push it to 'ops' + elif tokens[i] == '(': + ops.append(tokens[i]) + + # Current token is a number, push + # it to stack for numbers. + elif tokens[i].isdigit(): + val = 0 + + # There may be more than one + # digits in the number. + while (i < len(tokens) and + tokens[i].isdigit()): + + val = (val * 10) + int(tokens[i]) + i += 1 + + values.append(val) + + # right now the i points to + # the character next to the digit, + # since the for loop also increases + # the i, we would skip one + # token position; we need to + # decrease the value of i by 1 to + # correct the offset. + i-=1 + + # Closing brace encountered, + # solve entire brace. + elif tokens[i] == ')': + + while len(ops) != 0 and ops[-1] != '(': + + val2 = values.pop() + val1 = values.pop() + op = ops.pop() + + values.append(applyOp(val1, val2, op)) + + # pop opening brace. + ops.pop() + + # Current token is an operator. + else: + + # While top of 'ops' has same or + # greater precedence to current + # token, which is an operator. + # Apply operator on top of 'ops' + # to top two elements in values stack. + while (len(ops) != 0 and + precedence(ops[-1]) >= + precedence(tokens[i])): + + val2 = values.pop() + val1 = values.pop() + op = ops.pop() + + values.append(applyOp(val1, val2, op)) + + # Push current token to 'ops'. + ops.append(tokens[i]) + + i += 1 + + # Entire expression has been parsed + # at this point, apply remaining ops + # to remaining values. + while len(ops) != 0: + + val2 = values.pop() + val1 = values.pop() + op = ops.pop() + + values.append(applyOp(val1, val2, op)) + + # Top of 'values' contains result, + # return it. + return values[-1] + +# Driver Code +if __name__ == ""__main__"": + + print(evaluate(""10 + 2 * 6"")) + print(evaluate(""100 * 2 + 12"")) + print(evaluate(""100 * ( 2 + 12 )"")) + print(evaluate(""100 * ( 2 + 12 ) / 14"")) + +# This code is contributed +# by Rituraj Jain",linear,linear +"# Python program to evaluate value of a postfix expression + +# Class to convert the expression +class Evaluate: + + # Constructor to initialize the class variables + def __init__(self, capacity): + self.top = -1 + self.capacity = capacity + # This array is used a stack + self.array = [] + + # check if the stack is empty + def isEmpty(self): + return True if self.top == -1 else False + + # Return the value of the top of the stack + def peek(self): + return self.array[-1] + + # Pop the element from the stack + def pop(self): + if not self.isEmpty(): + self.top -= 1 + return self.array.pop() + else: + return ""$"" + + # Push the element to the stack + def push(self, op): + self.top += 1 + self.array.append(op) + + + # The main function that converts given infix expression + # to postfix expression + def evaluatePostfix(self, exp): + + # Iterate over the expression for conversion + for i in exp: + + # If the scanned character is an operand + # (number here) push it to the stack + if i.isdigit(): + self.push(i) + + # If the scanned character is an operator, + # pop two elements from stack and apply it. + else: + val1 = self.pop() + val2 = self.pop() + self.push(str(eval(val2 + i + val1))) + + return int(self.pop()) + + + +# Driver program to test above function +exp = ""231*+9-"" +obj = Evaluate(len(exp)) +print (""postfix evaluation: %d""%(obj.evaluatePostfix(exp))) +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python program to evaluate value of a postfix +# expression with integers containing multiple digits + +class evalpostfix: + def __init__(self): + self.stack =[] + self.top =-1 + def pop(self): + if self.top ==-1: + return + else: + self.top-= 1 + return self.stack.pop() + def push(self, i): + self.top+= 1 + self.stack.append(i) + + def centralfunc(self, ab): + for i in ab: + + # if the component of the list is an integer + try: + self.push(int(i)) + # if the component of the list is not an integer, + # it must be an operator. Using ValueError, we can + # evaluate components of the list other than type int + except ValueError: + val1 = self.pop() + val2 = self.pop() + if i == '/': + self.push(val2 / val1) + else: + # switch statement to perform operation + switcher ={'+':val2 + val1, '-':val2-val1, '*':val2 * val1, '^':val2**val1} + self.push(switcher.get(i)) + return int(self.pop()) + +str ='100 200 + 2 / 5 * 7 +' + +# splitting the given string to obtain +# integers and operators into a list +strconv = str.split(' ') +obj = evalpostfix() +print(obj.centralfunc(strconv)) + +# This code is contributed by Amarnath Reddy",linear,linear +"# Python program to reverse a +# stack using recursion + +# Below is a recursive function +# that inserts an element +# at the bottom of a stack. + + +def insertAtBottom(stack, item): + if isEmpty(stack): + push(stack, item) + else: + temp = pop(stack) + insertAtBottom(stack, item) + push(stack, temp) + +# Below is the function that +# reverses the given stack +# using insertAtBottom() + + +def reverse(stack): + if not isEmpty(stack): + temp = pop(stack) + reverse(stack) + insertAtBottom(stack, temp) + +# Below is a complete running +# program for testing above +# functions. + +# Function to create a stack. +# It initializes size of stack +# as 0 + + +def createStack(): + stack = [] + return stack + +# Function to check if +# the stack is empty + + +def isEmpty(stack): + return len(stack) == 0 + +# Function to push an +# item to stack + + +def push(stack, item): + stack.append(item) + +# Function to pop an +# item from stack + + +def pop(stack): + + # If stack is empty + # then error + if(isEmpty(stack)): + print(""Stack Underflow "") + exit(1) + + return stack.pop() + +# Function to print the stack + + +def prints(stack): + for i in range(len(stack)-1, -1, -1): + print(stack[i], end=' ') + print() + +# Driver Code + + +stack = createStack() +push(stack, str(4)) +push(stack, str(3)) +push(stack, str(2)) +push(stack, str(1)) +print(""Original Stack "") +prints(stack) + +reverse(stack) + +print(""Reversed Stack "") +prints(stack) + +# This code is contributed by Sunny Karira",linear,quadratic +"# Python program to sort a stack using recursion + +# Recursive method to insert element in sorted way + + +def sortedInsert(s, element): + + # Base case: Either stack is empty or newly inserted + # item is greater than top (more than all existing) + if len(s) == 0 or element > s[-1]: + s.append(element) + return + else: + + # Remove the top item and recur + temp = s.pop() + sortedInsert(s, element) + + # Put back the top item removed earlier + s.append(temp) + +# Method to sort stack + + +def sortStack(s): + + # If stack is not empty + if len(s) != 0: + + # Remove the top item + temp = s.pop() + + # Sort remaining stack + sortStack(s) + + # Push the top item back in sorted stack + sortedInsert(s, temp) + +# Printing contents of stack + + +def printStack(s): + for i in s[::-1]: + print(i, end="" "") + print() + + +# Driver Code +if __name__ == '__main__': + s = [] + s.append(30) + s.append(-5) + s.append(18) + s.append(14) + s.append(-3) + + print(""Stack elements before sorting: "") + printStack(s) + + sortStack(s) + + print(""\nStack elements after sorting: "") + printStack(s) + +# This code is contributed by Muskan Kalra.",linear,quadratic +"# Python program to sort a +# stack using auxiliary stack. + +# This function return the sorted stack +def sortStack ( stack ): + tmpStack = createStack() + while(isEmpty(stack) == False): + + # pop out the first element + tmp = top(stack) + pop(stack) + + # while temporary stack is not + # empty and top of stack is + # greater than temp + while(isEmpty(tmpStack) == False and + int(top(tmpStack)) > int(tmp)): + + # pop from temporary stack and + # push it to the input stack + push(stack,top(tmpStack)) + pop(tmpStack) + + # push temp in temporary of stack + push(tmpStack,tmp) + + return tmpStack + +# Below is a complete running +# program for testing above +# function. + +# Function to create a stack. +# It initializes size of stack +# as 0 +def createStack(): + stack = [] + return stack + +# Function to check if +# the stack is empty +def isEmpty( stack ): + return len(stack) == 0 + +# Function to push an +# item to stack +def push( stack, item ): + stack.append( item ) + +# Function to get top +# item of stack +def top( stack ): + p = len(stack) + return stack[p-1] + +# Function to pop an +# item from stack +def pop( stack ): + + # If stack is empty + # then error + if(isEmpty( stack )): + print(""Stack Underflow "") + exit(1) + + return stack.pop() + +# Function to print the stack +def prints(stack): + for i in range(len(stack)-1, -1, -1): + print(stack[i], end = ' ') + print() + +# Driver Code +stack = createStack() +push( stack, str(34) ) +push( stack, str(3) ) +push( stack, str(31) ) +push( stack, str(98) ) +push( stack, str(92) ) +push( stack, str(23) ) + +print(""Sorted numbers are: "") +sortedst = sortStack ( stack ) +prints(sortedst) + +# This code is contributed by +# Prasad Kshirsagar",linear,quadratic +"# Python3 program to implement Stack +# using linked list so that reverse +# can be done with O(1) extra space. +class StackNode: + + def __init__(self, data): + + self.data = data + self.next = None + +class Stack: + + def __init__(self): + + self.top = None + + # Push and pop operations + def push(self, data): + + if (self.top == None): + self.top = StackNode(data) + return + + s = StackNode(data) + s.next = self.top + self.top = s + + def pop(self): + + s = self.top + self.top = self.top.next + return s + + # Prints contents of stack + def display(self): + + s = self.top + + while (s != None): + print(s.data, end = ' ') + s = s.next + + # Reverses the stack using simple + # linked list reversal logic. + def reverse(self): + + prev = self.top + cur = self.top + cur = cur.next + succ = None + prev.next = None + + while (cur != None): + succ = cur.next + cur.next = prev + prev = cur + cur = succ + + self.top = prev + +# Driver code +if __name__=='__main__': + + s = Stack() + s.push(1) + s.push(2) + s.push(3) + s.push(4) + + print(""Original Stack"") + s.display() + print() + + # Reverse + s.reverse() + + print(""Reversed Stack"") + s.display() + +# This code is contributed by rutvik_56",constant,linear +"# Python3 code to delete middle of a stack +# without using additional data structure. + +# Deletes middle of stack of size +# n. Curr is current item number +class Stack: + def __init__(self): + self.items = [] + + def isEmpty(self): + return self.items == [] + + def push(self, item): + self.items.append(item) + + def pop(self): + return self.items.pop() + + def peek(self): + return self.items[len(self.items)-1] + + def size(self): + return len(self.items) + +def deleteMid(st, n, curr) : + + # If stack is empty or all items + # are traversed + if (st.isEmpty() or curr == n) : + return + + # Remove current item + x = st.peek() + st.pop() + + # Remove other items + deleteMid(st, n, curr+1) + + # Put all items back except middle + if (curr != int(n/2)) : + st.push(x) + +# Driver function to test above functions +st = Stack() + +# push elements into the stack +st.push('1') +st.push('2') +st.push('3') +st.push('4') +st.push('5') +st.push('6') +st.push('7') + +deleteMid(st, st.size(), 0) + +# Printing stack after deletion +# of middle. +while (st.isEmpty() == False) : + p = st.peek() + st.pop() + print (str(p) + "" "", end="""") + +# This code is contributed by +# Manish Shaw (manishshaw1)",linear,linear +"# Python code to delete middle of a stack with iterative method + +# Deletes middle of stack of size n. Curr is current item number +def deleteMid(st): + n = len(st) + tempSt = [] + count = 0 + + # Put first n/2 element of st in tempSt + while (count < (n / 2)-1): + c = st[0] + st.pop(0) + tempSt.insert(0, c) + count = count+1 + + # Delete middle element + st.pop(0) + + # Put all (n/2) element of tempSt in st + while (len(tempSt) != 0): + st.insert(0, tempSt[0]) + tempSt.pop(0) + + +# Driver Code +st = [] + +# insert elements into the stack +st.insert(0, 1) +st.insert(0, 2) +st.insert(0, 3) +st.insert(0, 4) +st.insert(0, 5) +st.insert(0, 6) +st.insert(0, 7) +deleteMid(st) + +# Printing stack after deletion of middle. +while (len(st) != 0): + p = st[0] + st.pop(0) + print(p, "" "") + +# This code is added by adityamaharshi21",linear,linear +"# Python3 program to sort an array using stack + +# This function return the sorted stack +def sortStack(input): + tmpStack = [] + while (len(input) > 0): + + # pop out the first element + tmp = input[-1] + input.pop() + + # while temporary stack is not empty + # and top of stack is smaller than temp + while (len(tmpStack) > 0 and tmpStack[-1] < tmp): + + # pop from temporary stack and + # append it to the input stack + input.append(tmpStack[-1]) + tmpStack.pop() + + # append temp in temporary of stack + tmpStack.append(tmp) + + return tmpStack + +def sortArrayUsingStacks(arr, n): + + # append array elements to stack + input = [] + i = 0 + while ( i < n ): + input.append(arr[i]) + i = i + 1 + + # Sort the temporary stack + tmpStack = sortStack(input) + i = 0 + + # Put stack elements in arrp[] + while (i < n): + arr[i] = tmpStack[-1] + tmpStack.pop() + i = i + 1 + + return arr + +# Driver code +arr = [10, 5, 15, 45] +n = len(arr) + +arr = sortArrayUsingStacks(arr, n) +i = 0 + +while (i < n): + print(arr[i] ,end= "" "") + i = i + 1 + +# This code is contributed by Arnab Kundu",linear,quadratic +"# Function to delete elements +def deleteElements(arr, n, k): + + # create an empty stack st + st = [] + st.append(arr[0]) + + # index to maintain the top + # of the stack + top = 0 + count = 0 + + for i in range(1, n): + + # pop till the present element + # is greater than stack's top + # element + while(len(st) != 0 and count < k + and st[top] < arr[i]): + st.pop() + count += 1 + top -= 1 + + st.append(arr[i]) + top += 1 + + # print the remaining elements + for i in range(0, len(st)): + print(st[i], "" "", end="""") + +# Driver code +k = 2 +arr = [20, 10, 25, 30, 40] +deleteElements(arr, len(arr), k) + +# This code is contributed by himan085.",linear,quadratic +"# Python3 program to count number of distinct +# instance where second highest number lie +# before highest number in all subarrays. +from typing import List + +MAXN = 100005 + +# Finding the next greater element +# of the array. +def makeNext(arr: List[int], n: int, + nextBig: List[int]) -> None: + + # Stack + s = [] + + for i in range(n - 1, -1, -1): + nextBig[i] = i + + while len(s) and s[-1][0] < arr[i]: + s.pop() + + if len(s): + nextBig[i] = s[-1][1] + + s.append((arr[i], i)) + +# Finding the previous greater +# element of the array. +def makePrev(arr: List[int], n: int, + prevBig: List[int]) -> None: + + # Stack + s = [] + for i in range(n): + prevBig[i] = -1 + + while (len(s) and s[-1][0] < arr[i]): + s.pop() + + if (len(s)): + prevBig[i] = s[-1][1] + + s.append((arr[i], i)) + +# Wrapper Function +def wrapper(arr: List[int], n: int) -> int: + + nextBig = [0] * MAXN + prevBig = [0] * MAXN + maxi = [0] * MAXN + ans = 0 + + # Finding previous largest element + makePrev(arr, n, prevBig) + + # Finding next largest element + makeNext(arr, n, nextBig) + + for i in range(n): + if (nextBig[i] != i): + maxi[nextBig[i] - i] = max( + maxi[nextBig[i] - i], + i - prevBig[i]) + + for i in range(n): + ans += maxi[i] + + return ans + +# Driver Code +if __name__ == ""__main__"": + + arr = [ 1, 3, 2, 4 ] + n = len(arr) + + print(wrapper(arr, n)) + +# This code is contributed by sanjeev2552",linear,linear +"# Python3 program to find maximum +# rectangular area in linear time + + +def max_area_histogram(histogram): + + # This function calculates maximum + # rectangular area under given + # histogram with n bars + + # Create an empty stack. The stack + # holds indexes of histogram[] list. + # The bars stored in the stack are + # always in increasing order of + # their heights. + stack = list() + + max_area = 0 # Initialize max area + + # Run through all bars of + # given histogram + index = 0 + while index < len(histogram): + + # If this bar is higher + # than the bar on top + # stack, push it to stack + + if (not stack) or (histogram[stack[-1]] <= histogram[index]): + stack.append(index) + index += 1 + + # If this bar is lower than top of stack, + # then calculate area of rectangle with + # stack top as the smallest (or minimum + # height) bar.'i' is 'right index' for + # the top and element before top in stack + # is 'left index' + else: + # pop the top + top_of_stack = stack.pop() + + # Calculate the area with + # histogram[top_of_stack] stack + # as smallest bar + area = (histogram[top_of_stack] * + ((index - stack[-1] - 1) + if stack else index)) + + # update max area, if needed + max_area = max(max_area, area) + + # Now pop the remaining bars from + # stack and calculate area with + # every popped bar as the smallest bar + while stack: + + # pop the top + top_of_stack = stack.pop() + + # Calculate the area with + # histogram[top_of_stack] + # stack as smallest bar + area = (histogram[top_of_stack] * + ((index - stack[-1] - 1) + if stack else index)) + + # update max area, if needed + max_area = max(max_area, area) + + # Return maximum area under + # the given histogram + return max_area + + +# Driver Code +if __name__ == '__main__': + hist = [6, 2, 5, 4, 5, 1, 6] + + # Function call + print(""Maximum area is"", + max_area_histogram(hist)) + +# This code is contributed +# by Jinay Shah",linear,linear +"# Python3 code for the above approach + + +def getMaxArea(arr): + s = [-1] + n = len(arr) + area = 0 + i = 0 + left_smaller = [-1]*n + right_smaller = [n]*n + while i < n: + while s and (s[-1] != -1) and (arr[s[-1]] > arr[i]): + right_smaller[s[-1]] = i + s.pop() + if((i > 0) and (arr[i] == arr[i-1])): + left_smaller[i] = left_smaller[i-1] + else: + left_smaller[i] = s[-1] + s.append(i) + i += 1 + for j in range(0, n): + area = max(area, arr[j]*(right_smaller[j]-left_smaller[j]-1)) + return area + + +# Driver code +if __name__ == '__main__': + hist = [6, 2, 5, 4, 5, 1, 6] + + # Function call + print(""maxArea = "", getMaxArea(hist)) + +# This code is contributed by Arunit Kumar",linear,linear +"# Python program to reverse a string using stack + +# Function to create an empty stack. +# It initializes size of stack as 0 + + +def createStack(): + stack = [] + return stack + +# Function to determine the size of the stack + + +def size(stack): + return len(stack) + +# Stack is empty if the size is 0 + + +def isEmpty(stack): + if size(stack) == 0: + return true + +# Function to add an item to stack . +# It increases size by 1 + + +def push(stack, item): + stack.append(item) + +# Function to remove an item from stack. +# It decreases size by 1 + + +def pop(stack): + if isEmpty(stack): + return + return stack.pop() + +# A stack based function to reverse a string + + +def reverse(string): + n = len(string) + + # Create a empty stack + stack = createStack() + + # Push all characters of string to stack + for i in range(0, n, 1): + push(stack, string[i]) + + # Making the string empty since all + # characters are saved in stack + string = """" + + # Pop all characters of string and + # put them back to string + for i in range(0, n, 1): + string += pop(stack) + + return string + + +# Driver program to test above functions +string = ""GeeksQuiz"" +string = reverse(string) +print(""Reversed string is "" + string) + +# This code is contributed by Sunny Karira",linear,linear +"# Recursive Python function to solve tower of hanoi + + +def TowerOfHanoi(n, from_rod, to_rod, aux_rod): + if n == 0: + return + TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) + print(""Move disk"", n, ""from rod"", from_rod, ""to rod"", to_rod) + TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) + + +# Driver code +N = 3 + +# A, C, B are the name of rods +TowerOfHanoi(N, 'A', 'C', 'B') + +# Contributed By Harshit Agrawal",linear,linear +"# Python code to implement the approach + + +def maxDepth(s): + + count = 0 + st = [] + + for i in range(len(s)): + if (s[i] == '('): + st.append(i) # pushing the bracket in the stack + elif (s[i] == ')'): + if (count < len(st)): + count = len(st) + # keeping track of the parenthesis and storing + # it before removing it when it gets balanced + st.pop() + + return count + +# Driver program + +s = ""( ((X)) (((Y))) )"" +print(maxDepth(s)) + + +# This code is contributed by shinjanpatra",constant,linear +"# A Python program to find the maximum depth of nested +# parenthesis in a given expression + +# function takes a string and returns the +# maximum depth nested parenthesis +def maxDepth(S): + current_max = 0 + max = 0 + n = len(S) + + # Traverse the input string + for i in range(n): + if S[i] == '(': + current_max += 1 + + if current_max > max: + max = current_max + else if S[i] == ')': + if current_max > 0: + current_max -= 1 + else: + return -1 + + # finally check for unbalanced string + if current_max != 0: + return -1 + + return max + +# Driver program +s = ""( ((X)) (((Y))) )"" +print (maxDepth(s)) + +# This code is contributed by BHAVYA JAIN",constant,linear +"# A naive method to find maximum of +# minimum of all windows of different sizes +INT_MIN = -1000000 + + +def printMaxOfMin(arr, n): + + # Consider all windows of different + # sizes starting from size 1 + for k in range(1, n + 1): + + # Initialize max of min for + # current window size k + maxOfMin = INT_MIN + + # Traverse through all windows + # of current size k + for i in range(n - k + 1): + + # Find minimum of current window + min = arr[i] + for j in range(k): + if (arr[i + j] < min): + min = arr[i + j] + + # Update maxOfMin if required + if (min > maxOfMin): + maxOfMin = min + + # Print max of min for current window size + print(maxOfMin, end="" "") + + +# Driver Code +arr = [10, 20, 30, 50, 10, 70, 30] +n = len(arr) +printMaxOfMin(arr, n) + +# This code is contributed by sahilshelangia",constant,cubic +"# An efficient Python3 program to find +# maximum of all minimums of windows of +# different sizes + + +def printMaxOfMin(arr, n): + + s = [] # Used to find previous + # and next smaller + + # Arrays to store previous and next + # smaller. Initialize elements of + # left[] and right[] + left = [-1] * (n + 1) + right = [n] * (n + 1) + + # Fill elements of left[] using logic discussed on + # https:#www.geeksforgeeks.org/next-greater-element + for i in range(n): + while (len(s) != 0 and + arr[s[-1]] >= arr[i]): + s.pop() + + if (len(s) != 0): + left[i] = s[-1] + + s.append(i) + + # Empty the stack as stack is going + # to be used for right[] + while (len(s) != 0): + s.pop() + + # Fill elements of right[] using same logic + for i in range(n - 1, -1, -1): + while (len(s) != 0 and arr[s[-1]] >= arr[i]): + s.pop() + + if(len(s) != 0): + right[i] = s[-1] + + s.append(i) + + # Create and initialize answer array + ans = [0] * (n + 1) + for i in range(n + 1): + ans[i] = 0 + + # Fill answer array by comparing minimums + # of all. Lengths computed using left[] + # and right[] + for i in range(n): + + # Length of the interval + Len = right[i] - left[i] - 1 + + # arr[i] is a possible answer for this + # Length 'Len' interval, check if arr[i] + # is more than max for 'Len' + ans[Len] = max(ans[Len], arr[i]) + + # Some entries in ans[] may not be filled + # yet. Fill them by taking values from + # right side of ans[] + for i in range(n - 1, 0, -1): + ans[i] = max(ans[i], ans[i + 1]) + + # Print the result + for i in range(1, n + 1): + print(ans[i], end="" "") + + +# Driver Code +if __name__ == '__main__': + + arr = [10, 20, 30, 50, 10, 70, 30] + n = len(arr) + printMaxOfMin(arr, n) + +# This code is contributed by PranchalK",linear,linear +"# Python3 Program to check whether valid +# expression is redundant or not + +# Function to check redundant brackets +# in a balanced expression +def checkRedundancy(Str): + + # create a stack of characters + st = [] + + # Iterate through the given expression + for ch in Str: + + # if current character is close + # parenthesis ')' + if (ch == ')'): + top = st[-1] + st.pop() + + # If immediate pop have open parenthesis + # '(' duplicate brackets found + flag = True + + while (top != '('): + + # Check for operators in expression + if (top == '+' or top == '-' or + top == '*' or top == '/'): + flag = False + + # Fetch top element of stack + top = st[-1] + st.pop() + + # If operators not found + if (flag == True): + return True + + else: + st.append(ch) # append open parenthesis '(', + # operators and operands to stack + return False + +# Function to check redundant brackets +def findRedundant(Str): + ans = checkRedundancy(Str) + if (ans == True): + print(""Yes"") + else: + print(""No"") + +# Driver code +if __name__ == '__main__': + Str = ""((a+b))"" + findRedundant(Str) + + +# This code is contributed by PranchalK",linear,linear +"# Python3 program to +# mark balanced and +# unbalanced parenthesis. +def identifyParenthesis(a): + st = [] + + # run the loop upto + # end of the string + for i in range (len(a)): + + # if a[i] is opening + # bracket then push + # into stack + if (a[i] == '('): + st.append(a[i]) + + # if a[i] is closing bracket ')' + elif (a[i] == ')'): + + # If this closing bracket + # is unmatched + if (len(st) == 0): + a = a.replace(a[i], ""-1"", 1) + + else: + + # replace all opening brackets with 0 + # and closing brackets with 1 + a = a.replace(a[i], ""1"", 1) + a = a.replace(st[-1], ""0"", 1) + st.pop() + + # if stack is not empty + # then pop out all + # elements from it and + # replace -1 at that + # index of the string + while (len(st) != 0): + a = a.replace(st[-1], 1, ""-1""); + st.pop() + + # print final string + print(a) + +# Driver code +if __name__ == ""__main__"": + + st = ""(a))"" + identifyParenthesis(st) + +# This code is contributed by Chitranayal",linear,linear +"# Python3 program to check if two expressions +# evaluate to same. +MAX_CHAR = 26; + +# Return local sign of the operand. For example, +# in the expr a-b-(c), local signs of the operands +# are +a, -b, +c +def adjSign(s, i): + if (i == 0): + return True; + if (s[i - 1] == '-'): + return False; + return True; + +# Evaluate expressions into the count vector of +# the 26 alphabets.If add is True, then add count +# to the count vector of the alphabets, else remove +# count from the count vector. +def eval(s, v, add): + + # stack stores the global sign + # for operands. + stk = [] + stk.append(True); + + # + means True + # global sign is positive initially + i = 0; + + while (i < len(s)): + + if (s[i] == '+' or s[i] == '-'): + i += 1 + continue; + + if (s[i] == '('): + + # global sign for the bracket is + # pushed to the stack + if (adjSign(s, i)): + stk.append(stk[-1]); + else: + stk.append(not stk[-1]); + + # global sign is popped out which + # was pushed in for the last bracket + elif (s[i] == ')'): + stk.pop(); + else: + + # global sign is positive (we use different + # values in two calls of functions so that + # we finally check if all vector elements + # are 0. + if (stk[-1]): + v[ord(s[i]) - ord('a')] += (1 if add else -1) if adjSign(s, i) else (-1 if add else 1) + + # global sign is negative here + else: + v[ord(s[i]) - ord('a')] += (-1 if add else 1) if adjSign(s, i) else (1 if add else -1) + + i += 1 + +# Returns True if expr1 and expr2 represent +# same expressions +def areSame(expr1, expr2): + + # Create a vector for all operands and + # initialize the vector as 0. + v = [0 for i in range(MAX_CHAR)]; + + # Put signs of all operands in expr1 + eval(expr1, v, True); + + # Subtract signs of operands in expr2 + eval(expr2, v, False); + + # If expressions are same, vector must + # be 0. + for i in range(MAX_CHAR): + if (v[i] != 0): + return False; + return True; + +# Driver Code +if __name__=='__main__': + expr1 = ""-(a+b+c)"" + expr2 = ""-a-b-c""; + if (areSame(expr1, expr2)): + print(""Yes""); + else: + print(""No""); + + # This code is contributed by rutvik_56.",linear,linear +"# Python program to find index of closing +# bracket for a given opening bracket. +from collections import deque + +def getIndex(s, i): + + # If input is invalid. + if s[i] != '[': + return -1 + + # Create a deque to use it as a stack. + d = deque() + + # Traverse through all elements + # starting from i. + for k in range(i, len(s)): + + # Pop a starting bracket + # for every closing bracket + if s[k] == ']': + d.popleft() + + # Push all starting brackets + elif s[k] == '[': + d.append(s[i]) + + # If deque becomes empty + if not d: + return k + + return -1 + +# Driver code to test above method. +def test(s, i): + matching_index = getIndex(s, i) + print(s + "", "" + str(i) + "": "" + str(matching_index)) + +def main(): + test(""[ABC[23]][89]"", 0) # should be 8 + test(""[ABC[23]][89]"", 4) # should be 7 + test(""[ABC[23]][89]"", 9) # should be 12 + test(""[ABC[23]][89]"", 1) # No matching bracket + +if __name__ == ""__main__"": + main()",linear,linear +"# Python3 program to check for +# balanced brackets. + +# function to check if +# brackets are balanced + + +def areBracketsBalanced(expr): + stack = [] + + # Traversing the Expression + for char in expr: + if char in [""("", ""{"", ""[""]: + + # Push the element in the stack + stack.append(char) + else: + + # IF current character is not opening + # bracket, then it must be closing. + # So stack cannot be empty at this point. + if not stack: + return False + current_char = stack.pop() + if current_char == '(': + if char != "")"": + return False + if current_char == '{': + if char != ""}"": + return False + if current_char == '[': + if char != ""]"": + return False + + # Check Empty Stack + if stack: + return False + return True + + +# Driver Code +if __name__ == ""__main__"": + expr = ""{()}[]"" + + # Function call + if areBracketsBalanced(expr): + print(""Balanced"") + else: + print(""Not Balanced"") + +# This code is contributed by AnkitRai01 and improved +# by Raju Pitta",linear,linear +"# Python3 program to determine whether +# given expression is balanced/ parenthesis +# expression or not. + +# Function to check if two brackets are +# matching or not. +def isMatching(a, b): + + if ((a == '{' and b == '}') or + (a == '[' and b == ']') or + (a == '(' and b == ')') or + a == 'X'): + return 1 + + return 0 + +# Recursive function to check if given +# expression is balanced or not. +def isBalanced(s, ele, ind): + + # Base case. + # If the string is balanced then all the + # opening brackets had been popped and + # stack should be empty after string is + # traversed completely. + if (ind == len(s)): + if len(ele) == 0: + return True + else: + return False + + # Variable to store element at the top + # of the stack. + # char topEle; + + # Variable to store result of + # recursive call. + # int res; + + # Case 1: When current element is an + # opening bracket then push that + # element in the stack. + if (s[ind] == '{' or s[ind] == '(' or + s[ind] == '['): + ele.append(s[ind]) + return isBalanced(s, ele, ind + 1) + + # Case 2: When current element is a closing + # bracket then check for matching bracket + # at the top of the stack. + elif (s[ind] == '}' or s[ind] == ')' or + s[ind] == ']'): + + # If stack is empty then there is no matching + # opening bracket for current closing bracket + # and the expression is not balanced. + if (len(ele) == 0): + return 0 + + topEle = ele[-1] + ele.pop() + + # Check bracket is matching or not. + if (isMatching(topEle, s[ind]) == 0): + return 0 + + return isBalanced(s, ele, ind + 1) + + # Case 3: If current element is 'X' then check + # for both the cases when 'X' could be opening + # or closing bracket. + elif (s[ind] == 'X'): + tmp = ele + tmp.append(s[ind]) + res = isBalanced(s, tmp, ind + 1) + + if (res): + return 1 + if (len(ele) == 0): + return 0 + + ele.pop() + + return isBalanced(s, ele, ind + 1) + +# Driver Code +s = ""{(X}[]"" +ele = [] + +# Check if the length of the given string is even +if(len(s)%2==0): + if (isBalanced(s, ele, 0)): print(""Balanced"") + else: print(""Not Balanced"") + +# If the length is not even, then the string is not balanced +else: print(""Not Balanced"") + +# This code is contributed by divyeshrabadiya07",linear,np +"# Python program for an efficient solution to check if +# a given array can represent Preorder traversal of +# a Binary Search Tree + +INT_MIN = -2**32 + +def canRepresentBST(pre): + + # Create an empty stack + s = [] + + # Initialize current root as minimum possible value + root = INT_MIN + + # Traverse given array + for value in pre: + #NOTE:value is equal to pre[i] according to the + #given algo + + # If we find a node who is on the right side + # and smaller than root, return False + if value < root : + return False + + # If value(pre[i]) is in right subtree of stack top, + # Keep removing items smaller than value + # and make the last removed items as new root + while(len(s) > 0 and s[-1] < value) : + root = s.pop() + + # At this point either stack is empty or value + # is smaller than root, push value + s.append(value) + + return True + +# Driver Program +pre1 = [40 , 30 , 35 , 80 , 100] +print (""true"" if canRepresentBST(pre1) == True else ""false"") +pre2 = [40 , 30 , 35 , 20 , 80 , 100] +print (""true"" if canRepresentBST(pre2) == True else ""false"") + +# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",linear,linear +"# Python3 program to illustrate if a given array can represent +# a preorder traversal of a BST or not +import sys + +preIndex = 0 + +# We are actually not building the tree +def buildBST_helper(n, pre, Min, Max): + global preIndex + if (preIndex >= n): + return + + if (Min <= pre[preIndex] and pre[preIndex] <= Max): + # build node + rootData = pre[preIndex] + preIndex+=1 + + # build left subtree + buildBST_helper(n, pre, Min, rootData) + + # build right subtree + buildBST_helper(n, pre, rootData, Max) + # else + # return NULL + +def canRepresentBST(arr, N): + global preIndex + # code here + Min, Max = sys.maxsize, -sys.maxsize + + buildBST_helper(N, arr, Min, Max) + + if preIndex == N: + return True + + return False + +preorder1 = [ 2, 4, 3 ] +"""""" + 2 + \ + 4 + / + 3 + +"""""" +n1 = len(preorder1) + +if (not canRepresentBST(preorder1, n1)): + print(""preorder1 can represent BST""); +else: + print(""preorder1 can not represent BST :("") + +preorder2 = [ 5, 3, 4, 1, 6, 10 ] +n2 = len(preorder2) +"""""" + 5 + / \ + 3 1 + \ / \ + 4 6 10 + +"""""" +if (canRepresentBST(preorder2, n2)): + print(""preorder2 can represent BST"") +else: + print(""preorder2 can not represent BST :("") + +preorder3 = [ 5, 3, 4, 8, 6, 10 ] +n3 = len(preorder3) +"""""" + 5 + / \ + 3 8 + \ / \ + 4 6 10 +"""""" +if (not canRepresentBST(preorder3, n3)): + print(""preorder3 can represent BST"") +else: + print(""preorder3 can not represent BST :("")",logn,linear +"# Python program to find the difference b/w left and +# right smaller element of every element in the array + +# Function to fill left smaller element for every +# element of arr[0..n-1]. These values are filled +# in SE[0..n-1] +def leftsmaller(arr, n, SE): + + # create an empty stack + sta = [] + # Traverse all array elements + # compute nearest smaller elements of every element + for i in range(n): + + # Keep removing top element from S while the top + # element is greater than or equal to arr[i] + while(sta != [] and sta[len(sta)-1] >= arr[i]): + sta.pop() + + # Store the smaller element of current element + if(sta != []): + SE[i]=sta[len(sta)-1] + # If all elements in S were greater than arr[i] + else: + SE[i]=0 + + # push this element + sta.append(arr[i]) + +# Function returns maximum difference b/w Left & +# right smaller element +def findMaxDiff(arr, n): + ls=[0]*n # to store left smaller elements + rs=[0]*n # to store right smaller elements + + # find left smaller elements of every element + leftsmaller(arr, n, ls) + + # find right smaller element of every element + # by sending reverse of array + leftsmaller(arr[::-1], n, rs) + + # find maximum absolute difference b/w LS & RRS + # In the reversed array right smaller for arr[i] is + # stored at RRS[n-i-1] + res = -1 + for i in range(n): + res = max(res, abs(ls[i] - rs[n-1-i])) + # return maximum difference b/w LS & RRS + return res + + +# Driver Program +if __name__=='__main__': + arr = [2, 4, 8, 7, 7, 9, 3] + print ""Maximum Diff :"", findMaxDiff(arr, len(arr)) + +#Contributed By: Harshit Sidhwa",linear,linear +"# Python 3 Program to find Right smaller element of next +# greater element + +# function find Next greater element +def nextGreater(arr, n, next, order): + + S = [] + + # Traverse all array elements in reverse order + # order == 'G' we compute next greater elements of + # every element + # order == 'S' we compute right smaller element of + # every element + for i in range(n-1,-1,-1): + + # Keep removing top element from S while the top + # element is smaller than or equal to arr[i] (if Key is G) + # element is greater than or equal to arr[i] (if order is S) + while (S!=[] and (arr[S[len(S)-1]] <= arr[i] + if (order=='G') else arr[S[len(S)-1]] >= arr[i] )): + + S.pop() + + # store the next greater element of current element + if (S!=[]): + next[i] = S[len(S)-1] + + # If all elements in S were smaller than arr[i] + else: + next[i] = -1 + + # Push this element + S.append(i) + +# Function to find Right smaller element of next greater +# element +def nextSmallerOfNextGreater(arr, n): + NG = [None]*n # stores indexes of next greater elements + RS = [None]*n # stores indexes of right smaller elements + + # Find next greater element + # Here G indicate next greater element + nextGreater(arr, n, NG, 'G') + + # Find right smaller element + # using same function nextGreater() + # Here S indicate right smaller elements + nextGreater(arr, n, RS, 'S') + + # If NG[i] == -1 then there is no smaller element + # on right side. We can find Right smaller of next + # greater by arr[RS[NG[i]]] + for i in range(n): + if (NG[i] != -1 and RS[NG[i]] != -1): + print(arr[RS[NG[i]]],end="" "") + else: + print(""-1"",end="" "") + +# Driver program +if __name__==""__main__"": + arr = [5, 1, 9, 2, 5, 1, 7] + n = len(arr) + nextSmallerOfNextGreater(arr, n) + +# this code is contributed by ChitraNayal",linear,linear +"# Python program to calculate maximum sum with equal +# stack sum. +# Returns maximum possible equal sum of three stacks +# with removal of top elements allowed +def maxSum(stack1, stack2, stack3, n1, n2, n3): + sum1, sum2, sum3 = 0, 0, 0 + + # Finding the initial sum of stack1. + for i in range(n1): + sum1 += stack1[i] + + # Finding the initial sum of stack2. + for i in range(n2): + sum2 += stack2[i] + + # Finding the initial sum of stack3. + for i in range(n3): + sum3 += stack3[i] + + # As given in question, first element is top + # of stack.. + top1, top2, top3 = 0, 0, 0 + ans = 0 + while (1): + # If any stack is empty + if (top1 == n1 or top2 == n2 or top3 == n3): + return 0 + + # If sum of all three stack are equal. + if (sum1 == sum2 and sum2 == sum3): + return sum1 + + # Finding the stack with maximum sum and + # removing its top element. + if (sum1 >= sum2 and sum1 >= sum3): + sum1 -= stack1[top1] + top1=top1+1 + else if (sum2 >= sum1 and sum2 >= sum3): + sum2 -= stack2[top2] + top2=top2+1 + else if (sum3 >= sum2 and sum3 >= sum1): + sum3 -= stack3[top3] + top3=top3+1 + +# Driven Program +stack1 = [ 3, 2, 1, 1, 1 ] +stack2 = [ 4, 3, 2 ] +stack3 = [ 1, 1, 4, 1 ] + +n1 = len(stack1) +n2 = len(stack2) +n3 = len(stack3) + +print (maxSum(stack1, stack2, stack3, n1, n2, n3)) + +#This code is contributed by Afzal Ansari",constant,linear +"# Python3 program to count the number less +# than N, whose all permutation is greater +# than or equal to the number. + +# Return the count of the number having +# all permutation greater than or equal +# to the number. + + +def countNumber(n): + result = 0 + + # Pushing 1 to 9 because all number + # from 1 to 9 have this property. + s = [] + for i in range(1, 10): + + if (i <= n): + s.append(i) + result += 1 + + # take a number from stack and add + # a digit smaller than or equal to last digit + # of it. + while len(s) != 0: + tp = s[-1] + s.pop() + for j in range(tp % 10, 10): + x = tp * 10 + j + if (x <= n): + s.append(x) + result += 1 + + return result + + +# Driver Code +if __name__ == '__main__': + + n = 15 + print(countNumber(n)) + +# This code is contributed by PranchalK",linear,linear +"# Python program to decode a string recursively +# encoded as count followed substring + +# Returns decoded string for 'str' +def decode(Str): + integerstack = [] + stringstack = [] + temp = """" + result = """" + i = 0 + # Traversing the string + while i < len(Str): + count = 0 + + # If number, convert it into number + # and push it into integerstack. + if (Str[i] >= '0' and Str[i] <='9'): + while (Str[i] >= '0' and Str[i] <= '9'): + count = count * 10 + ord(Str[i]) - ord('0') + i += 1 + i -= 1 + integerstack.append(count) + + # If closing bracket ']', pop element until + # '[' opening bracket is not found in the + # character stack. + elif (Str[i] == ']'): + temp = """" + count = 0 + + if (len(integerstack) != 0): + count = integerstack[-1] + integerstack.pop() + + while (len(stringstack) != 0 and stringstack[-1] !='[' ): + temp = stringstack[-1] + temp + stringstack.pop() + + if (len(stringstack) != 0 and stringstack[-1] == '['): + stringstack.pop() + + # Repeating the popped string 'temo' count + # number of times. + for j in range(count): + result = result + temp + + # Push it in the character stack. + for j in range(len(result)): + stringstack.append(result[j]) + + result = """" + + # If '[' opening bracket, push it into character stack. + elif (Str[i] == '['): + if (Str[i-1] >= '0' and Str[i-1] <= '9'): + stringstack.append(Str[i]) + + else: + stringstack.append(Str[i]) + integerstack.append(1) + + else: + stringstack.append(Str[i]) + + i += 1 + + # Pop all the element, make a string and return. + while len(stringstack) != 0: + result = stringstack[-1] + result + stringstack.pop() + + return result + +# Driven code +if __name__ == '__main__': + Str = ""3[b2[ca]]"" + print(decode(Str)) + +# This code is contributed by PranchalK.",linear,linear +"def decodeString(s): + st = [] + for i in range(len(s)): + + # When ']' is encountered, we need to start decoding + if s[i] == ']': + temp = """" + while len(st) > 0 and st[-1] != '[': + + # st.top() + temp makes sure that the + # string won't be in reverse order eg, if + # the stack contains 12[abc temp = c + """" => + # temp = b + ""c"" => temp = a + ""bc"" + temp = st[-1] + temp + st.pop() + + # remove the '[' from the stack + st.pop() + num = """" + + # remove the digits from the stack + while len(st) > 0 and ord(st[-1]) >= 48 and ord(st[-1]) <= 57: + num = st[-1] + num + st.pop() + number = int(num) + repeat = """" + for j in range(number): + repeat += temp + for c in range(len(repeat)): + if len(st) > 0: + if repeat == st[-1]: + break #otherwise this thingy starts appending the same decoded words + st.append(repeat) + + else: + st.append(s[i]) + + return st[0] + + +Str = ""3[b2[ca]]"" +print(decodeString(Str)) + +# This code is contributed by mukesh07. +# And debugged by ivannakreshchenetska",linear,linear +"# Python3 program for bubble sort +# using stack + +# Function for bubble sort using Stack +def bubbleSortStack(a, n): + s1 = [] + + # Push all elements of array in 1st stack + for i in range(n): + s1.append(a[i]); + s2 = [] + for i in range(n): + if (i % 2 == 0): + while (len(s1) != 0): + t = s1[-1] + s1.pop(); + if(len(s2) == 0): + s2.append(t); + else: + + # Swapping + if (s2[-1] > t): + temp = s2[-1] + s2.pop(); + s2.append(t); + s2.append(temp); + + else: + s2.append(t); + + # Tricky step + a[n - 1 - i] = s2[-1] + s2.pop(); + else: + + while(len(s2) != 0): + t = s2[-1] + s2.pop(); + + if(len(s1) == 0): + s1.append(t); + else: + if (s1[-1] > t): + temp = s1[-1] + s1.pop(); + + s1.append(t); + s1.append(temp); + else: + s1.append(t); + + # Tricky step + a[n - 1 - i] = s1[-1] + s1.pop(); + print(""["", end = '') + for i in range(n): + print(a[i], end = ', ') + print(']', end = '') + +# Driver code +if __name__=='__main__': + + a = [ 15, 12, 44, 2, 5, 10 ] + n = len(a) + + bubbleSortStack(a, n); + + # This code is contributed by rutvik_56.",linear,quadratic +"# Python program to print all ancestors of a given key + +# A class to create a new tree node +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# Iterative Function to print all ancestors of a +# given key +def printAncestors(root, key): + if (root == None): + return + + # Create a stack to hold ancestors + st = [] + + # Traverse the complete tree in postorder way till + # we find the key + while (1): + + # Traverse the left side. While traversing, push + # the nodes into the stack so that their right + # subtrees can be traversed later + while (root and root.data != key): + st.append(root) # push current node + root = root.left # move to next node + + # If the node whose ancestors are to be printed + # is found, then break the while loop. + if (root and root.data == key): + break + + # Check if right sub-tree exists for the node at top + # If not then pop that node because we don't need + # this node any more. + if (st[-1].right == None): + root = st[-1] + st.pop() + + # If the popped node is right child of top, + # then remove the top as well. Left child of + # the top must have processed before. + while (len(st) != 0 and st[-1].right == root): + root = st[-1] + st.pop() + + # if stack is not empty then simply set the root + # as right child of top and start traversing right + # sub-tree. + root = None if len(st) == 0 else st[-1].right + + # If stack is not empty, print contents of stack + # Here assumption is that the key is there in tree + while (len(st) != 0): + print(st[-1].data,end = "" "") + st.pop() + +# Driver code +if __name__ == '__main__': + + # Let us construct a binary tree + root = newNode(1) + root.left = newNode(2) + root.right = newNode(7) + root.left.left = newNode(3) + root.left.right = newNode(5) + root.right.left = newNode(8) + root.right.right = newNode(9) + root.left.left.left = newNode(4) + root.left.right.right = newNode(6) + root.right.right.left = newNode(10) + + key = 6 + printAncestors(root, key) + +# This code is contributed by PranchalK.",linear,linear +"# Given two arrays, check if one array is +# stack permutation of other. +from queue import Queue + +# function to check if Input queue +# is permutable to output queue +def checkStackPermutation(ip, op, n): + + # Input queue + Input = Queue() + for i in range(n): + Input.put(ip[i]) + + # output queue + output = Queue() + for i in range(n): + output.put(op[i]) + + # stack to be used for permutation + tempStack = [] + while (not Input.empty()): + ele = Input.queue[0] + Input.get() + if (ele == output.queue[0]): + output.get() + while (len(tempStack) != 0): + if (tempStack[-1] == output.queue[0]): + tempStack.pop() + output.get() + else: + break + else: + tempStack.append(ele) + + # If after processing, both Input + # queue and stack are empty then + # the Input queue is permutable + # otherwise not. + return (Input.empty() and + len(tempStack) == 0) + +# Driver Code +if __name__ == '__main__': + + # Input Queue + Input = [1, 2, 3] + + # Output Queue + output = [2, 1, 3] + + n = 3 + + if (checkStackPermutation(Input, + output, n)): + print(""Yes"") + else: + print(""Not Possible"") + +# This code is contributed by PranchalK",linear,linear +"# Given two arrays, check if one array is +# stack permutation of other. + +# function to check if input array is +# permutable to output array +def checkStackPermutation(ip, op, n): + + # we will be appending elements from input array to stack uptill top of our stack + # matches with first element of output array + s = [] + + # will maintain a variable j to iterate on output array + j = 0 + + # will iterate one by one in input array + for i in range(n): + + # appended an element from input array to stack + s.append(ip[i]) + + # if our stack isn't empty and top matches with output array + # then we will keep popping out from stack uptill top matches with + # output array + while(len(s) > 0 and s[- 1] == op[j]): + s.pop() + + # increasing j so next time we can compare next element in output array + j += 1 + + + # if output array was a correct permutation of input array then + # by now our stack should be empty + if(len(s) == 0): + return True + + return False + +# Driver program to test above function + +# Input Array +input = [4,5,6,7,8] + +# Output Array + +output = [8,7,6,5,4] +n = 5 +if (checkStackPermutation(input, output, n)): + print(""Yes"") +else: + print(""Not Possible"") + +# This code is contributed by shinjanpatra",linear,linear +"# Python3 program to keep track of +# maximum element in a stack + +class StackWithMax: + def __init__(self): + + # main stack + self.mainStack = [] + + # stack to keep track of + # max element + self.trackStack = [] + + def push(self, x): + self.mainStack.append(x) + if (len(self.mainStack) == 1): + self.trackStack.append(x) + return + + # If current element is greater than + # the top element of track stack, + # append the current element to track + # stack otherwise append the element + # at top of track stack again into it. + if (x > self.trackStack[-1]): + self.trackStack.append(x) + else: + self.trackStack.append(self.trackStack[-1]) + + def getMax(self): + return self.trackStack[-1] + + def pop(self): + self.mainStack.pop() + self.trackStack.pop() + +# Driver Code +if __name__ == '__main__': + + s = StackWithMax() + s.push(20) + print(s.getMax()) + s.push(10) + print(s.getMax()) + s.push(50) + print(s.getMax()) + +# This code is contributed by PranchalK",linear,constant +"# Python3 program to reverse the +# number using a stack + +# Stack to maintain order of digits +st = []; + +# Function to push digits into stack +def push_digits(number): + + while (number != 0): + st.append(number % 10); + number = int(number / 10); + +# Function to reverse the number +def reverse_number(number): + + # Function call to push number's + # digits to stack + push_digits(number); + + reverse = 0; + i = 1; + + # Popping the digits and forming + # the reversed number + while (len(st) > 0): + reverse = reverse + (st[len(st) - 1] * i); + st.pop(); + i = i * 10; + + # Return the reversed number formed + return reverse; + +# Driver Code +number = 39997; + +# Function call to reverse number +print(reverse_number(number)); + +# This code is contributed by mits",logn,logn +"# Python3 program to reverse first k +# elements of a queue. +from queue import Queue + +# Function to reverse the first K +# elements of the Queue + + +def reverseQueueFirstKElements(k, Queue): + if (Queue.empty() == True or + k > Queue.qsize()): + return + if (k <= 0): + return + + Stack = [] + + # put the first K elements + # into a Stack + for i in range(k): + Stack.append(Queue.queue[0]) + Queue.get() + + # Enqueue the contents of stack + # at the back of the queue + while (len(Stack) != 0): + Queue.put(Stack[-1]) + Stack.pop() + + # Remove the remaining elements and + # enqueue them at the end of the Queue + for i in range(Queue.qsize() - k): + Queue.put(Queue.queue[0]) + Queue.get() + +# Utility Function to print the Queue + + +def Print(Queue): + while (not Queue.empty()): + print(Queue.queue[0], end="" "") + Queue.get() + + +# Driver code +if __name__ == '__main__': + Queue = Queue() + Queue.put(10) + Queue.put(20) + Queue.put(30) + Queue.put(40) + Queue.put(50) + Queue.put(60) + Queue.put(70) + Queue.put(80) + Queue.put(90) + Queue.put(100) + + k = 5 + reverseQueueFirstKElements(k, Queue) + Print(Queue) + +# This code is contributed by PranchalK",constant,linear +"# Python3 program to check if successive +# pair of numbers in the stack are +# consecutive or not + +# Function to check if elements are +# pairwise consecutive in stack +def pairWiseConsecutive(s): + + # Transfer elements of s to aux. + aux = [] + while (len(s) != 0): + aux.append(s[-1]) + s.pop() + + # Traverse aux and see if elements + # are pairwise consecutive or not. + # We also need to make sure that + # original content is retained. + result = True + while (len(aux) > 1): + + # Fetch current top two + # elements of aux and check + # if they are consecutive. + x = aux[-1] + aux.pop() + y = aux[-1] + aux.pop() + if (abs(x - y) != 1): + result = False + + # append the elements to + # original stack. + s.append(x) + s.append(y) + + if (len(aux) == 1): + s.append(aux[-1]) + + return result + +# Driver Code +if __name__ == '__main__': + + s = [] + s.append(4) + s.append(5) + s.append(-2) + s.append(-3) + s.append(11) + s.append(10) + s.append(5) + s.append(6) + s.append(20) + + if (pairWiseConsecutive(s)): + print(""Yes"") + else: + print(""No"") + + print(""Stack content (from top)"", + ""after function call"") + while (len(s) != 0): + print(s[-1], end = "" "") + s.pop() + +# This code is contributed by PranchalK",linear,linear +"# Python3 Program to implement growable array based stack +# using tight strategy + +# constant amount at which stack is increased +BOUND = 4 + +# top of the stack +top = -1 +a = [] + +# length of stack +length = 0 + +# function to create new stack + + +def create_new(): + global length + + # allocate memory for new stack + new_a = [0 for i in range(length + BOUND)] + + # copying the content of old stack + for i in range(length): + new_a[i] = a[i] + + # re-sizing the length + length += BOUND + return new_a + +# function to push new element + + +def push(element): + + global top, a + + # if stack is full, create new one + if (top == length - 1): + a = create_new() + + top += 1 + + # insert element at top of the stack + a[top] = element + return a + +# function to pop an element + + +def pop(): + global top + + # stack is empty can't pop + if (top < 0) + print(""Stack is Empty"") + else: + top -= 1 + +# function to display + + +def display(): + global top + + # if top is less than 0, that means stack is empty + if (top < 0) + print(""Stack is Empty"") + else: + print(""Stack: "", end='') + for i in range(top + 1): + + print(a[i], end=' ') + print() + + +# Driver Code +if __name__ == '__main__': + + # creating initial stack + a = create_new() + + # pushing element to top of stack + push(1) + push(2) + push(3) + push(4) + display() + + # pushing more element when stack is full + push(5) + push(6) + display() + + push(7) + push(8) + display() + + # pushing more element so that stack can grow + push(9) + display() + +# This code is contributed by rutvik_56.",linear,linear +"# Python3 code to answer the query in constant time + +''' +BOP[] stands for ""Balanced open parentheses"" +BCP[] stands for ""Balanced close parentheses"" + +''' +# Function for precomputation +def constructBalanceArray(BOP, BCP, str, n): + + # Create a stack and push -1 + # as initial index to it. + stk = [] + + # Traverse all characters of given String + for i in range(n): + + # If opening bracket, push index of it + if (str[i] == '('): + stk.append(i); + + # If closing bracket, i.e., str[i] = ')' + else: + + # If closing bracket, i.e., str[i] = ')' + # && stack is not empty then mark both + # ""open & close"" bracket indexes as 1 . + # Pop the previous opening bracket's index + if (len(stk) != 0): + BCP[i] = 1; + BOP[stk[-1]] = 1; + stk.pop(); + + # If stack is empty. + else: + BCP[i] = 0; + + for i in range(1, n): + + BCP[i] += BCP[i - 1]; + BOP[i] += BOP[i - 1]; + +# Function return output of each query in O(1) +def query(BOP, BCP, s, e): + + if (BOP[s - 1] == BOP[s]): + return (BCP[e] - BOP[s]) * 2; + + else: + return (BCP[e] - BOP[s] + 1) * 2; + +# Driver code +if __name__=='__main__': + + string = ""())(())(())(""; + n = len(string) + + BCP = [0 for i in range(n + 1)]; + BOP = [0 for i in range(n + 1)]; + + constructBalanceArray(BOP, BCP, string, n); + startIndex = 5 + endIndex = 11; + print(""Maximum Length Correct "" + + ""Bracket Subsequence between "" + + str(startIndex) + "" and "" + str(endIndex) + + "" = "" + str(query(BOP, BCP, startIndex, + endIndex))); + startIndex = 4; + endIndex = 5; + print(""Maximum Length Correct "" + + ""Bracket Subsequence between "" + + str(startIndex) + "" and "" + str(endIndex) + + "" = "" + str(query(BOP, BCP, startIndex, + endIndex))) + startIndex = 1; + endIndex = 5; + print(""Maximum Length Correct "" + + ""Bracket Subsequence between "" + + str(startIndex) + "" and "" + str(endIndex) + + "" = "" + str(query(BOP, BCP, startIndex, + endIndex))); + +# This code is contributed by rutvik_56.",linear,linear +"# Function to find Maximum length of consecutive 1's in a binary string + +def maxConsecutive1(input): + # input.split('0') --> splits all sub-strings of consecutive 1's + # separated by 0's, output will be like ['11','1111','1','1','111'] + # map(len,input.split('0')) --> map function maps len function on each + # sub-string of consecutive 1's + # max() returns maximum element from a list + print max(map(len,input.split('0'))) + +# Driver program +if __name__ == ""__main__"": + input = '11000111101010111' + maxConsecutive1(input)",constant,linear +"# Function to print common characters of two Strings +# in alphabetical order +from collections import Counter + +def common(str1,str2): + + # convert both strings into counter dictionary + dict1 = Counter(str1) + dict2 = Counter(str2) + + # take intersection of these dictionaries + commonDict = dict1 & dict2 + + if len(commonDict) == 0: + print (-1) + return + + # get a list of common elements + commonChars = list(commonDict.elements()) + + # sort list in ascending order to print resultant + # string on alphabetical order + commonChars = sorted(commonChars) + + # join characters without space to produce + # resultant string + print (''.join(commonChars)) + +# Driver program +if __name__ == ""__main__"": + str1 = 'geeks' + str2 = 'forgeeks' + common(str1, str2)",linear,linear +"# Function Generate two output strings depending upon +# occurrence of character in input string + +from collections import Counter + +def generateStrings(input): + + # convert string into dictionary + # having characters as keys and frequency as value + freqDict = Counter(input) + + # separate out characters having frequency 1 and more than 1 + freq1 = [ key for (key,count) in freqDict.items() if count==1] + freqMore1 = [ key for (key,count) in freqDict.items() if count>1] + + # sort lists and concatenate characters + # with out space to print resultant strings + freq1.sort() + freqMore1.sort() + + # print output strings + print ('String with characters occurring once:') + print (''.join(freq1)) + print ('String with characters occurring multiple times:') + print (''.join(freqMore1)) + +# Driver program +if __name__ == ""__main__"": + input = ""geeksforgeeks"" + generateStrings(input)",linear,nlogn +"# function to mirror characters of a string + +def mirrorChars(input,k): + + # create dictionary + original = 'abcdefghijklmnopqrstuvwxyz' + reverse = 'zyxwvutsrqponmlkjihgfedcba' + dictChars = dict(zip(original,reverse)) + + # separate out string after length k to change + # characters in mirror + prefix = input[0:k-1] + suffix = input[k-1:] + mirror = '' + + # change into mirror + for i in range(0,len(suffix)): + mirror = mirror + dictChars[suffix[i]] + + # concat prefix and mirrored part + print (prefix+mirror) + +# Driver program +if __name__ == ""__main__"": + input = 'paradox' + k = 3 + mirrorChars(input,k)",linear,linear +"# Function to change string to a new character + +def newString(charSet,input): + + # map original character set of english + # onto new character set given + origCharSet = 'abcdefghijklmnopqrstuvwxyz' + mapChars = dict(zip(charSet,origCharSet)) + + # iterate through original string and get + # characters of original character set + changeChars = [mapChars[chr] for chr in input] + + # join characters without space to get new string + print (''.join(changeChars)) + +# Driver program +if __name__ == ""__main__"": + charSet = 'qwertyuiopasdfghjklzxcvbnm' + input = 'utta' + newString(charSet,input)",linear,linear +"# python program to print initials of a name +def name(s): + + # split the string into a list + l = s.split() + new = """" + + # traverse in the list + for i in range(len(l)-1): + s = l[i] + + # adds the capital first character + new += (s[0].upper()+'.') + + # l[-1] gives last item of list l. We + # use title to print first character in + # capital. + new += l[-1].title() + + return new + +# Driver code +s =""mohandas karamchand gandhi"" +print(name(s)) ",linear,linear +"# Python code to find if we can make first string +# from second by deleting some characters from +# second and rearranging remaining characters. +from collections import Counter + +def makeString(str1,str2): + + # convert both strings into dictionaries + # output will be like str1=""aabbcc"", + # dict1={'a':2,'b':2,'c':2} + # str2 = 'abbbcc', dict2={'a':1,'b':3,'c':2} + dict1 = Counter(str1) + dict2 = Counter(str2) + + # take intersection of two dictionaries + # output will be result = {'a':1,'b':2,'c':2} + result = dict1 & dict2 + + # compare resultant dictionary with first + # dictionary comparison first compares keys + # and then compares their corresponding values + return result == dict1 + +# Driver program +if __name__ == ""__main__"": + str1 = 'ABHISHEKsinGH' + str2 = 'gfhfBHkooIHnfndSHEKsiAnG' + if (makeString(str1,str2)==True): + print(""Possible"") + else: + print(""Not Possible"")",constant,linear +"# import from string all ascii_lowercase and asc_lower +from string import ascii_lowercase as asc_lower + +# function to check if all elements are present or not +def check(s): + return set(asc_lower) - set(s.lower()) == set([]) + +# driver code +string =""The quick brown fox jumps over the lazy dog"" +if(check(string)== True): + print(""The string is a pangram"") +else: + print(""The string isn't a pangram"")",constant,linear +"# Python program to Count all +# prefixes in given string with +# greatest frequency + +# Function to print the prefixes +def prefix(string1, alphabet1, alphabet2): + count = 0 + non_empty_string = """" + + string2 = list(string1) + + # Loop for iterating the length of + # the string and print the prefixes + # and the count of query prefixes. + for i in range(0, len(string2)): + non_empty_string = non_empty_string + (string2[i]) + + if (non_empty_string.count(alphabet1) > + non_empty_string.count(alphabet2)): + + # prints all required prefixes + print(non_empty_string) + + # increment count + count += 1 + + # returns count of the + # required prefixes + return(count) + +# Driver Code +print(prefix(""geeksforgeeks"", ""e"", ""g""))",linear,linear +"# Function to Check if both halves of +# the string have same set of characters +from collections import Counter + +def checkTwoHalves(input): + + length = len(input) + + # Break input string in two parts + if (length % 2 != 0): + first = input[0:length // 2] + second = input[(length // 2) + 1:] + else: + first = input[0:length // 2] + second = input[length // 2:] + + # Convert both halves into dictionary and compare + if Counter(first) == Counter(second): + print ('YES') + else: + print ('NO') + +# Driver program +if __name__ == ""__main__"": + input = 'abbaab' + checkTwoHalves(input)",linear,linear +"# Function to concatenated string with uncommon +# characters of two strings + +def uncommonConcat(str1, str2): + + # convert both strings into set + set1 = set(str1) + set2 = set(str2) + + # take intersection of two sets to get list of + # common characters + common = list(set1 & set2) + + # separate out characters in each string + # which are not common in both strings + result = [ch for ch in str1 if ch not in common] + [ch for ch in str2 if ch not in common] + + # join each character without space to get + # final string + print( ''.join(result) ) + +# Driver program +if __name__ == ""__main__"": + str1 = 'aacdb' + str2 = 'gafd' + uncommonConcat(str1,str2)",linear,linear +"# Function to concatenated string with uncommon +# characters of two strings + +def uncommonConcat(str1, str2): + + # convert both strings into set + set1 = set(str1) + set2 = set(str2) + + # Performing symmetric difference operation of set + # to pull out uncommon characters + uncommon = list(set1 ^ set2) + + # join each character without space to get + # final string + print( ''.join(uncommon) ) + +# Driver program +if __name__ == ""__main__"": + str1 = 'aacdb' + str2 = 'gafd' + uncommonConcat(str1,str2)",linear,linear +"# Python code to print Second most repeated +# word in a sequence in Python +from collections import Counter + + +def secondFrequent(input): + + # Convert given list into dictionary + # it's output will be like {'ccc':1,'aaa':3,'bbb':2} + dict = Counter(input) + + # Get the list of all values and sort it in ascending order + value = sorted(dict.values(), reverse=True) + + # Pick second largest element + secondLarge = value[1] + + # Traverse dictionary and print key whose + # value is equal to second large element + for (key, val) in dict.items(): + if val == secondLarge: + print(key) + return + + +# Driver program +if __name__ == ""__main__"": + input = ['aaa', 'bbb', 'ccc', 'bbb', 'aaa', 'aaa'] + secondFrequent(input)",linear,nlogn +"# returns the second most repeated word +from collections import Counter +class Solution: + def secFrequent(self, arr, n): + all_freq = dict(Counter(arr)) + store = [] + for w in sorted(all_freq, key=all_freq.get): + # if add key=all_freq.get will sort according to values + # without key=all_freq.get will sort according to keys + if w not in store: + store.append(w) + + return store[-2] +# driver code or main function +if __name__ == '__main__': + # no. of test cases + t = 1 + for _ in range(t): + # no of words + n = 7 + # String of words + arr = [""cat"",""mat"",""cat"",""mat"",""cat"",'ball',""tall""] + ob = Solution() + ans = ob.secFrequent(arr,n) + print(ans)",linear,nlogn +"import re + +def putSpace(input): + + # regex [A-Z][a-z]* means any string starting + # with capital character followed by many + # lowercase letters + words = re.findall('[A-Z][a-z]*', input) + + # Change first letter of each word into lower + # case + for i in range(0,len(words)): + words[i]=words[i][0].lower()+words[i][1:] + print(' '.join(words)) + + +# Driver program +if __name__ == ""__main__"": + input = 'BruceWayneIsBatman' + putSpace(input)",linear,linear +"def checkEmpty(input, pattern): + + # If both are empty + if len(input)== 0 and len(pattern)== 0: + return 'true' + + # If only pattern is empty + if len(pattern)== 0: + return 'true' + + while (len(input) != 0): + + # find sub-string in main string + index = input.find(pattern) + + # check if sub-string founded or not + if (index ==(-1)): + return 'false' + + # slice input string in two parts and concatenate + input = input[0:index] + input[index + len(pattern):] + return 'true' + +# Driver program +if __name__ == ""__main__"": + input ='GEEGEEKSKS' + pattern ='GEEKS' + print (checkEmpty(input, pattern))",constant,linear +"# Python code +# To reverse words in a given string + +# input string +string = ""geeks quiz practice code"" +# reversing words in a given string +s = string.split()[::-1] +l = [] +for i in s: + # apending reversed words to l + l.append(i) +# printing reverse words +print("" "".join(l))",linear,linear +"# Function to reverse words of string + +def rev_sentence(sentence): + + # first split the string into words + words = sentence.split(' ') + + # then reverse the split string list and join using space + reverse_sentence = ' '.join(reversed(words)) + + # finally return the joined string + return reverse_sentence + +if __name__ == ""__main__"": + input = 'geeks quiz practice code' + print (rev_sentence(input))",linear,linear +"# Function to reverse words of string +import re +def rev_sentence(sentence): + + # find all the words in sentence + words = re.findall('\w+', sentence) + + # Backward iterate over list of words and join using space + reverse_sentence = ' '.join(words[i] for i in range(len(words)-1, -1, -1)) + + # finally return the joined string + return reverse_sentence + +if __name__ == ""__main__"": + input = 'geeks quiz practice code' + print (rev_sentence(input))",linear,linear +"# Python code for run length encoding +from collections import OrderedDict +def runLengthEncoding(input): + + # Generate ordered dictionary of all lower + # case alphabets, its output will be + # dict = {'w':0, 'a':0, 'd':0, 'e':0, 'x':0} + dict=OrderedDict.fromkeys(input, 0) + + # Now iterate through input string to calculate + # frequency of each character, its output will be + # dict = {'w':4,'a':3,'d':1,'e':1,'x':6} + for ch in input: + dict[ch] += 1 + + # now iterate through dictionary to make + # output string from (key,value) pairs + output = '' + for key,value in dict.items(): + output = output + key + str(value) + return output + +# Driver function +if __name__ == ""__main__"": + input=""wwwwaaadexxxxxx"" + print (runLengthEncoding(input))",linear,linear +"def encode(message): + encoded_message = """" + i = 0 + + while (i <= len(message)-1): + count = 1 + ch = message[i] + j = i + while (j < len(message)-1): + if (message[j] == message[j+1]): + count = count+1 + j = j+1 + else: + break + encoded_message=encoded_message+str(count)+ch + i = j+1 + return encoded_message + +#Provide different values for message and test your program +encoded_message=encode(""ABBBBCCCCCCCCAB"") +print(encoded_message)",constant,quadratic +"# Python code to check if two strings are +# anagram +from collections import Counter + +def anagram(input1, input2): + + # Counter() returns a dictionary data + # structure which contains characters + # of input as key and their frequencies + # as it's corresponding value + return Counter(input1) == Counter(input2) + +# Driver function +if __name__ == ""__main__"": + input1 = 'abcd' + input2 = 'dcab' + print anagram(input1, input2)",constant,linear +"# Recursive Program to remove consecutive +# duplicates from string S. + + +def removeConsecutiveDuplicates(s): + if len(s) < 2: + return s + if s[0] != s[1]: + return s[0]+removeConsecutiveDuplicates(s[1:]) + return removeConsecutiveDuplicates(s[1:]) + + +# This code is contributed by direwolf707 +s1 = 'geeksforgeeks' +print(removeConsecutiveDuplicates(s1)) # geksforgeks +s2 = 'aabcca' +print(removeConsecutiveDuplicates(s2)) # ab + +# This code is contributed by rahulsood707.",constant,quadratic +"# Python3 program to remove consecutive +# duplicates from a given string. + +# A iterative function that removes +# consecutive duplicates from string S + + +def removeDuplicates(S): + + n = len(S) + + # We don't need to do anything for + # empty or single character string. + if (n < 2): + return + + # j is used to store index is result + # string (or index of current distinct + # character) + j = 0 + + # Traversing string + for i in range(n): + + # If current character S[i] + # is different from S[j] + if (S[j] != S[i]): + j += 1 + S[j] = S[i] + + # Putting string termination + # character. + j += 1 + S = S[:j] + return S + + +# Driver Code +if __name__ == '__main__': + + S1 = ""geeksforgeeks"" + S1 = list(S1.rstrip()) + S1 = removeDuplicates(S1) + print(*S1, sep="""") + + S2 = ""aabcca"" + S2 = list(S2.rstrip()) + S2 = removeDuplicates(S2) + print(*S2, sep="""") + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",constant,linear +"# Python program to find smallest +# number to find smallest number +# with N as sum of digits and +# divisible by 10^N. + +import math +def digitsNum(N): + + # If N = 0 the string will be 0 + if (N == 0) : + print(""0"", end = """") + + # If n is not perfectly divisible + # by 9 output the remainder + if (N % 9 != 0): + print (N % 9, end ="""") + + # Print 9 N/9 times + for i in range( 1, int(N / 9) + 1) : + print(""9"", end = """") + + # Append N zero's to the number so + # as to make it divisible by 10^N + for i in range(1, N + 1) : + print(""0"", end = """") + + print() + + +# Driver Code +N = 5 +print(""The number is : "",end="""") +digitsNum(N) + +# This code is contributed by Gitanjali.",constant,linear +"# Python3 program to find min sum of +# squares of characters after k removals +from queue import PriorityQueue + +MAX_CHAR = 26 + +# Main Function to calculate min sum of +# squares of characters after k removals +def minStringValue(str, k): + l = len(str) # find length of string + + # if K is greater than length of string + # so reduced string will become 0 + if(k >= l): + return 0 + + # Else find Frequency of each + # character and store in an array + frequency = [0] * MAX_CHAR + for i in range(0, l): + frequency[ord(str[i]) - 97] += 1 + + # Push each char frequency negative + # into a priority_queue as the queue + # by default is minheap + q = PriorityQueue() + for i in range(0, MAX_CHAR): + q.put(-frequency[i]) + + # Removal of K characters + while(k > 0): + + # Get top element in priority_queue + # multiply it by -1 as temp is negative + # remove it. Increment by 1 and again + # push into priority_queue + temp = q.get() + temp = temp + 1 + q.put(temp, temp) + k = k - 1 + + # After removal of K characters find + # sum of squares of string Value + result = 0; # initialize result + while not q.empty(): + temp = q.get() + temp = temp * (-1) + result += temp * temp + return result + +# Driver Code +if __name__ == ""__main__"": + str = ""abbccc"" + k = 2 + print(minStringValue(str, k)) + + str = ""aaab"" + k = 2 + print(minStringValue(str, k)) + +# This code is contributed +# by Sairahul Jella",constant,nlogn +"# Python program to find min sum of squares +# of characters after k removals +MAX_CHAR = 26 + +# Main Function to calculate min sum of +# squares of characters after k removals + +def minStringValue(str, k): + + alphabetCount =[] + for i in range(MAX_CHAR): + alphabetCount.append(0) + + # Here the array stored frequency the number of + # occurrences in string m[frequency]=number of alphabets + # with frequency i.e, in our example abbccc m[1]=1(1 + # a's occur),m[2]=1(2 b's occur),m[3]=1(3 c'soccur) + m = [] + for i in range(len(str)): + m.append(0) + + for i in range(len(str)): + alphabetCount[ord(str[i]) - ord('a')] += 1 + + # Store the maximum + maximum = 0 + + for i in range(MAX_CHAR): + m[alphabetCount[i]] += 1 + maximum = max(maximum, alphabetCount[i]) + + while (k > 0): + z = m[maximum] + if z <= k: + # Remove one occurrence of alphabet from each + # with frequency as maximum. + # So we will have k-z more remove operations to + # perform as z is number of characters and we + # perform one removal from each of the alphabet + # with that frequency. + k = k - z + # As we removed one occurrence from each the + # alphabets will no longer have the frequency + # of maximum their frequency will be decreased + # by one so add these number of alphabets to + # group with frequency one less than maximum. + # Remove them from maximum count. + m[maximum] = 0 + # Add those to frequency one less. + m[maximum - 1] += z + # new maximum will be one less. + maximum -= 1 + + else: + # if all the elements of that frequency cannot + # be removed we should partially remove them. + m[maximum] -= k + maximum -= 1 + m[maximum] += k + k = 0 + + ans = 0 + for i in range(len(str)): + # (square of frequency)*(number of + # characters corresponding to that frequency) + ans = ans + (i * i) * m[i] + + return ans + +# Driver Code +str = ""abbccc"" # Input 1 +k = 2 + +print(minStringValue(str, k)) + +str = ""aaab"" # Input 2 +k = 2 +print(minStringValue(str, k)) + + +# This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear +"# Python3 program to find maximum +# and minimum possible sums of +# two numbers that we can get if +# replacing digit from 5 to 6 +# and vice versa are allowed. + + +# Find new value of x after +# replacing digit ""from"" to ""to"" +def replaceDig(x, from1, to): + result = 0 + multiply = 1 + + while (x > 0): + reminder = x % 10 + + # Required digit found, + # replace it + if (reminder == from1): + result = result + to * multiply + + else: + result = result + reminder * multiply + + multiply *= 10 + x = int(x / 10) + return result + +# Returns maximum and minimum +# possible sums of x1 and x2 +# if digit replacements are allowed. +def calculateMinMaxSum(x1, x2): + + # We always get minimum sum + # if we replace 6 with 5. + minSum = replaceDig(x1, 6, 5) +replaceDig(x2, 6, 5) + + # We always get maximum sum + # if we replace 5 with 6. + maxSum = replaceDig(x1, 5, 6) +replaceDig(x2, 5, 6) + print(""Minimum sum ="" , minSum) + print(""Maximum sum ="" , maxSum,end="" "") + +# Driver code +if __name__=='__main__': + x1 = 5466 + x2 = 4555 + calculateMinMaxSum(x1, x2) + +# This code is contributed +# by mits",constant,logn +"# Python code for the above approach + +# this is function for finding sum of two +# numbers as string +def string_sum(str1, str2): + + if (len(str1) < len(str2)): + str1, str2 = str2,str1 + + m = len(str1) + n = len(str2) + ans = """" + + # sum the str2 with str1 + carry = 0 + for i in range(n): + + # Sum of current digits + ds = ((ord(str1[m - 1 - i]) - ord('0')) + + (ord(str2[n - 1 - i]) - ord('0')) + + carry) % 10 + + carry = ((ord(str1[m - 1 - i]) - ord('0')) + + (ord(str2[n - 1 - i]) - ord('0')) + + carry) // 10 + + ans = str(ds) + ans + + for i in range(n,m): + ds = (ord(str1[m - 1 - i]) - ord('0') + + carry) % 10 + carry = (ord(str1[m - 1 - i]) - ord('0') + + carry) // 10 + ans = str(ds) + ans + + if (carry): + ans = str(carry) + ans + return ans + +# Returns True if two substrings of given +# lengths of str[beg..] can cause a positive +# result. +def checkSumStrUtil(Str, beg,len1, len2): + + # Finding two substrings of given lengths + # and their sum + s1 = Str[beg: beg+len1] + s2 = Str[beg + len1: beg + len1 +len2] + s3 = string_sum(s1, s2) + + s3_len = len(s3) + + # if number of digits s3 is greater than + # the available string size + if (s3_len > len(Str) - len1 - len2 - beg): + return False + + # we got s3 as next number in main string + if (s3 == Str[beg + len1 + len2: beg + len1 + len2 +s3_len]): + + # if we reach at the end of the string + if (beg + len1 + len2 + s3_len == len(Str)): + return True + + # otherwise call recursively for n2, s3 + return checkSumStrUtil(Str, beg + len1, len2,s3_len) + + # we do not get s3 in main string + return False + +# Returns True if str is sum string, else False. +def isSumStr(Str): + + n = len(Str) + + # choosing first two numbers and checking + # whether it is sum-string or not. + for i in range(1,n): + for j in range(1,n-i): + if (checkSumStrUtil(Str, 0, i, j)): + return True + + return False + + +# Driver code +print(isSumStr(""1212243660"")) +print(isSumStr(""123456787"")) + +# This code is contributed by shinjanpatra",linear,cubic +"# Python program to find maximum value + +# Function to calculate the value +def calcMaxValue(str): + + # Store first character as integer + # in result + res = ord(str[0]) - 48 + + # Start traversing the string + for i in range(1, len(str)): + + # Check if any of the two numbers + # is 0 or 1, If yes then add current + # element + if(str[i] == '0' or + str[i] == '1' or res < 2): + res += ord(str[i]) - 48 + else: + res *= ord(str[i]) - 48 + + return res + +# Driver code +if __name__== ""__main__"": + str = ""01891""; + print(calcMaxValue(str)); + +# This code is contributed by Sairahul Jella",constant,linear +"# Python3 program to find the maximum segment +# value after putting k breaks. + +# Function to Find Maximum Number +def findMaxSegment(s, k): + + # Maximum segment length + seg_len = len(s) - k + + # Find value of first segment of seg_len + res = 0 + for i in range(seg_len): + res = res * 10 + (ord(s[i]) - ord('0')) + + # Find value of remaining segments + # using sliding window + seg_len_pow = pow(10, seg_len - 1) + curr_val = res + for i in range(1, len(s) - seg_len): + + # To find value of current segment, + # first remove leading digit from + # previous value + curr_val = curr_val - (ord(s[i - 1])- + ord('0')) * seg_len_pow + + # Then add trailing digit + curr_val = (curr_val * 10 + + (ord(s[i + seg_len - 1]) - ord('0'))) + + res = max(res, curr_val) + return res + +# Driver Code +if __name__ == '__main__': + s = ""8754"" + k = 2 + print(""Maximum number = "", + findMaxSegment(s, k)) + +# This code is contributed by PranchalK",constant,linear +"# Python 3 program to find +# if a number is divisible +# by 4 or not + +# Function to find that +# number divisible by +# 4 or not +def check(st): + n = len(st) + + # Empty string + if (n == 0): + return False + + # int(string_variable) is used in Python3 + # to convert string to integer + + # If there is single + # digit + if (n == 1): + return (int(st) % 4 == 0) + + # slicing of strings is used in Python to function as substring + st = st[n-2:] + # If number formed by + # last two digits is + # divisible by 4. + return (int(st) % 4 == 0) + + +# Driver code +st = ""76952"" + +# Function call +if(check(st)): + print(""Yes"") +else: + print(""No "") + +# This code is contributed by Abhijeet Kumar(abhijeet19403)",constant,constant +"# Python3 program to calculate number +# of substring + +# Return the number of substring divisible +# by 6 and starting at index i in s[] and +# previous sum of digits modulo 3 is m. +def f(i, m, s, memoize): + + # End of the string. + if (i == len(s)): + return 0 + + # If already calculated, return + # the stored value. + if (memoize[i][m] != -1): + return memoize[i][m] + + # Converting into integer. + x = ord(s[i]) - ord('0') + + # Increment result by 1, if current digit + # is divisible by 2 and sum of digits is + # divisible by 3. + # And recur for next index with new modulo. + ans = (((x + m) % 3 == 0 and x % 2 == 0) + + f(i + 1, (m + x) % 3, s, memoize)) + + memoize[i][m] = ans + return memoize[i][m] + +# Returns substrings divisible by 6. +def countDivBy6(s): + n = len(s) + + # For storing the value of all states. + memoize = [[-1] * 3 for i in range(n + 1)] + + ans = 0 + for i in range(len(s)): + + # If string contain 0, increment + # count by 1. + if (s[i] == '0'): + ans += 1 + + # Else calculate using recursive function. + # Pass previous sum modulo 3 as 0. + else: + ans += f(i, 0, s, memoize) + + return ans + +# Driver Code +if __name__ == '__main__': + s = ""4806"" + + print(countDivBy6(s)) + +# This code is contributed by PranchalK",linear,linear +"# Python3 implementation to check whether +# decimal representation of given binary +# number is divisible by 5 or not + +# function to return equivalent base 4 +# number of the given binary number +def equivalentBase4(bin): + if(bin == ""00""): + return 0 + if(bin == ""01""): + return 1 + if(bin == ""10""): + return 2 + if(bin == ""11""): + return 3 + +# function to check whether the given +# binary number is divisible by 5 or not +def isDivisibleBy5(bin): + l = len(bin) + if((l % 2) == 1): + + # add '0' in the beginning to + # make length an even number + bin = '0' + bin + + # to store sum of digits at odd + # and even places respectively + odd_sum = 0 + even_sum = 0 + isOddDigit = 1 + for i in range(0, len(bin), 2): + + # if digit of base 4 is at odd place, + # then add it to odd_sum + if(isOddDigit): + odd_sum += equivalentBase4(bin[i:i + 2]) + + # else digit of base 4 is at + # even place, add it to even_sum + else: + even_sum += equivalentBase4(bin[i:i + 2]) + + isOddDigit = isOddDigit ^ 1 + + # if this diff is divisible by 11(which is + # 5 in decimal) then, the binary number is + # divisible by 5 + if(abs(odd_sum - even_sum) % 5 == 0): + return ""Yes"" + else: + return ""No"" + +# Driver Code +if __name__==""__main__"": + bin = ""10000101001"" + print(isDivisibleBy5(bin)) + +# This code is contributed +# by Sairahul Jella",constant,linear +"# Python3 Program to count substrings +# which are divisible by 8 but not by 3 + +# Returns count of substrings +# divisible by 8 but not by 3. +def count(s, Len): + global MAX + cur = 0 + dig = 0 + Sum = [0] * MAX + dp = [[0, 0, 0] for i in range(MAX)] + + dp[0][0] = 1 + + # Iterating the string. + for i in range(1, Len + 1): + dig = int(s[i - 1]) - 48 + cur += dig + cur %= 3 + + Sum[i] = cur + + # Prefix sum of number of substrings + # whose sum of digits modulo 3 is + # 0, 1, 2. + dp[i][0] = dp[i - 1][0] + dp[i][1] = dp[i - 1][1] + dp[i][2] = dp[i - 1][2] + + dp[i][Sum[i]] += 1 + + ans = 0 + dprev = 0 + value = 0 + dprev2 = 0 + + # Iterating the string. + for i in range(1, Len + 1): + dig = int(s[i - 1]) - 48 + + # Since single digit 8 is + # divisible by 8 and not by 3. + if dig == 8: + ans += 1 + + # Taking two digit number. + if i - 2 >= 0: + dprev = int(s[i - 2]) - 48 # 10th position + value = dprev * 10 + dig # Complete 2 digit + # number + + if (value % 8 == 0) and (value % 3 != 0): + ans += 1 + + # Taking 3 digit number. + if i - 3 >= 0: + dprev2 = int(s[i - 3]) - 48 # 100th position + dprev = int(s[i - 2]) - 48 # 10th position + + # Complete 3 digit number. + value = (dprev2 * 100 + + dprev * 10 + dig) + + if value % 8 != 0: + continue + + # If number formed is divisible by 8 + # then last 3 digits are also divisible + # by 8. Then all the substring ending + # at this index are divisible. + ans += (i - 2) + + # But those substring also contain + # number which are not divisible + # by 3 so remove them. + ans -= (dp[i - 3][Sum[i]]) + + return ans + +# Driver Code +MAX = 1000 +Str = ""6564525600"" +Len = len(Str) +print(count(Str, Len)) + +# This code is contributed +# by PranchalK",linear,linear +"# Python3 program for divisibility +# of number by 999 + +# function to check divisibility +def isDivisible999(num): + n = len(num); + if(n == 0 or num[0] == '0'): + return true + + # Append required 0s at the beginning. + if((n % 3) == 1): + num = ""00"" + num + if((n % 3) == 2): + num = ""0"" + num + + # add digits in group of three in gSum + gSum = 0 + for i in range(0, n, 3): + + # group saves 3-digit group + group = 0 + group += (ord(num[i]) - 48) * 100 + group += (ord(num[i + 1]) - 48) * 10 + group += (ord(num[i + 2]) - 48) + gSum += group + + # calculate result till 3 digit sum + if(gSum > 1000): + num = str(gSum) + n = len(num) + gSum = isDivisible999(num) + return (gSum == 999) + +# Driver code +if __name__==""__main__"": + num = ""1998"" + n = len(num) + if(isDivisible999(num)): + print(""Divisible"") + else: + print(""Not divisible"") + +# This code is contributed +# by Sairahul Jella",constant,linear +"# Python3 program to implement division +# with large number +import math + +# A function to perform division of +# large numbers +def longDivision(number, divisor): + + # As result can be very large + # store it in string + ans = """"; + + # Find prefix of number that + # is larger than divisor. + idx = 0; + temp = ord(number[idx]) - ord('0'); + while (temp < divisor): + temp = (temp * 10 + ord(number[idx + 1]) - + ord('0')); + idx += 1; + + idx += 1; + + # Repeatedly divide divisor with temp. + # After every division, update temp to + # include one more digit. + while ((len(number)) > idx): + + # Store result in answer i.e. temp / divisor + ans += chr(math.floor(temp // divisor) + ord('0')); + + # Take next digit of number + temp = ((temp % divisor) * 10 + ord(number[idx]) - + ord('0')); + idx += 1; + + ans += chr(math.floor(temp // divisor) + ord('0')); + + # If divisor is greater than number + if (len(ans) == 0): + return ""0""; + + # else return ans + return ans; + +# Driver Code +number = ""1248163264128256512""; +divisor = 125; +print(longDivision(number, divisor)); + +# This code is contributed by mits",linear,np +"# Python3 program to find remainder of +# a large number when divided by 7. + +# Function which return Remainder +# after dividing the number by 7 +def remainderWith7(num): + + # This series is used to + # find remainder with 7 + series = [1, 3, 2, -1, -3, -2]; + + # Index of next element + # in series + series_index = 0; + + # Initialize result + result = 0; + + # Traverse num from end + for i in range((len(num) - 1), -1, -1): + + # Find current digit of num + digit = ord(num[i]) - 48; + + # Add next term to result + result += digit * series[series_index]; + + # Move to next term in series + series_index = (series_index + 1) % 6; + + # Make sure that result + # never goes beyond 7. + result %= 7; + + # Make sure that remainder + # is positive + + if (result < 0): + result = (result + 7) % 7; + return result; + +# Driver Code +str = ""12345""; +print(""Remainder with 7 is"", + remainderWith7(str)); + +# This code is contributed by mits",constant,linear +"# A simple Python3 code +# to check for even or odd + +# Returns true if n is even, else odd +def isEven(n): + return (n % 2 == 0) + +# Driver code +n = 101 +print(""Even"" if isEven(n) else ""Odd"") + +# This code is contributed by ""Sharad_Bhardwaj"".",constant,constant +"# A Python3 code program +# to check for even or odd + +# Returns true if n is even, else odd +def isEven(n): + + # n&1 is 1, then odd, else even + return (not(n & 1)) + +# Driver code +n = 101; +print(""Even"" if isEven(n) else ""Odd"") + +# This code is contributed by ""Sharad_Bhardwaj"".",constant,constant +"# Python 3 implementation +# to find product of +# digits of elements +# at k-th level + +# Function to find +# product of digits +# of elements at +# k-th level +def productAtKthLevel(tree, k): + + level = -1 + + # Initialize result + product = 1 + n = len(tree) + + for i in range(0, n): + + # increasing level number + if (tree[i] == '('): + level+=1 + + # decreasing level number + elif (tree[i] == ')'): + level-=1 + + else: + # check if current level is + # the desired level or not + if (level == k): + product *= (int(tree[i]) - int('0')) + + + + # required product + return product + + +# Driver program +tree = ""(0(5(6()())(4()(9()())))(7(1()())(3()())))"" +k = 2 + +print(productAtKthLevel(tree, k)) + +# This code is contributed by +# Smitha Dinesh Semwal",constant,linear +"# Python 3 implementation to find remainder +# when a large number is divided by 11 + +# Function to return remainder +def remainder(st) : + + # len is variable to store the + # length of number string. + ln = len(st) + + rem = 0 + + # loop that find remainder + for i in range(0, ln) : + num = rem * 10 + (int)(st[i]) + rem = num % 11 + + return rem + + +# Driver code +st = ""3435346456547566345436457867978"" +print(remainder(st)) + + +# This code is contributed by Nikita Tiwari.",constant,linear +"# Python 3 program to count number of +# ways to remove an element so that +# XOR of remaining string becomes 0. + +# Return number of ways in which XOR +# become ZERO by remove 1 element +def xorZero(str): + one_count = 0 + zero_count = 0 + n = len(str) + + # Counting number of 0 and 1 + for i in range(0, n, 1): + if (str[i] == '1'): + one_count += 1 + else: + zero_count += 1 + + # If count of ones is even + # then return count of zero + # else count of one + if (one_count % 2 == 0): + return zero_count + return one_count + +# Driver Code +if __name__ == '__main__': + str = ""11111"" + print(xorZero(str)) + +# This code is contributed by +# Surendra_Gangwar",constant,linear +"# 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.",constant,quadratic +"""""""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< count_vowels): + hard_words += 1 + else: + easy_words += 1 + + # Reset all counts + count_conso = 0 + count_vowels = 0 + consec_conso = 0 + + # Return difficulty of sentence + return (5 * hard_words + 3 * easy_words) + +# Driver Code +if __name__==""__main__"": + str = ""I am a geek"" + str2 = ""We are geeks"" + print(calcDiff(str)) + print(calcDiff(str2)) + +# This code is contributed +# by Sairahul Jella",constant,linear +"# Function to print common strings +# with minimum index sum +def find(list1, list2): + res = [] # resultant list + max_possible_sum = len(list1) + len(list2) - 2 + + # iterating over sum in ascending order + for sum in range(max_possible_sum + 1): + + # iterating over one list and check index + # (Corresponding to given sum) in other list + for i in range(sum + 1): + + # put common strings in resultant list + if (i < len(list1) and + (sum - i) < len(list2) and + list1[i] == list2[sum - i]): + res.append(list1[i]) + + # if common string found then break as we are + # considering index sums in increasing order. + if (len(res) > 0): + break + + # print the resultant list + for i in range(len(res)): + print(res[i], end = "" "") + +# Driver code + +# Creating list1 +list1 = [] +list1.append(""GeeksforGeeks"") +list1.append(""Udemy"") +list1.append(""Coursera"") +list1.append(""edX"") + +# Creating list2 +list2 = [] +list2.append(""Codecademy"") +list2.append(""Khan Academy"") +list2.append(""GeeksforGeeks"") + +find(list1, list2) + +# This code is contributed by Mohit Kumar",linear,linear +"# Hashing based Python3 program to find +# common elements with minimum index sum +import sys + +# Function to print common strings +# with minimum index sum +def find(list1, list2): + + # Mapping strings to their indices + Map = {} + for i in range(len(list1)): + Map[list1[i]] = i + + # Resultant list + res = [] + + minsum = sys.maxsize + + for j in range(len(list2)): + if list2[j] in Map: + + # If current sum is smaller + # than minsum + Sum = j + Map[list2[j]] + + if (Sum < minsum): + minsum = Sum + res.clear() + res.append(list2[j]) + + # If index sum is same then put this + # string in resultant list as well + else if (Sum == minsum): + res.append(list2[j]) + + # Print result + print(*res, sep = "" "") + +# Driver code + +# Creating list1 +list1 = [] +list1.append(""GeeksforGeeks"") +list1.append(""Udemy"") +list1.append(""Coursera"") +list1.append(""edX"") + +# Creating list2 +list2 = [] +list2.append(""Codecademy"") +list2.append(""Khan Academy"") +list2.append(""GeeksforGeeks"") +find(list1, list2) + +# This code is contributed by avanitrachhadiya2155",linear,linear +"# Python 3 program to count the uppercase, +# lowercase, special characters +# and numeric values + +# Function to count uppercase, lowercase, +# special characters and numbers +def Count(str): + upper, lower, number, special = 0, 0, 0, 0 + for i in range(len(str)): + if str[i].isupper(): + upper += 1 + else if str[i].islower(): + lower += 1 + else if str[i].isdigit(): + number += 1 + else: + special += 1 + print('Upper case letters:', upper) + print('Lower case letters:', lower) + print('Number:', number) + print('Special characters:', special) + +# Driver Code +str = ""#GeeKs01fOr@gEEks07"" +Count(str) + +# This code is contributed +# by Sushma Reddy",constant,linear +"# Python3 program to find the smallest window +# containing all characters of a pattern. +no_of_chars = 256 + +# Function to find smallest window +# containing all characters of 'pat' +def findSubString(string, pat): + + len1 = len(string) + len2 = len(pat) + + # Check if string's length is + # less than pattern's + # length. If yes then no such + # window can exist + if len1 < len2: + + print(""No such window exists"") + return """" + + hash_pat = [0] * no_of_chars + hash_str = [0] * no_of_chars + + # Store occurrence ofs characters of pattern + for i in range(0, len2): + hash_pat[ord(pat[i])] += 1 + + start, start_index, min_len = 0, -1, float('inf') + + # Start traversing the string + count = 0 # count of characters + for j in range(0, len1): + + # count occurrence of characters of string + hash_str[ord(string[j])] += 1 + + # If string's char matches with + # pattern's char then increment count + if (hash_str[ord(string[j])] <= + hash_pat[ord(string[j])]): + count += 1 + + # if all the characters are matched + if count == len2: + + # Try to minimize the window + while (hash_str[ord(string[start])] > + hash_pat[ord(string[start])] or + hash_pat[ord(string[start])] == 0): + + if (hash_str[ord(string[start])] > + hash_pat[ord(string[start])]): + hash_str[ord(string[start])] -= 1 + start += 1 + + # update window size + len_window = j - start + 1 + if min_len > len_window: + + min_len = len_window + start_index = start + + # If no window found + if start_index == -1: + print(""No such window exists"") + return """" + + # Return substring starting from + # start_index and length min_len + return string[start_index: start_index + min_len] + + +# Driver code +if __name__ == ""__main__"": + + string = ""this is a test string"" + pat = ""tist"" + + print(findSubString(string, pat)) + +# This code is contributed by Rituraj Jain",constant,linear +"''' Python solution ''' + + +def smallestWindow(s, p): + n = len(s) + if n < len(p): + return -1 + mp = [0]*256 + + # Starting index of ans + start = 0 + + # Answer + # Length of ans + ans = n + 1 + cnt = 0 + + # creating map + for i in p: + mp[ord(i)] += 1 + if mp[ord(i)] == 1: + cnt += 1 + + # References of Window + j = 0 + i = 0 + + # Traversing the window + while(j < n): + + # Calculating + mp[ord(s[j])] -= 1 + if mp[ord(s[j])] == 0: + cnt -= 1 + + # Condition matching + while cnt == 0: + if ans > j - i + 1: + + # calculating answer. + ans = j - i + 1 + start = i + + # Sliding I + # Calculation for removing I + mp[ord(s[i])] += 1 + if mp[ord(s[i])] > 0: + cnt += 1 + i += 1 + j += 1 + if ans > n: + return ""-1"" + return s[start:start+ans] + + +# Driver code +if __name__ == ""__main__"": + s = ""this is a test string"" + p = ""tist"" + result = smallestWindow(s, p) + print(result) + + # This code is contributed by cyclades.",constant,linear +"# Python3 program to count number of substrings +# with counts of distinct characters as k. + +MAX_CHAR = 26 + +# Returns true if all values +# in freq[] are either 0 or k. +def check(freq, k): + for i in range(0, MAX_CHAR): + if(freq[i] and freq[i] != k): + return False + return True + +# Returns count of substrings where +# frequency of every present character is k +def substrings(s, k): + res = 0 # Initialize result + + # Pick a starting point + for i in range(0, len(s)): + + # Initialize all frequencies as 0 + # for this starting point + freq = [0] * MAX_CHAR + + # One by one pick ending points + for j in range(i, len(s)): + + # Increment frequency of current char + index = ord(s[j]) - ord('a') + freq[index] += 1 + + # If frequency becomes more than + # k, we can't have more substrings + # starting with i + if(freq[index] > k): + break + + # If frequency becomes k, then check + # other frequencies as well + elif(freq[index] == k and + check(freq, k) == True): + res += 1 + + return res + +# Driver Code +if __name__ == ""__main__"": + s = ""aabbcc"" + k = 2 + print(substrings(s, k)) + + s = ""aabbc""; + k = 2; + print(substrings(s, k)) + +# This code is contributed +# by Sairahul Jella",constant,quadratic +"from collections import defaultdict + + +def have_same_frequency(freq: defaultdict, k: int): + return all([freq[i] == k or freq[i] == 0 for i in freq]) + + +def count_substrings(s: str, k: int) -> int: + count = 0 + distinct = len(set([i for i in s])) + for length in range(1, distinct + 1): + window_length = length * k + freq = defaultdict(int) + window_start = 0 + window_end = window_start + window_length - 1 + for i in range(window_start, min(window_end + 1, len(s))): + freq[s[i]] += 1 + while window_end < len(s): + if have_same_frequency(freq, k): + count += 1 + freq[s[window_start]] -= 1 + window_start += 1 + window_end += 1 + if window_end < len(s): + freq[s[window_end]] += 1 + return count + + +if __name__ == '__main__': + s = ""aabbcc"" + k = 2 + print(count_substrings(s, k)) + s = ""aabbc"" + k = 2 + print(count_substrings(s, k))",linear,quadratic +"# Python 3 program to construct a n +# length string with k distinct characters +# such that no two same characters are adjacent. + +# Function to find a string of length +# n with k distinct characters. +def findString(n, k): + + # Initialize result with first k + # Latin letters + res = """" + for i in range(k): + res = res + chr(ord('a') + i) + + # Fill remaining n-k letters by + # repeating k letters again and again. + count = 0 + for i in range(n - k) : + res = res + chr(ord('a') + count) + count += 1 + if (count == k): + count = 0; + + return res + +# Driver code +if __name__ == ""__main__"": + + n = 5 + k = 2 + print(findString(n, k)) + +# This code is contributed by ita_c",linear,linear +"# Python3 program to count number +# of substrings of a string + +def countNonEmptySubstr(str): + n = len(str); + return int(n * (n + 1) / 2); + +# driver code +s = ""abcde""; +print (countNonEmptySubstr(s)); + +# This code is contributed by +# Manish Shaw (manishshaw1)",constant,constant +"# Python3 program to count distinct strings with +# even odd swapping allowed. +MAX_CHAR = 26 + +# Returns encoding of string that can be used +# for hashing. The idea is to return same encoding +# for strings which can become same after swapping +# a even positioned character with other even characters +# OR swapping an odd character with other odd characters. +def encodeString(string): + + # hashEven stores the count of even indexed character + # for each string hashOdd stores the count of odd + # indexed characters for each string + hashEven = [0] * MAX_CHAR + hashOdd = [0] * MAX_CHAR + + # creating hash for each string + for i in range(len(string)): + c = string[i] + if i & 1: # If index of current character is odd + hashOdd[ord(c) - ord('a')] += 1 + else: + hashEven[ord(c) - ord('a')] += 1 + + # For every character from 'a' to 'z', we store its + # count at even position followed by a separator, + # followed by count at odd position. + encoding = """" + for i in range(MAX_CHAR): + encoding += str(hashEven[i]) + encoding += str('-') + encoding += str(hashOdd[i]) + encoding += str('-') + + return encoding + +# This function basically uses a hashing based set to +# store strings which are distinct according +# to criteria given in question. +def countDistinct(input, n): + countDist = 0 # Initialize result + + # Create an empty set and store all distinct + # strings in it. + s = set() + for i in range(n): + + # If this encoding appears first time, increment + # count of distinct encodings. + if encodeString(input[i]) not in s: + s.add(encodeString(input[i])) + countDist += 1 + + return countDist + +# Driver Code +if __name__ == ""__main__"": + input = [""abcd"", ""acbd"", ""adcb"", + ""cdba"", ""bcda"", ""badc""] + n = len(input) + print(countDistinct(input, n)) + +# This code is contributed by +# sanjeev2552",constant,linear +"# Python 3 program to find K'th character +# in decrypted string + +# Function to find K'th character +# in Encoded String +def encodedChar(str, k): + + # expand string variable is used + # to store final string after + # decompressing string str + expand = """" + + # Current substring + freq = 0 # Count of current substring + i = 0 + while(i < len(str)): + temp = """" # Current substring + freq = 0 # count frequency of current substring + + # read characters until you find + # a number or end of string + while (i < len(str) and + ord(str[i]) >= ord('a') and + ord(str[i]) <= ord('z')): + + # push character in temp + temp += str[i] + i += 1 + + # read number for how many times string temp + # will be repeated in decompressed string + while (i < len(str) and + ord(str[i]) >= ord('1') and + ord(str[i]) <= ord('9')): + + # generating frequency of temp + freq = freq * 10 + ord(str[i]) - ord('0') + i += 1 + + # now append string temp into expand + # equal to its frequency + for j in range(1, freq + 1, 1): + expand += temp + + # this condition is to handle the case + # when string str is ended with alphabets + # not with numeric value + if (freq == 0): + expand += temp + + return expand[k - 1] + +# Driver Code +if __name__ == '__main__': + str = ""ab4c12ed3"" + k = 21 + print(encodedChar(str, k)) + +# This code is contributed by +# Shashank_Sharma",constant,linear +"# Python program to find number of +# characters at same position as +# in English alphabets + +# Function to count the number of +# characters at same position as +# in English alphabets +def findCount(str): + result = 0 + + # Traverse the input string + for i in range(len(str)): + + # Check that index of characters of string is + # same as of English alphabets by using ASCII + # values and the fact that all lower case + # alphabetic characters come together in same + # order in ASCII table. And same is true for + # upper case. + if ((i == ord(str[i]) - ord('a')) or + (i == ord(str[i]) - ord('A'))): + result += 1 + return result + +# Driver Code +str = 'AbgdeF' +print(findCount(str)) + +# This code is contributed +# by SamyuktaSHegde",constant,linear +"# Python 3 program to count words whose ith letter +# is either (i-1)th, ith, or (i+1)th letter +# of given word. + +# Return the count of words. +def countWords( str, l): + + count = 1; + + # If word contain single letter, return 1. + if (l == 1): + return count + + # Checking for first letter. + if (str[0] == str[1]): + count *= 1 + else: + count *= 2 + + # Traversing the string and multiplying + # for combinations. + for j in range(1,l-1): + # If all three letters are same. + if (str[j] == str[j-1] and str[j] == str[j+1]): + count *= 1 + + # If two letter are distinct. + else if (str[j] == str[j-1] or + str[j] == str[j+1] or + str[j-1] == str[j+1]): + count *= 2 + + # If all three letter are distinct. + else: + count *= 3 + + # Checking for last letter. + if (str[l - 1] == str[l - 2]): + count *= 1 + else: + count *= 2 + + return count + +# Driven Program +if __name__ == ""__main__"": + + str = ""abc"" + l = len(str) + + print(countWords(str, l))",constant,linear +"# Python3 program to find Smallest and +# Largest Word in a String + +# defining the method to find the longest +# word and the shortest word +def minMaxLengthWords(inp): + length = len(inp) + si = ei = 0 + min_length = length + min_start_index = max_length = max_start_index = 0 + + # loop to find the length and stating index + # of both longest and shortest words + while ei <= length: + if (ei < length) and (inp[ei] != "" ""): + ei += 1 + else: + curr_length = ei - si + + # condition checking for the shortest word + if curr_length < min_length: + min_length = curr_length + min_start_index = si + + # condition for the longest word + if curr_length > max_length: + max_length = curr_length + max_start_index = si + ei += 1 + si = ei + + # extracting the shortest word using + # it's starting index and length + minWord = inp[min_start_index : + min_start_index + min_length] + + # extracting the longest word using + # it's starting index and length + maxWord = inp[max_start_index : max_length] + + # printing the final result + print(""Minimum length word: "", minWord) + print (""Maximum length word: "", maxWord) + +# Driver Code + +# Using this string to test our code +a = ""GeeksforGeeks A Computer Science portal for Geeks"" +minMaxLengthWords(a) + +# This code is contributed by Animesh_Gupta",linear,linear +" +# Python program to count all substrings with same +# first and last characters. + +# Returns true if first and last characters +# of s are same. +def checkEquality(s): + return (ord(s[0]) == ord(s[len(s) - 1])); + +def countSubstringWithEqualEnds(s): + result = 0; + n = len(s); + + # Starting point of substring + for i in range(n): + + # Length of substring + for j in range(1,n-i+1): + + # Check if current substring has same + # starting and ending characters. + if (checkEquality(s[i:i+j])): + result+=1; + + return result; + +# Driver code +s = ""abcab""; +print(countSubstringWithEqualEnds(s)); + +# This code contributed by PrinciRaj1992",linear,quadratic +"# Space efficient Python3 program to count all +# substrings with same first and last characters. +def countSubstringWithEqualEnds(s): + + result = 0; + n = len(s); + + # Iterating through all substrings in + # way so that we can find first and + # last character easily + for i in range(n): + for j in range(i, n): + if (s[i] == s[j]): + result = result + 1 + + return result + +# Driver Code +s = ""abcab""; +print(countSubstringWithEqualEnds(s)) + +# This code is contributed +# by Akanksha Rai",constant,quadratic +"# Most efficient Python program to count all +# substrings with same first and last characters. + +MAX_CHAR = 26; # assuming lower case only + +def countSubstringWithEqualEnds(s): + result = 0; + n = len(s); + + # Calculating frequency of each character + # in the string. + count = [0]*MAX_CHAR; + for i in range(n): + count[ord(s[i])-ord('a')]+=1; + + # Computing result using counts + for i in range(MAX_CHAR): + result += (count[i]*(count[i]+1)/2); + + return result; + +# Driver code +s = ""abcab""; +print(countSubstringWithEqualEnds(s)); + + +# This code is contributed by 29AjayKumar",constant,linear +"# Python 3 program to count substrings with same +# first and last characters + +# Function to count substrings with same first and +# last characters +def countSubstrs(str, i, j, n): + + # base cases + if (n == 1): + return 1 + if (n <= 0): + return 0 + + res = (countSubstrs(str, i + 1, j, n - 1) + + countSubstrs(str, i, j - 1, n - 1) + - countSubstrs(str, i + 1, j - 1, n - 2)) + + if (str[i] == str[j]): + res += 1 + + return res + +# driver code +str = ""abcab"" +n = len(str) +print(countSubstrs(str, 0, n - 1, n)) + +# This code is contributed by Smitha",linear,np +"# code +def countSubstr(s): + if len(s) == 0: + return 0 + charMap, numSubstr = countSubstrHelper(s, 0, len(s)-1) + return numSubstr + + +def countSubstrHelper(string, start, end): + if start >= end: # our base case for the recursion. When we have one character + return {string[start]: 1}, 1 + mid = (start + end)//2 + mapLeft, numSubstrLeft = countSubstrHelper( + string, start, mid) # solve the left half + mapRight, numSubstrRight = countSubstrHelper( + string, mid+1, end) # solve the right half + # add number of substrings from left and right + numSubstrSelf = numSubstrLeft + numSubstrRight + + # multiply the characters from left set with matching characters from right set + # then add to total number of substrings + for char in mapLeft: + if char in mapRight: + numSubstrSelf += mapLeft[char] * mapRight[char] + + # Add all the key,value pairs from right map to left map + for char in mapRight: + if char in mapLeft: + mapLeft[char] += mapRight[char] + else: + mapLeft[char] = mapRight[char] + # Return the map of character and the sum of substring from left, right and self + return mapLeft, numSubstrSelf + + +print(countSubstr(""abcab"")) + +# Contributed by Xavier Jean Baptiste",linear,nlogn +"# Python 3 program to count number of +# possible strings with n characters. + +# Function to calculate number of strings +def possibleStrings(n, r, b, g): + + # Store factorial of numbers up to n + # for further computation + fact = [0 for i in range(n + 1)] + fact[0] = 1 + for i in range(1, n + 1, 1): + fact[i] = fact[i - 1] * i + + # Find the remaining values to be added + left = n - (r + g + b) + sum = 0 + + # Make all possible combinations of + # R, B and G for the remaining value + for i in range(0, left + 1, 1): + for j in range(0, left - i + 1, 1): + k = left - (i + j) + + # Compute permutation of each + # combination one by one and add them. + sum = (sum + fact[n] / (fact[i + r] * + fact[j + b] * fact[k + g])) + + # Return total no. of + # strings/permutation + return sum + +# Driver code +if __name__ == '__main__': + n = 4 + r = 2 + b = 0 + g = 1 + print(int(possibleStrings(n, r, b, g))) + +# This code is contributed by +# Sanjit_Prasad",linear,quadratic +"# Python 3 program to count number of strings +# of n characters with + +# n is total number of characters. +# bCount and cCount are counts of 'b' +# and 'c' respectively. +def countStrUtil(dp, n, bCount=1,cCount=2): + + # Base cases + if (bCount < 0 or cCount < 0): + return 0 + if (n == 0): + return 1 + if (bCount == 0 and cCount == 0): + return 1 + + # if we had saw this combination previously + if (dp[n][bCount][cCount] != -1): + return dp[n][bCount][cCount] + + # Three cases, we choose, a or b or c + # In all three cases n decreases by 1. + res = countStrUtil(dp, n-1, bCount, cCount) + res += countStrUtil(dp, n-1, bCount-1, cCount) + res += countStrUtil(dp, n-1, bCount, cCount-1) + + dp[n][bCount][cCount] = res + return dp[n][bCount][cCount] + +# A wrapper over countStrUtil() +def countStr(n): + + dp = [ [ [-1 for x in range(2+1)] for y in range(1+1)]for z in range(n+1)] + return countStrUtil(dp, n) + +# Driver code +if __name__ == ""__main__"": + + n = 3 # Total number of characters + print(countStr(n)) + +# This code is contributed by chitranayal ",linear,linear +"# A O(1) Python3 program to find +# number of strings that can be +# made under given constraints. + +def countStr(n): + return (1 + (n * 2) + + (n * ((n * n) - 1) // 2)) + +# Driver code +if __name__ == ""__main__"": + n = 3 + print(countStr(n)) + +# This code is contributed +# by ChitraNayal",constant,constant +"# Python 3 program to find count of +# substring containing exactly K ones + +# method returns total number of +# substring having K ones +def countOfSubstringWithKOnes(s, K): + N = len(s) + res = 0 + countOfOne = 0 + freq = [0 for i in range(N + 1)] + + # initialize index having + # zero sum as 1 + freq[0] = 1 + + # loop over binary characters of string + for i in range(0, N, 1): + + # update countOfOne variable with + # value of ith character + countOfOne += ord(s[i]) - ord('0') + + # if value reaches more than K, + # then update result + if (countOfOne >= K): + + # add frequency of indices, having + # sum (current sum - K), to the result + res += freq[countOfOne - K] + + # update frequency of one's count + freq[countOfOne] += 1 + + return res + +# Driver code +if __name__ == '__main__': + s = ""10010"" + K = 1 + print(countOfSubstringWithKOnes(s, K)) + +# This code is contributed by +# Surendra_Gangwar",linear,linear +"# Python program to print all words that +# have the same unique character set + +# Function to group all strings with same characters +from collections import Counter + +def groupStrings(input): + # traverse all strings one by one + # dict is an empty dictionary + dict={} + + for word in input: + # sort the current string and take it's + # sorted value as key + # sorted return list of sorted characters + # we need to join them to get key as string + # Counter() method returns dictionary with frequency of + # each character as value + wordDict=Counter(word) + + # now get list of keys + key = wordDict.keys() + + # now sort these keys + key = sorted(key) + + # join these characters to produce key string + key = ''.join(key) + + # now check if this key already exist in + # dictionary or not + # if exist then simply append current word + # in mapped list on key + # otherwise first assign empty list to key and + # then append current word in it + if key in dict.keys(): + dict[key].append(word) + else: + dict[key]=[] + dict[key].append(word) + + # now traverse complete dictionary and print + # list of mapped strings in each key separated by , + for (key,value) in dict.items(): + print (','.join(dict[key])) + +# Driver program +if __name__ == ""__main__"": + input=['may','student','students','dog','studentssess','god','cat','act','tab','bat','flow','wolf','lambs','amy','yam','balms','looped','poodle'] + groupStrings(input)",linear,linear +"# Python3 program to print distinct +# characters of a string. +NO_OF_CHARS = 256 + +# Print duplicates present in the +# passed string +def printDistinct(str): + + # Create an array of size 256 and + # count of every character in it + count = [0] * NO_OF_CHARS + + # Count array with frequency of + # characters + for i in range (len(str)): + if(str[i] != ' '): + count[ord(str[i])] += 1 + n = i + + # Print characters having count + # more than 0 + for i in range(n): + if (count[ord(str[i])] == 1): + print (str[i], end = """") + +# Driver Code +if __name__ == ""__main__"": + + str = ""GeeksforGeeks"" + printDistinct(str) + +# This code is contributed by ita_c",constant,quadratic +"# Python3 program to find all distinct characters +# in a String + +MAX_CHAR = 256 + +# Function to print distinct characters in +# given Str[] +def printDistinct(Str): + + n = len(Str) + + # count[x] is going to store count of + # character 'x' in Str. If x is not present, + # then it is going to store 0. + count = [0 for i in range(MAX_CHAR)] + + # index[x] is going to store index of character + # 'x' in Str. If x is not present or x is + # more than once, then it is going to store a value + # (for example, length of String) that cannot be + # a valid index in Str[] + index = [n for i in range(MAX_CHAR)] + + + # Traverse the input String + for i in range(n): + + # Find current character and increment its + # count + x = ord(Str[i]) + count[x] += 1 + + # If this is first occurrence, then set value + # in index as index of it. + if (count[x] == 1 and x !=' '): + index[x] = i + + # If character repeats, then remove it from + # index[] + if (count[x] == 2): + index[x] = n + + + # Since size of index is constant, below operations + # take constant time. + index=sorted(index) + + for i in range(MAX_CHAR): + if index[i] == n: + break + print(Str[index[i]],end="""") + +# Driver code + +Str = ""GeeksforGeeks"" +printDistinct(Str) + +# This code is contributed by mohit kumar 29",linear,linear +"# Python3 program to print common characters +# of two Strings in alphabetical order + + +# Initializing size of array +MAX_CHAR=26 + +# Function to find similar characters +def printCommon( s1, s2): + # two arrays of length 26 to store occurrence + # of a letters alphabetically for each string + a1 = [0 for i in range(MAX_CHAR)] + a2 = [0 for i in range(MAX_CHAR)] + + length1 = len(s1) + length2 = len(s2) + + for i in range(0,length1): + a1[ord(s1[i]) - ord('a')] += 1 + + for i in range(0,length2): + a2[ord(s2[i]) - ord('a')] += 1 + + # If a common index is non-zero, it means + # that the letter corresponding to that + # index is common to both strings + for i in range(0,MAX_CHAR): + if (a1[i] != 0 and a2[i] != 0): + + # Find the minimum of the occurrence + # of the character in both strings and print + # the letter that many number of times + for j in range(0,min(a1[i],a2[i])): + ch = chr(ord('a')+i) + print (ch, end='') + + +# Driver code +if __name__==""__main__"": + s1 = ""geeksforgeeks"" + s2 = ""practiceforgeeks"" + printCommon(s1, s2); + +# This Code is contributed by Abhishek Sharma",constant,linear +"# Python3 Program to find all the +# common characters in n strings +MAX_CHAR = 26 + +def commonCharacters(strings, n) : + + # primary array for common characters + # we assume all characters are seen before. + prim = [True] * MAX_CHAR + + # for each strings + for i in range(n): + + # secondary array for common characters + # Initially marked false + sec = [False] * MAX_CHAR + + # for every character of ith strings + for j in range(len(strings[i])): + + # if character is present in all + # strings before, mark it. + if (prim[ord(strings[i][j]) - ord('a')]) : + sec[ord(strings[i][j]) - + ord('a')] = True + + # copy whole secondary array + # into primary + for i in range(MAX_CHAR): + prim[i] = sec[i] + + # displaying common characters + for i in range(26): + if (prim[i]) : + print(""%c "" % (i + ord('a')), + end = """") + +# Driver's Code +strings = [ ""geeksforgeeks"", ""gemkstones"", + ""acknowledges"", ""aguelikes"" ] +n = len(strings) +commonCharacters(strings, n) + +# This code is contributed by Niwesh Gupta",constant,linear +"# Python3 program Find concatenated string +# with uncommon characters of given strings + + +def concatenatedString(s1, s2): + res = """" # result + m = {} + + # store all characters of s2 in map + for i in range(0, len(s2)): + m[s2[i]] = 1 + + # Find characters of s1 that are not + # present in s2 and append to result + for i in range(0, len(s1)): + if(not s1[i] in m): + res = res + s1[i] + else: + m[s1[i]] = 2 + + # Find characters of s2 that are not + # present in s1. + for i in range(0, len(s2)): + if(m[s2[i]] == 1): + res = res + s2[i] + + return res + + +# Driver Code +if __name__ == ""__main__"": + s1 = ""abcs"" + s2 = ""cxzca"" + print(concatenatedString(s1, s2)) + +# This code is contributed +# by Sairahul099",linear,linear +"# Python program to remove vowels from a string +# Function to remove vowels +def rem_vowel(string): + vowels = ['a','e','i','o','u'] + result = [letter for letter in string if letter.lower() not in vowels] + result = ''.join(result) + print(result) + +# Driver program +string = ""GeeksforGeeks - A Computer Science Portal for Geeks"" +rem_vowel(string) +string = ""Loving Python LOL"" +rem_vowel(string)",constant,linear +"# Python program to remove vowels from a string +# Function to remove vowels + +# import the module for regular expression (re) +import re +def rem_vowel(string): + return (re.sub(""[aeiouAEIOU]"","""",string)) + +# Driver program +string = ""GeeksforGeeks - A Computer Science Portal for Geeks"" +print(rem_vowel(string))",constant,linear +"# Python3 implementation for printing +# sentence without repetitive vowels + +# function which returns True or False +# for occurrence of a vowel +def is_vow(c): + + # this compares vowel with + # character 'c' + return ((c == 'a') or (c == 'e') or + (c == 'i') or (c == 'o') or + (c == 'u')); + +# function to print resultant string +def removeVowels(str): + + # print 1st character + print(str[0], end = """"); + + # loop to check for each character + for i in range(1,len(str)): + + # comparison of consecutive + # characters + if ((is_vow(str[i - 1]) != True) or + (is_vow(str[i]) != True)): + + print(str[i], end = """"); + +# Driver code +str= "" geeks for geeks""; +removeVowels(str); + +# This code is contributed by mits",linear,linear +"# Python3 program to count vowels +# in a string + +# Function to check the Vowel +def isVowel(ch): + return ch.upper() in ['A', 'E', 'I', 'O', 'U'] + +# Returns count of vowels in str +def countVowels(str): + count = 0 + for i in range(len(str)): + + # Check for vowel + if isVowel(str[i]): + count += 1 + return count + +# Driver Code + +# string object +str = 'abc de' + +# Total number of Vowels +print(countVowels(str)) + +# This code is contributed +# by SamyuktaSHegde",constant,linear +"# Recursive Python 3 program to count the +# total number of vowels using recursion + +# Function to check the Vowel +def isVowel(ch): + return ch.upper() in ['A', 'E', 'I', 'O', 'U'] + +# to count total number of +# vowel from 0 to n +def countVovels(str, n): + if (n == 1): + return isVowel(str[n - 1]); + + return (countVovels(str, n - 1) + + isVowel(str[n - 1])); + +# Driver Code + +# string object +str = ""abc de""; + +# Total numbers of Vowel +print(countVovels(str, len(str))) + +# This code is contributed +# by Akanksha Rai",linear,linear +"# Iterative Python3 program to count +# total number of consonants + +# Function to check for consonant +def isConsonant(ch): + + # To handle lower case + ch = ch.upper() + + return not (ch == 'A' or ch == 'E' or + ch == 'I' or ch == 'O' or + ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90 + +def totalConsonants(string): + + count = 0 + + for i in range(len(string)): + + # To check is character is Consonant + if (isConsonant(string[i])): + count += 1 + + return count + +# Driver code +string = ""abc de"" +print(totalConsonants(string)) + + +# This code id contributed by Ansu Kumari.",constant,linear +"# Recursive Python3 program to count +# total number of consonants + +# Function to check for consonant +def isConsonant(ch): + + # To handle lower case + ch = ch.upper() + + return not (ch == 'A' or ch == 'E' or + ch == 'I' or ch == 'O' or + ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90 + +# To count total number of +# consonants from 0 to n-1 +def totalConsonants(string, n): + + if n == 1: + return isConsonant(string[0]) + + return totalConsonants(string, n - 1) + isConsonant(string[n-1]) + + +# Driver code +string = ""abc de"" +print(totalConsonants(string, len(string))) + + +# This code is contributed by Ansu Kuamri.",linear,linear +"# Python implementation of alternate vowel +# and consonant string + +# 'ch' is vowel or not +def isVowel(ch): + if(ch == 'a' or ch == 'e' or + ch == 'i' or ch == 'o' or + ch == 'u'): + return True + return False + +# create alternate vowel and consonant string +# str1[0...l1-1] and str2[start...l2-1] +def createAltStr(str1, str2, start, l): + finalStr = """" + i = 0 + + # first adding character of vowel/consonant + # then adding character of consonant/vowel + for j in range(start, l): + finalStr = (finalStr + str1[i]) + str2[j] + i + 1 + + return finalStr + +# function to find the required +# alternate vowel and consonant string +def findAltStr(str1): + nv = 0 + nc = 0 + vstr = """" + cstr = """" + l = len(str1) + for i in range(0, l): + + # count vowels and update vowel string + if(isVowel(str1[i])): + nv += 1 + vstr = vstr + str1[i] + + # count consonants and update + # consonant string + else: + nc += 1 + cstr = cstr + str1[i] + + # no such string can be formed + if(abs(nv - nc) >= 2): + return ""no such string"" + + # remove first character of vowel string + # then create alternate string with + # cstr[0...nc-1] and vstr[1...nv-1] + if(nv > nc): + return (vstr[0] + createAltStr(cstr, vstr, 1, nv)) + + # remove first character of consonant string + # then create alternate string with + # vstr[0...nv-1] and cstr[1...nc-1] + if(nc > nv): + return (cstr[0] + createAltStr(vstr, cstr, 1, nc)) + + # if both vowel and consonant + # strings are of equal length + # start creating string with consonant + if(cstr[0] < vstr[0]): + return createAltStr(cstr, vstr, 0, nv) + + return createAltStr(vstr, cstr, 0, nc) + +# Driver Code +if __name__ == ""__main__"": + str1 = ""geeks"" + print(findAltStr(str1)) + +# This code is contributed by Sairahul099",linear,linear +"# A simple Python 3 program to count number of +# substrings starting and ending with 1 + + +def countSubStr(st, n): + + # Initialize result + res = 0 + + # Pick a starting point + for i in range(0, n): + if (st[i] == '1'): + + # Search for all possible ending point + for j in range(i+1, n): + if (st[j] == '1'): + res = res + 1 + + return res + + +# Driver program to test above function +st = ""00100101"" +list(st) +n = len(st) +print(countSubStr(st, n), end="""") + + +# This code is contributed +# by Nikita Tiwari.",constant,quadratic +"# A Python3 program to count number of +# substrings starting and ending with 1 + + +def countSubStr(st, n): + + # Count of 1's in input string + m = 0 + + # Traverse input string and + # count of 1's in it + for i in range(0, n): + if (st[i] == '1'): + m = m + 1 + + # Return count of possible + # pairs among m 1's + return m * (m - 1) // 2 + + +# Driver program to test above function +st = ""00100101"" +list(st) +n = len(st) +print(countSubStr(st, n), end="""") + + +# This code is contributed +# by Nikita Tiwari.",constant,linear +"class GFG : + @staticmethod + def helper( n, str, i) : + + # if 'i' is on the last index + if (i == n - 1) : + return 1 if (str[i] == '1') else 0 + + # if current char is 1 + # add 1 to the answer + if (str[i] == '1') : + return 1 + GFG.helper(n, str, i + 1) + else : + return GFG.helper(n, str, i + 1) + @staticmethod + def countSubStr( str) : + n = len(str) + + # counting the number of 1's in the string + count = GFG.helper(n, str, 0) + + # return the number of combinations + return int((count * (count - 1)) / 2) + @staticmethod + def main( args) : + str = list(""00100101"") + print(GFG.countSubStr(str)) + + +if __name__==""__main__"": + GFG.main([]) + + # This code is contributed by aadityaburujwale.",linear,linear +"# Python program to find number of distinct +# permutations of a string. + +MAX_CHAR = 26 + +# Utility function to find factorial of n. +def factorial(n) : + + fact = 1; + for i in range(2, n + 1) : + fact = fact * i; + return fact + +# Returns count of distinct permutations +# of str. +def countDistinctPermutations(st) : + + length = len(st) + freq = [0] * MAX_CHAR + + # finding frequency of all the lower + # case alphabet and storing them in + # array of integer + for i in range(0, length) : + if (st[i] >= 'a') : + freq[(ord)(st[i]) - 97] = freq[(ord)(st[i]) - 97] + 1; + + # finding factorial of number of + # appearances and multiplying them + # since they are repeating alphabets + fact = 1 + for i in range(0, MAX_CHAR) : + fact = fact * factorial(freq[i]) + + # finding factorial of size of string + # and dividing it by factorial found + # after multiplying + return factorial(length) // fact + +# Driver code +st = ""fvvfhvgv"" +print (countDistinctPermutations(st)) + +# This code is contributed by Nikita Tiwari.",linear,linear +"# Python3 program to check if it is +# possible to split string or not +MAX_CHAR = 26 + +# Function to check if we +# can split string or not +def checkCorrectOrNot(s): + + global MAX_CHAR + + # Counter array initialized with 0 + count1 = [0] * MAX_CHAR + count2 = [0] * MAX_CHAR + + # Length of the string + n = len(s) + + if n == 1: + return true + + # Traverse till the middle + # element is reached + i = 0; j = n - 1 + + while (i < j): + + # First half + count1[ord(s[i]) - ord('a')] += 1 + + # Second half + count2[ord(s[j]) - ord('a')] += 1 + + i += 1; j -= 1 + + # Checking if values are + # different set flag to 1 + for i in range(MAX_CHAR): + + if count1[i] != count2[i]: + return False + + return True + + +# Driver Code + +# String to be checked +s = ""ababc"" + +print(""Yes"" if checkCorrectOrNot(s) else ""No"") + + +# This code is contributed by Ansu Kumari.",constant,linear +"# Python3 program to check if it is +# possible to split string or not +MAX_CHAR = 26 + +# Function to check if we +# can split string or not +def checkCorrectOrNot(s): + + global MAX_CHAR + + # Counter array initialized with 0 + count = [0] * MAX_CHAR + + # Length of the string + n = len(s) + + if n == 1: + return true + + # Traverse till the middle + # element is reached + i = 0; j = n-1 + + while i < j: + + # First half + count[ord(s[i]) - ord('a')] += 1 + + # Second half + count[ord(s[j])-ord('a')] -= 1 + + i += 1; j -= 1 + + # Checking if values are + # different, set flag to 1 + for i in range(MAX_CHAR): + + if count[i] != 0: + return False + + return True + + +# Driver Code + +# String to be checked +s = ""abab"" + +print(""Yes"" if checkCorrectOrNot(s) else ""No"") + + +# This code is contributed by Ansu Kumari.",constant,linear +"# Python program to count all +# words with count +# exactly 2. + +# Returns count of words with frequency +# exactly 2. +def countWords(stri, n): + m = dict() + for i in range(n): + m[stri[i]] = m.get(stri[i],0) + 1 + + res = 0 + for i in m.values(): + if i == 2: + res += 1 + + return res + +# Driver code +s = [ ""hate"", ""love"", ""peace"", ""love"", + ""peace"", ""hate"", ""love"", ""peace"", + ""love"", ""peace"" ] +n = len(s) +print(countWords(s, n)) + +# This code is contributed +# by Shubham Rana",linear,linear +"# importing Counter from collections +from collections import Counter + +# Python program to count all words with count exactly 2. +# Returns count of words with frequency exactly 2. +def countWords(stri, n): + + # Calculating frequency using Counter + m = Counter(stri) + + count = 0 + # Traversing in freq dictionary + for i in m: + if m[i] == 2: + count += 1 + + return count + +# Driver code +s = [""hate"", ""love"", ""peace"", ""love"", + ""peace"", ""hate"", ""love"", ""peace"", + ""love"", ""peace""] +n = len(s) +print(countWords(s, n)) + +# This code is contributed by vikkycirus",linear,linear +"# Python3 program to get same frequency character +# string by removal of at most one char +M = 26 + +# Utility method to get index of character ch +# in lower alphabet characters +def getIdx(ch): + return (ord(ch) - ord('a')) + +# Returns true if all non-zero elements +# values are same +def allSame(freq, N): + + # get first non-zero element + for i in range(0, N): + if(freq[i] > 0): + same = freq[i] + break + + # check equality of each element + # with variable same + for j in range(i + 1, N): + if(freq[j] > 0 and freq[j] != same): + return False + + return True + +# Returns true if we can make all +# character frequencies same +def possibleSameCharFreqByOneRemoval(str1): + l = len(str1) + + # fill frequency array + freq = [0] * M + for i in range(0, l): + freq[getIdx(str1[i])] += 1 + + # if all frequencies are same, + # then return true + if(allSame(freq, M)): + return True + + # Try decreasing frequency of all character + # by one and then check all equality of all + # non-zero frequencies + for i in range(0, 26): + + # Check character only if it + # occurs in str + if(freq[i] > 0): + freq[i] -= 1 + + if(allSame(freq, M)): + return True + freq[i] += 1 + + return False + +# Driver code +if __name__ == ""__main__"": + str1 = ""xyyzz"" + if(possibleSameCharFreqByOneRemoval(str1)): + print(""Yes"") + else: + print(""No"") + +# This code is contributed by Sairahul099",constant,linear +"# Python 3 program to check if +# a string can be made +# valid by removing at most 1 character. + +# Assuming only lower case characters +CHARS = 26 + +# To check a string S can be converted to a “valid” +# string by removing less than or equal to one +# character. + +def isValidString(str): + + freq = [0]*CHARS + + # freq[] : stores the frequency of each + # character of a string + for i in range(len(str)): + freq[ord(str[i])-ord('a')] += 1 + + # Find first character with non-zero frequency + freq1 = 0 + count_freq1 = 0 + for i in range(CHARS): + + if (freq[i] != 0): + + freq1 = freq[i] + count_freq1 = 1 + break + + # Find a character with frequency different + # from freq1. + freq2 = 0 + count_freq2 = 0 + for j in range(i+1,CHARS): + + if (freq[j] != 0): + + if (freq[j] == freq1): + count_freq1 += 1 + else: + + count_freq2 = 1 + freq2 = freq[j] + break + + # If we find a third non-zero frequency + # or count of both frequencies become more + # than 1, then return false + for k in range(j+1,CHARS): + + if (freq[k] != 0): + + if (freq[k] == freq1): + count_freq1 += 1 + if (freq[k] == freq2): + count_freq2 += 1 + + # If we find a third non-zero freq + else: + return False + + # If counts of both frequencies is more than 1 + if (count_freq1 > 1 and count_freq2 > 1): + return False + + # Return true if we reach here + return True + +# Driver code +if __name__ == ""__main__"": + str= ""abcbc"" + + if (isValidString(str)): + print(""YES"") + else: + print(""NO"") + +# this code is contributed by +# ChitraNayal",constant,linear +"# Python program to check if a string can be made +# valid by removing at most 1 character using hashmap. + +# To check a string S can be converted to a variation +# string +def checkForVariation(strr): + if(len(strr) == 0): + return True + + mapp = {} + + # Run loop form 0 to length of string + for i in range(len(strr)): + if strr[i] in mapp: + mapp[strr[i]] += 1 + else: + mapp[strr[i]] = 1 + + # declaration of variables + first = True + second = True + val1 = 0 + val2 = 0 + countOfVal1 = 0 + countOfVal2 = 0 + + for itr in mapp: + i = itr + + # if first is true than countOfVal1 increase + if(first): + val1 = i + first = False + countOfVal1 += 1 + continue + + if(i == val1): + countOfVal1 += 1 + continue + + # if second is true than countOfVal2 increase + if(second): + val2 = i + countOfVal2 += 1 + second = False + continue + + if(i == val2): + countOfVal2 += 1 + continue + if(countOfVal1 > 1 and countOfVal2 > 1): + return False + + else: + return True + +# Driver code +print(checkForVariation(""abcbc"")) + +# This code is contributed by rag2127",linear,nlogn +"# Python program +from collections import Counter + +# To check a string S can be +# converted to a variation +# string +def checkForVariation(strr): + + freq = Counter(strr) + + # Converting these values to list + valuelist = list(freq.values()) + + # Counting frequencies again + ValueCounter = Counter(valuelist) + if(len(ValueCounter) == 1): + return True + elif(len(ValueCounter) == 2 and + min(ValueCounter.values()) == 1): + return True + + # If no conditions satisfied return false + return False + + +# Driver code +string = ""abcbc"" + +# passing string to checkForVariation Function +print(checkForVariation(string)) + +# This code is contributed by vikkycirus",linear,linear +"# Python3 program to get number of ways to increase +# LCS by 1 + +M = 26 + +# Method returns total ways to increase LCS length by 1 +def waysToIncreaseLCSBy1(str1, str2): + m = len(str1) + n = len(str2) + + # Fill positions of each character in vector + # vector position[M]; + position = [[] for i in range(M)] + for i in range(1, n+1, 1): + position[ord(str2[i-1])-97].append(i) + + # Initializing 2D array by 0 values + lcsl = [[0 for i in range(n+2)] for j in range(m+2)] + lcsr = [[0 for i in range(n+2)] for j in range(m+2)] + + # Filling LCS array for prefix substrings + for i in range(1, m+1, 1): + for j in range(1, n+1,1): + if (str1[i-1] == str2[j-1]): + lcsl[i][j] = 1 + lcsl[i-1][j-1] + else: + lcsl[i][j] = max(lcsl[i-1][j], + lcsl[i][j-1]) + + # Filling LCS array for suffix substrings + for i in range(m, 0, -1): + for j in range(n, 0, -1): + if (str1[i-1] == str2[j-1]): + lcsr[i][j] = 1 + lcsr[i+1][j+1] + else: + lcsr[i][j] = max(lcsr[i+1][j], + lcsr[i][j+1]) + + # Looping for all possible insertion positions + # in first string + ways = 0 + for i in range(0, m+1,1): + # Trying all possible lower case characters + for C in range(0, 26,1): + # Now for each character, loop over same + # character positions in second string + for j in range(0, len(position[C]),1): + p = position[C][j] + + # If both, left and right substrings make + # total LCS then increase result by 1 + if (lcsl[i][p-1] + lcsr[i+1][p+1] == lcsl[m][n]): + ways += 1 + return ways + + +# Driver code to test above methods +str1 = ""abcabc"" +str2 = ""abcd"" +print(waysToIncreaseLCSBy1(str1, str2)) + +# This code is contributed by ankush_953",quadratic,quadratic +"# Python3 implementation to find the character in +# first that is present at minimum index +# in second String + +# function to find the minimum index character +def printMinIndexChar(Str, patt): + + # to store the index of character having + # minimum index + minIndex = 10**9 + + # lengths of the two Strings + m =len(Str) + n =len(patt) + + # traverse 'patt' + for i in range(n): + + # for each character of 'patt' traverse 'Str' + for j in range(m): + + # if patt[i] is found in 'Str', check if + # it has the minimum index or not. If yes, + # then update 'minIndex' and break + if (patt[i] == Str[j] and j < minIndex): + minIndex = j + break + + + + + # print the minimum index character + if (minIndex != 10**9): + print(""Minimum Index Character = "",Str[minIndex]) + + # if no character of 'patt' is present in 'Str' + else: + print(""No character present"") + + +# Driver code + +Str = ""geeksforgeeks"" +patt = ""set"" +printMinIndexChar(Str, patt) + +# This code is contributed by mohit kumar 29",constant,quadratic +"# Python3 implementation to +# find the character in first +# string that is present at +# minimum index in second string +import sys + +# Function to find the +# minimum index character +def printMinIndexChar(st, patt): + + # unordered_map 'um' + # implemented as hash table + um = {} + + # to store the index of + # character having minimum index + minIndex = sys.maxsize + + # Lengths of the two strings + m = len(st) + n = len(patt) + + # Store the first index of + # each character of 'str' + for i in range (m): + if (st[i] not in um): + um[st[i]] = i + + # traverse the string 'patt' + for i in range(n): + + # If patt[i] is found in 'um', + # check if it has the minimum + # index or not accordingly + # update 'minIndex' + if (patt[i] in um and + um[patt[i]] < minIndex): + minIndex = um[patt[i]] + + # Print the minimum index character + if (minIndex != sys.maxsize): + print (""Minimum Index Character = "", + st[minIndex]) + + # If no character of 'patt' + # is present in 'str' + else: + print (""No character present"") + +# Driver program to test above +if __name__ == ""__main__"": + + st = ""geeksforgeeks"" + patt = ""set"" + printMinIndexChar(st, patt) + +# This code is contributed by Chitranayal",linear,linear +"# Python3 implementation of program to find the maximum length +# that can be removed + +# Function to find the length of longest sub-string that +# can me make removed +# arr --> pair type of array whose first field store +# character in and second field stores +# corresponding index of that character +def longestNull(S): + + arr=[] + + # store {'@',-1} in arr , here this value will + # work as base index + arr.append(['@', -1]) + + maxlen = 0 # Initialize result + + # one by one iterate characters of String + for i in range(len(S)): + # make pair of char and index , then store + # them into arr + arr.append([S[i], i]) + + # now if last three elements of arr[] are making + # sub-string""100"" or not + while (len(arr)>=3 and + arr[len(arr)-3][0]=='1' and + arr[len(arr)-2][0]=='0' and + arr[len(arr)-1][0]=='0'): + + # if above condition is true then delete + # sub-string""100"" from arr[] + arr.pop() + arr.pop() + arr.pop() + + # index of current last element in arr[] + tmp = arr[-1] + # This is important, here 'i' is the index of + # current character inserted into arr[] + # and 'tmp' is the index of last element in arr[] + # after continuous deletion of sub-String + # ""100"" from arr[] till we make it null, difference + # of these to 'i-tmp' gives the length of current + # sub-string that can be make null by continuous + # deletion of sub-string""100"" + maxlen = max(maxlen, i - tmp[1]) + + + return maxlen + + +# Driver code + +print(longestNull(""1011100000100"")) + +# This code is contributed by mohit kumar 29",linear,linear +"# Simple Python3 program to find pairs with +# distance equal to English alphabet distance + +# Function to count pairs +def countPairs(str1): + result = 0; + n = len(str1) + for i in range(0, n): + for j in range(i + 1, n): + + # Increment count if characters + # are at same distance + if (abs(ord(str1[i]) - + ord(str1[j])) == abs(i - j)): + result += 1; + + return result; + +# Driver code +if __name__ == ""__main__"": + str1 = ""geeksforgeeks""; + print(countPairs(str1)); + +# This code is contributed +# by Sairahul099",linear,quadratic +"# An optimized C++ program to find pairs with +# distance equal to English alphabet distance + +MAX_CHAR = 26 + +# Function to count pairs with distance +# equal to English alphabet distance +def countPairs(str1): + result = 0; + n = len(str1) + + for i in range(0, n): + + # This loop runs at most 26 times + for j in range(1, MAX_CHAR + 1): + if((i + j) < n): + if ((abs(ord(str1[i + j]) - + ord(str1[i])) == j)): + result += 1; + + return result + +# Driver code +if __name__ == ""__main__"": + str1 = ""geeksforgeeks""; + print(countPairs(str1)) + +# This code is contributed +# by Sairahul099",linear,quadratic +"# Python3 program to count the +# number of pairs +MAX = 256 + +# Function to count the number +# of equal pairs +def countPairs(s): + + # Hash table + cnt = [0 for i in range(0, MAX)] + + # Traverse the string and count + # occurrence + for i in range(len(s)): + cnt[ord(s[i]) - 97] += 1 + + # Stores the answer + ans = 0 + + # Traverse and check the occurrence + # of every character + for i in range(0, MAX): + ans += cnt[i] * cnt[i] + + return ans + +# Driver code +if __name__==""__main__"": + s = ""geeksforgeeks"" + print(countPairs(s)) + +# This code is contributed +# by Sairahul099 ",linear,linear +"# Python3 Program to count strings with +# adjacent characters. +def countStrs(n): + + # Initializing arr[n+1][27] to 0 + dp = [[0 for j in range(27)] + for i in range(n + 1)] + + # Initialing 1st row all 1 from 0 to 25 + for i in range(0, 26): + dp[1][i] = 1 + + # Begin evaluating from i=2 since + # 1st row is set + for i in range(2, n + 1): + for j in range(0, 26): + + # j=0 is 'A' which can make strings + # of length i using strings of length + # i-1 and starting with 'B' + if(j == 0): + dp[i][j] = dp[i - 1][j + 1]; + else: + dp[i][j] = (dp[i - 1][j - 1] + + dp[i - 1][j + 1]) + + # Our result is sum of last row. + sum = 0 + for i in range(0, 26): + sum = sum + dp[n][i] + + return sum + +# Driver's Code +if __name__ == ""__main__"": + n = 3 + print(""Total strings are : "", countStrs(n)) + +# This code is contributed by Sairahul Jella",linear,linear +"# Python3 program to print Number of Words, +# Vowels and Frequency of Each Character + +# A method to count the number of +# uppercase character, vowels and number of words +def words(str): + wcount = vcount = ucount = i = 0 + while i < len(str): + ch = str[i] + + # condition checking for word count + if (ch == "" "" or ch == "".""): + wcount += 1 + + # condition checking for vowels + # in lower case + if(ch == ""a"" or ch == ""e"" or + ch == ""i"" or ch == 'o' or ch == ""u""): + vcount += 1 + + # condition checking for vowels in uppercase + if (ch == ""A"" or ch == ""E"" or + ch == ""I"" or ch == 'O' or ch == ""U""): + vcount += 1 + + # condition checking for upper case characters + if (ord(ch) >= 65 and ord(ch) <= 90): + ucount += 1 + i += 1 + + print(""number of words = "", wcount) + print(""number of vowels = "", vcount) + print(""number of upper case characters = "", + ucount) + +# a method to print the frequency +# of each character. +def frequency(str): + i = 1 + + # checking each and every + # ascii code character + while i < 127: + ch1 = chr(i) + c = 0 + j = 0 + while j < len(str): + ch2 = str[j] + if(ch1 == ch2): + c += 1 + j += 1 + + # condition to print the frequency + if c > 0: + print(""Character:"", ch1 + + "" Frequency:"", c) + i += 1 + +# Driver Code + +# sample string to check the code +s = ""Geeks for Geeks."" + +# function calling +words(s) +frequency(s) + +# This code is contributed by Animesh_Gupta",constant,linear +"# Python3 program to Find longest subsequence where +# every character appears at-least k times + +MAX_CHARS = 26 + +def longestSubseqWithK(s, k): + + n = len(s) + + # Count frequencies of all characters + freq = [0]*MAX_CHARS + for i in range(n): + freq[ord(s[i]) - ord('a')]+=1 + + # Traverse given string again and print + # all those characters whose frequency + # is more than or equal to k. + for i in range(n ): + if (freq[ord(s[i]) - ord('a')] >= k): + print(s[i],end="""") + +# Driver code +if __name__ == ""__main__"": + + s = ""geeksforgeeks"" + k = 2 + longestSubseqWithK(s, k)",linear,linear +"# Python3 program to Find longest subsequence where every +# character appears at-least k times +def longestSubseqWithK(Str, k): + n = len(Str) + hm = {} + + # Count frequencies of all characters + for i in range(n): + c = Str[i] + if(c in hm): + hm += 1 + + else: + hm = 1 + + # Traverse given string again and print + # all those characters whose frequency + # is more than or equal to k. + for i in range(n): + c = Str[i] + if (hm >= k): + print(c,end="""") + +# Driver code +Str = ""geeksforgeeks"" +k = 2 +longestSubseqWithK(Str, k) + +# This code is contributed by shinjanpatra",linear,nlogn +"# Recursive Python program to check +# if a string is subsequence +# of another string + +# Returns true if str1[] is a +# subsequence of str2[]. + + +def isSubSequence(string1, string2, m, n): + # Base Cases + if m == 0: + return True + if n == 0: + return False + + # If last characters of two + # strings are matching + if string1[m-1] == string2[n-1]: + return isSubSequence(string1, string2, m-1, n-1) + + # If last characters are not matching + return isSubSequence(string1, string2, m, n-1) + + +# Driver program to test the above function +string1 = ""gksrek"" +string2 = ""geeksforgeeks"" + +if isSubSequence(string1, string2, len(string1), len(string2)): + print (""Yes"") +else: + print (""No"") + +# This code is contributed by BHAVYA JAIN",linear,linear +"# Iterative JavaScript program to check +# If a string is subsequence of another string + +# Returns true if s1 is subsequence of s2 +def issubsequence(s1, s2): + + n,m = len(s1),len(s2) + i,j = 0,0 + while (i < n and j < m): + if (s1[i] == s2[j]): + i += 1 + j += 1 + + # If i reaches end of s1,that mean we found all + # characters of s1 in s2, + # so s1 is subsequence of s2, else not + return i == n + + +# driver code +s1 = ""gksrek"" +s2 = ""geeksforgeeks"" +if (issubsequence(s1, s2)): + print(""gksrek is subsequence of geekforgeeks"") +else: + print(""gksrek is not a subsequence of geekforgeeks"") + +# This code is contributed by shinjanpatra",constant,linear +"# Python 3 program to count +# subsequences of the form +# a ^ i b ^ j c ^ k + +# Returns count of subsequences +# of the form a ^ i b ^ j c ^ k +def countSubsequences(s): + + # Initialize counts of different + # subsequences caused by different + # combination of 'a' + aCount = 0 + + # Initialize counts of different + # subsequences caused by different + # combination of 'a' and different + # combination of 'b' + bCount = 0 + + # Initialize counts of different + # subsequences caused by different + # combination of 'a', 'b' and 'c'. + cCount = 0 + + # Traverse all characters + # of given string + for i in range(len(s)): + + # If current character is 'a', + # then there are following + # possibilities : + # a) Current character begins + # a new subsequence. + # b) Current character is part + # of aCount subsequences. + # c) Current character is not + # part of aCount subsequences. + if (s[i] == 'a'): + aCount = (1 + 2 * aCount) + + # If current character is 'b', then + # there are following possibilities : + # a) Current character begins a + # new subsequence of b's with + # aCount subsequences. + # b) Current character is part + # of bCount subsequences. + # c) Current character is not + # part of bCount subsequences. + else if (s[i] == 'b'): + bCount = (aCount + 2 * bCount) + + # If current character is 'c', then + # there are following possibilities : + # a) Current character begins a + # new subsequence of c's with + # bCount subsequences. + # b) Current character is part + # of cCount subsequences. + # c) Current character is not + # part of cCount subsequences. + else if (s[i] == 'c'): + cCount = (bCount + 2 * cCount) + + return cCount + +# Driver code +if __name__ == ""__main__"": + s = ""abbc"" + print(countSubsequences(s)) + +# This code is contributed +# by ChitraNayal",constant,linear +"# Python 3 program to count subsequences +# of a string divisible by n. + +# Returns count of subsequences of +# str divisible by n. +def countDivisibleSubseq(str, n): + l = len(str) + + # division by n can leave only n remainder + # [0..n-1]. dp[i][j] indicates number of + # subsequences in string [0..i] which leaves + # remainder j after division by n. + dp = [[0 for x in range(l)] + for y in range(n)] + + # Filling value for first digit in str + dp[int(str[0]) % n][0] += 1 + + for i in range(1, l): + + # start a new subsequence with index i + dp[int(str[i]) % n][i] += 1 + + for j in range(n): + + # exclude i'th character from all the + # current subsequences of string [0...i-1] + dp[j][i] += dp[j][i-1] + + # include i'th character in all the current + # subsequences of string [0...i-1] + dp[(j * 10 + int(str[i])) % n][i] += dp[j][i-1] + + return dp[0][l-1] + +# Driver code +if __name__ == ""__main__"": + + str = ""1234"" + n = 4 + print(countDivisibleSubseq(str, n)) + +# This code is contributed by ita_c",quadratic,quadratic +"# Python 3 Program to find the ""GFG"" +# subsequence in the given string +MAX = 100 + +# Print the count of ""GFG"" subsequence +# in the string +def countSubsequence(s, n): + cntG = 0 + cntF = 0 + result = 0 + C=0 + + + # Traversing the given string + for i in range(n): + if (s[i] == 'G'): + + # If the character is 'G', increment + # the count of 'G', increase the result + # and update the array. + cntG += 1 + result += C + continue + + # If the character is 'F', increment + # the count of 'F' and update the array. + if (s[i] == 'F'): + cntF += 1 + C += cntG + continue + + # Ignore other character. + else: + continue + + print(result) + +# Driver Code +if __name__ == '__main__': + s = ""GFGFG"" + n = len(s) + countSubsequence(s, n) + +# This code is contributed by +# Sanjit_Prasad",constant,linear +"# Python3 program to print +# distinct subsequences of +# a given string +import math + +# Create an empty set +# to store the subsequences +sn = [] +global m +m = 0 + +# Function for generating +# the subsequences + + +def subsequences(s, op, i, j): + + # Base Case + if(i == m): + op[j] = None + temp = """".join([i for i in op if i]) + + # Insert each generated + # subsequence into the set + sn.append(temp) + return + + # Recursive Case + else: + + # When a particular + # character is taken + op[j] = s[i] + + subsequences(s, op, + i + 1, j + 1) + + # When a particular + # character isn't taken + subsequences(s, op, + i + 1, j) + return + + +# Driver Code +str = ""ggg"" +m = len(str) +n = int(math.pow(2, m) + 1) + +# Output array for storing +# the generating subsequences +# in each call +op = [None for i in range(n)] + +# Function Call +subsequences(str, op, 0, 0) + +# Output will be the number +# of elements in the set +print(len(set(sn))) + +# This code is contributed by avanitrachhadiya2155",linear,np +"# Python3 program to count number of +# distinct subsequences of a given string + +MAX_CHAR = 256 + +def countSub(ss): + + # create an array to store index of last + last = [-1 for i in range(MAX_CHAR + 1)] + + # length of input string + n = len(ss) + + # dp[i] is going to store count of + # discount subsequence of length of i + dp = [-2 for i in range(n + 1)] + + # empty substring has only + # one subsequence + dp[0] = 1 + + # Traverse through all lengths + # from 1 to n + for i in range(1, n + 1): + + # number of subsequence with + # substring str[0...i-1] + dp[i] = 2 * dp[i - 1] + + # if current character has appeared + # before, then remove all subsequences + # ending with previous occurrence. + if last[ord(ss[i - 1])] != -1: + dp[i] = dp[i] - dp[last[ord(ss[i - 1])]] + last[ord(ss[i - 1])] = i - 1 + + return dp[n] + +# Driver code +print(countSub(""gfg"")) + +# This code is contributed +# by mohit kumar 29",linear,linear +"# Python3 program for above approach + +# Returns count of distinct +# subsequences of str. +def countSub(s): + + Map = {} + + # Iterate from 0 to length of s + for i in range(len(s)): + Map[s[i]] = -1 + + allCount = 0 + levelCount = 0 + + # Iterate from 0 to length of s + for i in range(len(s)): + c = s[i] + + # Check if i equal to 0 + if (i == 0): + allCount = 1 + Map = 1 + levelCount = 1 + continue + + # Replace levelCount with + # allCount + 1 + levelCount = allCount + 1 + + # If map is less than 0 + if (Map < 0): + allCount = allCount + levelCount + else: + allCount = allCount + levelCount - Map + + Map = levelCount + + # Return answer + return allCount + +# Driver Code +List = [ ""abab"", ""gfg"" ] + +for s in List: + cnt = countSub(s) + withEmptyString = cnt + 1 + + print(""With empty string count for"", + s, ""is"", withEmptyString) + print(""Without empty string count for"", + s, ""is"", cnt) + +# This code is contributed by rag2127",constant,linear +"# Python 3 program to find LCS +# with permutations allowed + +# Function to calculate longest string +# str1 --> first string +# str2 --> second string +# count1[] --> hash array to calculate frequency +# of characters in str1 +# count[2] --> hash array to calculate frequency +# of characters in str2 +# result --> resultant longest string whose +# permutations are sub-sequence +# of given two strings +def longestString(str1, str2): + + count1 = [0] * 26 + count2 = [0] * 26 + + # calculate frequency of characters + for i in range( len(str1)): + count1[ord(str1[i]) - ord('a')] += 1 + for i in range(len(str2)): + count2[ord(str2[i]) - ord('a')] += 1 + + # Now traverse hash array + result = """" + for i in range(26): + + # append character ('a'+i) in + # resultant string 'result' by + # min(count1[i],count2i]) times + for j in range(1, min(count1[i], + count2[i]) + 1): + result = result + chr(ord('a') + i) + + print(result) + +# Driver Code +if __name__ == ""__main__"": + + str1 = ""geeks"" + str2 = ""cake"" + longestString(str1, str2) + +# This code is contributed by ita_c",constant,linear +"# A simple recursive Python +# program to find shortest +# uncommon subsequence. +MAX = 1005 + +# A recursive function to +# find the length of shortest +# uncommon subsequence +def shortestSeq(S, T, m, n): + + # S String is empty + if m == 0: + return MAX + + # T String is empty + if(n <= 0): + return 1 + + # Loop to search for + # current character + for k in range(n): + if(T[k] == S[0]): + break + + # char not found in T + if(k == n): + return 1 + + # Return minimum of following + # two Not including current + # char in answer Including + # current char + return min(shortestSeq(S[1 : ], T, m - 1, n), + 1 + shortestSeq((S[1 : ]), T[k + 1 : ], + m - 1, n - k - 1)) + +# Driver code +S = ""babab"" +T = ""babba"" + +m = len(S) +n = len(T) +ans = shortestSeq(S, T, m, n) +if(ans >= MAX): + ans =- 1 +print(""Length of shortest subsequence is:"", ans) + +# This code is contributed by avanitrachhadiya2155",quadratic,cubic +"# A dynamic programming based Python program +# to find shortest uncommon subsequence. +MAX = 1005 + +# Returns length of shortest common subsequence +def shortestSeq(S: list, T: list): + m = len(S) + n = len(T) + + # declaring 2D array of m + 1 rows and + # n + 1 columns dynamically + dp = [[0 for i in range(n + 1)] + for j in range(m + 1)] + + # T string is empty + for i in range(m + 1): + dp[i][0] = 1 + + # S string is empty + for i in range(n + 1): + dp[0][i] = MAX + + for i in range(1, m + 1): + for j in range(1, n + 1): + ch = S[i - 1] + k = j - 1 + while k >= 0: + if T[k] == ch: + break + k -= 1 + + # char not present in T + if k == -1: + dp[i][j] = 1 + else: + dp[i][j] = min(dp[i - 1][j], + dp[i - 1][k] + 1) + + ans = dp[m][n] + if ans >= MAX: + ans = -1 + + return ans + +# Driver Code +if __name__ == ""__main__"": + S = ""babab"" + T = ""babba"" + + print(""Length of shortest subsequence is:"", + shortestSeq(S, T)) + +# This code is contributed by +# sanjeev2552",quadratic,cubic +"# A dynamic programming based Python3 program print +# shortest supersequence of two strings + +# returns shortest supersequence of X and Y +def printShortestSuperSeq(m, n, x, y): + + # dp[i][j] contains length of shortest + # supersequence for X[0..i-1] and Y[0..j-1] + dp = [[0 for i in range(n + 1)] + for j in range(m + 1)] + + # Fill table in bottom up manner + for i in range(m + 1): + for j in range(n + 1): + + # Below steps follow recurrence relation + if i == 0: + dp[i][j] = j + elif j == 0: + dp[i][j] = i + elif x[i - 1] == y[j - 1]: + dp[i][j] = 1 + dp[i - 1][j - 1] + else: + dp[i][j] = 1 + min(dp[i - 1][j], + dp[i][j - 1]) + + # Following code is used to print + # shortest supersequence + + # dp[m][n] stores the length of the + # shortest supersequence of X and Y + + # string to store the shortest supersequence + string = """" + + # Start from the bottom right corner and + # add the characters to the output string + i = m + j = n + while i * j > 0: + + # If current character in X and Y are same, + # then current character is part of + # shortest supersequence + if x[i - 1] == y[j - 1]: + + # Put current character in result + string = x[i - 1] + string + + # reduce values of i, j and index + i -= 1 + j -= 1 + + # If current character in X and Y are different + elif dp[i - 1][j] > dp[i][j - 1]: + + # Put current character of Y in result + string = y[j - 1] + string + + # reduce values of j and index + j -= 1 + else: + + # Put current character of X in result + string = x[i - 1] + string + + # reduce values of i and index + i -= 1 + + # If Y reaches its end, put remaining characters + # of X in the result string + while i > 0: + string = x[i - 1] + string + i -= 1 + + # If X reaches its end, put remaining characters + # of Y in the result string + while j > 0: + string = y[j - 1] + string + j -= 1 + + return string + +# Driver Code +if __name__ == ""__main__"": + x = ""GXTXAYB"" + y = ""AGGTAB"" + m = len(x) + n = len(y) + + # Take the smaller string as x and larger one as y + if m > n: + x, y = y, x + m, n = n, m + + print(*printShortestSuperSeq(m, n, x, y)) + +# This code is contributed by +# sanjeev2552",quadratic,quadratic +"# Space optimized Python +# implementation of LCS problem + +# Returns length of LCS for +# X[0..m-1], Y[0..n-1] +def lcs(X, Y): + + # Find lengths of two strings + m = len(X) + n = len(Y) + + L = [[0 for i in range(n+1)] for j in range(2)] + + # Binary index, used to index current row and + # previous row. + bi = bool + + for i in range(m): + # Compute current binary index + bi = i&1 + + for j in range(n+1): + if (i == 0 or j == 0): + L[bi][j] = 0 + + elif (X[i] == Y[j - 1]): + L[bi][j] = L[1 - bi][j - 1] + 1 + + else: + L[bi][j] = max(L[1 - bi][j], + L[bi][j - 1]) + + # Last filled entry contains length of LCS + # for X[0..n-1] and Y[0..m-1] + return L[bi][n] + +# Driver Code +X = ""AGGTAB"" +Y = ""GXTXAYB"" + +print(""Length of LCS is"", lcs(X, Y)) + +# This code is contributed by Soumen Ghosh.",linear,quadratic +"# Python3 program to find largest word in Dictionary +# by deleting some characters of given string + +# Returns true if str1[] is a subsequence of str2[]. +# m is length of str1 and n is length of str2 +def isSubSequence(str1, str2): + + m = len(str1); + n = len(str2); + + j = 0; # For index of str1 (or subsequence + + # Traverse str2 and str1, and compare current + # character of str2 with first unmatched char + # of str1, if matched then move ahead in str1 + i = 0; + while (i < n and j < m): + if (str1[j] == str2[i]): + j += 1; + i += 1; + + # If all characters of str1 were found in str2 + return (j == m); + +# Returns the longest string in dictionary which is a +# subsequence of str. +def findLongestString(dict1, str1): + result = """"; + length = 0; + + # Traverse through all words of dictionary + for word in dict1: + + # If current word is subsequence of str and is largest + # such word so far. + if (length < len(word) and isSubSequence(word, str1)): + result = word; + length = len(word); + + # Return longest string + return result; + +# Driver program to test above function + +dict1 = [""ale"", ""apple"", ""monkey"", ""plea""]; +str1 = ""abpcplea"" ; +print(findLongestString(dict1, str1)); + +# This code is conribued by mits",constant,quadratic +"# Python3 program to find largest word in Dictionary +# by deleting some characters of given string + +res="""" + +def check(d,s): + global res + i = 0 + j = 0 + while(i < len(d) and j < len(s)): + + if(d[i] == s[j]): + i += 1 + j += 1 + else: + j += 1 + + if(i == len(d) and len(res) < len(d)): + res = d + +def LongestWord(d, S): + + # sort the dictionary word + # for smallest lexicographical order + d.sort() + + for c in d : + check(c,S) + + return res + +# Driver program +dict = [ ""ale"", ""apple"", ""monkey"", ""plea"" ] +str = ""abpcplea"" +print(LongestWord(dict, str)) + +# This code is contributed by shinjanpatra",constant,quadratic +"# Python3 program to check if +# a string is perfect reversible or not + +# This function basically checks +# if string is palindrome or not +def isReversible(str): + i = 0; j = len(str) - 1; + + # iterate from left and right + while (i < j): + if (str[i] != str[j]): + return False; + i += 1; + j -= 1; + return True; + +# Driver Code +str = ""aba""; +if (isReversible(str)): + print(""YES""); +else: + print(""NO""); + +# This code is contributed by Princi Singh",constant,linear +"# Python3 Program to reverse an equation +# Function to reverse order of words +def reverseEquation(s): + + # Reverse String + result="""" + for i in range(len(s)): + + # A space marks the end of the word + if(s[i]=='+' or s[i]=='-' or s[i]=='/' or s[i]=='*'): + + # insert the word at the beginning + # of the result String + result = s[i] + result + + # insert the symbol + else: + result = s[i] + result + return result + +# Driver Code +s = ""a+b*c-d/e"" +print(reverseEquation(s)) + +# This code is contributed by simranjenny84",linear,linear +"# Python3 program for Left +# Rotation and Right +# Rotation of a String + +# In-place rotates s towards left by d +def leftrotate(s, d): + tmp = s[d : ] + s[0 : d] + return tmp + +# In-place rotates s +# towards right by d +def rightrotate(s, d): + + return leftrotate(s, len(s) - d) + +# Driver code +if __name__==""__main__"": + + str1 = ""GeeksforGeeks"" + print(leftrotate(str1, 2)) + + str2 = ""GeeksforGeeks"" + print(rightrotate(str2, 2)) + +# This code is contributed by Rutvik_56",constant,linear +"# Python3 program for Left +# Rotation and Right +# Rotation of a String + +def leftrotate(str1, n): + # extended string + temp = str1 + str1 + l = len(str1) + # Return string + return temp[n :l+n] +def rightrotate(str1, n): + return leftrotate(str1, len(str1)-n) + + return temp[l-n : l1-n ] +# Driver code +if __name__==""__main__"": + + str1 = ""GeeksforGeeks"" + print(leftrotate(str1, 2)) + + str2 = ""GeeksforGeeks"" + print(rightrotate(str2, 2)) + +# This code is contributed by sam snehil",linear,linear +"# A simple Python3 program to generate +# all rotations of a given string + +# Print all the rotated strings. +def printRotatedString(str): + + lenn = len(str) + + # Generate all rotations + # one by one and print + temp = [0] * (lenn) + for i in range(lenn): + j = i # Current index in str + k = 0 # Current index in temp + + # Copying the second part from + # the point of rotation. + while (j < len(str)): + + temp[k] = str[j] + k += 1 + j += 1 + + + # Copying the first part from + # the point of rotation. + j = 0 + while (j < i) : + + temp[k] = str[j] + j += 1 + k += 1 + + + print(*temp, sep = """") + +# Driver Code +if __name__ == '__main__': + str = ""geeks"" + printRotatedString(str) + +# This code is contributed +# by SHUBHAMSINGH10",linear,quadratic +"# An efficient Python3 program to print +# all rotations of a string. + +# Print all the rotated string. +def printRotatedString(string) : + + n = len(string) + + # Concatenate str with itself + temp = string + string + + # Print all substrings of size n. + # Note that size of temp is 2n + for i in range(n) : + + for j in range(n) : + print(temp[i + j], end = """") + + print() + +# Driver Code +if __name__ == ""__main__"" : + + string = ""geeks"" + printRotatedString(string) + +# This code is contributed by Ryuga",linear,quadratic +"# Python 3 program to determine minimum +# number of rotations required to yield +# same string. + +# Returns count of rotations to get the +# same string back. +def findRotations(str): + + # tmp is the concatenated string. + tmp = str + str + n = len(str) + + for i in range(1, n + 1): + + # substring from i index of + # original string size. + substring = tmp[i: i+n] + + # if substring matches with + # original string then we will + # come out of the loop. + if (str == substring): + return i + return n + +# Driver code +if __name__ == '__main__': + + str = ""abc"" + print(findRotations(str)) + +# This code is contributed +# by 29AjayKumar.",linear,quadratic +"# Python program to determine minimum number +# of rotations required to yield same +# string. + +# Returns count of rotations to get the +# same string back. +def findRotations(Str): + + ans = 0 # to store the answer + n = len(Str) # length of the String + + # All the length where we can partition + for i in range(1 , len(Str) - 1): + + # right part + left part = rotated String + # we are checking whether the rotated String is equal to + # original String + if(Str[i: n] + Str[0: i] == Str): + ans = i + break + + if(ans == 0): + return n + return ans + +# Driver code +Str = ""abc"" +print(findRotations(Str)) + +# This code is contributed by shinjanpatra",constant,quadratic +"# Python 3 program to determine minimum +# number of rotations required to yield +# same string. + +# input +string = 'aaaa' +check = '' + +for r in range(1, len(string)+1): + # checking the input after each rotation + check = string[r:] + string[:r] + + # following if statement checks if input is + # equals to check , if yes it will print r and + # break out of the loop + if check == string: + print(r) + break + +# This code is contributed +# by nagasowmyanarayanan.",linear,quadratic +"# Python program to check if +# two strings are rotations +# of each other +def isRotation(a: str, b: str) -> bool: + n = len(a) + m = len(b) + if (n != m): + return False + + # create lps[] that + # will hold the longest + # prefix suffix values + # for pattern + lps = [0 for _ in range(n)] + + # length of the previous + # longest prefix suffix + length = 0 + i = 1 + + # lps[0] is always 0 + lps[0] = 0 + + # the loop calculates + # lps[i] for i = 1 to n-1 + while (i < n): + if (a[i] == b[length]): + length += 1 + lps[i] = length + i += 1 + else: + if (length == 0): + lps[i] = 0 + i += 1 + else: + length = lps[length - 1] + i = 0 + + # Match from that rotating + # point + for k in range(lps[n - 1], m): + if (b[k] != a[i]): + return False + i += 1 + return True + +# Driver code +if __name__ == ""__main__"": + + s1 = ""ABACD"" + s2 = ""CDABA"" + print(""1"" if isRotation(s1, s2) else ""0"") + +# This code is contributed by sanjeev2552",linear,linear +"# Python3 program to count +# all rotation divisible +# by 4. + +# Returns count of all +# rotations divisible +# by 4 +def countRotations(n) : + + l = len(n) + + # For single digit number + if (l == 1) : + oneDigit = (int)(n[0]) + + if (oneDigit % 4 == 0) : + return 1 + return 0 + + + # At-least 2 digit number + # (considering all pairs) + count = 0 + for i in range(0, l - 1) : + twoDigit = (int)(n[i]) * 10 + (int)(n[i + 1]) + + if (twoDigit % 4 == 0) : + count = count + 1 + + # Considering the number + # formed by the pair of + # last digit and 1st digit + twoDigit = (int)(n[l - 1]) * 10 + (int)(n[0]) + if (twoDigit % 4 == 0) : + count = count + 1 + + return count + +# Driver program +n = ""4834"" +print(""Rotations: "" , + countRotations(n)) + +# This code is contributed by Nikita tiwari.",constant,linear +"# Python3 program to check if all rows +# of a matrix are rotations of each other + +MAX = 1000 + +# Returns true if all rows of mat[0..n-1][0..n-1] +# are rotations of each other. +def isPermutedMatrix(mat, n) : + + # Creating a string that contains + # elements of first row. + str_cat = """" + for i in range(n) : + str_cat = str_cat + ""-"" + str(mat[0][i]) + + # Concatenating the string with itself + # so that substring search operations + # can be performed on this + str_cat = str_cat + str_cat + + # Start traversing remaining rows + for i in range(1, n) : + + # Store the matrix into vector + # in the form of strings + curr_str = """" + + for j in range(n) : + curr_str = curr_str + ""-"" + str(mat[i][j]) + + # Check if the current string is present + # in the concatenated string or not + if (str_cat.find(curr_str)) : + return True + + return False + +# Driver code +if __name__ == ""__main__"" : + n = 4 + mat = [[1, 2, 3, 4], + [4, 1, 2, 3], + [3, 4, 1, 2], + [2, 3, 4, 1]] + + if (isPermutedMatrix(mat, n)): + print(""Yes"") + else : + print(""No"") + +# This code is contributed by Ryuga",linear,cubic +"# Python program to reverse a string using recursion + +# Function to print reverse of the passed string +def reverse(string): + if len(string) == 0: + return + + temp = string[0] + reverse(string[1:]) + print(temp, end='') + +# Driver program to test above function +string = ""Geeks for Geeks"" +reverse(string) + +# A single line statement to reverse string in python +# string[::-1] + +# This code is contributed by Bhavya Jain",linear,quadratic +"# Python3 program to print reverse +# of words in a string. + + +def wordReverse(str): + i = len(str)-1 + start = end = i+1 + result = '' + + while i >= 0: + if str[i] == ' ': + start = i+1 + while start != end: + result += str[start] + start += 1 + result += ' ' + end = i + i -= 1 + start = 0 + while start != end: + result += str[start] + start += 1 + return result + + +# Driver Code +str = 'I AM A GEEK' +print(wordReverse(str)) + +# This code is contributed +# by SamyuktaSHegde",linear,linear +"# Python code for the same approach +def reverse_words(s): + + left, i, n = 0, 0, len(s) + + while (s[i] == ' '): + i += 1 + + left = i + + while (i < n): + + if (i + 1 == n or s[i] == ' '): + + j = i - 1 + if (i + 1 == n): + j += 1 + + while (left < j): + s = s[0:left] + s[j] + s[left+1:j] + s[left] + s[j+1:] + + left += 1 + j -= 1 + + left = i + 1 + + if (i > left and s[left] == ' '): + left = i + + i += 1 + + s = s[::-1] + + return s + +# driver code +Str = ""I AM A GEEK"" +Str = reverse_words(Str) +print(Str) + +# This code is contributed by shinjanpatra",constant,linear +"# Python3 program to reverse string without +# affecting it's special character +def rev(s, l, r) : + while l= 'a' and s[i] <= 'z' or s[i] >= 'A' and s[i] <= 'Z' : + # storing elements in array + temp[x] = s[i] + x += 1 + + # reversing the character array + rev(temp, 0, x) + + lst = list(s) + x = 0 + + for i in range(len(s)) : + if s[i] >= 'a' and s[i] <= 'z' or s[i] >= 'A' and s[i] <= 'Z' : + # updating the origional string + lst[i] = temp[x] + x += 1 + + revStr = """" + for i in range(len(s)) : + revStr += lst[i] + + print(""reverse string is :"",revStr); + +# Driver Code +if __name__ == ""__main__"" : + + s=""Ab,c,de!$"" + + reverse(s) + +# This code is contributed by aditya942003patil",linear,linear +"def reverseString(text): + index = -1 + + # Loop from last index until half of the index + for i in range(len(text)-1, int(len(text)/2), -1): + + # match character is alphabet or not + if text[i].isalpha(): + temp = text[i] + while True: + index += 1 + if text[index].isalpha(): + text[i] = text[index] + text[index] = temp + break + return text + +# Driver code +string = ""a!!!b.c.d,e'f,ghi"" +print (""Input string: "", string) +string = reverseSting(list(string)) +print (""Output string: "", """".join(string)) + +# This code is contributed by shiva9610",constant,linear +"# Python3 program to reverse a string preserving +# spaces. + +# Function to reverse the string +# and preserve the space position +def reverses(st): + + # Mark spaces in result + n = len(st) + result = [0] * n + + for i in range(n): + if (st[i] == ' '): + result[i] = ' ' + + # Traverse input string from beginning + # and put characters in result from end + j = n - 1 + for i in range(len(st)): + + # Ignore spaces in input string + if (st[i] != ' '): + + # Ignore spaces in result. + if (result[j] == ' '): + j -= 1 + + result[j] = st[i] + j -= 1 + + return ''.join(result) + +# Driver code +if __name__ == ""__main__"": + + st = ""internship at geeks for geeks"" + print(reverses(st)) + +# This code is contributed by ukasp",linear,linear +"# Python3 program to implement +# the above approach +def preserveSpace(Str): + + n = len(Str) + Str = list(Str) + + # Initialize two pointers + # as two corners + start = 0 + end = n - 1 + + # Move both pointers + # toward each other + while(start < end): + + # If character at start + # or end is space, + # ignore it + if(Str[start] == ' '): + start += 1 + continue + elif(Str[end] == ' '): + end -= 1 + continue + + # If both are not + # spaces, do swap + else: + Str[start], Str[end] = (Str[end], + Str[start]) + start += 1 + end -= 1 + print(''.join(Str)) + +# Driver code +Str = ""internship at geeks for geeks"" +preserveSpace(Str); + +# This code is contributed by avanitrachhadiya2155",constant,linear +"# Python3 Program for removing characters +# from reversed string where vowels are +# present in original string + +# Function for replacing the string +def replaceOriginal(s, n): + + # initialize a string of length n + r = [' '] * n + + # Traverse through all characters of string + for i in range(n): + + # assign the value to string r + # from last index of string s + r[i] = s[n - 1 - i] + + # if s[i] is a consonant then + # print r[i] + if (s[i] != 'a' and s[i] != 'e' and + s[i] != 'i' and s[i] != 'o' and + s[i] != 'u'): + print(r[i], end = """") + print() + +# Driver Code +if __name__ == ""__main__"": + s = ""geeksforgeeks"" + n = len(s) + replaceOriginal(s, n) + +# This code is contributed by +# sanjeev2552",linear,linear +"# Python3 program to reverse order of vowels + +# utility function to check for vowel +def isVowel(c): + if (c == 'a' or c == 'A' or c == 'e' or + c == 'E' or c == 'i' or c == 'I' or + c == 'o' or c == 'O' or c == 'u' or c == 'U'): + return True + return False + +# Function to reverse order of vowels +def reverserVowel(string): + j = 0 + vowel = [0] * len(string) + string = list(string) + + # Storing the vowels separately + for i in range(len(string)): + if isVowel(string[i]): + vowel[j] = string[i] + j += 1 + + # Placing the vowels in the reverse + # order in the string + for i in range(len(string)): + if isVowel(string[i]): + j -= 1 + string[i] = vowel[j] + + return ''.join(string) + +# Driver Code +if __name__ == ""__main__"": + string = ""hello world"" + print(reverserVowel(string)) + +# This code is contributed by +# sanjeev2552",linear,linear +"# Python3 program to reverse order of vowels + +# utility function to check for vowel +def isVowel(c): + return (c=='a' or c=='A' or c=='e' or + c=='E' or c=='i' or c=='I' or + c=='o' or c=='O' or c=='u' or + c=='U') + +# Function to reverse order of vowels +def reverseVowel(str): + + # Start two indexes from two corners + # and move toward each other + i = 0 + j = len(str) - 1 + while (i < j): + if not isVowel(str[i]): + i += 1 + continue + if (not isVowel(str[j])): + j -= 1 + continue + + # swapping + str[i], str[j] = str[j], str[i] + i += 1 + j -= 1 + return str + +# Driver function +if __name__ == ""__main__"": + str = ""hello world"" + print(*reverseVowel(list(str)), sep = """") + +# This code is contributed by SHUBHAMSINGH10",constant,linear +"# Python3 program to reverse string +# according to the number of words + +# Reverse the letters of the word +def reverse(string, start, end): + + # Temporary variable to store character + temp = '' + while start <= end: + + # Swapping the first and last character + temp = string[start] + string[start] = string[end] + string[end] = temp + start += 1 + end -= 1 + +# This function forms the required string +def reverseletter(string, start, end): + wstart, wend = start, start + + while wend < end: + if string[wend] == "" "": + wend += 1 + continue + + # Checking the number of words + # present in string to reverse + while wend <= end and string[wend] != "" "": + wend += 1 + wend -= 1 + + # Reverse the letter + # of the words + reverse(string, wstart, wend) + wend += 1 + +# Driver Code +if __name__ == ""__main__"": + string = ""Ashish Yadav Abhishek Rajput Sunil Pundir"" + string = list(string) + reverseletter(string, 0, len(string) - 1) + print(''.join(string)) + +# This code is contributed by +# sanjeev2552",constant,linear +"# Python3 program to reverse each word +# in a linked list + +# Node of a linked list +class Node: + def __init__(self, next = None, data = None): + self.next = next + self.data = data + +# Function to create newNode +# in a linked list +def newNode(c) : + + temp = Node() + temp.c = c + temp.next = None + return temp + +# reverse each node data +def reverse_word(str) : + s = """" + i = 0 + while(i < len(str) ): + s = str[i] + s + i = i + 1 + return s + +def reverse( head) : + ptr = head + + # iterate each node and call reverse_word + # for each node data + while (ptr != None): + ptr.c = reverse_word(ptr.c) + ptr = ptr.next + + return head + +# printing linked list +def printList( head) : + + while (head != None): + print( head.c ,end = "" "") + head = head.next + +# Driver program +head = newNode(""Geeksforgeeks"") +head.next = newNode(""a"") +head.next.next = newNode(""computer"") +head.next.next.next = newNode(""science"") +head.next.next.next.next = newNode(""portal"") +head.next.next.next.next.next = newNode(""for"") +head.next.next.next.next.next.next = newNode(""geeks"") + +print( ""List before reverse: "") +printList(head) + +head = reverse(head) + +print( ""\n\nList after reverse: "") +printList(head) + +# This code is contributed by Arnab Kundu",constant,linear +"# Python3 code to check if +# cyclic order is possible +# among strings under given +# constraints +M = 26 + +# Utility method for a depth +# first search among vertices +def dfs(g, u, visit): + visit[u] = True + + for i in range(len(g[u])): + if(not visit[g[u][i]]): + dfs(g, g[u][i], visit) + +# Returns true if all vertices +# are strongly connected i.e. +# can be made as loop +def isConnected(g, mark, s): + + # Initialize all vertices + # as not visited + visit = [False for i in range(M)] + + # Perform a dfs from s + dfs(g, s, visit) + + # Now loop through + # all characters + for i in range(M): + + # I character is marked + # (i.e. it was first or last + # character of some string) + # then it should be visited + # in last dfs (as for looping, + # graph should be strongly + # connected) */ + if(mark[i] and (not visit[i])): + return False + + # If we reach that means + # graph is connected + return True + +# return true if an order among +# strings is possible +def possibleOrderAmongString(arr, N): + + # Create an empty graph + g = {} + + # Initialize all vertices + # as not marked + mark = [False for i in range(M)] + + # Initialize indegree and + # outdegree of every + # vertex as 0. + In = [0 for i in range(M)] + out = [0 for i in range(M)] + + # Process all strings + # one by one + for i in range(N): + + # Find first and last + # characters + f = (ord(arr[i][0]) - + ord('a')) + l = (ord(arr[i][-1]) - + ord('a')) + + # Mark the characters + mark[f] = True + mark[l] = True + + # Increase indegree + # and outdegree count + In[l] += 1 + out[f] += 1 + + if f not in g: + g[f] = [] + + # Add an edge in graph + g[f].append(l) + + # If for any character + # indegree is not equal to + # outdegree then ordering + # is not possible + for i in range(M): + if(In[i] != out[i]): + return False + + return isConnected(g, mark, + ord(arr[0][0]) - + ord('a')) + +# Driver code +arr = [""ab"", ""bc"", + ""cd"", ""de"", + ""ed"", ""da""] +N = len(arr) +if(possibleOrderAmongString(arr, N) == + False): + print(""Ordering not possible"") +else: + print(""Ordering is possible"") + +# This code is contributed by avanitrachhadiya2155",linear,linear +"# Python3 program to sort an Array of +# Strings according to their lengths + +# Function to print the sorted array of string +def printArraystring(string, n): + for i in range(n): + print(string[i], end = "" "") + +# Function to Sort the array of string +# according to lengths. This function +# implements Insertion Sort. +def sort(s, n): + for i in range(1, n): + temp = s[i] + + # Insert s[j] at its correct position + j = i - 1 + while j >= 0 and len(temp) < len(s[j]): + s[j + 1] = s[j] + j -= 1 + + s[j + 1] = temp + +# Driver code +if __name__ == ""__main__"": + arr = [""GeeksforGeeks"", ""I"", ""from"", ""am""] + n = len(arr) + + # Function to perform sorting + sort(arr, n) + + # Calling the function to print result + printArraystring(arr, n) + +# This code is contributed by +# sanjeev2552",constant,quadratic +"from functools import cmp_to_key + +# Function to check the small string +def compare(s1,s2): + return len(s1) - len(s2) + +# Function to print the sorted array of string +def printArraystring(str,n): + for i in range(n): + print(str[i],end = "" "") + +# Driver function +arr = [""GeeksforGeeks"", ""I"", ""from"", ""am""] +n = len(arr) + +# Function to perform sorting +arr.sort(key = cmp_to_key(compare)) + +# Calling the function to print result +printArraystring(arr, n) + +# This code is contributed by shinjanpatra.",constant,nlogn +"# Python code for the above approach +def printsorted(arr): + + # Sorting using sorted function + # providing key as len + print(*sorted(arr, key=len)) + + +# Driver code +arr = [""GeeksforGeeks"", ""I"", ""from"", ""am""] + +# Passing list to printsorted function +printsorted(arr) + +# this code is contributed by vikkycirus",constant,nlogn +"# Python3 program to sort an array of strings +# using Trie + +MAX_CHAR = 26 + +class Trie: + + # index is set when node is a leaf + # node, otherwise -1; + # to make new trie + def __init__(self): + self.child = [None for i in range(MAX_CHAR)] + self.index = -1 + + +# def to insert in trie +def insert(root,str,index): + + node = root + + for i in range(len(str)): + + # taking ascii value to find index of + # child node + ind = ord(str[i]) - ord('a') + + # making new path if not already + if (node.child[ind] == None): + node.child[ind] = Trie() + + # go to next node + node = node.child[ind] + + + # Mark leaf (end of word) and store + # index of word in arr[] + node.index = index + + +# function for preorder traversal +def preorder(node, arr): + + if (node == None): + return False + + for i in range(MAX_CHAR): + if (node.child[i] != None): + + # if leaf node then print key + if (node.child[i].index != -1): + print(arr[node.child[i].index]) + + preorder(node.child[i], arr) + + + +def printSorted(arr,n): + + root = Trie() + + # insert all keys of dictionary into trie + for i in range(n): + insert(root, arr[i], i) + + # print keys in lexicographic order + preorder(root, arr) + + +# Driver code + +arr = [ ""abc"", ""xy"", ""bcd"" ] +n = len(arr) +printSorted(arr, n) + +# This code is contributed by shinjanpatra",linear,linear +"# Python3 program to sort a string +# of characters + +# function to print string in +# sorted order +def sortString(str) : + str = ''.join(sorted(str)) + print(str) + +# Driver Code +s = ""geeksforgeeks"" +sortString(s) + +# This code is contributed by Smitha",constant,nlogn +"# Python 3 program to sort a string +# of characters + +MAX_CHAR = 26 + +# function to print string in sorted order +def sortString(str): + + # Hash array to keep count of characters. + # Initially count of all characters is + # initialized to zero. + charCount = [0 for i in range(MAX_CHAR)] + + # Traverse string and increment + # count of characters + for i in range(0, len(str), 1): + + # 'a'-'a' will be 0, 'b'-'a' will be 1, + # so for location of character in count + # array we will do str[i]-'a'. + charCount[ord(str[i]) - ord('a')] += 1 + + # Traverse the hash array and print + # characters + for i in range(0, MAX_CHAR, 1): + for j in range(0, charCount[i], 1): + print(chr(ord('a') + i), end = """") + +# Driver Code +if __name__ == '__main__': + s = ""geeksforgeeks"" + sortString(s) + +# This code is contributed by +# Sahil_Shelangia",constant,linear +"# Python program to sort +# a string in descending +# order using library function + +def descOrder(s): + s.sort(reverse = True) + str1 = ''.join(s) + print(str1) + +def main(): + s = list('geeksforgeeks') + + # function call + descOrder(s) + +if __name__==""__main__"": + main() + +# This code is contributed by +# prabhat kumar singh",constant,constant +"# Python program to sort a string of characters +# in descending order + +MAX_CHAR = 26; + +# function to print string in sorted order +def sortString(str): + + # Hash array to keep count of characters. + # Initially count of all charters is + # initialized to zero. + charCount = [0]*MAX_CHAR; + + # Traverse string and increment + # count of characters + for i in range(len(str)): + + # 'a'-'a' will be 0, 'b'-'a' will be 1, + # so for location of character in count + # array we will do str[i]-'a'. + charCount[ord(str[i]) - ord('a')]+=1; + + # Traverse the hash array and print + # characters + for i in range(MAX_CHAR - 1,-1, -1): + for j in range(charCount[i]): + print(chr(97+i),end=""""); + +# Driver program to test above function +s = ""alkasingh""; +sortString(s); + +# This code is contributed by Princi Singh",constant,linear +"# Python 3 implementation to print array +# of strings in sorted order without +# copying one string into another + +# function to print strings in sorted order +def printInSortedOrder(arr, n): + index = [0] * n + + # Initially the index of the strings + # are assigned to the 'index[]' + for i in range(n): + index[i] = i + + # selection sort technique is applied + for i in range(n - 1): + min = i + for j in range(i + 1, n): + + # with the help of 'index[]' + # strings are being compared + if (arr[index[min]] > arr[index[j]]): + min = j + + # index of the smallest string is placed + # at the ith index of 'index[]' + if (min != i): + index[min], index[i] = index[i], index[min] + + # printing strings in sorted order + for i in range(n): + print(arr[index[i]], end = "" "") + +# Driver Code +if __name__ == ""__main__"": + + arr = [""geeks"", ""quiz"", ""geeks"", ""for""] + n = 4 + printInSortedOrder(arr, n) + +# This code is contributed by ita_c",linear,quadratic +"# Python3 implementation to sort +# the given string without using +# any sorting technique + +# Function to sort the given string +# without using any sorting technique +def sortString(str, n): + + # To store the final sorted string + new_str = """" + + # for each character 'i' + for i in range(ord('a'), ord('z') + 1): + + # if character 'i' is present at a particular + # index then add character 'i' to 'new_str' + for j in range(n): + if (str[j] == chr(i)): + new_str += str[j] + + # required final sorted string + return new_str + +# Driver Code +str = ""geeksforgeeks"" +n = len(str) +print(sortString(str, n)) + +# This code is contributed by Anant Agarwal.",constant,linear +"# Python 3 implementation to sort the given +# string without using any sorting technique +def sortString(st, n): + + # A character array to store the no.of occurrences of each character + # between 'a' to 'z' + arr = [0] * 26 + + # to store the final sorted string + new_str = """" + + # To store each occurrence of character by relative indexing + for i in range(n): + arr[ord(st[i]) - ord('a')] += 1 + + # To traverse the character array and append it to new_str + for i in range(26): + while(arr[i] > 0): + new_str += chr(i+ord('a')) + arr[i] -= 1 + + return new_str + +# Driver program to test above +if __name__ == ""__main__"": + + st = ""geeksforgeeks"" + n = len(st) + print(sortString(st, n)) + + # This code is contributed by ukasp.",constant,linear +"# Python3 program for above implementation +MAX_CHAR = 26 + +# Function to return string in lexicographic +# order followed by integers sum +def arrangeString(string): + char_count = [0] * MAX_CHAR + s = 0 + + # Traverse the string + for i in range(len(string)): + + # Count occurrence of uppercase alphabets + if string[i] >= ""A"" and string[i] <= ""Z"": + char_count[ord(string[i]) - ord(""A"")] += 1 + + # Store sum of integers + else: + s += ord(string[i]) - ord(""0"") + + res = """" + + # Traverse for all characters A to Z + for i in range(MAX_CHAR): + ch = chr(ord(""A"") + i) + + # Append the current character + # in the string no. of times it + # occurs in the given string + while char_count[i]: + res += ch + char_count[i] -= 1 + + # Append the sum of integers + if s > 0: + res += str(s) + + # return resultant string + return res + +# Driver code +if __name__ == ""__main__"": + string = ""ACCBA10D2EW30"" + print(arrangeString(string)) + +# This code is contributed by +# sanjeev2552",linear,linear +"# Python3 program to print +# all permutations of a +# string in sorted order. +from collections import defaultdict + +# Calculating factorial +# of a number +def factorial(n): + + f = 1 + + for i in range (1, n + 1): + f = f * i + return f + +# Method to find total +# number of permutations +def calculateTotal(temp, n): + + f = factorial(n) + + # Building Map to store + # frequencies of all + # characters. + hm = defaultdict (int) + + for i in range (len(temp)): + hm[temp[i]] += 1 + + # Traversing map and + # finding duplicate elements. + for e in hm: + x = hm[e] + if (x > 1): + temp5 = factorial(x) + f //= temp5 + return f + +def nextPermutation(temp): + + # Start traversing from + # the end and find position + # 'i-1' of the first character + # which is greater than its successor + for i in range (len(temp) - 1, 0, -1): + if (temp[i] > temp[i - 1]): + break + + # Finding smallest character + # after 'i-1' and greater + # than temp[i-1] + min = i + x = temp[i - 1] + for j in range (i + 1, len(temp)): + if ((temp[j] < temp[min]) and + (temp[j] > x)): + min = j + + # Swapping the above + # found characters. + temp[i - 1], temp[min] = (temp[min], + temp[i - 1]) + + # Sort all digits from + # position next to 'i-1' + # to end of the string + temp[i:].sort() + + # Print the String + print (''.join(temp)) + +def printAllPermutations(s): + + # Sorting String + temp = list(s) + temp.sort() + + # Print first permutation + print (''.join( temp)) + + # Finding the total permutations + total = calculateTotal(temp, + len(temp)) + for i in range (1, total): + nextPermutation(temp) + +# Driver Code +if __name__ == ""__main__"": + + s = ""AAB"" + printAllPermutations(s) + +# This code is contributed by Chitranayal",linear,quadratic +"# Python program to get minimum cost to sort +# strings by reversal operation + +# Returns minimum cost for sorting arr[] +# using reverse operation. This function +# returns -1 if it is not possible to sort. +def ReverseStringMin(arr, reverseCost, n): + + # dp[i][j] represents the minimum cost to + # make first i strings sorted. + # j = 1 means i'th string is reversed. + # j = 0 means i'th string is not reversed. + + dp = [[float(""Inf"")] * 2 for i in range(n)] + + # initializing dp array for first string + dp[0][0] = 0 + + dp[0][1] = reverseCost[0] + + # getting array of reversed strings + rev_arr = [i[::-1] for i in arr] + + # looping for all strings + for i in range(1, n): + + # Looping twice, once for string and once + # for reversed string + for j in range(2): + + # getting current string and current + # cost according to j + curStr = arr[i] if j==0 else rev_arr[i] + + curCost = 0 if j==0 else reverseCost[i] + + # Update dp value only if current string + # is lexicographically larger + if (curStr >= arr[i - 1]): + + dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost) + + if (curStr >= rev_arr[i - 1]): + + dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost) + + # getting minimum from both entries of last index + res = min(dp[n-1][0], dp[n-1][1]) + + return res if res != float(""Inf"") else -1 + + +# Driver code +def main(): + + + arr = [""aa"", ""ba"", ""ac""] + + reverseCost = [1, 3, 1] + + n = len(arr) + + dp = [float(""Inf"")] * n + + res = ReverseStringMin(arr, reverseCost,n) + + if res != -1 : + + print (""Minimum cost to sort sorting is"" , res) + + else : + print (""Sorting not possible"") + + +if __name__ == '__main__': + main() + +#This code is contributed by Neelam Yadav",linear,linear +"# Python program for printing +# all numbers containing 1,2 and 3 + + +def printNumbers(numbers): + + # convert all numbers + # to strings + numbers = map(str, numbers) + result = [] + for num in numbers: + + # check if each number + # in the list has 1,2 and 3 + if ('1' in num and + '2' in num and + '3' in num): + result.append(num) + + # if there are no + # valid numbers + if not result: + result = ['-1'] + + return sorted(result) + + +# Driver Code +numbers = [123, 1232, 456, + 234, 32145] +result = printNumbers(numbers) +print ', '.join(num for num in result) + +# This code is contributed +# by IshitaTripathi",linear,nlogn +"# Python3 program to implement binary search +# in a sparse array + +def sparseSearch(arr , key , low , high): + + left = 0; right = 0 + + while low <= high: + + mid = low + (high - low) // 2 + + if arr[mid] == '': + left = mid - 1 + right = mid + 1 + + while True: + + # Check for out of bounds + if left < low and right > high: + return -1 + + elif left >= low and arr[left] != '': + # Search left + mid = left + break + + elif right <= high and arr[right] != '': + # Search right + mid = right + break + + left -= 1 + right += 1 + + if arr[mid] == key: + print('Found string {} at index {}'.format + (arr[mid] , mid)) + return mid + + # Classical Binary search + # search left + elif arr[mid] > key: + high = mid - 1 + + # search right + elif arr[mid] < key: + low = mid + 1 + + return -1 + +if __name__ == '__main__': + + arr = [""for"", ""geeks"", """", """", """", """", ""ide"", + ""practice"", """", """", """", ""quiz""] + key = 'geeks' + + low = 0 + high = len(arr) - 1 + + sparseSearch(arr , key , low , high) + +# This is Code contributed by +# Ashwin Viswanathan +# Additional Updates by Meghna Natraj",logn,logn +"# Python3 Program to find maximum +# lowercase alphabets present +# between two uppercase alphabets + +MAX_CHAR = 26 + +# Function which computes the +# maximum number of distinct +# lowercase alphabets between +# two uppercase alphabets +def maxLower(str): + n = len(str) + + # Ignoring lowercase characters + # in the beginning. + i = 0 + for i in range(n): + if str[i] >= 'A' and str[i] <= 'Z': + i += 1 + break + + # We start from next of first capital + # letter and traverse through + # remaining character. + maxCount = 0 + count = [] + for j in range(MAX_CHAR): + count.append(0) + + for j in range(i, n): + + # If character is in uppercase, + if str[j] >= 'A' and str[j] <= 'Z': + + # Count all distinct lower + # case characters + currCount = 0 + for k in range(MAX_CHAR): + if count[k] > 0: + currCount += 1 + + # Update maximum count + maxCount = max(maxCount, currCount) + + # Reset count array + for y in count: + y = 0 + + # If character is in lowercase + if str[j] >= 'a' and str[j] <= 'z': + count[ord(str[j]) - ord('a')] += 1 + + return maxCount + +# Driver function +str = ""zACaAbbaazzC""; +print(maxLower(str)) + +# This code is contributed by Upendra Bartwal",constant,linear +"# Python3 Program to find maximum +# lowercase alphabets present +# between two uppercase alphabets + +# Function which computes the +# maximum number of distinct +# lowercase alphabets between +# two uppercase alphabets +def maxLower(str): + + n = len(str); + + # Ignoring lowercase characters + # in the beginning. + i = 0; + for i in range(n): + + if (str[i] >= 'A' and + str[i] <= 'Z'): + i += 1; + break; + + # We start from next of first + # capital letter and traverse + # through remaining character. + maxCount = 3; + s = set() + + for i in range(n): + + # If character is in + # uppercase, + if (str[i] >= 'A' and + str[i] <= 'Z'): + + # Update maximum count if + # lowercase character before + # this is more. + maxCount = max(maxCount, + len(s)); + + # clear the set + s.clear(); + + # If character is in + # lowercase + if (str[i] >= 'a' and + str[i] <= 'z'): + s.add(str[i]); + return maxCount; + +# Driver Code +if __name__ == '__main__': + + str = ""zACaAbbaazzC""; + print(maxLower(str)); + +# This code is contributed by 29AjayKumar",linear,linear +"# Python3 program to Convert characters +# of a string to opposite case + +str = ""GeEkSfOrGeEkS"" +x="""" +for i in str: + if(i.isupper()): + x+=i.lower() + else: + x+=i.upper() +print(x)",constant,linear +"# Python3 program to Convert characters +# of a string to opposite case + +str = ""GeEkSfOrGeEkS"" +x="""" +upperalphabets=""ABCDEFGHIJKLMNOPQRSTUVWXYZ"" +loweralphabets=""abcdefghijklmnopqrstuvwxyz"" +for i in str: + if i in upperalphabets: + x+=loweralphabets[upperalphabets.index(i)] + else: + x+=upperalphabets[loweralphabets.index(i)] +print(x)",constant,linear +"# Python3 program to convert a +# sentence to gOOGLE cASE. +def convert(str): + + # empty strings + w = """" + z = """"; + + # convert input string + # to upper case + str = str.upper() + "" ""; + + for i in range(len(str)): + + # checki if character is not + # a space and adding it to + # string w + ch = str[i]; + if (ch != ' '): + w = w + ch; + else: + + # converting first character + # to lower case and subsequent + # initial letter of another + # word to lower case + z = (z + (w[0]).lower() + + w[1:len(w)] + "" ""); + w = """"; + + return z; + +# Driver code +if __name__ == '__main__': + + str = ""I got intern at geeksforgeeks""; + print(convert(str)); + +# This code is contributed by 29AjayKumar",linear,linear +"# Python program to convert given +# sentence to camel case. +import math + +# Function to remove spaces +# and convert into camel case +def convert( s): + + n = len(s) + s1 = """" + s1 = s1 + s[0].lower() + i = 1 + while i < n: + # check for spaces in the sentence + if (s[i] == ' ' and i <= n): + + # conversion into upper case + s1 = s1 + "" "" + (s[i + 1]).lower() + i = i + 1 + + # If not space, copy character + else: + s1 = s1 + (s[i]).upper() + + # increase index of string by s1 + i = i + 1 + + # return string to main + return s1 + +# Driver code +str = ""I get intern at geeksforgeeks"" +print(convert(str)) + +# This code is contributed by Gitanjali.",constant,linear +"# Python program to convert +# given sentence to camel case. + +# Function to remove spaces +# and convert into camel case +def convert(s): + if(len(s) == 0): + return + s1 = '' + s1 += s[0].upper() + for i in range(1, len(s)): + if (s[i] == ' '): + s1 += s[i + 1].upper() + i += 1 + elif(s[i - 1] != ' '): + s1 += s[i] + print(s1) + + +# Driver Code +def main(): + s = ""I get intern at geeksforgeeks"" + convert(s) + +if __name__==""__main__"": + main() + +# This code is contributed +# prabhat kumar singh + ",constant,linear +"# Python code to print all permutations +# with respect to cases + +# function to generate permutations + + +def permute(ip, op): + + # base case + if len(ip) == 0: + print(op, end="" "") + return + + # pick lower and uppercase + ch = ip[0].lower() + ch2 = ip[0].upper() + ip = ip[1:] + permute(ip, op+ch) + permute(ip, op+ch2) + +# driver code + + +def main(): + ip = ""AB"" + permute(ip, """") + + +main() + +# This Code is Contributed by Vivek Maddeshiya",linear,np +"# Python code to print all permutations +# with respect to cases + +# Function to generate permutations + + +def permute(inp): + n = len(inp) + + # Number of permutations is 2^n + mx = 1 << n + + # Converting string to lower case + inp = inp.lower() + + # Using all subsequences and permuting them + for i in range(mx): + # If j-th bit is set, we convert it to upper case + combination = [k for k in inp] + for j in range(n): + if (((i >> j) & 1) == 1): + combination[j] = inp[j].upper() + + temp = """" + # Printing current combination + for i in combination: + temp += i + print temp, + + +# Driver code +permute(""ABC"") + +# This code is contributed by Sachin Bisht",linear,quadratic +"# Python3 program to get toggle case of a string +x = 32; + +# tOGGLE cASE = swaps CAPS to lower +# case and lower case to CAPS +def toggleCase(a): + + for i in range(len(a)): + + # Bitwise EXOR with 32 + a = a[:i] + chr(ord(a[i]) ^ 32) + a[i + 1:]; + return a; + +# Driver Code +str = ""CheRrY""; +print(""Toggle case: "", end = """"); +str = toggleCase(str); +print(str); + +print(""Original string: "", end = """"); +str = toggleCase(str); +print(str); + +# This code is contributed by 29AjayKumar",constant,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))",constant,linear +"# Python program to print the first non-repeating character + +string = ""geeksforgeeks"" +index = -1 +fnc = """" +for i in string: + if string.count(i) == 1: + fnc += i + break + else: + index += 1 +if index == 1: + print(""Either all characters are repeating or string is empty"") +else: + print(""First non-repeating character is"", fnc)",constant,quadratic +"# python3 implementation + + +def FirstNonRepeat(s): + + for i in s: + + if (s.find(i, (s.find(i)+1))) == -1: + + print(""First non-repeating character is"", i) + + break + + return + +# __main__ + + +s = 'geeksforgeeks' + +FirstNonRepeat(s)",constant,quadratic +"# Python program to print the first non-repeating character +NO_OF_CHARS = 256 + +# Returns an array of size 256 containing count +# of characters in the passed char array + + +def getCharCountArray(string): + count = [0] * NO_OF_CHARS + for i in string: + count[ord(i)] += 1 + return count + +# The function returns index of first non-repeating +# character in a string. If all characters are repeating +# then returns -1 + + +def firstNonRepeating(string): + count = getCharCountArray(string) + index = -1 + k = 0 + + for i in string: + if count[ord(i)] == 1: + index = k + break + k += 1 + + return index + + +# Driver program to test above function +string = ""geeksforgeeks"" +index = firstNonRepeating(string) +if index == 1: + print(""Either all characters are repeating or string is empty"") +else: + print(""First non-repeating character is"", string[index]) + +# This code is contributed by Bhavya Jain",constant,linear +"# Python3 program to find first non-repeating +# character +import sys + +NO_OF_CHARS = 256 + +# The function returns index of the first +# non-repeating character in a string. If +# all characters are repeating then +# returns sys.maxsize : + + +def firstNonRepeating(Str): + + arr = [[] for i in range(NO_OF_CHARS)] + for i in range(NO_OF_CHARS): + arr[i] = [0, 0] + + for i in range(len(Str)): + arr[ord(Str[i])][0] += 1 + arr[ord(Str[i])][1] = i + + res = sys.maxsize + for i in range(NO_OF_CHARS): + + # If this character occurs only + # once and appears before the + # current result, then update the + # result + if (arr[i][0] == 1): + res = min(res, arr[i][1]) + + return res + + +# Driver program to test above functionS +Str = ""geeksforgeeks"" +index = firstNonRepeating(Str) +if (index == sys.maxsize): + print(""Either all characters are repeating or string is empty"") +else: + print(""First non-repeating character is "", Str[index]) + +# This code is contributed by shinjanpatra",constant,linear +"# this function return the index of first non-repeating +# character if found, or else it returns -1 +import sys + + +def firstNonRepeating(Str): + fi = [-1 for i in range(256)] + + # sets all repeating characters to -2 and non-repeating characters + # contain the index where they occur + for i in range(len(Str)): + + if(fi[ord(Str[i])] == -1): + fi[ord(Str[i])] = i + else: + fi[ord(Str[i])] = -2 + + res = sys.maxsize + + for i in range(256): + + # If this character is not -1 or -2 then it + # means that this character occurred only once + # so find the min index of all characters that + # occur only once, that's our first index + if(fi[i] >= 0): + res = min(res, fi[i]) + + # if res remains INT_MAX, it means there are no + # characters that repeat only once or the string is empty + if(res == sys.maxsize): + return -1 + else: + return res + + +Str = ""geeksforgeeks"" +firstIndex = firstNonRepeating(Str) + +if (firstIndex == -1): + print(""Either all characters are repeating or string is empty"") +else: + print(""First non-repeating character is "" + str(Str[firstIndex])) + +# This code is contributed by shinjanpatra",constant,linear +"# Python implementation +from collections import Counter + +# Function which repeats +# first Nonrepeating character + + +def printNonrepeated(string): + + # Calculating frequencies + # using Counter function + freq = Counter(string) + + # Traverse the string + for i in string: + if(freq[i] == 1): + print(""First non-repeating character is "" + i) + break + + +# Driver code +string = ""geeksforgeeks"" + +# passing string to printNonrepeated function +printNonrepeated(string) + +# this code is contributed by vikkycirus",constant,linear +"# Python program to print all permutations with repetition +# of characters + +def toString(List): + return ''.join(List) + +# The main function that recursively prints all repeated +# permutations of the given string. It uses data[] to store +# all permutations one by one +def allLexicographicRecur (string, data, last, index): + length = len(string) + + # One by one fix all characters at the given index and + # recur for the subsequent indexes + for i in range(length): + + # Fix the ith character at index and if this is not + # the last index then recursively call for higher + # indexes + data[index] = string[i] + + # If this is the last index then print the string + # stored in data[] + if index==last: + print (toString(data)) + else: + allLexicographicRecur(string, data, last, index+1) + +# This function sorts input string, allocate memory for data +# (needed for allLexicographicRecur()) and calls +# allLexicographicRecur() for printing all permutations +def allLexicographic(string): + length = len(string) + + # Create a temp array that will be used by + # allLexicographicRecur() + data = [""""] * (length+1) + + # Sort the input string so that we get all output strings in + # lexicographically sorted order + string = sorted(string) + + # Now print all permutations + allLexicographicRecur(string, data, length-1, 0) + +# Driver program to test the above functions +string = ""ABC"" +print (""All permutations with repetition of "" + string + "" are:"") +allLexicographic(string) + +# This code is contributed to Bhavya Jain",linear,np +"# A Python program to find first non-repeating character from +# a stream of characters +MAX_CHAR = 256 + +def findFirstNonRepeating(): + + # inDLL[x] contains pointer to a DLL node if x is present + # in DLL. If x is not present, then inDLL[x] is NULL + inDLL = [] * MAX_CHAR + + # repeated[x] is true if x is repeated two or more times. + # If x is not seen so far or x is seen only once. then + # repeated[x] is false + repeated = [False] * MAX_CHAR + + # Let us consider following stream and see the process + stream = ""geekforgeekandgeeksandquizfor"" + for i in range(len(stream)): + x = stream[i] + print (""Reading "" + x + "" from stream"") + + # We process this character only if it has not occurred + # or occurred only once. repeated[x] is true if x is + # repeated twice or more.s + if not repeated[ord(x)]: + + # If the character is not in DLL, then add this + # at the end of DLL + if not x in inDLL: + inDLL.append(x) + else: + inDLL.remove(x) + repeated[ord(x)] = True + + if len(inDLL) != 0: + print (""First non-repeating character so far is "") + print (str(inDLL[0])) + +# Driver program +findFirstNonRepeating() + +# This code is contributed by BHAVYA JAIN",constant,linear +"# Python3 program to check if a can be converted to +# a that has repeated subs of length k. + +# Returns True if S can be converted to a +# with k repeated subs after replacing k +# characters. +def check( S, k): + + # Length of must be a multiple of k + n = len(S) + + if (n % k != 0): + return False + + # Map to store s of length k and their counts + mp = {} + for i in range(0, n, k): + mp[S[i:k]] = mp.get(S[i:k], 0) + 1 + + # If is already a repetition of k subs, + # return True. + if (len(mp) == 1): + return True + + # If number of distinct subs is not 2, then + # not possible to replace a . + if (len(mp) != 2): + return False + + # One of the two distinct must appear exactly once. + # Either the first entry appears once, or it appears + # n/k-1 times to make other sub appear once. + for i in mp: + if i == (n//k - 1) or mp[i] == 1: + return True + + return False + +# Driver code + +if check(""abababcd"", 2): + print(""Yes"") +else: + print(""No"") + +# This code is contributed by mohit kumar 29 ",linear,linear +"# Python3 program to find smallest possible +# length of a string of only three characters + +# A memoized function find result recursively. +# a, b and c are counts of 'a's, 'b's and +# 'c's in str +def length(a, b, c): + + global DP + + #print(a, b, c) + + # If this subproblem is already + # evaluated + if a < 0 or b < 0 or c < 0: + return 0 + + if (DP[a][b] != -1): + return DP[a][b] + + # If there is only one type + # of character + if (a == 0 and b == 0): + DP[a][b] = c + return c + if (a == 0 and c == 0): + DP[a][b] = b + return b + if (b == 0 and c == 0): + DP[a][b] = a + return a + + # If only two types of characters + # are present + if (a == 0): + DP[a][b] = length(a + 1, b - 1, + c - 1) + return DP[a][b] + + if (b == 0): + DP[a][b] = length(a - 1, b + 1, + c - 1) + return DP[a][b] + + if (c == 0): + DP[a][b] = length(a - 1, b - 1, + c + 1) + return DP[a][b] + + # If all types of characters are present. + # Try combining all pairs. + x = length(a - 1, b - 1, c + 1) + y = length(a - 1, b + 1, c - 1) + z = length(a + 1, b - 1, c - 1) + + DP[a][b] = min([x, y, z]) + + return DP[a][b] + +# Returns smallest possible length with +# given operation allowed. +def stringReduction(str): + + n = len(str) + + # Counting occurrences of three different + # characters 'a', 'b' and 'c' in str + count = [0] * 3 + + for i in range(n): + count[ord(str[i]) - ord('a')] += 1 + + return length(count[0], count[1], count[2]) + +# Driver code +if __name__ == '__main__': + + DP = [[[-1 for i in range(110)] + for i in range(110)] + for i in range(110)] + + str = ""abcbbaacb"" + + print(stringReduction(str)) + +# This code is contributed by mohit kumar 29",linear,linear +"# Python3 program to find smallest possible +# length of a string of only three characters + +# Returns smallest possible length +# with given operation allowed. +def stringReduction(str): + + n = len(str) + + # Counint occurrences of three different + # characters 'a', 'b' and 'c' in str + count = [0] * 3 + for i in range(n): + count[ord(str[i]) - ord('a')] += 1 + + # If all characters are same. + if (count[0] == n or count[1] == n or + count[2] == n): + return n + + # If all characters are present even number + # of times or all are present odd number of + # times. + if ((count[0] % 2) == (count[1] % 2) and + (count[1] % 2) == (count[2] % 2)): + return 2 + + # Answer is 1 for all other cases. + return 1 + +# Driver code +if __name__ == ""__main__"": + + str = ""abcbbaacb"" + print(stringReduction(str)) + +# This code is contributed by ita_c",constant,linear +"# Python3 program to find if its possible to +# distribute balls without repetition + + +MAX_CHAR = 26 + +# function to find if its possible to +# distribute balls or not +def distributingBalls(k, n, string) : + + # count array to count how many times + # each color has occurred + a = [0] * MAX_CHAR + + for i in range(n) : + # increasing count of each color + # every time it appears + a[ord(string[i]) - ord('a')] += 1 + + for i in range(MAX_CHAR) : + # to check if any color appears + # more than K times if it does + # we will print NO + if (a[i] > k) : + return False + + return True + + +# Driver code +if __name__ == ""__main__"" : + + n, k = 6, 3 + string = ""aacaab"" + + if (distributingBalls(k, n, string)) : + print(""YES"") + else : + print(""NO"") + +# This code is contributed by Ryuga",constant,linear +"# Python 3 program to find the +# maximum consecutive repeating +# character in given string + +# function to find out the maximum +# repeating character in given string +def maxRepeating(str): + + l = len(str) + count = 0 + + # Find the maximum repeating + # character starting from str[i] + res = str[0] + for i in range(l): + + cur_count = 1 + for j in range(i + 1, l): + + if (str[i] != str[j]): + break + cur_count += 1 + + # Update result if required + if cur_count > count : + count = cur_count + res = str[i] + return res + +# Driver code +if __name__ == ""__main__"": + + str = ""aaaabbaaccde"" + print(maxRepeating(str)) + +# This code is contributed +# by ChitraNayal",constant,quadratic +"# Python 3 program to find the +# maximum consecutive repeating +# character in given string + +# Returns the maximum repeating +# character in a given string +def maxRepeating(str): + + n = len(str) + count = 0 + res = str[0] + cur_count = 1 + + # Traverse string except + # last character + for i in range(n): + + # If current character + # matches with next + if (i < n - 1 and + str[i] == str[i + 1]): + cur_count += 1 + + # If doesn't match, update result + # (if required) and reset count + else: + if cur_count > count: + count = cur_count + res = str[i] + cur_count = 1 + return res + +# Driver code +if __name__ == ""__main__"": + str = ""aaaabbaaccde"" + print(maxRepeating(str)) + +# This code is contributed +# by ChitraNayal",constant,linear +"# Python3 program for a Queue based approach +# to find first non-repeating character +from queue import Queue + +# function to find first non +# repeating character of sa Stream +def firstnonrepeating(Str): + global MAX_CHAR + q = Queue() + charCount = [0] * MAX_CHAR + + # traverse whole Stream + for i in range(len(Str)): + + # push each character in queue + q.put(Str[i]) + + # increment the frequency count + charCount[ord(Str[i]) - + ord('a')] += 1 + + # check for the non repeating + # character + while (not q.empty()): + if (charCount[ord(q.queue[0]) - + ord('a')] > 1): + q.get() + else: + print(q.queue[0], end = "" "") + break + + if (q.empty()): + print(-1, end = "" "") + print() + +# Driver Code +MAX_CHAR = 26 +Str = ""aabc"" +firstnonrepeating(Str) + +# This code is contributed by PranchalK",linear,linear +"# Python 3 program to find k'th +# non-repeating character in a string +MAX_CHAR = 256 + +# Returns index of k'th non-repeating +# character in given string str[] +def kthNonRepeating(str, k): + + n = len(str) + + # count[x] is going to store count of + # character 'x' in str. If x is not + # present, then it is going to store 0. + count = [0] * MAX_CHAR + + # index[x] is going to store index of + # character 'x' in str. If x is not + # present or x is repeating, then it + # is going to store a value (for example, + # length of string) that cannot be a valid + # index in str[] + index = [0] * MAX_CHAR + + # Initialize counts of all characters + # and indexes of non-repeating characters. + for i in range( MAX_CHAR): + count[i] = 0 + index[i] = n # A value more than any + # index in str[] + + # Traverse the input string + for i in range(n): + + # Find current character and + # increment its count + x = str[i] + count[ord(x)] += 1 + + # If this is first occurrence, then + # set value in index as index of it. + if (count[ord(x)] == 1): + index[ord(x)] = i + + # If character repeats, then remove + # it from index[] + if (count[ord(x)] == 2): + index[ord(x)] = n + + # Sort index[] in increasing order. This step + # takes O(1) time as size of index is 256 only + index.sort() + + # After sorting, if index[k-1] is value, + # then return it, else return -1. + return index[k - 1] if (index[k - 1] != n) else -1 + +# Driver code +if __name__ == ""__main__"": + str = ""geeksforgeeks"" + k = 3 + res = kthNonRepeating(str, k) + if(res == -1): + print(""There are less than k"", + ""non-repeating characters"") + else: + print(""k'th non-repeating character is"", + str[res]) + +# This code is contributed +# by ChitraNayal",linear,nlogn +"MAX_CHAR = 256 + +def kthNonRepeating(Input,k): + inputLength = len(Input) + + # indexArr will store index of non-repeating characters, + # inputLength for characters not in input and + # inputLength+1 for repeated characters. + + # initialize all values in indexArr as inputLength. + indexArr = [inputLength for i in range(MAX_CHAR)] + + for i in range(inputLength): + c = Input[i] + if (indexArr[ord(c)] == inputLength): + indexArr[ord(c)] = i + else: + indexArr[ord(c)] = inputLength + 2 + indexArr.sort() + if(indexArr[k - 1] != inputLength): + return indexArr[k - 1] + else: + return -1 + +Input = ""geeksforgeeks"" +k = 3 +res = kthNonRepeating(Input, k) +if(res == -1): + print(""There are less than k non-repeating characters"") +else: + print(""k'th non-repeating character is"", Input[res]) + +# This code is contributed by rag2127",linear,nlogn +"# Python3 program to find the first +# character that is repeated + +def findRepeatFirstN2(s): + + # this is O(N^2) method + p = -1 + for i in range(len(s)): + + for j in range (i + 1, len(s)): + + if (s[i] == s[j]): + p = i + break + + if (p != -1): + break + + return p + +# Driver code +if __name__ == ""__main__"": + + str = ""geeksforgeeks"" + pos = findRepeatFirstN2(str) + if (pos == -1): + print (""Not found"") + else: + print (str[pos]) + +# This code is contributed +# by ChitraNayal",constant,quadratic +"# Python 3 program to find the first +# character that is repeated + +# 256 is taken just to ensure nothing +# is left, actual max ASCII limit is 128 + +MAX_CHAR = 256 + +def findRepeatFirst(s): + + # this is optimized method + p = -1 + + # initialized counts of occurrences + # of elements as zero + hash = [0 for i in range(MAX_CHAR)] + + # initialized positions + pos = [0 for i in range(MAX_CHAR)] + + for i in range(len(s)): + k = ord(s[i]) + if (hash[k] == 0): + hash[k] += 1 + pos[k] = i + elif(hash[k] == 1): + hash[k] += 1 + + for i in range(MAX_CHAR): + if (hash[i] == 2): + if (p == -1): # base case + p = pos[i] + elif(p > pos[i]): + p = pos[i] + return p + +# Driver code +if __name__ == '__main__': + str = ""geeksforgeeks"" + pos = findRepeatFirst(str); + if (pos == -1): + print(""Not found"") + else: + print(str[pos]) + +# This code is contributed by +# Shashank_Sharma",constant,linear +"# Python implementation +from collections import Counter + +# Function which repeats +# first repeating character +def printrepeated(string): + + # Calculating frequencies + # using Counter function + freq = Counter(string) + + # Traverse the string + for i in string: + if(freq[i] > 1): + print(i) + break + + +# Driver code +string = ""geeksforgeeks"" + +# passing string to printrepeated function +printrepeated(string) + +# this code is contributed by vikkycirus",linear,linear +"# Python3 code to find the first repeating character in a +# string +INT_MAX = 2147483647 + +# Function to find left most repeating character. +def firstRep(s): + map = dict() + c = '#' + index = INT_MAX + + # single traversal of string. + i = 0 + while (i < len(s)): + p = s[i] + if (not (p in map.keys())): + map[p] = i + else: + if (map.get(p) < index): + index = map.get(p) + c = p + i += 1 + return c + +if __name__ == ""__main__"": + + # Input string. + s = ""abccdbd"" + print(firstRep(s), end="""") + print(""\n"", end="""") + +# This code is contributed by Aarti_Rathi",constant,linear +"# Python program to find the first +# repeated character in a string +def firstRepeatedChar(str): + + h = {} # Create empty hash + + # Traverse each characters in string + # in lower case order + for ch in str: + + # If character is already present + # in hash, return char + if ch in h: + return ch; + + # Add ch to hash + else: + h[ch] = 0 + + return '' + + +# Driver code +print(firstRepeatedChar(""geeksforgeeks""))",linear,linear +"# Python3 program to find out the second +# most repeated word + +# Function to find the word +def secMostRepeated(seq): + + # Store all the words with its occurrence + occ = {} + for i in range(len(seq)): + occ[seq[i]] = occ.get(seq[i], 0) + 1 + + # Find the second largest occurrence + first_max = -10**8 + sec_max = -10**8 + + for it in occ: + if (occ[it] > first_max): + sec_max = first_max + first_max = occ[it] + + elif (occ[it] > sec_max and + occ[it] != first_max): + sec_max = occ[it] + + # Return with occurrence equals + # to sec_max + for it in occ: + if (occ[it] == sec_max): + return it + +# Driver code +if __name__ == '__main__': + + seq = [ ""ccc"", ""aaa"", ""ccc"", + ""ddd"", ""aaa"", ""aaa"" ] + print(secMostRepeated(seq)) + +# This code is contributed by mohit kumar 29",linear,linear +"# Efficiently check First repeated character +# in Python + +# Returns -1 if all characters of str are +# unique. +# Assumptions : (1) str contains only characters +# from 'a' to 'z' +## (2) integers are stored using 32 +## bits +def FirstRepeated(string): + + # An integer to store presence/absence + # of 26 characters using its 32 bits. + checker = 0 + + pos = 0 + for i in string: + val = ord(i) - ord('a'); + + # If bit corresponding to current + # character is already set + if ((checker & (1 << val)) > 0): + return pos + + # set bit in checker + checker |= (1 << val) + pos += 1 + + return -1 + +# Driver code +string = ""abcfdeacf"" +i = FirstRepeated(string) +if i != -1: + print (""Char = "", string[i], "" and Index = "", i) +else: + print (""No repeated Char"") + +# This code is contributed by Sachin Bisht",constant,linear +"# Queries for same characters in a repeated +# string + +# Print whether index i and j have same +# element or not. +def query(s, i, j): + n = len(s) + + # Finding relative position of index i,j. + i %= n + j %= n + + # Checking is element are same at index i, j. + print(""Yes"") if s[i] == s[j] else print(""No"") + +# Driver code +if __name__ == ""__main__"": + X = ""geeksforgeeks"" + query(X, 0, 8) + query(X, 8, 13) + query(X, 6, 15) + +# This code is contributed by +# sanjeev2552",constant,constant +"# Python program to return the maximum occurring character in the input string +ASCII_SIZE = 256 + + +def getMaxOccurringChar(str): + # Create array to keep the count of individual characters + # Initialize the count array to zero + count = [0] * ASCII_SIZE + + # Utility variables + max = -1 + c = '' + + # Traversing through the string and maintaining the count of + # each character + for i in str: + count[ord(i)] += 1 + + for i in str: + if max < count[ord(i)]: + max = count[ord(i)] + c = i + + return c + + +# Driver program to test the above function +str = ""sample string"" +print(""Max occurring character is"", getMaxOccurringChar(str)) + +# Although this program can be written in atmost 3 lines in Python +# the above program has been written for a better understanding of +# the reader + +# Shorter version of the program +# import collections +# str = ""sample string"" +# print ""Max occurring character is "" + +# collections.Counter(str).most_common(1)[0][0] + +# This code has been contributed by Bhavya Jain",constant,linear +"# Python3 program to print all occurrences +# of every character together. + +# Since only lower case characters are there +MAX_CHAR = 26 + +# Function to print the string +def printGrouped(string): + n = len(string) + + # Initialize counts of all characters as 0 + count = [0] * MAX_CHAR + + # Count occurrences of all characters in string + for i in range(n): + count[ord(string[i]) - ord(""a"")] += 1 + + # Starts traversing the string + for i in range(n): + + # Print the character till its count in + # hash array + while count[ord(string[i]) - ord(""a"")]: + print(string[i], end = """") + count[ord(string[i]) - ord(""a"")] -= 1 + + # Make this character's count value as 0. + count[ord(string[i]) - ord(""a"")] = 0 + +# Driver code +if __name__ == ""__main__"": + string = ""geeksforgeeks"" + printGrouped(string) + +# This code is contributed by +# sanjeev2552",constant,linear +"# Python3 program to print the string +# in given pattern + +# Function to print the string +def printStringAlternate(string): + + occ = {} + + # Start traversing the string + for i in range(0, len(string)): + + # Convert uppercase to lowercase + temp = string[i].lower() + + # Increment occurrence count + occ[temp] = occ.get(temp, 0) + 1 + + # If count is odd then print the character + if occ[temp] & 1: + print(string[i], end = """") + + print() + +# Driver code +if __name__ == ""__main__"": + + string = ""Geeks for geeks"" + string2 = ""It is a long day Dear"" + + printStringAlternate(string) + printStringAlternate(string2) + +# This code is contributed by Rituraj Jain",linear,linear +"# Python3 program for above implementation + +# Function to print the string +def printString(str, ch, count): + occ, i = 0, 0 + + # If given count is 0 + # print the given string and return + if (count == 0): + print(str) + + # Start traversing the string + for i in range(len(str)): + + # Increment occ if current char + # is equal to given character + if (str[i] == ch): + occ += 1 + + # Break the loop if given character has + # been occurred given no. of times + if (occ == count): + break + + # Print the string after the occurrence + # of given character given no. of times + if (i < len(str)- 1): + print(str[i + 1: len(str) - i + 2]) + + # Otherwise string is empty + else: + print(""Empty string"") + +# Driver code +if __name__ == '__main__': + str = ""geeks for geeks"" + printString(str, 'e', 2) + +# This code is contributed +# by 29AjayKumar",constant,linear +"# Python3 Program to find all occurrences of the word in +# a matrix +ROW = 3 +COL = 5 + +# check whether given cell (row, col) is a valid +# cell or not. +def isvalid(row, col, prevRow, prevCol): + + # return true if row number and column number + # is in range + return (row >= 0) and (row < ROW) and (col >= 0) and \ + (col < COL) and not (row== prevRow and col == prevCol) + +# These arrays are used to get row and column +# numbers of 8 neighboursof a given cell +rowNum = [-1, -1, -1, 0, 0, 1, 1, 1] +colNum = [-1, 0, 1, -1, 1, -1, 0, 1] + +# A utility function to do DFS for a 2D boolean +# matrix. It only considers the 8 neighbours as +# adjacent vertices +def DFS(mat, row, col,prevRow, prevCol, word,path, index, n): + + # return if current character doesn't match with + # the next character in the word + if (index > n or mat[row][col] != word[index]): + return + + # append current character position to path + path += word[index] + ""("" + str(row)+ "", "" + str(col) + "") "" + + # current character matches with the last character\ + # in the word + if (index == n): + print(path) + return + + # Recur for all connected neighbours + for k in range(8): + if (isvalid(row + rowNum[k], col + colNum[k],prevRow, prevCol)): + DFS(mat, row + rowNum[k], col + colNum[k],row, col, word, path, index + 1, n) + +# The main function to find all occurrences of the +# word in a matrix +def findWords(mat,word, n): + + # traverse through the all cells of given matrix + for i in range(ROW): + for j in range(COL): + + # occurrence of first character in matrix + if (mat[i][j] == word[0]): + # check and print if path exists + DFS(mat, i, j, -1, -1, word, """", 0, n) + +# Driver code +mat = [['B', 'N', 'E', 'Y', 'S'], + ['H', 'E', 'D', 'E', 'S'], + ['S', 'G', 'N', 'D', 'E']] +word = list(""DES"") +findWords(mat, word, len(word) - 1) + +# This code is contributed by SHUBHAMSINGH10",quadratic,quadratic +"# Python3 program to arrange given string + +# Function which arrange the given string +def arrangeString(str1,x,y): + count_0=0 + count_1 =0 + n = len(str1) + + # Counting number of 0's and 1's in the + # given string. + for i in range(n): + if str1[i] == '0': + count_0 +=1 + else: + count_1 +=1 + + # Printing first all 0's x-times + # and decrement count of 0's x-times + # and do the similar task with '1' + while count_0>0 or count_1>0: + for i in range(0,x): + if count_0>0: + print(""0"",end="""") + count_0 -=1 + for j in range(0,y): + if count_1>0: + print(""1"",end="""") + count_1 -=1 + +# Driver code +if __name__=='__main__': + str1 = ""01101101101101101000000"" + x = 1 + y = 2 + arrangeString(str1, x, y) + +# This code is contributed by +# Shrikant13",constant,quadratic +"# Finds maximum occurring digit +# without using any array/string + +# Simple function to count +# occurrences of digit d in x +def countOccurrences(x, d): + count = 0; # Initialize count + # of digit d + while (x): + + # Increment count if current + # digit is same as d + if (x % 10 == d): + count += 1; + x = int(x / 10); + + return count; + +# Returns the max occurring +# digit in x +def maxOccurring(x): + + # Handle negative number + if (x < 0): + x = -x; + + result = 0; # Initialize result + # which is a digit + max_count = 1; # Initialize count + # of result + + # Traverse through all digits + for d in range(10): + + # Count occurrences of current digit + count = countOccurrences(x, d); + + # Update max_count and + # result if needed + if (count >= max_count): + max_count = count; + result = d; + + return result; + +# Driver Code +x = 1223355; +print(""Max occurring digit is"", + maxOccurring(x)); + +# This code is contributed by mits.",constant,constant +"# Python3 program to bring all spaces +# in front of string using swapping technique + +# Function to find spaces and move to beginning +def moveSpaceInFront(s): + + # Traverse from end and swap spaces + i = len(s) - 1; + for j in range(i, -1, -1): + if (s[j] != ' '): + s = swap(s, i, j); + i -= 1; + return s; + +def swap(c, i, j): + c = list(c) + c[i], c[j] = c[j], c[i] + return ''.join(c) + +# Driver code +s = ""Hey there, it's GeeksforGeeks""; +s = moveSpaceInFront(s); +print(s); + +# This code is contributed +# by Princi Singh",constant,linear +"# Python3 program to bring all spaces +# in front of string using swapping technique + +# Function to find spaces and +# move to beginning +def moveSpaceInFront(s): + + # Keep copying non-space characters + i = len(s) - 1; + + for j in range(i, -1, -1): + if (s[j] != ' '): + s = s[:i] + s[j] + s[i + 1:] + i -= 1; + + # Move spaces to be beginning + while (i >= 0): + s = s[:i] + ' ' + s[i + 1:] + i -= 1 + return s; + +# Driver code +s = ""Hey there, it's GeeksforGeeks""; +s = moveSpaceInFront(s); +print(s); + +# This code is contributed +# by Princi Singh",constant,linear +"# Python3 program to put spaces between words +# starting with capital letters. + +# Function to amend the sentence +def amendSentence(string): + string = list(string) + + # Traverse the string + for i in range(len(string)): + + # Convert to lowercase if its + # an uppercase character + if string[i] >= 'A' and string[i] <= 'Z': + string[i] = chr(ord(string[i]) + 32) + + # Print space before it + # if its an uppercase character + if i != 0: + print("" "", end = """") + + # Print the character + print(string[i], end = """") + + # if lowercase character + # then just print + else: + print(string[i], end = """") + +# Driver Code +if __name__ == ""__main__"": + string = ""BruceWayneIsBatman"" + amendSentence(string) + +# This code is contributed by +# sanjeev2552",constant,linear +"# Python program to Remove +# extra spaces from a string +input_string = \ + ' Hello Geeks . Welcome , Do you love Geeks , Geeks ? ' +output_string = [] +space_flag = False # Flag to check if spaces have occurred + +for index in range(len(input_string)): + + if input_string[index] != ' ': + if space_flag == True: + if (input_string[index] == '.' + or input_string[index] == '?' + or input_string[index] == ','): + pass + else: + output_string.append(' ') + space_flag = False + output_string.append(input_string[index]) + elif input_string[index - 1] != ' ': + space_flag = True + +print (''.join(output_string))",constant,linear +"# Python 3 program to find the string which +# contain the first character of each word +# of another string. + +# Function to find string which has first +# character of each word. +def firstLetterWord(str): + + result = """" + + # Traverse the string. + v = True + for i in range(len(str)): + + # If it is space, set v as true. + if (str[i] == ' '): + v = True + + # Else check if v is true or not. + # If true, copy character in output + # string and set v as false. + elif (str[i] != ' ' and v == True): + result += (str[i]) + v = False + + return result + +# Driver Code +if __name__ == ""__main__"": + + str = ""geeks for geeks"" + print(firstLetterWord(str)) + +# This code is contributed by ita_c",linear,linear +"# An efficient Python3 implementation +# of above approach +charBuffer = [] +def processWords(input): + + """""" we are splitting the input based on + spaces (s)+ : this regular expression + will handle scenarios where we have words + separated by multiple spaces """""" + s = input.split("" "") + + for values in s: + """""" charAt(0) will pick only the first + character from the string and append + to buffer """""" + charBuffer.append(values[0]) + return charBuffer + +# Driver Code +if __name__ == '__main__': + input = ""geeks for geeks"" + print(*processWords(input), sep = """") + +# This code is contributed +# by SHUBHAMSINGH10",linear,quadratic +"# Python 3 program to print all strings +# that can be made by placing spaces +from math import pow + +def printSubsequences(str): + n = len(str) + opsize = int(pow(2, n - 1)) + + for counter in range(opsize): + for j in range(n): + print(str[j], end = """") + if (counter & (1 << j)): + print("" "", end = """") + + print(""\n"", end = """") + +# Driver code +if __name__ == '__main__': + str = ""ABC"" + printSubsequences(str) + +# This code is contributed by +# Sanjit_Prasad",constant,quadratic +"class Solution: + + # Function is to check whether two strings are anagram of each other or not. + def isAnagram(self, a, b): + + if sorted(a) == sorted(b): + return True + else: + return False + +# { +# Driver Code Starts + +if __name__ == '__main__': + a = ""gram"" + b = ""arm"" + if(Solution().isAnagram(a, b)): + print(""The two strings are anagram of each other"") + else: + print(""The two strings are not anagram of each other"") +# } Driver Code Ends",constant,nlogn +"# Python program to check if two strings are anagrams of +# each other +NO_OF_CHARS = 256 + +# Function to check whether two strings are anagram of +# each other + + +def areAnagram(str1, str2): + + # Create two count arrays and initialize all values as 0 + count1 = [0] * NO_OF_CHARS + count2 = [0] * NO_OF_CHARS + + # For each character in input strings, increment count + # in the corresponding count array + for i in str1: + count1[ord(i)] += 1 + + for i in str2: + count2[ord(i)] += 1 + + # If both strings are of different length. Removing this + # condition will make the program fail for strings like + # ""aaca"" and ""aca"" + if len(str1) != len(str2): + return 0 + + # Compare count arrays + for i in xrange(NO_OF_CHARS): + if count1[i] != count2[i]: + return 0 + + return 1 + + +# Driver code +str1 = ""gram"" +str2 = ""arm"" + +# Function call +if areAnagram(str1, str2): + print ""The two strings are anagram of each other"" +else: + print ""The two strings are not anagram of each other"" + +# This code is contributed by Bhavya Jain",constant,linear +"# Python program to check if two strings +# are anagrams of each other + +NO_OF_CHARS = 256 + +# function to check if two strings +# are anagrams of each other +def areAnagram(str1,str2): + + # If both strings are of different + # length. Removing this condition + # will make the program fail for + # strings like ""aaca"" and ""aca"" + if(len(str1) != len(str2)): + return False; + + # Create a count array and initialize + # all values as 0 + count=[0 for i in range(NO_OF_CHARS)] + i=0 + + # For each character in input strings, + # increment count in the corresponding + # count array + for i in range(len(str1)): + count[ord(str1[i]) - ord('a')] += 1; + count[ord(str2[i]) - ord('a')] -= 1; + + # See if there is any non-zero + # value in count array + for i in range(NO_OF_CHARS): + if (count[i] != 0): + return False + + + return True + +# Driver code +str1=""gram"" +str2=""arm"" + +# Function call +if (areAnagram(str1, str2)): + print(""The two strings are anagram of each other"") +else: + print(""The two strings are not anagram of each other"") + + +# This code is contributed by patel2127",constant,linear +"# Python3 implementation of the approach +# Function that returns True if a and b +# are anagarams of each other + + +def isAnagram(a, b): + + # Check if length of both strings is same or not + if (len(a) != len(b)): + return False + + # Create a HashMap containing Character as Key and + # Integer as Value. We will be storing character as + # Key and count of character as Value. + map = {} + # Loop over all character of String a and put in + # HashMap. + for i in range(len(a)): + # Check if HashMap already contain current + # character or not + if (a[i] in map): + # If contains increase count by 1 for that + # character + map[a[i]] += 1 + + else: + # else set that character in map and set + # count to 1 as character is encountered + # first time + map[a[i]] = 1 + + # Now loop over String b + for i in range(len(b)): + # Check if current character already exists in + # HashMap/map + if (b[i] in map): + # If contains reduce count of that + # character by 1 to indicate that current + # character has been already counted as + # idea here is to check if in last count of + # all characters in last is zero which + # means all characters in String a are + # present in String b. + map[b[i]] -= 1 + else: + return False + + # Extract all keys of HashMap/map + keys = map.keys() + # Loop over all keys and check if all keys are 0. + # If so it means it is anagram. + for key in keys: + if (map[key] != 0): + return False + + # Returning True as all keys are zero + return True + + +# Driver code +str1 = ""gram"" +str2 = ""arm"" + +# Function call +if (isAnagram(str1, str2)): + print(""The two strings are anagram of each other"") +else: + print(""The two strings are not anagram of each other"") + + +# This code is contributed by shinjanpatra",constant,linear +"# Python program to search all +# anagrams of a pattern in a text + +MAX=256 + +# This function returns true +# if contents of arr1[] and arr2[] +# are same, otherwise false. +def compare(arr1, arr2): + for i in range(MAX): + if arr1[i] != arr2[i]: + return False + return True + +# This function search for all +# permutations of pat[] in txt[] +def search(pat, txt): + + M = len(pat) + N = len(txt) + + # countP[]: Store count of + # all characters of pattern + # countTW[]: Store count of + # current window of text + countP = [0]*MAX + + countTW = [0]*MAX + + for i in range(M): + (countP[ord(pat[i]) ]) += 1 + (countTW[ord(txt[i]) ]) += 1 + + # Traverse through remaining + # characters of pattern + for i in range(M,N): + + # Compare counts of current + # window of text with + # counts of pattern[] + if compare(countP, countTW): + print(""Found at Index"", (i-M)) + + # Add current character to current window + (countTW[ ord(txt[i]) ]) += 1 + + # Remove the first character of previous window + (countTW[ ord(txt[i-M]) ]) -= 1 + + # Check for the last window in text + if compare(countP, countTW): + print(""Found at Index"", N-M) + +# Driver program to test above function +txt = ""BACDGABCDA"" +pat = ""ABCD"" +search(pat, txt) + +# This code is contributed +# by Upendra Singh Bartwal",linear,linear +"# Python 3 program to find minimum +# number of characters +# to be removed to make two +# strings anagram. + +CHARS = 26 + +# function to calculate minimum +# numbers of characters +# to be removed to make two +# strings anagram +def remAnagram(str1, str2): + + # make hash array for both string + # and calculate + # frequency of each character + count1 = [0]*CHARS + count2 = [0]*CHARS + + # count frequency of each character + # in first string + i = 0 + while i < len(str1): + count1[ord(str1[i])-ord('a')] += 1 + i += 1 + + # count frequency of each character + # in second string + i =0 + while i < len(str2): + count2[ord(str2[i])-ord('a')] += 1 + i += 1 + + # traverse count arrays to find + # number of characters + # to be removed + result = 0 + for i in range(26): + result += abs(count1[i] - count2[i]) + return result + +# Driver program to run the case +if __name__ == ""__main__"": + str1 = ""bcadeh"" + str2 = ""hea"" + print(remAnagram(str1, str2)) + +# This code is contributed by +# ChitraNayal",constant,linear +"# Python3 program to find minimum +# number of characters to be +# removed to make two strings +# anagram. + +# function to calculate minimum +# numbers of characters to be +# removed to make two strings anagram +def makeAnagram(a, b): + buffer = [0] * 26 + for char in a: + buffer[ord(char) - ord('a')] += 1 + for char in b: + buffer[ord(char) - ord('a')] -= 1 + return sum(map(abs, buffer)) + +# Driver Code +if __name__ == ""__main__"" : + + str1 = ""bcadeh"" + str2 = ""hea"" + print(makeAnagram(str1, str2)) + +# This code is contributed +# by Raghib Ahsan",constant,linear +"# Python3 program to check if two +# strings are k anagram or not. +MAX_CHAR = 26 + +# Function to check that is +# k-anagram or not +def arekAnagrams(str1, str2, k) : + + # If both strings are not of equal + # length then return false + n = len(str1) + if (len(str2)!= n) : + return False + + count1 = [0] * MAX_CHAR + count2 = [0] * MAX_CHAR + + # Store the occurrence of all + # characters in a hash_array + for i in range(n): + count1[ord(str1[i]) - + ord('a')] += 1 + for i in range(n): + count2[ord(str2[i]) - + ord('a')] += 1 + + count = 0 + + # Count number of characters that + # are different in both strings + for i in range(MAX_CHAR): + if (count1[i] > count2[i]) : + count = count + abs(count1[i] - + count2[i]) + + # Return true if count is less + # than or equal to k + return (count <= k) + +# Driver Code +if __name__ == '__main__': + str1 = ""anagram"" + str2 = ""grammar"" + k = 2 + if (arekAnagrams(str1, str2, k)): + print(""Yes"") + else: + print(""No"") + +# This code is contributed +# by SHUBHAMSINGH10",constant,linear +"# Optimized Python3 program +# to check if two strings +# are k anagram or not. +MAX_CHAR = 26; + +# Function to check if str1 +# and str2 are k-anagram or not +def areKAnagrams(str1, str2, k): + # If both strings are + # not of equal length + # then return false + + n = len(str1); + if (len(str2) != n): + return False; + + hash_str1 = [0]*(MAX_CHAR); + + # Store the occurrence of + # all characters in a hash_array + for i in range(n): + hash_str1[ord(str1[i]) - ord('a')]+=1; + + # Store the occurrence of all + # characters in a hash_array + count = 0; + for i in range(n): + if (hash_str1[ord(str2[i]) - ord('a')] > 0): + hash_str1[ord(str2[i]) - ord('a')]-=1; + else: + count+=1; + + if (count > k): + return False; + + # Return true if count is + # less than or equal to k + return True; + +# Driver code +str1 = ""fodr""; +str2 = ""gork""; +k = 2; +if (areKAnagrams(str1, str2, k) == True): + print(""Yes""); +else: + print(""No""); + +# This code is contributed by mits",constant,linear +"# Python 3 program for the above approach +import sys + +# Function to check k +# anagram of two strings + + +def kAnagrams(str1, str2, k): + + flag = 0 + + list1 = [] + + # First Condition: If both the + # strings have different length , + # then they cannot form anagram + if (len(str1) != len(str2)): + sys.exit() + + # Converting str1 to Character Array arr1 + arr1 = list(str1) + + # Converting str2 to Character Array arr2 + arr2 = list(str2) + + # Sort arr1 in increasing order + arr1.sort() + + # Sort arr2 in increasing order + arr2.sort() + + # Iterate till str1.length() + for i in range(len(str1)): + + # Condition if arr1[i] is + # not equal to arr2[i] + # then add it to list + if (arr1[i] != arr2[i]): + list1.append(arr2[i]) + + # Condition to check if + # strings for K-anagram or not + if (len(list1) <= k): + flag = 1 + + if (flag == 1): + return True + else: + return False + + +# Driver Code +if __name__ == ""__main__"": + + str1 = ""fodr"" + str2 = ""gork"" + k = 2 + + # Function Call + kAnagrams(str1, str2, k) + if (kAnagrams(str1, str2, k) == True): + print(""Yes"") + else: + print(""No"")",constant,linear +"# A simple Python program to check if binary +# representations of two numbers are anagram. +SIZE = 8 +def bit_anagram_check(a, b): + + # Find reverse binary representation of a + # and store it in binary_a[] + global size + + i = 0 + binary_a = [0] * SIZE + while (a > 0): + binary_a[i] = a % 2 + a //= 2 + i += 1 + + # Find reverse binary representation of b + # and store it in binary_a[] + j = 0 + binary_b = [0] * SIZE + while (b > 0): + binary_b[j] = b % 2 + b //= 2 + j += 1 + + # Sort two binary representations + binary_a.sort() + binary_b.sort() + + # Compare two sorted binary representations + for i in range(SIZE): + if (binary_a[i] != binary_b[i]): + return 0 + return 1 + +# Driver code +if __name__ == ""__main__"": + + a = 8 + b = 4 + print(bit_anagram_check(a, b)) + + # This code is contributed by ukasp.",constant,constant +"# Python3 program to check if binary +# representations of two numbers are anagrams. + +# Check each bit in a number is set or not +# and return the total count of the set bits. +def countSetBits(n) : + + count = 0 + while n>0 : + count += n & 1 + n >>= 1 + return count + +def areAnagrams(A, B) : + return countSetBits(A) == countSetBits(B) + +# Driver code +if __name__ == ""__main__"" : + + a,b = 8,4 + if areAnagrams(a, b) : + print(""1"") + else : + print(""0"") + +# this code is contributed by aditya942003patil",constant,constant +"# Python3 program for finding all anagram +# pairs in the given array +from collections import defaultdict + +# Utility function for +# printing anagram list +def printAnagram(store: dict) -> None: + + for (k, v) in store.items(): + temp_vec = v + size = len(temp_vec) + + if (size > 1): + for i in range(size): + print(temp_vec[i], end = "" "") + + print() + +# Utility function for storing +# the vector of strings into HashMap +def storeInMap(vec: list) -> None: + + store = defaultdict(lambda: list) + + for i in range(len(vec)): + tempString = vec[i] + tempString = ''.join(sorted(tempString)) + + # Check for sorted string + # if it already exists + if (tempString not in store): + temp_vec = [] + temp_vec.append(vec[i]) + store[tempString] = temp_vec + + else: + + # Push new string to + # already existing key + temp_vec = store[tempString] + temp_vec.append(vec[i]) + store[tempString] = temp_vec + + # Print utility function for + # printing all the anagrams + printAnagram(store) + +# Driver code +if __name__ == ""__main__"": + + # Initialize vector of strings + arr = [] + arr.append(""geeksquiz"") + arr.append(""geeksforgeeks"") + arr.append(""abcd"") + arr.append(""forgeeksgeeks"") + arr.append(""zuiqkeegs"") + arr.append(""cat"") + arr.append(""act"") + arr.append(""tca"") + + # Utility function for storing + # strings into hashmap + storeInMap(arr) + +# This code is contributed by sanjeev2552",linear,quadratic +"# Python3 program to count total anagram +# substring of a string +def countOfAnagramSubstring(s): + + # Returns total number of anagram + # substrings in s + n = len(s) + mp = dict() + + # loop for length of substring + for i in range(n): + sb = '' + for j in range(i, n): + sb = ''.join(sorted(sb + s[j])) + mp[sb] = mp.get(sb, 0) + + # increase count corresponding + # to this dict array + mp[sb] += 1 + + anas = 0 + + # loop over all different dictionary + # items and aggregate substring count + for k, v in mp.items(): + anas += (v*(v-1))//2 + return anas + +# Driver Code +s = ""xyyx"" +print(countOfAnagramSubstring(s)) + +# This code is contributed by fgaim",linear,quadratic +"# Python3 Program to find minimum number +# of manipulations required to make +# two strings identical + +# Counts the no of manipulations +# required +def countManipulations(s1, s2): + + count = 0 + + # store the count of character + char_count = [0] * 26 + + for i in range(26): + char_count[i] = 0 + + # iterate though the first String + # and update count + for i in range(len( s1)): + char_count[ord(s1[i]) - + ord('a')] += 1 + + # iterate through the second string + # update char_count. + # if character is not found in + # char_count then increase count + for i in range(len(s2)): + char_count[ord(s2[i]) - ord('a')] -= 1 + + for i in range(26): + if char_count[i] != 0: + count += abs(char_count[i]) + + + return count / 2 + +# Driver code +if __name__ == ""__main__"": + + s1 = ""ddcf"" + s2 = ""cedk"" + + print(countManipulations(s1, s2)) + +# This code is contributed by ita_c",constant,linear +"# Python program to check if a given string is a rotation +# of a palindrome + +# A utility function to check if a string str is palindrome +def isPalindrome(string): + + # Start from leftmost and rightmost corners of str + l = 0 + h = len(string) - 1 + + # Keep comparing characters while they are same + while h > l: + l+= 1 + h-= 1 + if string[l-1] != string[h + 1]: + return False + + # If we reach here, then all characters were matching + return True + +# Function to check if a given string is a rotation of a +# palindrome. +def isRotationOfPalindrome(string): + + # If string itself is palindrome + if isPalindrome(string): + return True + + # Now try all rotations one by one + n = len(string) + for i in range(n-1): + string1 = string[i + 1:n] + string2 = string[0:i + 1] + + # Check if this rotation is palindrome + string1+=(string2) + if isPalindrome(string1): + return True + + return False + +# Driver program +print (""1"" if isRotationOfPalindrome(""aab"") == True else ""0"") +print (""1"" if isRotationOfPalindrome(""abcde"") == True else ""0"") +print (""1"" if isRotationOfPalindrome(""aaaad"") == True else ""0"") + +# This code is contributed by BHAVYA JAIN",linear,quadratic +"# Python3 implementation of above idea + +# A function to check if n is palindrome +def isPalindrome(n: int) -> bool: + + # Find reverse of n + rev = 0 + i = n + while i > 0: + rev = rev * 10 + i % 10 + i //= 10 + + # If n and rev are same, + # then n is palindrome + return (n == rev) + +# prints palindrome between min and max +def countPal(minn: int, maxx: int) -> None: + for i in range(minn, maxx + 1): + if isPalindrome(i): + print(i, end = "" "") + +# Driver Code +if __name__ == ""__main__"": + countPal(100, 2000) + +# This code is contributed by +# sanjeev2552",constant,logn +"# Python 3 implementation of O(n^2) +# time and O(1) space method +# to find the longest palindromic substring +class LongestPalinSubstring : + maxLength = 0 + + # variables to store and + res = None + + # update maxLength and res + # A utility function to get the longest palindrome + # starting and expanding out from given center indices + @staticmethod + def cSubUtil( s, l, r) : + + # check if the indices lie in the range of string + # and also if it is palindrome + while (l >= 0 and r < len(s) and s[l] == s[r]) : + + # expand the boundary + l -= 1 + r += 1 + + # if it's length is greater than maxLength update + # maxLength and res + if (r - l - 1 >= LongestPalinSubstring.maxLength) : + LongestPalinSubstring.res = s[l + 1:r] + LongestPalinSubstring.maxLength = r - l - 1 + return + + # A function which takes a string prints the LPS and + # returns the length of LPS + @staticmethod + def longestPalSubstr( str) : + LongestPalinSubstring.res = """" + LongestPalinSubstring.maxLength = 1 + + # for every index in the string check palindromes + # starting from that index + i = 0 + while (i < len(str)) : + + # check for odd length palindromes + LongestPalinSubstring.cSubUtil(str, i, i) + + # check for even length palindromes + LongestPalinSubstring.cSubUtil(str, i, i + 1) + i += 1 + print(""Longest palindrome substring is: "", end ="""") + print(LongestPalinSubstring.res) + return LongestPalinSubstring.maxLength + + # Driver program to test above function + @staticmethod + def main( args) : + str1 = ""forgeeksskeegfor"" + print(""Length is: "" + str(LongestPalinSubstring.longestPalSubstr(str1))) + +if __name__==""__main__"": + LongestPalinSubstring.main([]) + + # This code is contributed by phasing17.",constant,quadratic +"# Python3 program to Count number of ways we +# can get palindrome string from a given +# string + +# function to find the substring of the +# string +def substring(s, a, b): + s1 = """" + + # extract the specified position of + # the string + for i in range(a, b, 1): + s1 += s[i] + + return s1 + +# can get palindrome string from a +# given string +def allPalindromeSubstring(s): + v = [] + + # moving the pivot from starting till + # end of the string + pivot = 0.0 + while pivot < len(s): + + # set radius to the first nearest + # element on left and right + palindromeRadius = pivot - int(pivot) + + # if the position needs to be + # compared has an element and the + # characters at left and right + # matches + while ((pivot + palindromeRadius) < len(s) and + (pivot - palindromeRadius) >= 0 and + (s[int(pivot - palindromeRadius)] == + s[int(pivot + palindromeRadius)])): + v.append(s[int(pivot - palindromeRadius): + int(pivot + palindromeRadius + 1)]) + + # increasing the radius by 1 to point + # to the next elements in left and right + palindromeRadius += 1 + + pivot += 0.5 + return v + +# Driver Code +if __name__ == ""__main__"": + v = allPalindromeSubstring(""hellolle"") + print(len(v)) + print(v) + + v = allPalindromeSubstring(""geeksforgeeks"") + print(len(v)) + print(v) + +# This code is contributed by +# sanjeev2552",linear,cubic +"# Python program Online algorithm for checking palindrome +# in a stream + +# d is the number of characters in input alphabet +d = 256 + +# q is a prime number used for evaluating Rabin Karp's +# Rolling hash +q = 103 + +def checkPalindromes(string): + + # Length of input string + N = len(string) + + # A single character is always a palindrome + print string[0] + "" Yes"" + + # Return if string has only one character + if N == 1: + return + + # Initialize first half reverse and second half for + # as firstr and second characters + firstr = ord(string[0]) % q + second = ord(string[1]) % q + + h = 1 + i = 0 + j = 0 + + # Now check for palindromes from second character + # onward + for i in xrange(1,N): + + # If the hash values of 'firstr' and 'second' + # match, then only check individual characters + if firstr == second: + + # Check if str[0..i] is palindrome using + # simple character by character match + for j in xrange(0,i/2): + if string[j] != string[i-j]: + break + j += 1 + if j == i/2: + print string[i] + "" Yes"" + else: + print string[i] + "" No"" + else: + print string[i] + "" No"" + + # Calculate hash values for next iteration. + # Don't calculate hash for next characters if + # this is the last character of string + if i != N-1: + + # If i is even (next i is odd) + if i % 2 == 0: + + # Add next character after first half at + # beginning of 'firstr' + h = (h*d) % q + firstr = (firstr + h*ord(string[i/2]))%q + + # Add next character after second half at + # the end of second half. + second = (second*d + ord(string[i+1]))%q + else: + # If next i is odd (next i is even) then we + # need not to change firstr, we need to remove + # first character of second and append a + # character to it. + second = (d*(second + q - ord(string[(i+1)/2])*h)%q + + ord(string[i+1]))%q + +# Driver program +txt = ""aabaacaabaa"" +checkPalindromes(txt) +# This code is contributed by Bhavya Jain",constant,quadratic +"# Python3 program to print all palindromic +# partitions of a given string. +def checkPalindrome(string): + + # Returns true if str is palindrome, + # else false + length = len(string) + length -= 1 + for i in range(length): + if string[i] != string[length]: + return False + length -= 1 + return True + +def printSolution(partitions): + for i in range(len(partitions)): + for j in range(len(partitions[i])): + print(partitions[i][j], end = "" "") + print() + +def addStrings(v, s, temp, index): + + # Goes through all indexes and + # recursively add remaining partitions + # if current string is palindrome. + length = len(s) + string = """" + + current = temp[:] + + if index == 0: + temp = [] + for i in range(index, length): + string += s[i] + if checkPalindrome(string): + temp.append(string) + if i + 1 < length: + addStrings(v, s, temp[:], i + 1) + else: + v.append(temp) + temp = current + +def partition(s, v): + + # Generates all palindromic partitions + # of 's' and stores the result in 'v'. + temp = [] + addStrings(v, s, temp[:], 0) + printSolution(v) + +# Driver Code +if __name__ == ""__main__"": + s = ""geeks"" + partitions = [] + partition(s, partitions) + +# This code is contributed by +# vibhu4agarwal",linear,quadratic +"# Python3 code to Count Palindromic +# Subsequence in a given String + +# Function return the total +# palindromic subsequence + + +def countPS(str): + + N = len(str) + + # Create a 2D array to store the count + # of palindromic subsequence + cps = [[0 for i in range(N + 2)]for j in range(N + 2)] + + # palindromic subsequence of length 1 + for i in range(N): + cps[i][i] = 1 + + # check subsequence of length L + # is palindrome or not + for L in range(2, N + 1): + + for i in range(N): + k = L + i - 1 + if (k < N): + if (str[i] == str[k]): + cps[i][k] = (cps[i][k - 1] + + cps[i + 1][k] + 1) + else: + cps[i][k] = (cps[i][k - 1] + + cps[i + 1][k] - + cps[i + 1][k - 1]) + + # return total palindromic subsequence + return cps[0][N - 1] + + +# Driver program +str = ""abcb"" +print(""Total palindromic subsequence are : "", countPS(str)) + + +# This code is contributed by Anant Agarwal.",quadratic,quadratic +"# Python 3 program to counts Palindromic +# Subsequence in a given String using recursion + +str = ""abcb"" + +# Function return the total +# palindromic subsequence + + +def countPS(i, j): + + if(i > j): + return 0 + + if(dp[i][j] != -1): + return dp[i][j] + + if(i == j): + dp[i][j] = 1 + return dp[i][j] + + else if (str[i] == str[j]): + dp[i][j] = (countPS(i + 1, j) + + countPS(i, j - 1) + 1) + return dp[i][j] + else: + dp[i][j] = (countPS(i + 1, j) + + countPS(i, j - 1) - + countPS(i + 1, j - 1)) + return dp[i][j] + + +# Driver code +if __name__ == ""__main__"": + + dp = [[-1 for x in range(1000)] + for y in range(1000)] + + n = len(str) + print(""Total palindromic subsequence are :"", + countPS(0, n - 1)) + +# This code is contributed by ita_c",quadratic,quadratic +"# Python 3 program for getting minimum character +# to be added at front to make string palindrome + +# function for checking string is +# palindrome or not +def ispalindrome(s): + + l = len(s) + + i = 0 + j = l - 1 + while i <= j: + + if(s[i] != s[j]): + return False + i += 1 + j -= 1 + + return True + +# Driver code +if __name__ == ""__main__"": + + s = ""BABABAA"" + cnt = 0 + flag = 0 + + while(len(s) > 0): + + # if string becomes palindrome then break + if(ispalindrome(s)): + flag = 1 + break + + else: + cnt += 1 + + # erase the last element of the string + s = s[:-1] + + # print the number of insertion at front + if(flag): + print(cnt) + +# This code is contributed by ita_c",constant,quadratic +"# Python3 program for getting minimum +# character to be added at the front +# to make string palindrome + +# Returns vector lps for given string str +def computeLPSArray(string): + + M = len(string) + lps = [None] * M + + length = 0 + lps[0] = 0 # lps[0] is always 0 + + # the loop calculates lps[i] + # for i = 1 to M-1 + i = 1 + while i < M: + + if string[i] == string[length]: + + length += 1 + lps[i] = length + i += 1 + + else: # (str[i] != str[len]) + + # This is tricky. Consider the example. + # AAACAAAA and i = 7. The idea is + # similar to search step. + if length != 0: + + length = lps[length - 1] + + # Also, note that we do not + # increment i here + + else: # if (len == 0) + + lps[i] = 0 + i += 1 + + return lps + +# Method returns minimum character +# to be added at front to make +# string palindrome +def getMinCharToAddedToMakeStringPalin(string): + + revStr = string[::-1] + + # Get concatenation of string, + # special character and reverse string + concat = string + ""$"" + revStr + + # Get LPS array of this + # concatenated string + lps = computeLPSArray(concat) + + # By subtracting last entry of lps + # vector from string length, we + # will get our result + return len(string) - lps[-1] + +# Driver Code +if __name__ == ""__main__"": + + string = ""AACECAAAA"" + print(getMinCharToAddedToMakeStringPalin(string)) + +# This code is contributed by Rituraj Jain",linear,linear +"# Python3 program to get largest palindrome changing +# atmost K digits + +# Returns maximum possible +# palindrome using k changes +def maximumPalinUsingKChanges(strr, k): + palin = strr[::] + + # Initialize l and r by leftmost and + # rightmost ends + l = 0 + r = len(strr) - 1 + + # first try to make palindrome + while (l <= r): + + # Replace left and right character by + # maximum of both + if (strr[l] != strr[r]): + palin[l] = palin[r] = + max(strr[l], strr[r]) + + # print(strr[l],strr[r]) + k -= 1 + l += 1 + r -= 1 + + # If k is negative then we can't make + # palindrome + if (k < 0): + return ""Not possible"" + + l = 0 + r = len(strr) - 1 + + while (l <= r): + + # At mid character, if K>0 then change + # it to 9 + if (l == r): + if (k > 0): + palin[l] = '9' + + # If character at lth (same as rth) is + # less than 9 + if (palin[l] < '9'): + + # If none of them is changed in the + # previous loop then subtract 2 from K + # and convert both to 9 + if (k >= 2 and palin[l] == strr[l] and + palin[r] == strr[r]): + k -= 2 + palin[l] = palin[r] = '9' + + # If one of them is changed in the previous + # loop then subtract 1 from K (1 more is + # subtracted already) and make them 9 + elif (k >= 1 and (palin[l] != strr[l] or + palin[r] != strr[r])): + k -= 1 + palin[l] = palin[r] = '9' + + l += 1 + r -= 1 + + return palin + + +# Driver code +st = ""43435"" +strr = [i for i in st] +k = 3 +a = maximumPalinUsingKChanges(strr, k) +print("""".join(a)) + +# This code is contributed by mohit kumar 29",linear,linear +"# A recursive Python program +# to check whether a given +# number is palindrome or not + +# A recursive function that +# check a str[s..e] is +# palindrome or not. +def isPalRec(st, s, e) : + + # If there is only one character + if (s == e): + return True + + # If first and last + # characters do not match + if (st[s] != st[e]) : + return False + + # If there are more than + # two characters, check if + # middle substring is also + # palindrome or not. + if (s < e + 1) : + return isPalRec(st, s + 1, e - 1); + + return True + +def isPalindrome(st) : + n = len(st) + + # An empty string is + # considered as palindrome + if (n == 0) : + return True + + return isPalRec(st, 0, n - 1); + + +# Driver Code +st = ""geeg"" +if (isPalindrome(st)) : + print ""Yes"" +else : + print ""No"" + +# This code is contributed +# by Nikita Tiwari.",linear,linear +"def isPalindrome(s, i): + if(i > len(s)/2): + return True + ans = False + if((s[i] is s[len(s) - i - 1]) and isPalindrome(s, i + 1)): + ans = True + return ans + +str = ""geeg"" +if (isPalindrome(str, 0)): + print(""Yes"") +else: + print(""No"") + +# This code is contributed by akashish__",linear,linear +"# Python 3 implementation to find maximum +# length substring which is not palindrome + +# utility function to check whether +# a string is palindrome or not +def isPalindrome(str): + + # Check for palindrome. + n = len(str) + for i in range(n // 2): + if (str[i] != str[n - i - 1]): + return False + + # palindrome string + return True + +# function to find maximum length +# substring which is not palindrome +def maxLengthNonPalinSubstring(str): + n = len(str) + ch = str[0] + + # to check whether all characters + # of the string are same or not + i = 1 + for i in range(1, n): + if (str[i] != ch): + break + + # All characters are same, we can't + # make a non-palindromic string. + if (i == n): + return 0 + + # If string is palindrome, we can make + # it non-palindrome by removing any + # corner character + if (isPalindrome(str)): + return n - 1 + + # Complete string is not a palindrome. + return n + +# Driver Code +if __name__ == ""__main__"": + + str = ""abba"" + print(""Maximum length ="", + maxLengthNonPalinSubstring(str)) + +# This code is contributed by ita_c",linear,linear +"# Python3 program to query the number of +# palindromic substrings of a string in a range +M = 50 + +# Utility method to construct the dp array +def constructDP(dp, string): + + l = len(string) + + # declare 2D array isPalin, isPalin[i][j] + # will be 1 if str(i..j) is palindrome + # and initialize it with zero + isPalin = [[0 for i in range(l + 1)] + for j in range(l + 1)] + + # loop for starting index of range + for i in range(l - 1, -1, -1): + + # initialize value for one + # character strings as 1 + isPalin[i][i], dp[i][i] = 1, 1 + + # loop for ending index of range + for j in range(i + 1, l): + + # isPalin[i][j] will be 1 if ith and jth + # characters are equal and mid substring + # str(i+1..j-1) is also a palindrome + isPalin[i][j] = (string[i] == string[j] and + (i + 1 > j - 1 or isPalin[i + 1][j - 1])) + + # dp[i][j] will be addition of number + # of palindromes from i to j-1 and i+1 + # to j subtracting palindromes from i+1 + # to j-1 (as counted twice) plus 1 if + # str(i..j) is also a palindrome + dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] - + dp[i + 1][j - 1] + isPalin[i][j]) + +# Method returns count of palindromic +# substring in range (l, r) +def countOfPalindromeInRange(dp, l, r): + return dp[l][r] + +# Driver code +if __name__ == ""__main__"": + + string = ""xyaabax"" + dp = [[0 for i in range(M)] + for j in range(M)] + + constructDP(dp, string) + + l, r = 3, 5 + print(countOfPalindromeInRange(dp, l, r)) + +# This code is contributed by Rituraj Jain",quadratic,quadratic +"# 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",constant,linear +"# Python3 program to find n=th even +# length string. +import math as mt + +# Function to find nth even length +# Palindrome + + +def evenlength(n): + + # string r to store resultant + # palindrome. Initialize same as s + res = n + + # In this loop string r stores + # reverse of string s after the + # string s in consecutive manner . + for j in range(len(n) - 1, -1, -1): + res += n[j] + + return res + + +# Driver code +n = ""10"" + +# Function call +print(evenlength(n)) + +# This code is contributed by +# Mohit kumar 29",linear,linear +"# code to make 'ab' free string +def abFree(s): + + # Traverse from end. Keep track of count + # b's. For every 'a' encountered, add b_count + # to result and double b_count. + b_count = 0 + res = 0 + for i in range(len(s)): + if s[~i] == 'a': + res = (res + b_count) + b_count = (b_count * 2) + else: + b_count += 1 + return res + +# driver code +s = 'abbaa' +print(abFree(s)) + +s = 'aab' +print(abFree(s)) + +s ='ababab' +print(abFree(s))",linear,linear +"# Python3 implementation of program to find the maximum length +# that can be removed + +# Function to find the length of longest sub-string that +# can me make removed +# arr --> pair type of array whose first field store +# character in and second field stores +# corresponding index of that character +def longestNull(S): + + arr=[] + + # store {'@',-1} in arr , here this value will + # work as base index + arr.append(['@', -1]) + + maxlen = 0 # Initialize result + + # one by one iterate characters of String + for i in range(len(S)): + # make pair of char and index , then store + # them into arr + arr.append([S[i], i]) + + # now if last three elements of arr[] are making + # sub-string""100"" or not + while (len(arr)>=3 and + arr[len(arr)-3][0]=='1' and + arr[len(arr)-2][0]=='0' and + arr[len(arr)-1][0]=='0'): + + # if above condition is true then delete + # sub-string""100"" from arr[] + arr.pop() + arr.pop() + arr.pop() + + # index of current last element in arr[] + tmp = arr[-1] + # This is important, here 'i' is the index of + # current character inserted into arr[] + # and 'tmp' is the index of last element in arr[] + # after continuous deletion of sub-String + # ""100"" from arr[] till we make it null, difference + # of these to 'i-tmp' gives the length of current + # sub-string that can be make null by continuous + # deletion of sub-string""100"" + maxlen = max(maxlen, i - tmp[1]) + + + return maxlen + + +# Driver code + +print(longestNull(""1011100000100"")) + +# This code is contributed by mohit kumar 29",linear,linear +"# Python 3 program to find minimum number of +# flip to make binary string alternate + +# Utility method to flip a character +def flip( ch): + return '1' if (ch == '0') else '0' + +# Utility method to get minimum flips when +# alternate string starts with expected char +def getFlipWithStartingCharcter(str, expected): + + flipCount = 0 + for i in range(len( str)): + + # if current character is not expected, + # increase flip count + if (str[i] != expected): + flipCount += 1 + + # flip expected character each time + expected = flip(expected) + return flipCount + +# method return minimum flip to make binary +# string alternate +def minFlipToMakeStringAlternate(str): + + # return minimum of following two + # 1) flips when alternate string starts with 0 + # 2) flips when alternate string starts with 1 + return min(getFlipWithStartingCharcter(str, '0'), + getFlipWithStartingCharcter(str, '1')) + +# Driver code to test above method +if __name__ == ""__main__"": + + str = ""0001010111"" + print(minFlipToMakeStringAlternate(str))",constant,linear +"# An efficient Python 3 program to +# find 2's complement + +# Function to find two's complement +def findTwoscomplement(str): + n = len(str) + + # Traverse the string to get first + # '1' from the last of string + i = n - 1 + while(i >= 0): + if (str[i] == '1'): + break + + i -= 1 + + # If there exists no '1' concatenate 1 + # at the starting of string + if (i == -1): + return '1'+str + + # Continue traversal after the + # position of first '1' + k = i - 1 + while(k >= 0): + + # Just flip the values + if (str[k] == '1'): + str = list(str) + str[k] = '0' + str = ''.join(str) + else: + str = list(str) + str[k] = '1' + str = ''.join(str) + + k -= 1 + + # return the modified string + return str + +# Driver code +if __name__ == '__main__': + str = ""00000101"" + print(findTwoscomplement(str)) + +# This code is contributed by +# Sanjit_Prasad",constant,linear +"# Python 3 program to count all +# distinct binary strings with +# two consecutive 1's + + +# Returns count of n length +# binary strings with +# consecutive 1's +def countStrings(n): + + # Count binary strings without + # consecutive 1's. + # See the approach discussed on be + # ( http://goo.gl/p8A3sW ) + a = [0] * n + b = [0] * n + a[0] = b[0] = 1 + for i in range(1, n): + a[i] = a[i - 1] + b[i - 1] + b[i] = a[i - 1] + + # Subtract a[n-1]+b[n-1] from 2^n + return (1 << n) - a[n - 1] - b[n - 1] + + +# Driver code +print(countStrings(5)) + + +# This code is contributed +# by Nikita tiwari.",linear,linear +"# Recursive Python program to generate all +# binary strings formed by replacing +# each wildcard character by 0 or 1 + +# Recursive function to generate all binary +# strings formed by replacing each wildcard +# character by 0 or 1 +def _print(string, index): + if index == len(string): + print(''.join(string)) + return + + if string[index] == ""?"": + + # replace '?' by '0' and recurse + string[index] = '0' + _print(string, index + 1) + + # replace '?' by '1' and recurse + string[index] = '1' + _print(string, index + 1) + + # NOTE: Need to backtrack as string + # is passed by reference to the + # function + string[index] = '?' + else: + _print(string, index + 1) + +# Driver code +if __name__ == ""__main__"": + + string = ""1??0?101"" + string = list(string) + _print(string, 0) + + # This code is contributed by + # sanjeev2552 + +# Note: function name _print is used because +# print is already a predefined function in Python",quadratic,np +"# Iterative Python program to generate all binary +# strings formed by replacing each wildcard +# character by 0 or 1 + +# Iterative function to generate all binary strings +# formed by replacing each wildcard character by 0 +# or 1 +def Print(Str): + q = [] + q.append(Str) + while(len(q) > 0): + Str = q[0] + + # find position of first occurrence of wildcard + try: + index = Str.index('?') + except ValueError: + index = -1 + + # If no matches were found, + # find returns -1 + if(index != -1): + + # replace '?' by '0' and push string into queue + s1=Str.replace('?','0',1) + q.append(s1) + + # replace '?' by '1' and push string into queue + s2=Str.replace('?','1',1) + q.append(s2) + else: + # If no wildcard characters are left, + # print the string. + print(Str) + q.pop(0) + +# Driver code +Str = ""1??0?101"" +Print(Str) + +# This code is contributed by Pushpesh Raj",np,quadratic +"#we store processed strings in all (array) +#we see if string as ""?"", if so, replace it with 0 and 1 +#and send it back to recursive func until base case is reached +#which is no wildcard left + +res = [] +def genBin(s): + if '?' in s: + s1 = s.replace('?','0',1) #only replace once + s2 = s.replace('?','1',1) #only replace once + genBin(s1) + genBin(s2) + else: res.append(s) + +# Driver code +genBin(""1??0?101"") +print(res) + +# This code is contributed by +# divay pandey",np,quadratic +"# The function that adds two-bit sequences and returns the addition +def addBitStrings(str1, str2): + ans = '' + i = len(str1) - 1 + j = len(str2) - 1 + carry = 0 + while i >= 0 or j >= 0 or carry: + if i >= 0: + carry += ord(str1[i]) - ord('0') + i = i - 1 + else: + carry += 0 + + if j >= 0: + carry += ord(str2[j]) - ord('0') + j = j - 1 + else: + carry += 0 + + ans = chr(ord('0') + carry % 2) + ans + carry = carry // 2 + return ans + + +# Driver program to test above functions +str1 = '1100011' +str2 = '10' + +print('Sum is ', addBitStrings(str1, str2)) + +# This code is contributed by ajaymakavan.",constant,linear +"# Python program to count +# all distinct binary strings +# without two consecutive 1's + +def countStrings(n): + + a=[0 for i in range(n)] + b=[0 for i in range(n)] + a[0] = b[0] = 1 + for i in range(1,n): + a[i] = a[i-1] + b[i-1] + b[i] = a[i-1] + + return a[n-1] + b[n-1] + +# Driver program to test +# above functions + +print(countStrings(3)) + +# This code is contributed +# by Anant Agarwal.",linear,linear +"class Subset_sum : + @staticmethod + def countStrings( n) : + a = 1 + b = 1 + i = 1 + while (i < n) : + # Here we have used the temp variable because + # we want to assign the older value of a to b + temp = a + b + b = a + a = temp + i += 1 + return a + b + + # Driver program to test above function + @staticmethod + def main( args) : + print(Subset_sum.countStrings(3)) + + +if __name__==""__main__"": + Subset_sum.main([]) + + # This code is contributed by aadityaburujwale.",constant,linear +"# Python 3program to check if a +# string is of the form a^nb^n. + +# Returns true str is of the +# form a^nb^n. + + +def isAnBn(str): + + n = len(str) + + # After this loop 'i' has + # count of a's + for i in range(n): + if (str[i] != 'a'): + break + + # Since counts of a's and b's should + # be equal, a should appear exactly + # n/2 times + if (i * 2 != n): + return False + + # Rest of the characters must + # be all 'b' + for j in range(i, n): + if (str[j] != 'b'): + return False + + return True + + +# Driver code +if __name__ == ""__main__"": + str = ""abab"" + print(""Yes"") if isAnBn(str) else print(""No"") + +# This code is contributed +# by ChitraNayal",constant,linear +"# Python3 code to check +# a^nb^n pattern + +def isanbn(str): + n=len(str) + + # if length of str is odd return No + if n&1: + return ""No"" + + # check first half is 'a' and other half is full of 'b' + for i in range(int(n/2)): + if str[i]!='a' or str[n-i-1]!='b': + return ""No"" + return ""Yes"" + +# Driver code +input_str = ""ab"" + +# Function call +print(isanbn(input_str))",constant,linear +"# Python3 implementation to find the binary +# representation of next greater integer + +# function to find the required +# binary representation +def nextGreater(num1): + + l = len(num1); + num = list(num1); + + # examine bits from the right + i = l-1; + while(i >= 0): + # if '0' is encountered, convert + # it to '1' and then break + if (num[i] == '0'): + num[i] = '1'; + break; + + # else convert '1' to '0' + else: + num[i] = '0'; + i-=1; + + # if the binary representation + # contains only the set bits + num1 = ''.join(num); + if (i < 0): + num1 = '1' + num1; + + # final binary representation + # of the required integer + return num1; + +# Driver Code +num = ""10011""; +print(""Binary representation of next number = "",nextGreater(num)); + +# This code is contributed by mits",linear,linear +"# Python3 program to find next permutation in a +# binary string. + +# Function to find the next greater number +# with same number of 1's and 0's +def nextGreaterWithSameDigits(bnum): + l = len(bnum) + bnum = list(bnum) + for i in range(l - 2, 0, -1): + + # locate first 'i' from end such that + # bnum[i]=='0' and bnum[i+1]=='1' + # swap these value and break + if (bnum[i] == '0' and bnum[i + 1] == '1'): + ch = bnum[i] + bnum[i] = bnum[i + 1] + bnum[i + 1] = ch + break + + # if no swapping performed + if (i == 0): + return ""no greater number"" + + # Since we want the smallest next value, + # shift all 1's at the end in the binary + # substring starting from index 'i+2' + j = i + 2 + k = l - 1 + while (j < k): + if (bnum[j] == '1' and bnum[k] == '0'): + ch = bnum[j] + bnum[j] = bnum[k] + bnum[k] = ch + j += 1 + k -= 1 + + # special case while swapping if '0' + # occurs then break + else if (bnum[i] == '0'): + break + else: + j += 1 + + # required next greater number + return bnum + +# Driver code +bnum = ""10010"" +print(""Binary representation of next greater number = "",*nextGreaterWithSameDigits(bnum),sep="""") + +# This code is contributed by shubhamsingh10",constant,linear +"# Python Program to find the length of +# substring with maximum difference of +# zeros and ones in binary string. + +# Returns the length of substring with +# maximum difference of zeroes and ones +# in binary string +def findLength(string, n): + current_sum = 0 + max_sum = 0 + + # traverse a binary string from left + # to right + for i in range(n): + + # add current value to the current_sum + # according to the Character + # if it's '0' add 1 else -1 + current_sum += (1 if string[i] == '0' else -1) + + if current_sum < 0: + current_sum = 0 + + # update maximum sum + max_sum = max(current_sum, max_sum) + + # return -1 if string does not contain + # any zero that means all ones + # otherwise max_sum + return max_sum if max_sum else 0 + +# Driven Program +s = ""11000010001"" +n = 11 +print(findLength(s, n)) + +# This code is contributed by Ansu Kumari.",linear,linear +"# Python3 regex program to check for valid string +import re + +# Method to check for valid string +def checkString(str): + # regular expression for invalid string + regex = ""10+1"" + x = re.search(""10+1"", str) + return x is None + +#Driver method +str = ""00011111111100000"" + +if checkString(str): + print(""VALID"") +else: + print(""NOT VALID"") + +#this code is contributed by phasing17",constant,linear +"# Python 3 program to find min flips in +# binary string to make all characters equal + +# To find min number of flips in +# binary string +def findFlips(str, n): + + last = ' ' + res = 0 + + for i in range( n) : + + # If last character is not equal + # to str[i] increase res + if (last != str[i]): + res += 1 + last = str[i] + + # To return min flips + return res // 2 + +# Driver Code +if __name__ == ""__main__"": + + str = ""00011110001110"" + n = len(str) + + print(findFlips(str, n)) + +# This code is contributed by ita_c",constant,linear +"# Python Solution for above problem: + +# This function adds two binary +# strings return the resulting string +def add_binary_nums(x, y): + max_len = max(len(x), len(y)) + + x = x.zfill(max_len) + y = y.zfill(max_len) + + # initialize the result + result = '' + + # initialize the carry + carry = 0 + + # Traverse the string + for i in range(max_len - 1, -1, -1): + r = carry + r += 1 if x[i] == '1' else 0 + r += 1 if y[i] == '1' else 0 + result = ('1' if r % 2 == 1 else '0') + result + carry = 0 if r < 2 else 1 # Compute the carry. + + if carry !=0 : result = '1' + result + + return result.zfill(max_len) + +# Driver code +print(add_binary_nums('1101', '100')) + +# This code is contributed +# by Anand Khatri",linear,linear +"# Python 3 program to convert +# string into binary string + +# utility function +def strToBinary(s): + bin_conv = [] + + for c in s: + + # convert each char to + # ASCII value + ascii_val = ord(c) + + # Convert ASCII value to binary + binary_val = bin(ascii_val) + bin_conv.append(binary_val[2:]) + + return (' '.join(bin_conv)) + +# Driver Code +if __name__ == '__main__': + s = 'geeks' + +print (strToBinary(s)) + +# This code is contributed +# by Vikas Chitturi",linear,linear +"# Python3 program to Generate all binary string +# without consecutive 1's of size K + +# A utility function generate all string without +# consecutive 1'sof size K +def generateAllStringsUtil(K, str, n): + + # print binary string without consecutive 1's + if (n == K): + + # terminate binary string + print(*str[:n], sep = """", end = "" "") + return + + # if previous character is '1' then we put + # only 0 at end of string + # example str = ""01"" then new string be ""000"" + if (str[n-1] == '1'): + str[n] = '0' + generateAllStringsUtil (K, str, n + 1) + + # if previous character is '0' than we put + # both '1' and '0' at end of string + # example str = ""00"" then new string ""001"" and ""000"" + if (str[n-1] == '0'): + str[n] = '0' + generateAllStringsUtil(K, str, n + 1) + str[n] = '1' + generateAllStringsUtil(K, str, n + 1) + +# function generate all binary string without +# consecutive 1's +def generateAllStrings(K): + + # Base case + if (K <= 0): + return + + # One by one stores every + # binary string of length K + str = [0] * K + + # Generate all Binary string starts with '0' + str[0] = '0' + generateAllStringsUtil (K, str, 1) + + # Generate all Binary string starts with '1' + str[0] = '1' + generateAllStringsUtil (K, str, 1) + +# Driver code +K = 3 +generateAllStrings (K) + +# This code is contributed by SHUBHAMSINGH10",linear,np +"def All_Binary_Strings(arr,num,r): + + if(r == num): + + for i in range(num): + print(arr[i],end="""") + print(end="" "") + return + + elif(arr[r-1]): + + arr[r] = 0 + All_Binary_Strings(arr, num, r + 1) + + else: + + arr[r] = 0 + All_Binary_Strings(arr,num,r+1) + arr[r] = 1 + All_Binary_Strings(arr,num,r+1) + + +def Print(a,num): + a[0] = 0 + All_Binary_Strings(a,num,1) + a[0] = 1 + All_Binary_Strings(a,num,1) + + +# driver's code + +n = 2 +a = [False for i in range(n)] +Print(a,n) + +# This code is contributed by shinjanpatra",linear,np +"def All_Binary_Strings(str,num): + + Len = len(str) + if(Len == num): + print(str,end = "" "") + return + + elif(str[Len - 1]=='1'): + All_Binary_Strings(str+'0',num) + else: + All_Binary_Strings(str+'0',num) + All_Binary_Strings(str+'1',num) + +def Print(num): + + word = """" + word += '0' + All_Binary_Strings(word,num) + word = '1' + All_Binary_Strings(word,num) + +# Driver's code +n = 4 +Print(n) + +# This code is contributed by shinjanpatra.",linear,np +"# Python 3 implementation to check +# whether given binary number is +# evenly divisible by 2^k or not + +# function to check whether +# given binary number is +# evenly divisible by 2^k or not +def isDivisible(str, k): + n = len(str) + c = 0 + + # count of number of 0 from last + for i in range(0, k): + if (str[n - i - 1] == '0'): + c += 1 + + # if count = k, number is evenly + # divisible, so returns true else + # false + return (c == k) + +# Driver program to test above +# first example +str1 = ""10101100"" +k = 2 +if (isDivisible(str1, k)): + print(""Yes"") +else: + print(""No"") + +# Second example +str2 = ""111010100"" +k = 2 +if (isDivisible(str2, k)): + print(""Yes"") +else: + print(""No"") + +# This code is contributed by Smitha",constant,constant +"# Python3 Program to find ith character in +# a binary string. + +# Function to store binary Representation +def binary_conversion(s, m): + while(m): + temp = m % 2 + s += str(temp) + m = m // 2 + + return s[::-1] + +# Function to find ith character +def find_character(n, m, i): + s = """" + + +# Function to change decimal to binary + s = binary_conversion(s, m) + s1 = """" + + for x in range(n): + for j in range(len(s)): + if s[j] == ""1"": + s1 += ""10"" + else: + s1 += ""01"" + + # Assign s1 string in s string + s = s1 + s1 = """" + e = ord(s[i]) + r = ord('0') + + return e-r + +# Driver code +m, n, i = 5, 2, 8 + +print(find_character(n,m,i)) + +# This code is contributed by mohit kumar 29",linear,quadratic +"# python program to count substrings +# with odd decimal value +import math + +# function to count number of substrings +# with odd decimal representation +def countSubstr( s): + + n = len(s) + + # auxiliary array to store count + # of 1's before ith index + auxArr= [0 for i in range(n)] + + if (s[0] == '1'): + auxArr[0] = 1 + + # store count of 1's before + # i-th index + for i in range(0,n): + + if (s[i] == '1'): + auxArr[i] = auxArr[i-1]+1 + else: + auxArr[i] = auxArr[i-1] + + + # variable to store answer + count = 0 + + # traverse the string reversely to + # calculate number of odd substrings + # before i-th index + for i in range(n-1,-1,-1): + if (s[i] == '1'): + count += auxArr[i] + + return count +# Driver method +s = ""1101"" +print (countSubstr(s)) + +# This code is contributed by Gitanjali.",linear,linear +"# Python3 program to generate n-bit Gray codes +import math as mt + +# This function generates all n bit Gray +# codes and prints the generated codes +def generateGrayarr(n): + + # base case + if (n <= 0): + return + + # 'arr' will store all generated codes + arr = list() + + # start with one-bit pattern + arr.append(""0"") + arr.append(""1"") + + # Every iteration of this loop generates + # 2*i codes from previously generated i codes. + i = 2 + j = 0 + while(True): + + if i >= 1 << n: + break + + # Enter the previously generated codes + # again in arr[] in reverse order. + # Nor arr[] has double number of codes. + for j in range(i - 1, -1, -1): + arr.append(arr[j]) + + # append 0 to the first half + for j in range(i): + arr[j] = ""0"" + arr[j] + + # append 1 to the second half + for j in range(i, 2 * i): + arr[j] = ""1"" + arr[j] + i = i << 1 + + # print contents of arr[] + for i in range(len(arr)): + print(arr[i]) + +# Driver Code +generateGrayarr(3) + +# This code is contributed +# by Mohit kumar 29",np,np +"# Python3 program to generate +# n-bit Gray codes + +# This function generates all n +# bit Gray codes and prints the +# generated codes +def generateGray(n): + + # Base case + if (n <= 0): + return [""0""] + if (n == 1): + return [ ""0"", ""1"" ] + + # Recursive case + recAns = generateGray(n - 1) + + mainAns = [] + + # Append 0 to the first half + for i in range(len(recAns)): + s = recAns[i] + mainAns.append(""0"" + s) + + # Append 1 to the second half + for i in range(len(recAns) - 1, -1, -1): + s = recAns[i] + mainAns.append(""1"" + s) + + return mainAns + +# Function to generate the +# Gray code of N bits +def generateGrayarr(n): + + arr = generateGray(n) + + # Print contents of arr + print(*arr, sep = ""\n"") + +# Driver Code +generateGrayarr(3) + +# This code is contributed by avanitrachhadiya2155",np,np +"# Python3 implementation of the above approach +def GreyCode(n): + + # power of 2 + for i in range(1 << n): + + # Generating the decimal + # values of gray code then using + # bitset to convert them to binary form + val = (i ^ (i >> 1)) + + # Converting to binary string + s = bin(val)[2::] + print(s.zfill(n), end = "" "") + +# Driver Code +n = 4 + +# Function call +GreyCode(n) + +# This code is contributed by phasing17",linear,np +"# Python 3 program to print all N-bit binary + +# function to generate n digit numbers + + +def printRec(number, extraOnes, remainingPlaces): + + # if number generated + if (0 == remainingPlaces): + print(number, end="" "") + return + + # Append 1 at the current number and + # reduce the remaining places by one + printRec(number + ""1"", extraOnes + 1, + remainingPlaces - 1) + + # If more ones than zeros, append 0 to + # the current number and reduce the + # remaining places by one + if (0 < extraOnes): + printRec(number + ""0"", extraOnes - 1, + remainingPlaces - 1) + + +def printNums(n): + str = """" + printRec(str, 0, n) + + +# Driver Code +if __name__ == '__main__': + n = 4 + + # Function call + printNums(n) + +# This code is contributed by +# Surendra_Gangwar",linear,linear +"# Python3 program to print +# all N-bit binary + +# Function to get the binary +# representation of the number N +def getBinaryRep(N, num_of_bits): + + r = """"; + num_of_bits -= 1 + + # loop for each bit + while (num_of_bits >= 0): + if (N & (1 << num_of_bits)): + r += (""1""); + else: + r += (""0""); + num_of_bits -= 1 + + return r; + +def NBitBinary(N): + + r = [] + first = 1 << (N - 1); + last = first * 2; + + # generate numbers in the range + # of (2^N)-1 to 2^(N-1) inclusive + for i in range (last - 1, + first - 1, -1): + zero_cnt = 0; + one_cnt = 0; + t = i; + num_of_bits = 0; + + # longest prefix check + while (t): + if (t & 1): + one_cnt += 1 + else: + zero_cnt += 1 + num_of_bits += 1 + t = t >> 1; + + # if counts of 1 is greater + # than counts of zero + if (one_cnt >= zero_cnt): + + # do sub-prefixes check + all_prefix_match = True; + msk = (1 << num_of_bits) - 2; + prefix_shift = 1; + + while (msk): + prefix = ((msk & i) >> + prefix_shift); + prefix_one_cnt = 0; + prefix_zero_cnt = 0; + + while (prefix): + if (prefix & 1): + prefix_one_cnt += 1 + else: + prefix_zero_cnt += 1 + prefix = prefix >> 1; + + if (prefix_zero_cnt > + prefix_one_cnt): + all_prefix_match = False; + break; + + prefix_shift += 1 + msk = msk & (msk << 1); + + if (all_prefix_match): + r.append(getBinaryRep(i, + num_of_bits)); + return r + +# Driver code +if __name__ == ""__main__"": + + n = 4; + + # Function call + results = NBitBinary(n); + for i in range (len(results)): + print (results[i], + end = "" "") + print () + +# This code is contributed by Chitranayal",linear,quadratic +"# Python3 program to add n binary strings + +# This function adds two binary strings and +# return result as a third string +def addBinaryUtil(a, b): + + result = """"; # Initialize result + s = 0; # Initialize digit sum + + # Traverse both strings + # starting from last characters + i = len(a) - 1; + j = len(b) - 1; + while (i >= 0 or j >= 0 or s == 1): + + # Compute sum of last digits and carry + s += (ord(a[i]) - ord('0')) if(i >= 0) else 0; + s += (ord(b[j]) - ord('0')) if(j >= 0) else 0; + + # If current digit sum is 1 or 3, + # add 1 to result + result = chr(s % 2 + ord('0')) + result; + + # Compute carry + s //= 2; + + # Move to next digits + i -= 1; + j -= 1; + + return result; + +# function to add n binary strings +def addBinary(arr, n): + result = """"; + for i in range(n): + result = addBinaryUtil(result, arr[i]); + return result; + +# Driver code +arr = [""1"", ""10"", ""11""]; +n = len(arr); +print(addBinary(arr, n)); + +# This code is contributed by mits",linear,linear +"# Python3 program to generate power +# set in lexicographic order. + +# str : Stores input string +# n : Length of str. +# curr : Stores current permutation +# index : Index in current permutation, curr +def permuteRec(string, n, index = -1, curr = """"): + + # base case + if index == n: + return + + if len(curr) > 0: + print(curr) + + for i in range(index + 1, n): + curr += string[i] + permuteRec(string, n, i, curr) + + # backtracking + curr = curr[:len(curr) - 1] + +# Generates power set in lexicographic order +def powerSet(string): + string = ''.join(sorted(string)) + permuteRec(string, len(string)) + +# Driver Code +if __name__ == ""__main__"": + string = ""cab"" + powerSet(string) + +# This code is contributed by vibhu4agarwal",constant,quadratic +"# Python3 program to print nth permutation +# with using next_permute() + +# next_permutation method implementation +def next_permutation(L): + n = len(L) + i = n - 2 + while i >= 0 and L[i] >= L[i + 1]: + i -= 1 + + if i == -1: + return False + + j = i + 1 + while j < n and L[j] > L[i]: + j += 1 + j -= 1 + + L[i], L[j] = L[j], L[i] + + left = i + 1 + right = n - 1 + + while left < right: + L[left], L[right] = L[right], L[left] + left += 1 + right -= 1 + + return True + +# Function to print nth permutation +# using next_permute() +def nPermute(string, n): + string = list(string) + new_string = [] + + # Sort the string in lexicographically + # ascending order + string.sort() + j = 2 + + # Keep iterating until + # we reach nth position + while next_permutation(string): + new_string = string + + # check for nth iteration + if j == n: + break + j += 1 + + # print string after nth iteration + print(''.join(new_string)) + +# Driver Code +if __name__ == ""__main__"": + string = ""GEEKSFORGEEKS"" + n = 100 + nPermute(string, n) + +# This code is contributed by +# sanjeev2552",constant,nlogn +"# A simple Python3 program to find lexicographically +# minimum rotation of a given string + +# This function return lexicographically minimum +# rotation of str +def minLexRotation(str_) : + + # Find length of given string + n = len(str_) + + # Create an array of strings to store all rotations + arr = [0] * n + + # Create a concatenation of string with itself + concat = str_ + str_ + + # One by one store all rotations of str in array. + # A rotation is obtained by getting a substring of concat + for i in range(n) : + arr[i] = concat[i : n + i] + + # Sort all rotations + arr.sort() + + # Return the first rotation from the sorted array + return arr[0] + +# Driver Code +print(minLexRotation(""GEEKSFORGEEKS"")) +print(minLexRotation(""GEEKSQUIZ"")) +print(minLexRotation(""BCABDADAB"")) + +# This code is contributed by divyamohan123",linear,quadratic +"# Python program to print all distinct +# subsequences of a string. + +# Finds and stores result in st for a given +# string s. +def generate(st, s): + if len(s) == 0: + return + + # If current string is not already present. + if s not in st: + st.add(s) + + # Traverse current string, one by one + # remove every character and recur. + for i in range(len(s)): + t = list(s).copy() + t.remove(s[i]) + t = ''.join(t) + generate(st, t) + + return + + +# Driver Code +if __name__ == ""__main__"": + s = ""xyz"" + st = set() + generate(st, s) + for i in st: + print(i) + +# This code is contributed by +# sanjeev2552",linear,quadratic +"# Python 3 code to find the lexicographically +# smallest string +def lexSmallest(a, n): + # Sort strings using above compare() + for i in range(0,n): + for j in range(i+1,n): + if(a[i]+a[j]>a[j]+a[i]): + s=a[i] + a[i]=a[j] + a[j]=s + + # Concatenating sorted strings + answer = """" + for i in range( n): + answer += a[i] + return answer + +# Driver code +if __name__ == ""__main__"": + + a = [ ""c"", ""cb"", ""cba"" ] + n = len(a) + print(lexSmallest(a, n)) + +# This code is contributed by vibhu karnwal + + + ",linear,quadratic +"# Python Program to create concatenation of all +# substrings in lexicographic order. + +def lexicographicSubConcat(s): + n = len(s); + + # Creating an array to store substrings + sub_count = (n * (n + 1))//2; + arr = [0]*sub_count; + + # finding all substrings of string + index = 0; + for i in range(n): + for j in range(1,n - i + 1): + arr[index] = s[i:i + j]; + index += 1; + + # Sort all substrings in lexicographic + # order + arr.sort(); + + # Concatenating all substrings + res = """"; + for i in range(sub_count): + res += arr[i]; + + return res; + +s = ""abc""; +print(lexicographicSubConcat(s)); + +# This code is contributed by Princi Singh",linear,cubic +"# Python3 for constructing smallest palindrome + +# function for printing palindrome +def constructPalin(string, l): + string = list(string) + i = -1 + j = l + + # iterate till i= 0): + if (str[i] == 'a'): + str2 = str2.replace(str2[i], 'b') + p += 1 + + if (p == k): + break + i -= 1 + + print(str2) + +# Driver Code +if __name__ == '__main__': + str = ""pqrs"" + n = len(str) + k = 2 + + findString(str, n, k) + +# This code is contributed by +# Surendra_Gangwar",linear,linear +"# Python 3 program to find lexicographically +# next string + +def nextWord(s): + + # If string is empty. + if (s == "" ""): + return ""a"" + + # Find first character from right + # which is not z. + i = len(s) - 1 + while (s[i] == 'z' and i >= 0): + i -= 1 + + # If all characters are 'z', append + # an 'a' at the end. + if (i == -1): + s = s + 'a' + + # If there are some non-z characters + else: + s = s.replace(s[i], chr(ord(s[i]) + 1), 1) + + return s + +# Driver code +if __name__ == '__main__': + str = ""samez"" + print(nextWord(str)) + +# This code is contributed by +# Sanjit_Prasad",constant,linear +"# Python3 program to find lexicographically largest +# subsequence where every character appears at +# least k times. + +# Find lexicographically largest subsequence of +# s[0..n-1] such that every character appears +# at least k times. The result is filled in t[] +def subsequence(s, t, n, k): + last = 0 + cnt = 0 + new_last = 0 + size = 0 + + string = 'zyxwvutsrqponmlkjihgfedcba' + + # Starting from largest character 'z' to 'a' + for ch in string: + cnt = 0 + for i in range(last, n): + if s[i] == ch: + cnt += 1 + + # If frequency is greater than k + if cnt >= k: + + # From the last point we leave + for i in range(last, n): + + # check if string contain ch + if s[i] == ch: + + # If yes, append to output string + t[size] = ch + new_last = i + size += 1 + + # Update the last point. + last = new_last + +# Driver Code +if __name__ == ""__main__"": + s = ['b', 'a', 'n', 'a', 'n', 'a'] + n = len(s) + k = 2 + t = [''] * n + subsequence(s, t, n - 1, k) + t = ''.join(t) + print(t) + +# This code is contributed by +# sanjeev2552",linear,linear +"# Python3 implementation of lexicographically first +# alternate vowel and consonant string +SIZE = 26 + +# 'ch' is vowel or not +def isVowel(ch): + if (ch == 'a' or ch == 'e' or + ch == 'i' or ch == 'o' or + ch == 'u'): + return True + return False + +# create alternate vowel and consonant string +# str1[0...l1-1] and str2[start...l2-1] +def createAltStr(str1, str2, start, l): + finalStr = """" + i = 0 + j = start + + # first adding character of vowel/consonant + # then adding character of consonant/vowel + while j < l: + finalStr += str1[i] + str2[j] + i += 1 + j += 1 + return finalStr + +# function to find the required lexicographically +# first alternate vowel and consonant string +def findAltStr(string): + + # hash table to store frequencies + # of each character in 'str' + char_freq = [0] * SIZE # initialize all elements + # of char_freq[] to 0 + nv = 0 + nc = 0 + vstr = """" + cstr = """" + l = len(string) + + for i in range(l): + ch = string[i] + + # count vowels + if isVowel(ch): + nv += 1 + + # count consonants + else: + nc += 1 + + # update frequency of 'ch' in + # char_freq[] + char_freq[ord(ch) - 97] += 1 + + # no such string can be formed + if abs(nv - nc) >= 2: + return ""no such string"" + + # form the vowel string 'vstr' and + # consonant string 'cstr' which contains + # characters in lexicographical order + for i in range(SIZE): + ch = chr(i + 97) + for j in range(1, char_freq[i] + 1): + if isVowel(ch): + vstr += ch + else: + cstr += ch + + # remove first character of vowel string + # then create alternate string with + # cstr[0...nc-1] and vstr[1...nv-1] + if nv > nc: + return vstr[0] + createAltStr(cstr, + vstr, 1, nv) + + # remove first character of consonant string + # then create alternate string with + # vstr[0...nv-1] and cstr[1...nc-1] + if nc > nv: + return cstr[0] + createAltStr(vstr, + cstr, 1, nc) + + # if both vowel and consonant + # strings are of equal length + # start creating string with consonant + if cstr[0] < vstr[0]: + return createAltStr(cstr, vstr, 0, nv) + + # start creating string with vowel + return createAltStr(vstr, cstr, 0, nc) + +# Driver Code +if __name__ == ""__main__"": + string = ""aeroplane"" + print(findAltStr(string)) + +# This code is contributed by +# sanjeev2552",constant,linear +"# Python3 program to find the string +# in lexicographic order which is +# in between given two strings + +# Function to find the lexicographically +# next string +def lexNext(s, n): + + # Iterate from last character + for i in range(n - 1, -1, -1): + + # If not 'z', increase by one + if s[i] != 'z': + k = ord(s[i]) + s[i] = chr(k + 1) + return ''.join(s) + + # if 'z', change it to 'a' + s[i] = 'a' + +# Driver Code +if __name__ == ""__main__"": + S = ""abcdeg"" + T = ""abcfgh"" + n = len(S) + + S = list(S) + res = lexNext(S, n) + + # If not equal, print the + # resultant string + if res != T: + print(res) + else: + print(-1) + +# This code is contributed by +# sanjeev2552",constant,linear +"# Python3 program to print n-th permutation + +MAX_CHAR = 26 +MAX_FACT = 20 +fact = [None] * (MAX_FACT) + +# Utility for calculating factorials +def precomputeFactorials(): + + fact[0] = 1 + for i in range(1, MAX_FACT): + fact[i] = fact[i - 1] * i + +# Function for nth permutation +def nPermute(string, n): + + precomputeFactorials() + + # length of given string + length = len(string) + + # Count frequencies of all + # characters + freq = [0] * (MAX_CHAR) + for i in range(0, length): + freq[ord(string[i]) - ord('a')] += 1 + + # out string for output string + out = [None] * (MAX_CHAR) + + # iterate till sum equals n + Sum, k = 0, 0 + + # We update both n and sum in + # this loop. + while Sum != n: + + Sum = 0 + + # check for characters present in freq[] + for i in range(0, MAX_CHAR): + if freq[i] == 0: + continue + + # Remove character + freq[i] -= 1 + + # calculate sum after fixing + # a particular char + xsum = fact[length - 1 - k] + for j in range(0, MAX_CHAR): + xsum = xsum // fact[freq[j]] + Sum += xsum + + # if sum > n fix that char as + # present char and update sum + # and required nth after fixing + # char at that position + if Sum >= n: + out[k] = chr(i + ord('a')) + n -= Sum - xsum + k += 1 + break + + # if sum < n, add character back + if Sum < n: + freq[i] += 1 + + # if sum == n means this char will provide + # its greatest permutation as nth permutation + i = MAX_CHAR-1 + while k < length and i >= 0: + if freq[i]: + out[k] = chr(i + ord('a')) + freq[i] -= 1 + i += 1 + k += 1 + + i -= 1 + + # print result + print(''.join(out[:k])) + +# Driver Code +if __name__ == ""__main__"": + + n = 2 + string = ""geeksquiz"" + + nPermute(string, n) + +# This code is contributed by Rituraj Jain",linear,linear +"# Python program to find lexicographic +# rank of a string + +# A utility function to find factorial +# of n +def fact(n): + f = 1 + while n >= 1: + f = f * n + n = n - 1 + return f + +# A utility function to count smaller +# characters on right of arr[low] +def findSmallerInRight(st, low, high): + countRight = 0 + i = low + 1 + while i <= high: + if st[i] < st[low]: + countRight = countRight + 1 + i = i + 1 + + return countRight + +# A function to find rank of a string +# in all permutations of characters +def findRank(st): + ln = len(st) + mul = fact(ln) + rank = 1 + i = 0 + + while i < ln: + mul = mul // (ln - i) + + # count number of chars smaller + # than str[i] from str[i + 1] to + # str[len-1] + countRight = findSmallerInRight(st, i, ln-1) + + rank = rank + countRight * mul + i = i + 1 + + return rank + + +# Driver code +if __name__ == '__main__': + st = ""string"" + + # Function call + print(findRank(st)) + +# This code is contributed by Nikita Tiwari.",constant,quadratic +"# A O(n) solution for finding rank of string +MAX_CHAR = 256 + +# All elements of count[] are initialized with 0 +count = [0]*(MAX_CHAR + 1) + +# A utility function to find factorial of n +def fact(n): + return 1 if(n <= 1) else (n * fact(n - 1)) + +# Construct a count array where value at every index +# contains count of smaller characters in whole string +def populateAndIncreaseCount(str): + for i in range(len(str)): + count[ord(str[i])] += 1 + + for i in range(1, MAX_CHAR): + count[i] += count[i - 1] + +# Removes a character ch from count[] array +# constructed by populateAndIncreaseCount() +def updatecount(ch): + + for i in range(ord(ch), MAX_CHAR): + count[i] -= 1 + +# A function to find rank of a string in all permutations +# of characters +def findRank(str): + len1 = len(str) + mul = fact(len1) + rank = 1 + + # Populate the count array such that count[i] + # contains count of characters which are present + # in str and are smaller than i + populateAndIncreaseCount(str) + + for i in range(len1): + mul = mul//(len1 - i) + + # count number of chars smaller than str[i] + # from str[i+1] to str[len-1] + rank += count[ord(str[i]) - 1] * mul + + # Reduce count of characters greater than str[i] + updatecount(str[i]) + + return rank + + +# Driver code +if __name__ == '__main__': + str = ""string"" + print(findRank(str)) + +# This is code is contributed by chandan_jnu",constant,linear +"# Python3 Program for Bad Character Heuristic +# of Boyer Moore String Matching Algorithm + +NO_OF_CHARS = 256 + +def badCharHeuristic(string, size): + ''' + The preprocessing function for + Boyer Moore's bad character heuristic + ''' + + # Initialize all occurrence as -1 + badChar = [-1]*NO_OF_CHARS + + # Fill the actual value of last occurrence + for i in range(size): + badChar[ord(string[i])] = i; + + # return initialized list + return badChar + +def search(txt, pat): + ''' + A pattern searching function that uses Bad Character + Heuristic of Boyer Moore Algorithm + ''' + m = len(pat) + n = len(txt) + + # create the bad character list by calling + # the preprocessing function badCharHeuristic() + # for given pattern + badChar = badCharHeuristic(pat, m) + + # s is shift of the pattern with respect to text + s = 0 + while(s <= n-m): + j = m-1 + + # Keep reducing index j of pattern while + # characters of pattern and text are matching + # at this shift s + while j>=0 and pat[j] == txt[s+j]: + j -= 1 + + # If the pattern is present at current shift, + # then index j will become -1 after the above loop + if j<0: + print(""Pattern occur at shift = {}"".format(s)) + + ''' + Shift the pattern so that the next character in text + aligns with the last occurrence of it in pattern. + The condition s+m < n is necessary for the case when + pattern occurs at the end of text + ''' + s += (m-badChar[ord(txt[s+m])] if s+m 0: + L[i] = min(L[iMirror], diff) + + # Attempt to expand palindrome centered at currentRightPosition i + # Here for odd positions, we compare characters and + # if match then increment LPS Length by ONE + # If even position, we just increment LPS by ONE without + # any character comparison + try: + while ((i + L[i]) < N and (i - L[i]) > 0) and \ + (((i + L[i] + 1) % 2 == 0) or \ + (text[(i + L[i] + 1) // 2] == text[(i - L[i] - 1) // 2])): + L[i]+=1 + except Exception as e: + pass + + if L[i] > maxLPSLength: # Track maxLPSLength + maxLPSLength = L[i] + maxLPSCenterPosition = i + + # If palindrome centered at currentRightPosition i + # expand beyond centerRightPosition R, + # adjust centerPosition C based on expanded palindrome. + if i + L[i] > R: + C = i + R = i + L[i] + + # Uncomment it to print LPS Length array + # printf(""%d "", L[i]); + start = (maxLPSCenterPosition - maxLPSLength) // 2 + end = start + maxLPSLength - 1 + print (""LPS of string is "" + text + "" : "",text[start:end+1]) + +# Driver program +text1 = ""babcbabcbaccba"" +findLongestPalindromicString(text1) + +text2 = ""abaaba"" +findLongestPalindromicString(text2) + +text3 = ""abababa"" +findLongestPalindromicString(text3) + +text4 = ""abcbabcbabcba"" +findLongestPalindromicString(text4) + +text5 = ""forgeeksskeegfor"" +findLongestPalindromicString(text5) + +text6 = ""caba"" +findLongestPalindromicString(text6) + +text7 = ""abacdfgdcaba"" +findLongestPalindromicString(text7) + +text8 = ""abacdfgdcabba"" +findLongestPalindromicString(text8) + +text9 = ""abacdedcaba"" +findLongestPalindromicString(text9) + +# This code is contributed by BHAVYA JAIN",linear,linear +"# Python 3 program to print the +# string in 'plus' pattern +max = 100 + +# Function to make a cross +# in the matrix +def carveCross(str): + + n = len(str) + if (n % 2 == 0) : + + ''' As, it is not possible to make + the cross exactly in the middle of + the matrix with an even length string.''' + print(""Not possible. Please enter "" + , ""odd length string.\n"") + + else : + + # declaring a 2D array i.e a matrix + arr = [[ False for x in range(max)] + for y in range(max)] + m = n // 2 + + ''' Now, we will fill all the + elements of the array with 'X''' + for i in range( n) : + for j in range(n) : + arr[i][j] = 'X' + + '''Now, we will place the characters + of the string in the matrix, such + that a cross is formed in it.''' + for i in range(n): + + ''' here the characters of the + string will be added in the + middle column of our array.''' + arr[i][m] = str[i] + + for i in range(n): + + # here the characters of the + # string will be added in the + # middle row of our array. + arr[m][i] = str[i] + + # Now finally, we will print + # the array + for i in range(n): + for j in range(n): + print( arr[i][j] , end="" "") + + print() + +# Driver Code +if __name__ == ""__main__"": + str = ""PICTURE"" + carveCross(str) + +# This code is contributed +# by ChitraNayal",constant,quadratic +"# Python3 program to implement +# wildcard pattern matching +# algorithm + +# Function that matches input +# txt with given wildcard pattern +def stringmatch(txt, pat, n, m): + + # empty pattern can only + # match with empty sting + # Base case + if (m == 0): + return (n == 0) + + # step 1 + # initialize markers : + i = 0 + j = 0 + index_txt = -1 + index_pat = -1 + while(i < n - 2): + + # For step - (2, 5) + if (j < m and txt[i] == pat[j]): + i += 1 + j += 1 + + # For step - (3) + elif(j < m and pat[j] == '?'): + i += 1 + j += 1 + + # For step - (4) + elif(j < m and pat[j] == '*'): + index_txt = i + index_pat = j + j += 1 + + # For step - (5) + elif(index_pat != -1): + j = index_pat + 1 + i = index_txt + 1 + index_txt += 1 + + # For step - (6) + else: + return False + # For step - (7) + while (j < m and pat[j] == '*'): + j += 1 + + # Final Check + if(j == m): + return True + + return False + +# Driver code +strr = ""baaabab"" +pattern = ""*****ba*****ab"" + +# char pattern[] = ""ba*****ab"" +# char pattern[] = ""ba * ab"" +# char pattern[] = ""a * ab"" +if (stringmatch(strr, pattern, len(strr), + len(pattern))): + print(""Yes"") +else: + print( ""No"") + +pattern2 = ""a*****ab""; +if (stringmatch(strr, pattern2, len(strr), + len(pattern2))): + print(""Yes"") +else: + print( ""No"") + +# This code is contributed +# by sahilhelangia",constant,linear +"# Python3 program to replace c1 with c2 +# and c2 with c1 +def replace(s, c1, c2): + l = len(s) + + # loop to traverse in the string + for i in range(l): + + # check for c1 and replace + if (s[i] == c1): + s = s[0:i] + c2 + s[i + 1:] + + # check for c2 and replace + elif (s[i] == c2): + s = s[0:i] + c1 + s[i + 1:] + return s + +# Driver Code +if __name__ == '__main__': + s = ""grrksfoegrrks"" + c1 = 'e' + c2 = 'r' + print(replace(s, c1, c2)) + +# This code is contributed +# by PrinciRaj1992",constant,linear +"# Python program for implementation of +# Aho-Corasick algorithm for string matching + +# defaultdict is used only for storing the final output +# We will return a dictionary where key is the matched word +# and value is the list of indexes of matched word +from collections import defaultdict + +# For simplicity, Arrays and Queues have been implemented using lists. +# If you want to improve performance try using them instead +class AhoCorasick: + def __init__(self, words): + + # Max number of states in the matching machine. + # Should be equal to the sum of the length of all keywords. + self.max_states = sum([len(word) for word in words]) + + # Maximum number of characters. + # Currently supports only alphabets [a,z] + self.max_characters = 26 + + # OUTPUT FUNCTION IS IMPLEMENTED USING out [] + # Bit i in this mask is 1 if the word with + # index i appears when the machine enters this state. + # Lets say, a state outputs two words ""he"" and ""she"" and + # in our provided words list, he has index 0 and she has index 3 + # so value of out[state] for this state will be 1001 + # It has been initialized to all 0. + # We have taken one extra state for the root. + self.out = [0]*(self.max_states+1) + + # FAILURE FUNCTION IS IMPLEMENTED USING fail [] + # There is one value for each state + 1 for the root + # It has been initialized to all -1 + # This will contain the fail state value for each state + self.fail = [-1]*(self.max_states+1) + + # GOTO FUNCTION (OR TRIE) IS IMPLEMENTED USING goto [[]] + # Number of rows = max_states + 1 + # Number of columns = max_characters i.e 26 in our case + # It has been initialized to all -1. + self.goto = [[-1]*self.max_characters for _ in range(self.max_states+1)] + + # Convert all words to lowercase + # so that our search is case insensitive + for i in range(len(words)): + words[i] = words[i].lower() + + # All the words in dictionary which will be used to create Trie + # The index of each keyword is important: + # ""out[state] & (1 << i)"" is > 0 if we just found word[i] + # in the text. + self.words = words + + # Once the Trie has been built, it will contain the number + # of nodes in Trie which is total number of states required <= max_states + self.states_count = self.__build_matching_machine() + + + # Builds the String matching machine. + # Returns the number of states that the built machine has. + # States are numbered 0 up to the return value - 1, inclusive. + def __build_matching_machine(self): + k = len(self.words) + + # Initially, we just have the 0 state + states = 1 + + # Convalues for goto function, i.e., fill goto + # This is same as building a Trie for words[] + for i in range(k): + word = self.words[i] + current_state = 0 + + # Process all the characters of the current word + for character in word: + ch = ord(character) - 97 # Ascii value of 'a' = 97 + + # Allocate a new node (create a new state) + # if a node for ch doesn't exist. + if self.goto[current_state][ch] == -1: + self.goto[current_state][ch] = states + states += 1 + + current_state = self.goto[current_state][ch] + + # Add current word in output function + self.out[current_state] |= (1< 0: + word = self.words[j] + + # Start index of word is (i-len(word)+1) + result[word].append(i-len(word)+1) + + # Return the final result dictionary + return result + +# Driver code +if __name__ == ""__main__"": + words = [""he"", ""she"", ""hers"", ""his""] + text = ""ahishers"" + + # Create an Object to initialize the Trie + aho_chorasick = AhoCorasick(words) + + # Get the result + result = aho_chorasick.search_words(text) + + # Print the result + for word in result: + for i in result[word]: + print(""Word"", word, ""appears from"", i, ""to"", i+len(word)-1) + +# This code is contributed by Md Azharuddin",linear,linear +"# Python program to calculate number of times +# the pattern occurred in given string + +# Returns count of occurrences of ""1(0+)1"" +def countPattern(s): + length = len(s) + oneSeen = False + + count = 0 # Initialize result + for i in range(length): + + # Check if encountered '1' forms a valid + # pattern as specified + if (s[i] == '1' and oneSeen): + if (s[i - 1] == '0'): + count += 1 + + # if 1 encountered for first time + # set oneSeen to 1 + if (s[i] == '1' and oneSeen == 0): + oneSeen = True + + # Check if there is any other character + # other than '0' or '1'. If so then set + # oneSeen to 0 to search again for new + # pattern + if (s[i] != '0' and s[i] != '1'): + oneSeen = False + + + + return count + +# Driver code +s = ""100001abc101"" +print(countPattern(s)) + +# This code is contributed by Sachin Bisht",constant,linear +"# Python3 program to find if a string follows +# order defined by a given pattern +CHAR_SIZE = 256 + +# Returns true if characters of str follow +# order defined by a given ptr. +def checkPattern(Str, pat): + + # Initialize all orders as -1 + label = [-1] * CHAR_SIZE + + # Assign an order to pattern characters + # according to their appearance in pattern + order = 1 + + for i in range(len(pat)): + + # Give the pattern characters order + label[ord(pat[i])] = order + + # Increment the order + order += 1 + + # Now one by one check if string + # characters follow above order + last_order = -1 + + for i in range(len(Str)): + if (label[ord(Str[i])] != -1): + + # If order of this character is less + # than order of previous, return false + if (label[ord(Str[i])] < last_order): + return False + + # Update last_order for next iteration + last_order = label[ord(Str[i])] + + # return that str followed pat + return True + +# Driver Code +if __name__ == '__main__': + + Str = ""engineers rock"" + pattern = ""gsr"" + + print(checkPattern(Str, pattern)) + +# This code is contributed by himanshu77",constant,linear +"# Python code for finding count +# of string in a given 2D +# character array. + +# utility function to search +# complete string from any +# given index of 2d array +def internalSearch(ii, needle, row, col, hay, + row_max, col_max): + + found = 0 + if (row >= 0 and row <= row_max and + col >= 0 and col <= col_max and + needle[ii] == hay[row][col]): + match = needle[ii] + ii += 1 + hay[row][col] = 0 + if (ii == len(needle)): + found = 1 + else: + + # through Backtrack searching + # in every directions + found += internalSearch(ii, needle, row, + col + 1, hay, row_max, col_max) + found += internalSearch(ii, needle, row, + col - 1, hay, row_max, col_max) + found += internalSearch(ii, needle, row + 1, + col, hay, row_max, col_max) + found += internalSearch(ii, needle, row - 1, + col, hay, row_max, col_max) + hay[row][col] = match + return found + +# Function to search the string in 2d array +def searchString(needle, row, col,strr, + row_count, col_count): + found = 0 + for r in range(row_count): + for c in range(col_count): + found += internalSearch(0, needle, r, c, + strr, row_count - 1, col_count - 1) + + return found + +# Driver code + +needle = ""MAGIC"" +inputt = [""BBABBM"",""CBMBBA"",""IBABBG"", + ""GOZBBI"",""ABBBBC"",""MCIGAM""] + +strr = [0] * len(inputt) + +for i in range(len(inputt)): + strr[i] = list(inputt[i]) + +print(""count: "", searchString(needle, 0, 0, strr, + len(strr), len(strr[0]))) + +# This code is contributed by SHUBHAMSINGH10",quadratic,quadratic +"# Python3 program to check if we can +# break a into four distinct strings. + +# Return if the given string can be +# split or not. +def check(s): + + # We can always break a of size 10 or + # more into four distinct strings. + if (len(s) >= 10): + return True + + # Brute Force + for i in range(1, len(s)): + + for j in range(i + 1, len(s)): + + for k in range(j + 1, len(s)): + + # Making 4 from the given + s1 = s[0:i] + s2 = s[i:j - i] + s3 = s[j: k - j] + s4 = s[k: len(s) - k] + + # Checking if they are distinct or not. + if (s1 != s2 and s1 != s3 and s1 != s4 and + s2 != s3 and s2 != s4 and s3 != s4): + return True + + return False + +# Driver Code +if __name__ == '__main__': + str = ""aaabb"" + + print(""Yes"") if(check(str)) else print(""NO"") + +# This code is contributed +# by SHUBHAMSINGH10",linear,np +"# Python 3 program to split an alphanumeric +# string using STL +def splitString(str): + + alpha = """" + num = """" + special = """" + for i in range(len(str)): + if (str[i].isdigit()): + num = num+ str[i] + elif((str[i] >= 'A' and str[i] <= 'Z') or + (str[i] >= 'a' and str[i] <= 'z')): + alpha += str[i] + else: + special += str[i] + + print(alpha) + print(num ) + print(special) + +# Driver code +if __name__ == ""__main__"": + + str = ""geeks01$$for02geeks03!@!!"" + splitString(str) + +# This code is contributed by ita_c",linear,linear +"# Python3 program to split a numeric +# string in an Increasing +# sequence if possible + +# Function accepts a string and +# checks if string can be split. +def split(Str) : + Len = len(Str) + + # if there is only 1 number + # in the string then + # it is not possible to split it + if (Len == 1) : + print(""Not Possible"") + return + + s1, s2 = """", """" + for i in range((Len // 2) + 1) : + flag = 0 + + # storing the substring from + # 0 to i+1 to form initial + # number of the increasing sequence + s1 = Str[0 : i + 1] + num1 = int(s1) + num2 = num1 + 1 + + # convert string to integer + # and add 1 and again convert + # back to string s2 + s2 = str(num2) + k = i + 1 + while (flag == 0) : + l = len(s2) + + # if s2 is not a substring + # of number than not possible + if (k + l > Len) : + flag = 1 + break + + # if s2 is the next substring + # of the numeric string + if ((Str[k : k + l] == s2)) : + flag = 0 + + # Increase num2 by 1 i.e the + # next number to be looked for + num2 += 1 + k = k + l + + # check if string is fully + # traversed then break + if (k == Len) : + break + s2 = str(num2) + l = len(s2) + if (k + 1 > len) : + + # If next string doesnot occurs + # in a given numeric string + # then it is not possible + flag = 1 + break + else : + flag = 1 + + # if the string was fully traversed + # and conditions were satisfied + if (flag == 0) : + print(""Possible"", s1) + break + + # if conditions failed to hold + elif (flag == 1 and i > (Len // 2) - 1) : + print(""Not Possible"") + break + +# Driver code +Str = ""99100"" + +# Call the split function +# for splitting the string +split(Str) + +# This code is contributed by divyesh072019.",linear,quadratic +"# Python3 Program to find number of way +# to split string such that each partition +# starts with distinct character with +# maximum number of partitions. + +# Returns the number of we can split +# the string +def countWays(s): + count = [0] * 26; + + # Finding the frequency of each + # character. + for x in s: + count[ord(x) - + ord('a')] = (count[ord(x) - + ord('a')]) + 1; + + # making frequency of first character + # of string equal to 1. + count[ord(s[0]) - ord('a')] = 1; + + # Finding the product of frequency + # of occurrence of each character. + ans = 1; + for i in range(26): + if (count[i] != 0): + ans *= count[i]; + + return ans; + +# Driver Code +if __name__ == '__main__': + s = ""acbbcc""; + print(countWays(s)); + +# This code is contributed by Rajput-Ji",constant,linear +"# Python3 program to check if a can be splitted +# into two strings such that one is divisible by 'a' +# and other is divisible by 'b'. + +# Finds if it is possible to partition str +# into two parts such that first part is +# divisible by a and second part is divisible +# by b. +def findDivision(str, a, b): + lenn = len(str) + + # Create an array of size lenn+1 and + # initialize it with 0. + # Store remainders from left to right + # when divided by 'a' + lr = [0] * (lenn + 1) + lr[0] = (int(str[0]))%a + for i in range(1, lenn): + lr[i] = ((lr[i - 1] * 10) % a + \ + int(str[i])) % a + + # Compute remainders from right to left + # when divided by 'b' + rl = [0] * (lenn + 1) + rl[lenn - 1] = int(str[lenn - 1]) % b + power10 = 10 + for i in range(lenn - 2, -1, -1): + rl[i] = (rl[i + 1] + int(str[i]) * power10) % b + power10 = (power10 * 10) % b + + # Find a point that can partition a number + for i in range(0, lenn - 1): + + # If split is not possible at this point + if (lr[i] != 0): + continue + + # We can split at i if one of the following + # two is true. + # a) All characters after str[i] are 0 + # b) after str[i] is divisible by b, i.e., + # str[i+1..n-1] is divisible by b. + if (rl[i + 1] == 0): + print(""YES"") + for k in range(0, i + 1): + print(str[k], end = """") + + print("","", end = "" "") + + for i in range(i + 1, lenn): + print(str[k], end = """") + return + + print(""NO"") + +# Driver code +str = ""123"" +a, b = 12, 3 +findDivision(str, a, b) + +# This code is contributed by SHUBHAMSINGH10",linear,linear +"# Python program to check if a string can be splitted +# into two strings such that one is divisible by 'a' +# and other is divisible by 'b'. + +# Finds if it is possible to partition str +# into two parts such that first part is +# divisible by a and second part is divisible +# by b. +def findDivision(S, a, b): + + for i in range(len(S)-1): + + firstPart = S[0: i + 1] + secondPart = S[i + 1:] + + if (int(firstPart) % a == 0 + and int(secondPart) % b == 0): + return firstPart + "" "" + secondPart + + return ""-1"" + +# Driver code +Str = ""125"" +a,b = 12,3 +result = findDivision(Str, a, b) + +if (result == ""-1""): + print(""NO"") + +else: + print(""YES"") + print(result) + +# This code is contributed by shinjanpatra",constant,linear +"# Python3 code to implement the approach + +# This code kind of uses sliding window technique. First +# checking if string[0] and string[0..n-1] is divisible if +# yes then return else run a loop from 1 to n-1 and check if +# taking this (0-i)index number and (i+1 to n-1)index number +# on our two declared variables if they are divisible by given two numbers respectively +# in any iteration return them simply +def stringPartition(s, a, b): + # code here + n = len(s) + + # if length is 1 not possible + if (n == 1): + return ""-1"" + + else: + # Checking if number formed bt S[0] and S[1->n-1] is divisible + a1 = int(s[0]) + a2 = int(s[1]) + multiplyer = 10 + for i in range(2, n): + a2 = a2 * multiplyer + int(s[i]) + + i = 1 + if (a1 % a == 0 and a2 % b == 0): + k1 = '1' * (s[0]) + k2 = """" + for j in range(1, n): + k2 += s[j] + return k1 + "" "" + k2 # return the numbers formed as string + + # from here by using sliding window technique we + # will iterate and check for every i that if the + # two current numbers formed are divisible if yes + # return else form the two new numbers for next + # iteration using sliding window technique + q1 = 10 + q2 = 1 + for i in range(1, n - 1): + q2 *= 10 + while (i < n - 1): + x = s[i] + ad = int(x) + a1 = a1 * q1 + ad + a2 = a2 - q2 * ad + if (a1 % a == 0 and a2 % b == 0): + k1 = """" + k2 = """" + for j in range(i + 1): + k1 += s[j] + for j in range(i + 1, n): + k2 += s[j] + return k1 + "" "" + k2 + + q2 //= 10 + i += 1 + + return ""-1"" + +# Driver code +str = ""123"" +a = 12 +b = 3 +result = stringPartition(str, a, b) + +if (result == ""-1""): + print(""NO"") +else: + print(""YES"") + print(result) + +# This code is contributed by phasing17",constant,linear +"# Python3 program to count ways to divide +# a string in two parts a and b such that +# b/pow(10, p) == a + +def calculate( N ): + length = len(N) + l = int((length) / 2) + count = 0 + + for i in range(l + 1): + print(i) + + # substring representing int a + s = N[0: 0 + i] + + # no of digits in a + l1 = len(s) + print(s,l1) + + # consider only most significant + # l1 characters of remaining + # string for int b + t = N[i: l1 + i] + + # if any of a or b contains + # leading 0s discard this + try: + if s[0] == '0' or t[0] == '0': + continue + except: + continue + + # if both are equal + if s == t: + count+=1 + print(i,N[i],count) + return count + +# driver code to test above function +N = str(""2202200"") +print(calculate(N)) + +# This code is contributed by ""Sharad_Bhardwaj"".",linear,quadratic +"# Python program to print n equal parts of string + +# Function to print n equal parts of string + + +def divideString(string, n): + str_size = len(string) + + # Check if string can be divided in n equal parts + if str_size % n != 0: + print (""Invalid Input: String size is not divisible by n"") + return + + # Calculate the size of parts to find the division points + part_size = str_size/n + k = 0 + for i in string: + if k % part_size == 0: + print () + print (i,end='') + k += 1 + + +# Driver program to test the above function +# Length of string is 28 +string = ""a_simple_divide_string_quest"" + +# Print 4 equal parts of the string +divideString(string, 4) + +# This code is contributed by Bhavya Jain",constant,linear +"# Python code for the same approach +def divide(Str,n): + + if (len(Str) % n != 0): + print(""Invalid Input: String size"",end="""") + print("" is not divisible by n"") + return + + parts = len(Str) // n + start = 0 + + while (start < len(Str)): + print(Str[start: start + parts]) + start += parts + # if(start < len(Str)) cout << endl; to ignore + # final new line + +# driver code +Str = ""a_simple_divide_string_quest"" +divide(Str, 4) + +# This code is contributed By shinjanpatra",linear,linear +"# Python program to find minimum breaks needed +# to break a string in dictionary words. + +import sys + + +class TrieNode: + + def __init__(self): + + self.endOfTree = False + self.children = [None for i in range(26)] + + + +root = TrieNode() +minWordBreak = sys.maxsize + +# If not present, inserts a key into the trie + # If the key is the prefix of trie node, just + # marks leaf node +def insert(key): + + global root,minWordBreak + + length = len(key) + + pcrawl = root + + for i in range(length): + + index = ord(key[i])- ord('a') + + if(pcrawl.children[index] == None): + pcrawl.children[index] = TrieNode() + pcrawl = pcrawl.children[index] + + # mark last node as leaf + pcrawl.endOfTree = True + +# function break the string into minimum cut +# such the every substring after breaking +# in the dictionary. +def _minWordBreak(key): + + global minWordBreak + + minWordBreak = sys.maxsize + + minWordBreakUtil(root, key, 0, sys.maxsize, 0) + +def minWordBreakUtil(node,key,start,min_Break,level): + + global minWordBreak,root + + pCrawl = node + + # base case, update minimum Break + if (start == len(key)): + min_Break = min(min_Break, level - 1) + if(min_Break= start): + if (X[i] == open): + c += 1 + elif (X[i] == close): + c -= 1 + if (c == 0): + return i + i -= 1 + + return -1 + +# Function to check balanced +# parentheses +def isBalanced(X, n): + + for i in range(n): + + # Handling case of opening + # parentheses + if (X[i] == '('): + j = matchClosing(X, i, n - 1, '(', ')') + elif (X[i] == '{'): + j = matchClosing(X, i, n - 1, '{', '}') + elif (X[i] == '['): + j = matchClosing(X, i, n - 1, '[', ']') + + # Handling case of closing + # parentheses + else : + if (X[i] == ')'): + j = matchingOpening(X, 0, i, '(', ')') + elif (X[i] == '}'): + j = matchingOpening(X, 0, i, '{', '}') + elif (X[i] == ']'): + j = matchingOpening(X, 0, i, '[', ']') + + # If corresponding matching opening + # parentheses doesn't lie in given + # interval return 0 + if (j < 0 or j >= i): + return False + + # else continue + continue + + # If corresponding closing parentheses + # doesn't lie in given interval, return 0 + if (j >= n or j < 0): + return False + + # if found, now check for each opening and + # closing parentheses in this interval + start = i + end = j + + for k in range(start + 1, end) : + if (X[k] == '(') : + x = matchClosing(X, k, end, '(', ')') + if (not(k < x and x < end)): + return False + + elif (X[k] == ')'): + x = matchingOpening(X, start, k, '(', ')') + if (not(start < x and x < k)): + return False + + if (X[k] == '{'): + x = matchClosing(X, k, end, '{', '}') + if (not(k < x and x < end)): + return False + + elif (X[k] == '}'): + x = matchingOpening(X, start, k, '{', '}') + if (not(start < x and x < k)): + return False + + if (X[k] == '['): + x = matchClosing(X, k, end, '[', ']') + if (not(k < x and x < end)): + return False + + elif (X[k] == ']'): + x = matchingOpening(X, start, k, '[', ']') + if (not(start < x and x < k)): + return False + + return True + +# Driver Code +if __name__ == ""__main__"": + + X = ""[()]()"" + n = 6 + if (isBalanced(X, n)): + print(""Yes"") + else: + print(""No"") + + Y = ""[[()]])"" + n = 7 + if (isBalanced(Y, n)): + print(""Yes"") + else: + print(""No"") + +# This code is contributed by ita_c",constant,cubic +"# Python3 program to check for +# balanced brackets. + +# function to check if +# brackets are balanced + + +def areBracketsBalanced(expr): + stack = [] + + # Traversing the Expression + for char in expr: + if char in [""("", ""{"", ""[""]: + + # Push the element in the stack + stack.append(char) + else: + + # IF current character is not opening + # bracket, then it must be closing. + # So stack cannot be empty at this point. + if not stack: + return False + current_char = stack.pop() + if current_char == '(': + if char != "")"": + return False + if current_char == '{': + if char != ""}"": + return False + if current_char == '[': + if char != ""]"": + return False + + # Check Empty Stack + if stack: + return False + return True + + +# Driver Code +if __name__ == ""__main__"": + expr = ""{()}[]"" + + # Function call + if areBracketsBalanced(expr): + print(""Balanced"") + else: + print(""Not Balanced"") + +# This code is contributed by AnkitRai01 and improved +# by Raju Pitta",linear,linear +"# Python3 program to find length of +# the longest balanced subsequence + +def maxLength(s, n): + + dp = [[0 for i in range(n)] + for i in range(n)] + + # Considering all balanced + # substrings of length 2 + for i in range(n - 1): + if (s[i] == '(' and s[i + 1] == ')'): + dp[i][i + 1] = 2 + + # Considering all other substrings + for l in range(2, n): + i = -1 + for j in range(l, n): + i += 1 + if (s[i] == '(' and s[j] == ')'): + dp[i][j] = 2 + dp[i + 1][j - 1] + for k in range(i, j): + dp[i][j] = max(dp[i][j], dp[i][k] + + dp[k + 1][j]) + return dp[0][n - 1] + +# Driver Code +s = ""()(((((()"" +n = len(s) +print(maxLength(s, n)) + +# This code is contributed +# by sahishelangia",quadratic,quadratic +"# Python3 program to find length of +# the longest balanced subsequence + +def maxLength(s, n): + + # As it's subsequence - assuming first + # open brace would map to a first close + # brace which occurs after the open brace + # to make subsequence balanced and second + # open brace would map to second close + # brace and so on. + + # Variable to count all the open brace + # that does not have the corresponding + # closing brace. + invalidOpenBraces = 0; + + # To count all the close brace that does + # not have the corresponding open brace. + invalidCloseBraces = 0; + + # Iterating over the String + for i in range(n): + if( s[i] == '(' ): + + # Number of open braces that + # hasn't been closed yet. + invalidOpenBraces += 1 + else: + if(invalidOpenBraces == 0): + # Number of close braces that + # cannot be mapped to any open + # brace. + invalidCloseBraces += 1 + else: + # Mapping the ith close brace + # to one of the open brace. + invalidOpenBraces -= 1 + + return ( +n - ( +invalidOpenBraces + invalidCloseBraces)) + +# Driver Code +s = ""()(((((()"" +n = len(s) +print(maxLength(s, n))",constant,linear +"# Python3 program to determine whether +# given expression is balanced/ parenthesis +# expression or not. + +# Function to check if two brackets are +# matching or not. +def isMatching(a, b): + + if ((a == '{' and b == '}') or + (a == '[' and b == ']') or + (a == '(' and b == ')') or + a == 'X'): + return 1 + + return 0 + +# Recursive function to check if given +# expression is balanced or not. +def isBalanced(s, ele, ind): + + # Base case. + # If the string is balanced then all the + # opening brackets had been popped and + # stack should be empty after string is + # traversed completely. + if (ind == len(s)): + if len(ele) == 0: + return True + else: + return False + + # Variable to store element at the top + # of the stack. + # char topEle; + + # Variable to store result of + # recursive call. + # int res; + + # Case 1: When current element is an + # opening bracket then push that + # element in the stack. + if (s[ind] == '{' or s[ind] == '(' or + s[ind] == '['): + ele.append(s[ind]) + return isBalanced(s, ele, ind + 1) + + # Case 2: When current element is a closing + # bracket then check for matching bracket + # at the top of the stack. + elif (s[ind] == '}' or s[ind] == ')' or + s[ind] == ']'): + + # If stack is empty then there is no matching + # opening bracket for current closing bracket + # and the expression is not balanced. + if (len(ele) == 0): + return 0 + + topEle = ele[-1] + ele.pop() + + # Check bracket is matching or not. + if (isMatching(topEle, s[ind]) == 0): + return 0 + + return isBalanced(s, ele, ind + 1) + + # Case 3: If current element is 'X' then check + # for both the cases when 'X' could be opening + # or closing bracket. + elif (s[ind] == 'X'): + tmp = ele + tmp.append(s[ind]) + res = isBalanced(s, tmp, ind + 1) + + if (res): + return 1 + if (len(ele) == 0): + return 0 + + ele.pop() + + return isBalanced(s, ele, ind + 1) + +# Driver Code +s = ""{(X}[]"" +ele = [] + +# Check if the length of the given string is even +if(len(s)%2==0): + if (isBalanced(s, ele, 0)): print(""Balanced"") + else: print(""Not Balanced"") + +# If the length is not even, then the string is not balanced +else: print(""Not Balanced"") + +# This code is contributed by divyeshrabadiya07",linear,np +"# Python3 program to evaluate value +# of an expression. +import math as mt + +def evaluateBoolExpr(s): + + n = len(s) + + # Traverse all operands by jumping + # a character after every iteration. + for i in range(0, n - 2, 2): + + # If operator next to current + # operand is AND.''' + if (s[i + 1] == ""A""): + + if (s[i + 2] == ""0"" or s[i] == ""0""): + s[i + 2] = ""0"" + else: + s[i + 2] = ""1"" + + # If operator next to current + # operand is OR. + else if (s[i + 1] == ""B""): + if (s[i + 2] == ""1"" or s[i] == ""1""): + s[i + 2] = ""1"" + else: + s[i + 2] = ""0"" + + # If operator next to current operand + # is XOR (Assuming a valid input) + else: + if (s[i + 2] == s[i]): + s[i + 2] = ""0"" + else: + s[i + 2] = ""1"" + + return ord(s[n - 1]) - ord(""0"") + +# Driver code +s = ""1C1B1B0A0"" +string=[s[i] for i in range(len(s))] +print(evaluateBoolExpr(string)) + +# This code is contributed +# by mohit kumar 29",linear,linear +"# Python code to implement the approach + + +def maxDepth(s): + + count = 0 + st = [] + + for i in range(len(s)): + if (s[i] == '('): + st.append(i) # pushing the bracket in the stack + elif (s[i] == ')'): + if (count < len(st)): + count = len(st) + # keeping track of the parenthesis and storing + # it before removing it when it gets balanced + st.pop() + + return count + +# Driver program + +s = ""( ((X)) (((Y))) )"" +print(maxDepth(s)) + + +# This code is contributed by shinjanpatra",constant,linear +"# A Python program to find the maximum depth of nested +# parenthesis in a given expression + +# function takes a string and returns the +# maximum depth nested parenthesis +def maxDepth(S): + current_max = 0 + max = 0 + n = len(S) + + # Traverse the input string + for i in range(n): + if S[i] == '(': + current_max += 1 + + if current_max > max: + max = current_max + else if S[i] == ')': + if current_max > 0: + current_max -= 1 + else: + return -1 + + # finally check for unbalanced string + if current_max != 0: + return -1 + + return max + +# Driver program +s = ""( ((X)) (((Y))) )"" +print (maxDepth(s)) + +# This code is contributed by BHAVYA JAIN",constant,linear +"# Python3 Program to find all combinations of Non- +# overlapping substrings formed from given +# string + +# find all combinations of non-overlapping +# substrings formed by input string str +# index – index of the next character to +# be processed +# out - output string so far +def findCombinations(string, index, out): + if index == len(string): + print(out) + + for i in range(index, len(string), 1): + + # append substring formed by str[index, + # i] to output string + findCombinations(string, i + 1, out + ""("" + + string[index:i + 1] + "")"") + +# Driver Code +if __name__ == ""__main__"": + + # input string + string = ""abcd"" + findCombinations(string, 0, """") + +# This code is contributed by +# sanjeev2552",quadratic,quadratic +"# Method to find an equal index +def findIndex(str): + l = len(str) + open = [0] * (l + 1) + close = [0] * (l + 1) + index = -1 + + open[0] = 0 + close[l] = 0 + if (str[0]=='('): + open[1] = 1 + if (str[l - 1] == ')'): + close[l - 1] = 1 + + # Store the number of + # opening brackets + # at each index + for i in range(1, l): + if (str[i] == '('): + open[i + 1] = open[i] + 1 + else: + open[i + 1] = open[i] + + # Store the number + # of closing brackets + # at each index + for i in range(l - 2, -1, -1): + if ( str[i] == ')'): + close[i] = close[i + 1] + 1 + else: + close[i] = close[i + 1] + + # check if there is no + # opening or closing brackets + if (open[l] == 0): + return len + if (close[0] == 0): + return 0 + + # check if there is any + # index at which both + # brackets are equal + for i in range(l + 1): + if (open[i] == close[i]): + index = i + + return index + +# Driver Code +str = ""(()))(()()())))"" +print(findIndex(str)) + +# This code is contributed +# by ChitraNayal",linear,linear +"# Method to find an equal index +def findIndex(str): + cnt_close = 0 + l = len(str) + for i in range(1, l): + if(str[i] == ')'): + cnt_close = cnt_close + 1 + + for i in range(1, l): + if(cnt_close == i): + return i + # If no opening brackets + return l + + +# Driver Code +str = ""(()))(()()())))"" +print(findIndex(str)) + +# This code is contributed by Aditya Kumar (adityakumar129)",constant,linear +"# Python3 program to check if two expressions +# evaluate to same. +MAX_CHAR = 26; + +# Return local sign of the operand. For example, +# in the expr a-b-(c), local signs of the operands +# are +a, -b, +c +def adjSign(s, i): + if (i == 0): + return True; + if (s[i - 1] == '-'): + return False; + return True; + +# Evaluate expressions into the count vector of +# the 26 alphabets.If add is True, then add count +# to the count vector of the alphabets, else remove +# count from the count vector. +def eval(s, v, add): + + # stack stores the global sign + # for operands. + stk = [] + stk.append(True); + + # + means True + # global sign is positive initially + i = 0; + + while (i < len(s)): + + if (s[i] == '+' or s[i] == '-'): + i += 1 + continue; + + if (s[i] == '('): + + # global sign for the bracket is + # pushed to the stack + if (adjSign(s, i)): + stk.append(stk[-1]); + else: + stk.append(not stk[-1]); + + # global sign is popped out which + # was pushed in for the last bracket + elif (s[i] == ')'): + stk.pop(); + else: + + # global sign is positive (we use different + # values in two calls of functions so that + # we finally check if all vector elements + # are 0. + if (stk[-1]): + v[ord(s[i]) - ord('a')] += (1 if add else -1) if adjSign(s, i) else (-1 if add else 1) + + # global sign is negative here + else: + v[ord(s[i]) - ord('a')] += (-1 if add else 1) if adjSign(s, i) else (1 if add else -1) + + i += 1 + +# Returns True if expr1 and expr2 represent +# same expressions +def areSame(expr1, expr2): + + # Create a vector for all operands and + # initialize the vector as 0. + v = [0 for i in range(MAX_CHAR)]; + + # Put signs of all operands in expr1 + eval(expr1, v, True); + + # Subtract signs of operands in expr2 + eval(expr2, v, False); + + # If expressions are same, vector must + # be 0. + for i in range(MAX_CHAR): + if (v[i] != 0): + return False; + return True; + +# Driver Code +if __name__=='__main__': + expr1 = ""-(a+b+c)"" + expr2 = ""-a-b-c""; + if (areSame(expr1, expr2)): + print(""Yes""); + else: + print(""No""); + + # This code is contributed by rutvik_56.",linear,linear +"# Python3 Program to check whether valid +# expression is redundant or not + +# Function to check redundant brackets +# in a balanced expression +def checkRedundancy(Str): + + # create a stack of characters + st = [] + + # Iterate through the given expression + for ch in Str: + + # if current character is close + # parenthesis ')' + if (ch == ')'): + top = st[-1] + st.pop() + + # If immediate pop have open parenthesis + # '(' duplicate brackets found + flag = True + + while (top != '('): + + # Check for operators in expression + if (top == '+' or top == '-' or + top == '*' or top == '/'): + flag = False + + # Fetch top element of stack + top = st[-1] + st.pop() + + # If operators not found + if (flag == True): + return True + + else: + st.append(ch) # append open parenthesis '(', + # operators and operands to stack + return False + +# Function to check redundant brackets +def findRedundant(Str): + ans = checkRedundancy(Str) + if (ans == True): + print(""Yes"") + else: + print(""No"") + +# Driver code +if __name__ == '__main__': + Str = ""((a+b))"" + findRedundant(Str) + + +# This code is contributed by PranchalK",linear,linear +"# Python3 program to find sum of given +# array of string type in integer form + +# Function to find the sum of given array +def calculateSum(arr, n): + + # if string is empty + if (n == 0): + return 0 + + s = arr[0] + + # stoi function to convert + # string into integer + value = int(s) + sum = value + + for i in range(2 , n, 2): + + s = arr[i] + + # stoi function to convert + # string into integer + value = int(s) + + # Find operator + operation = arr[i - 1][0] + + # If operator is equal to '+', + # add value in sum variable + # else subtract + if (operation == '+'): + sum += value + else: + sum -= value + + return sum + +# Driver Function +arr = [""3"", ""+"", ""4"", ""-"",""7"", ""+"", ""13""] +n = len(arr) +print(calculateSum(arr, n)) + +# This code is contributed by Smitha",constant,linear +"# Python3 implementation to print the bracket number + +# function to print the bracket number +def printBracketNumber(exp, n): + + # used to print the bracket number + # for the left bracket + left_bnum = 1 + + # used to obtain the bracket number + # for the right bracket + right_bnum = list() + + # traverse the given expression 'exp' + for i in range(n): + + # if current character is a left bracket + if exp[i] == '(': + + # print 'left_bnum', + print(left_bnum, end = "" "") + + # push 'left_bnum' on to the stack 'right_bnum' + right_bnum.append(left_bnum) + + # increment 'left_bnum' by 1 + left_bnum += 1 + + # else if current character is a right bracket + elif exp[i] == ')': + + # print the top element of stack 'right_bnum' + # it will be the right bracket number + print(right_bnum[-1], end = "" "") + + # pop the top element from the stack + right_bnum.pop() + +# Driver Code +if __name__ == ""__main__"": + exp = ""(a+(b*c))+(d/e)"" + n = len(exp) + + printBracketNumber(exp, n) + +# This code is contributed by +# sanjeev2552",linear,linear +"# Python program to find index of closing +# bracket for a given opening bracket. +from collections import deque + +def getIndex(s, i): + + # If input is invalid. + if s[i] != '[': + return -1 + + # Create a deque to use it as a stack. + d = deque() + + # Traverse through all elements + # starting from i. + for k in range(i, len(s)): + + # Pop a starting bracket + # for every closing bracket + if s[k] == ']': + d.popleft() + + # Push all starting brackets + elif s[k] == '[': + d.append(s[i]) + + # If deque becomes empty + if not d: + return k + + return -1 + +# Driver code to test above method. +def test(s, i): + matching_index = getIndex(s, i) + print(s + "", "" + str(i) + "": "" + str(matching_index)) + +def main(): + test(""[ABC[23]][89]"", 0) # should be 8 + test(""[ABC[23]][89]"", 4) # should be 7 + test(""[ABC[23]][89]"", 9) # should be 12 + test(""[ABC[23]][89]"", 1) # No matching bracket + +if __name__ == ""__main__"": + main()",linear,linear +"# Python3 program to construct string from binary tree + +# A binary tree node has data, pointer to left +# child and a pointer to right child +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +# Function to construct string from binary tree +def treeToString(root: Node, string: list): + + # base case + if root is None: + return + + # push the root data as character + string.append(str(root.data)) + + # if leaf node, then return + if not root.left and not root.right: + return + + # for left subtree + string.append('(') + treeToString(root.left, string) + string.append(')') + + # only if right child is present to + # avoid extra parenthesis + if root.right: + string.append('(') + treeToString(root.right, string) + string.append(')') + +# Driver Code +if __name__ == ""__main__"": + + # Let us construct below tree + # 1 + # / \ + # 2 3 + # / \ \ + # 4 5 6 + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.right = Node(6) + string = [] + treeToString(root, string) + print(''.join(string)) + +# This code is contributed by +# sanjeev2552",linear,linear +"# Python3 program to conStruct a +# binary tree from the given String + +# Helper class that allocates a new node + + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +# This function is here just to test + + +def preOrder(node): + if (node == None): + return + print(node.data, end=' ') + preOrder(node.left) + preOrder(node.right) + +# function to return the index of +# close parenthesis + + +def findIndex(Str, si, ei): + if (si > ei): + return -1 + + # Inbuilt stack + s = [] + for i in range(si, ei + 1): + + # if open parenthesis, push it + if (Str[i] == '('): + s.append(Str[i]) + + # if close parenthesis + elif (Str[i] == ')'): + if (s[-1] == '('): + s.pop(-1) + + # if stack is empty, this is + # the required index + if len(s) == 0: + return i + # if not found return -1 + return -1 + +# function to conStruct tree from String + + +def treeFromString(Str, si, ei): + + # Base case + if (si > ei): + return None + + # new root + root = newNode(ord(Str[si]) - ord('0')) + index = -1 + + # if next char is '(' find the + # index of its complement ')' + if (si + 1 <= ei and Str[si + 1] == '('): + index = findIndex(Str, si + 1, ei) + + # if index found + if (index != -1): + + # call for left subtree + root.left = treeFromString(Str, si + 2, + index - 1) + + # call for right subtree + root.right = treeFromString(Str, index + 2, + ei - 1) + return root + + +# Driver Code +if __name__ == '__main__': + Str = ""4(2(3)(1))(6(5))"" + root = treeFromString(Str, 0, len(Str) - 1) + preOrder(root) + +# This code is contributed by pranchalK",linear,quadratic +"class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + + +def preOrder(node): + if (node == None): + return + print(node.data, end="" "") + preOrder(node.left) + preOrder(node.right) + + +def treeFromStringHelper(si, ei, arr, root): + + if si[0] >= ei: + return None + + if arr[si[0]] == ""("": + + if arr[si[0]+1] != "")"": + if root.left is None: + if si[0] >= ei: + return + new_root = newNode(arr[si[0]+1]) + root.left = new_root + si[0] += 2 + treeFromStringHelper(si, ei, arr, new_root) + + else: + si[0] += 2 + + if root.right is None: + if si[0] >= ei: + return + + if arr[si[0]] != ""("": + si[0] += 1 + return + + new_root = newNode(arr[si[0]+1]) + root.right = new_root + si[0] += 2 + treeFromStringHelper(si, ei, arr, new_root) + else: + return + + if arr[si[0]] == "")"": + if si[0] >= ei: + return + si[0] += 1 + return + + return + + +def treeFromString(string): + + root = newNode(string[0]) + + if len(string) > 1: + si = [1] + ei = len(string)-1 + + treeFromStringHelper(si, ei, string, root) + + return root + +# Driver Code +if __name__ == '__main__': + Str = ""4(2(3)(1))(6(5))"" + root = treeFromString(Str) + preOrder(root) + +# This code is contributed by dheerajalimchandani",linear,quadratic +"# Simple Python3 program to convert +# all substrings from decimal to given base. +import math + +def substringConversions(s, k, b): + + l = len(s); + for i in range(l): + + if((i + k) < l + 1): + + # Saving substring in sub + sub = s[i : i + k]; + + # Evaluating decimal for current + # substring and printing it. + sum, counter = 0, 0; + for i in range(len(sub) - 1, -1, -1): + + sum = sum + ((ord(sub[i]) - ord('0')) * + pow(b, counter)); + counter += 1; + + print(sum , end = "" ""); + +# Driver code +s = ""12212""; +b, k = 3, 3; +substringConversions(s, b, k); + +# This code is contributed +# by Princi Singh",linear,quadratic +"# Simple Python3 program to convert all +# substrings from decimal to given base. +import math as mt + +def substringConversions(str1, k, b): + + for i in range(0, len(str1) - k + 1): + + # Saving substring in sub + sub = str1[i:k + i] + + # Evaluating decimal for current + # substring and printing it. + Sum = 0 + counter = 0 + for i in range(len(sub) - 1, -1, -1): + Sum = (Sum + ((ord(sub[i]) - ord('0')) * + pow(b, counter))) + counter += 1 + + print(Sum, end = "" "") + +# Driver code +str1 = ""12212"" +b = 3 +k = 3 +substringConversions(str1, b, k) + +# This code is contributed by +# Mohit Kumar 29",linear,linear +"# Python3 program to demonstrate above steps +# of binary fractional to decimal conversion + +# Function to convert binary fractional +# to decimal +def binaryToDecimal(binary, length) : + + # Fetch the radix point + point = binary.find('.') + + # Update point if not found + if (point == -1) : + point = length + + intDecimal = 0 + fracDecimal = 0 + twos = 1 + + # Convert integral part of binary + # to decimal equivalent + for i in range(point-1, -1, -1) : + + # Subtract '0' to convert + # character into integer + intDecimal += ((ord(binary[i]) - + ord('0')) * twos) + twos *= 2 + + # Convert fractional part of binary + # to decimal equivalent + twos = 2 + + for i in range(point + 1, length): + + fracDecimal += ((ord(binary[i]) - + ord('0')) / twos); + twos *= 2.0 + + # Add both integral and fractional part + ans = intDecimal + fracDecimal + + return ans + +# Driver code : +if __name__ == ""__main__"" : + n = ""110.101"" + print(binaryToDecimal(n, len(n))) + + n = ""101.1101"" + print(binaryToDecimal(n, len(n))) + +# This code is contributed +# by aishwarya.27",linear,linear +"# Python3 program to convert fractional +# decimal to binary number + +# Function to convert decimal to binary +# upto k-precision after decimal point +def decimalToBinary(num, k_prec) : + + binary = """" + + # Fetch the integral part of + # decimal number + Integral = int(num) + + # Fetch the fractional part + # decimal number + fractional = num - Integral + + # Conversion of integral part to + # binary equivalent + while (Integral) : + + rem = Integral % 2 + + # Append 0 in binary + binary += str(rem); + + Integral //= 2 + + # Reverse string to get original + # binary equivalent + binary = binary[ : : -1] + + # Append point before conversion + # of fractional part + binary += '.' + + # Conversion of fractional part + # to binary equivalent + while (k_prec) : + + # Find next bit in fraction + fractional *= 2 + fract_bit = int(fractional) + + if (fract_bit == 1) : + + fractional -= fract_bit + binary += '1' + + else : + binary += '0' + + k_prec -= 1 + + return binary + +# Driver code +if __name__ == ""__main__"" : + + n = 4.47 + k = 3 + print(decimalToBinary(n, k)) + + n = 6.986 + k = 5 + print(decimalToBinary(n, k)) + +# This code is contributed by Ryuga",linear,linear +"# Python3 implementation to convert +# a sentence into its equivalent +# mobile numeric keypad sequence + +# Function which computes the +# sequence + + +def printSequence(arr, input): + + # length of input string + n = len(input) + output = """" + + for i in range(n): + + # checking for space + if(input[i] == ' '): + output = output + ""0"" + else: + # calculating index for each + # character + position = ord(input[i]) - ord('A') + output = output + arr[position] + # output sequence + return output + + +# Driver code +str = [""2"", ""22"", ""222"", + ""3"", ""33"", ""333"", + ""4"", ""44"", ""444"", + ""5"", ""55"", ""555"", + ""6"", ""66"", ""666"", + ""7"", ""77"", ""777"", ""7777"", + ""8"", ""88"", ""888"", + ""9"", ""99"", ""999"", ""9999""] + +input = ""GEEKSFORGEEKS"" +print(printSequence(str, input)) + +# This code is contributed by upendra bartwal",linear,linear +"# Python Program for above implementation + +# Function to check is it possible to convert +# first string into another string or not. +def isItPossible(str1, str2, m, n): + + # To Check Length of Both String is Equal or Not + if (m != n): + return False + + # To Check Frequency of A's and B's are + # equal in both strings or not. + if str1.count('A') != str2.count('A') \ + or str1.count('B') != str2.count('B'): + return False + + # Start traversing + for i in range(m): + if (str1[i] != '#'): + for j in range(n): + # To Check no two elements cross each other. + if ((str2[j] != str1[i]) and str2[j] != '#'): + return False + + if (str2[j] == str1[i]): + str2[j] = '#' + + # To Check Is it Possible to Move + # towards Left or not. + if (str1[i] == 'A' and i < j): + return False + + # To Check Is it Possible to Move + # towards Right or not. + if (str1[i] == 'B' and i > j): + return False + + break + + return True + +# Drivers code + +str1 = ""A#B#"" +str2 = ""A##B"" + +m = len(str1) +n = len(str2) + +str1 = list(str1) +str2 = list(str2) + +if(isItPossible(str1, str2, m, n)): + print(""Yes"") +else: + print(""No"") + +# This code is contributed by ankush_953",linear,quadratic +"# Python 3 Program to convert str1 to +# str2 in exactly k operations + +# Returns true if it is possible to convert +# str1 to str2 using k operations. +def isConvertible(str1, str2, k): + + # Case A (i) + if ((len(str1) + len(str2)) < k): + return True + + # finding common length of both string + commonLength = 0 + for i in range(0, min(len(str1), + len(str2)), 1): + if (str1[i] == str2[i]): + commonLength += 1 + else: + break + + # Case A (ii)- + if ((k - len(str1) - len(str2) + 2 * + commonLength) % 2 == 0): + return True + + # Case B- + return False + +# Driver Code +if __name__ == '__main__': + str1 = ""geek"" + str2 = ""geek"" + k = 7 + if (isConvertible(str1, str2, k)): + print(""Yes"") + else: + print(""No"") + + str1 = ""geeks"" + str2 = ""geek"" + k = 5 + if (isConvertible(str1, str2, k)): + print(""Yes"") + else: + print(""No"") + +# This code is contributed by +# Sanjit_Prasad",constant,linear +"# Python3 program to convert +# decimal number to roman numerals + +ls=[1000,900,500,400,100,90,50,40,10,9,5,4,1] +dict={1:""I"",4:""IV"",5:""V"",9:""IX"",10:""X"",40:""XL"",50:""L"",90:""XC"",100:""C"",400:""CD"",500:""D"",900:""CM"",1000:""M""} +ls2=[] + +# Function to convert decimal to Roman Numerals +def func(no,res): + for i in range(0,len(ls)): + if no in ls: + res=dict[no] + rem=0 + break + if ls[i]= div: + div *= 10 + + div //= 10 + + res = """" + + while A: + + # main significant digit extracted + # into lastNum + lastNum = (A // div) + + if lastNum <= 3: + res += (romansDict[div] * lastNum) + elif lastNum == 4: + res += (romansDict[div] + + romansDict[div * 5]) + elif 5 <= lastNum <= 8: + res += (romansDict[div * 5] + + (romansDict[div] * (lastNum - 5))) + elif lastNum == 9: + res += (romansDict[div] + + romansDict[div * 10]) + + A = math.floor(A % div) + div //= 10 + + return res + +# Driver code +print(""Roman Numeral of Integer is:"" + + str(integerToRoman(3549)))",constant,linear +"# Python program to convert Roman Numerals +# to Numbers + +# This function returns value of each Roman symbol + + +def value(r): + if (r == 'I'): + return 1 + if (r == 'V'): + return 5 + if (r == 'X'): + return 10 + if (r == 'L'): + return 50 + if (r == 'C'): + return 100 + if (r == 'D'): + return 500 + if (r == 'M'): + return 1000 + return -1 + + +def romanToDecimal(str): + res = 0 + i = 0 + + while (i < len(str)): + + # Getting value of symbol s[i] + s1 = value(str[i]) + + if (i + 1 < len(str)): + + # Getting value of symbol s[i + 1] + s2 = value(str[i + 1]) + + # Comparing both values + if (s1 >= s2): + + # Value of current symbol is greater + # or equal to the next symbol + res = res + s1 + i = i + 1 + else: + + # Value of current symbol is greater + # or equal to the next symbol + res = res + s2 - s1 + i = i + 2 + else: + res = res + s1 + i = i + 1 + + return res + + +# Driver code +print(""Integer form of Roman Numeral is""), +print(romanToDecimal(""MCMIV""))",constant,linear +"# Program to convert Roman +# Numerals to Numbers +roman = {} +roman['I'] = 1 +roman['V'] = 5 +roman['X'] = 10 +roman['L'] = 50 +roman['C'] = 100 +roman['D'] = 500 +roman['M'] = 1000 + +# This function returns value +# of a Roman symbol +def romanToInt(s): + sum = 0 + n = len(s) + + i = 0 + while i < n : + + # If present value is less than next value, + # subtract present from next value and add the + # resultant to the sum variable. + # print(roman[s[i]],roman[s[i+1]]) + if (i != n - 1 and roman[s[i]] < roman[s[i + 1]]): + sum += roman[s[i + 1]] - roman[s[i]] + i += 2 + continue + else: + sum += roman[s[i]] + i += 1 + return sum + +# Driver Code + +# Considering inputs given are valid +input = ""MCMIV"" + +print(f""Integer form of Roman Numeral is {romanToInt(input)}"") + +# This code is contributed by shinjanpatra",constant,constant +"def romanToInt(s): + translations = { + ""I"": 1, + ""V"": 5, + ""X"": 10, + ""L"": 50, + ""C"": 100, + ""D"": 500, + ""M"": 1000 + } + number = 0 + s = s.replace(""IV"", ""IIII"").replace(""IX"", ""VIIII"") + s = s.replace(""XL"", ""XXXX"").replace(""XC"", ""LXXXX"") + s = s.replace(""CD"", ""CCCC"").replace(""CM"", ""DCCCC"") + for char in s: + number += translations[char] + print(number) + +romanToInt('MCMIV')",constant,constant +"# Python3 program to check if a string can +# be converted to another string by +# performing operations + + +# function to check if a string can be +# converted to another string by +# performing following operations +def check(s1,s2): + + # calculates length + n = len(s1) + m = len(s2) + dp=([[False for i in range(m+1)] + for i in range(n+1)]) + + # mark 1st position as true + dp[0][0] = True + + # traverse for all DPi, j + for i in range(len(s1)): + for j in range(len(s2)+1): + + # if possible for to convert i + # characters of s1 to j characters + # of s2 + if (dp[i][j]): + + # if upper_case(s1[i])==s2[j] + # is same + if ((j < len(s2) and + (s1[i].upper()== s2[j]))): + dp[i + 1][j + 1] = True + + # if not upper then deletion is + # possible + if (s1[i].isupper()==False): + dp[i + 1][j] = True + return (dp[n][m]) + +# driver code +if __name__=='__main__': + + s1 = ""daBcd"" + s2 = ""ABC"" + if (check(s1, s2)): + print(""YES"") + else: + print(""NO"") + +# this code is contributed by +# sahilshelangia",quadratic,quadratic +"# Python code to +# transform string + +# def to change +# character's case +def change_case(s) : + + a = list(s) + l = len(s) + + for i in range(0, l) : + + # If character is + # lowercase change + # to uppercase + if(a[i] >= 'a' and + a[i] <= 'z') : + a[i] = s[i].upper() + + # If character is uppercase + # change to lowercase + elif(a[i] >= 'A' and + a[i] <= 'Z') : + a[i] = s[i].lower() + + return a + +# def to delete vowels +def delete_vowels(s) : + + temp = """" + a = list(s) + l = len(s) + for i in range(0, l) : + + # If character + # is consonant + if(a[i] != 'a' and a[i] != 'e' and + a[i] != 'i' and a[i] != 'o' and + a[i] != 'u' and a[i] != 'A' and + a[i] != 'E' and a[i] != 'O' and + a[i] != 'U' and a[i] != 'I') : + temp = temp + a[i] + + return temp + +# def to insert ""#"" +def insert_hash(s) : + + temp = """" + a = list(s) + l = len(s) + + for i in range(0, l) : + + # If character is + # not special + if((a[i] >= 'a' and + a[i] <= 'z') or + (a[i] >= 'A' and + a[i] <= 'Z')) : + temp = temp + '#' + a[i] + else : + temp = temp + a[i] + + return temp + +# def to +# transform string +def transformSting(a) : + + b = delete_vowels(a) + c = change_case(b) + d = insert_hash(c) + + print (d) + +# Driver Code +a = ""SunshinE!!"" + +# Calling def +transformSting(a) + +# This code is contributed by +# Manish Shaw(manishshaw1)",linear,linear +"# Python implementation of above approach + +# A utility function to reverse string str[low..high] +def Reverse(string: list, low: int, high: int): + while low < high: + string[low], string[high] = string[high], string[low] + low += 1 + high -= 1 + +# Cycle leader algorithm to move all even +# positioned elements at the end. +def cycleLeader(string: list, shift: int, len: int): + i = 1 + while i < len: + j = i + item = string[j + shift] + + while True: + + # odd index + if j & 1: + j = len // 2 + j // 2 + + # even index + else: + j //= 2 + + # keep the back-up of element at new position + string[j + shift], item = item, string[j + shift] + + if j == i: + break + i *= 3 + +# The main function to transform a string. This function +# mainly uses cycleLeader() to transform +def moveNumberToSecondHalf(string: list): + k, lenFirst = 0, 0 + lenRemaining = len(string) + shift = 0 + + while lenRemaining: + k = 0 + + # Step 1: Find the largest prefix + # subarray of the form 3^k + 1 + while pow(3, k) + 1 <= lenRemaining: + k += 1 + lenFirst = pow(3, k - 1) + 1 + lenRemaining -= lenFirst + + # Step 2: Apply cycle leader algorithm + # for the largest subarrau + cycleLeader(string, shift, lenFirst) + + # Step 4.1: Reverse the second half of first subarray + Reverse(string, shift // 2, shift - 1) + + # Step 4.2: Reverse the first half of second sub-string + Reverse(string, shift, shift + lenFirst // 2 - 1) + + # Step 4.3 Reverse the second half of first sub-string + # and first half of second sub-string together + Reverse(string, shift // 2, shift + lenFirst // 2 - 1) + + # Increase the length of first subarray + shift += lenFirst + +# Driver Code +if __name__ == ""__main__"": + + string = ""a1b2c3d4e5f6g7"" + string = list(string) + moveNumberToSecondHalf(string) + print(''.join(string)) + +# This code is contributed by +# sanjeev2552",constant,quadratic +"# Python3 program to count the distinct +# transformation of one string to other. + +def countTransformation(a, b): + n = len(a) + m = len(b) + + # If b = """" i.e., an empty string. There + # is only one way to transform (remove all + # characters) + if m == 0: + return 1 + + dp = [[0] * (n) for _ in range(m)] + + # Fill dp[][] in bottom up manner + # Traverse all character of b[] + for i in range(m): + + # Traverse all characters of a[] for b[i] + for j in range(i, n): + + # Filling the first row of the dp + # matrix. + if i == 0: + if j == 0: + if a[j] == b[i]: + dp[i][j] = 1 + else: + dp[i][j] = 0 + else if a[j] == b[i]: + dp[i][j] = dp[i][j - 1] + 1 + else: + dp[i][j] = dp[i][j - 1] + + # Filling other rows + else: + if a[j] == b[i]: + dp[i][j] = (dp[i][j - 1] + + dp[i - 1][j - 1]) + else: + dp[i][j] = dp[i][j - 1] + return dp[m - 1][n - 1] + +# Driver Code +if __name__ == ""__main__"": + a = ""abcccdf"" + b = ""abccdf"" + print(countTransformation(a, b)) + +# This code is contributed by vibhu4agarwal",quadratic,quadratic +"# Class to define a node +# structure of the tree +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None + +# Function to convert ternary +# expression to a Binary tree +# It returns the root node +# of the tree +def convert_expression(expression, i): + if i >= len(expression): + return None + + # Create a new node object + # for the expression at + # ith index + root = Node(expression[i]) + + i += 1 + + # if current character of + # ternary expression is '?' + # then we add next character + # as a left child of + # current node + if (i < len(expression) and + expression[i] is ""?""): + root.left = convert_expression(expression, i + 1) + + # else we have to add it + # as a right child of + # current node expression[0] == ':' + elif i < len(expression): + root.right = convert_expression(expression, i + 1) + return root + +# Function to print the tree +# in a pre-order traversal pattern +def print_tree(root): + if not root: + return + print(root.data, end=' ') + print_tree(root.left) + print_tree(root.right) + +# Driver Code +if __name__ == ""__main__"": + string_expression = ""a?b?c:d:e"" + root_node = convert_expression(string_expression, 0) + print_tree(root_node) + +# This code is contributed +# by Kanav Malhotra",linear,linear +"# Python Program to convert prefix to Infix +def prefixToInfix(prefix): + stack = [] + + # read prefix in reverse order + i = len(prefix) - 1 + while i >= 0: + if not isOperator(prefix[i]): + + # symbol is operand + stack.append(prefix[i]) + i -= 1 + else: + + # symbol is operator + str = ""("" + stack.pop() + prefix[i] + stack.pop() + "")"" + stack.append(str) + i -= 1 + + return stack.pop() + +def isOperator(c): + if c == ""*"" or c == ""+"" or c == ""-"" or c == ""/"" or c == ""^"" or c == ""("" or c == "")"": + return True + else: + return False + +# Driver code +if __name__==""__main__"": + str = ""*-A/BC-/AKL"" + print(prefixToInfix(str)) + +# This code is contributed by avishekarora",linear,linear +"# Write Python3 code here +# -*- coding: utf-8 -*- + +# Example Input +s = ""*-A/BC-/AKL"" + +# Stack for storing operands +stack = [] + +operators = set(['+', '-', '*', '/', '^']) + +# Reversing the order +s = s[::-1] + +# iterating through individual tokens +for i in s: + + # if token is operator + if i in operators: + + # pop 2 elements from stack + a = stack.pop() + b = stack.pop() + + # concatenate them as operand1 + + # operand2 + operator + temp = a+b+i + stack.append(temp) + + # else if operand + else: + stack.append(i) + +# printing final output +print(*stack)",linear,linear +"# Python3 Program to convert postfix to prefix + +# function to check if +# character is operator or not + + +def isOperator(x): + + if x == ""+"": + return True + + if x == ""-"": + return True + + if x == ""/"": + return True + + if x == ""*"": + return True + + return False + +# Convert postfix to Prefix expression + + +def postToPre(post_exp): + + s = [] + + # length of expression + length = len(post_exp) + + # reading from right to left + for i in range(length): + + # check if symbol is operator + if (isOperator(post_exp[i])): + + # pop two operands from stack + op1 = s[-1] + s.pop() + op2 = s[-1] + s.pop() + + # concat the operands and operator + temp = post_exp[i] + op2 + op1 + + # Push string temp back to stack + s.append(temp) + + # if symbol is an operand + else: + + # push the operand to the stack + s.append(post_exp[i]) + + + ans = """" + for i in s: + ans += i + return ans + + +# Driver Code +if __name__ == ""__main__"": + + post_exp = ""AB+CD-"" + + # Function call + print(""Prefix : "", postToPre(post_exp)) + +# This code is contributed by AnkitRai01",linear,linear +"# Python3 program to find infix for +# a given postfix. +def isOperand(x): + return ((x >= 'a' and x <= 'z') or + (x >= 'A' and x <= 'Z')) + +# Get Infix for a given postfix +# expression +def getInfix(exp) : + + s = [] + + for i in exp: + + # Push operands + if (isOperand(i)) : + s.insert(0, i) + + # We assume that input is a + # valid postfix and expect + # an operator. + else: + + op1 = s[0] + s.pop(0) + op2 = s[0] + s.pop(0) + s.insert(0, ""("" + op2 + i + + op1 + "")"") + + # There must be a single element in + # stack now which is the required + # infix. + return s[0] + +# Driver Code +if __name__ == '__main__': + + exp = ""ab*c+"" + print(getInfix(exp.strip())) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10)",linear,linear +"# Python 3 program for space optimized +# solution of Word Wrap problem. +import sys + +# Function to find space optimized +# solution of Word Wrap problem. +def solveWordWrap(arr, n, k): + + dp = [0] * n + + # Array in which ans[i] store index + # of last word in line starting with + # word arr[i]. + ans = [0] * n + + # If only one word is present then + # only one line is required. Cost + # of last line is zero. Hence cost + # of this line is zero. Ending point + # is also n-1 as single word is + # present. + dp[n - 1] = 0 + ans[n - 1] = n - 1 + + # Make each word first word of line + # by iterating over each index in arr. + for i in range(n - 2, -1, -1): + currlen = -1 + dp[i] = sys.maxsize + + # Keep on adding words in current + # line by iterating from starting + # word upto last word in arr. + for j in range(i, n): + + # Update number of characters + # in current line. arr[j] is + # number of characters in + # current word and 1 + # represents space character + # between two words. + currlen += (arr[j] + 1) + + # If limit of characters + # is violated then no more + # words can be added to + # current line. + if (currlen > k): + break + + # If current word that is + # added to line is last + # word of arr then current + # line is last line. Cost of + # last line is 0. Else cost + # is square of extra spaces + # plus cost of putting line + # breaks in rest of words + # from j+1 to n-1. + if (j == n - 1): + cost = 0 + else: + cost = ((k - currlen) * + (k - currlen) + dp[j + 1]) + + # Check if this arrangement gives + # minimum cost for line starting + # with word arr[i]. + if (cost < dp[i]): + dp[i] = cost + ans[i] = j + + # Print starting index and ending index + # of words present in each line. + i = 0 + while (i < n): + print(i + 1 , ans[i] + 1, end = "" "") + i = ans[i] + 1 + +# Driver Code +if __name__ == ""__main__"": + + arr = [3, 2, 2, 5 ] + n = len(arr) + M = 6 + solveWordWrap(arr, n, M) + +# This code is contributed by ita_c",linear,quadratic +"# Python 3 program to print shortest possible +# path to type all characters of given string +# using a remote + +# Function to print shortest possible path +# to type all characters of given string +# using a remote +def printPath(str): + i = 0 + + # start from character 'A' present + # at position (0, 0) + curX = 0 + curY = 0 + while (i < len(str)): + + # find coordinates of next character + nextX = int((ord(str[i]) - ord('A')) / 5) + nextY = (ord(str[i]) - ord('B') + 1) % 5 + + # Move Up if destination is above + while (curX > nextX): + print(""Move Up"") + curX -= 1 + + # Move Left if destination is to the left + while (curY > nextY): + print(""Move Left"") + curY -= 1 + + # Move down if destination is below + while (curX < nextX): + print(""Move Down"") + curX += 1 + + # Move Right if destination is to the right + while (curY < nextY): + print(""Move Right"") + curY += 1 + + # At this point, destination is reached + print(""Press OK"") + i += 1 + +# Driver code +if __name__ == '__main__': + str = ""COZY"" + + printPath(str) + +# This code is contributed by +# Sanjit_Prasad",constant,quadratic +"# Python program to check whether second string +# can be formed from first string +def canMakeStr2(s1, s2): + + # Create a count array and count + # frequencies characters in s1 + count = {s1[i] : 0 for i in range(len(s1))} + + for i in range(len(s1)): + count[s1[i]] += 1 + + # Now traverse through str2 to check + # if every character has enough counts + for i in range(len(s2)): + if (count.get(s2[i]) == None or count[s2[i]] == 0): + return False + count[s2[i]] -= 1 + return True + +# Driver Code +s1 = ""geekforgeeks"" +s2 = ""for"" + +if canMakeStr2(s1, s2): + print(""Yes"") +else: + print(""No"")",constant,linear +"# python code to find the reverse +# alphabetical order from a given +# position + +# Function which take the given string and the +# position from which the reversing shall be +# done and returns the modified string +def compute(st, n): + + # Creating a string having reversed + # alphabetical order + reverseAlphabet = ""zyxwvutsrqponmlkjihgfedcba"" + l = len(st) + + # The string up to the point specified in the + # question, the string remains unchanged and + # from the point up to the length of the + # string, we reverse the alphabetical order + answer = """" + for i in range(0, n): + answer = answer + st[i]; + + for i in range(n, l): + answer = (answer + + reverseAlphabet[ord(st[i]) - ord('a')]); + + return answer; + +# Driver function +st = ""pneumonia"" +n = 4 +answer = compute(st, n - 1) +print(answer) + +# This code is contributed by Sam007.",constant,linear +"# A Python program to find last +# index of character x in given +# string. + +# Returns last index of x if it +# is present. Else returns -1. +def findLastIndex(str, x): + index = -1 + for i in range(0, len(str)): + if str[i] == x: + index = i + return index + +# Driver program + +# String in which char is to be found +str = ""geeksforgeeks"" + +# char whose index is to be found +x = 'e' + +index = findLastIndex(str, x) + +if index == -1: + print(""Character not found"") +else: + print('Last index is', index) + +# This code is contributed by shrikant13.",constant,linear +"# Simple Python3 program to find last +# index of character x in given string. + +# Returns last index of x if it is +# present. Else returns -1. +def findLastIndex(str, x): + + # Traverse from right + for i in range(len(str) - 1, -1,-1): + if (str[i] == x): + return i + + return -1 + +# Driver code +str = ""geeksforgeeks"" +x = 'e' +index = findLastIndex(str, x) + +if (index == -1): + print(""Character not found"") +else: + print(""Last index is "" ,index) + +# This code is contributed by Smitha",constant,linear +"# python program to find position +# of a number in a series of +# numbers with 4 and 7 as the +# only digits. +def findpos(n): + i = 0 + j = len(n) + pos = 0 + while (i maxValueInMap): + maxValueInMap = val + winner = key + + # If there is a tie, pick lexicographically + # smaller. + else if (val == maxValueInMap and + winner > key): + winner = key + + print(winner) + + +# Driver code +if __name__ == ""__main__"": + + votes = [""john"", ""johnny"", ""jackie"", + ""johnny"", ""john"", ""jackie"", + ""jamie"", ""jamie"", ""john"", + ""johnny"", ""jamie"", ""johnny"", + ""john""] + + findWinner(votes) + +# This code is contributed by ukasp",linear,linear +"# Python 3 program to check if a query +# string is present is given set. +MAX_CHAR = 256 + +def isPresent(s, q): + + # Count occurrences of all characters + # in s. + freq = [0] * MAX_CHAR + for i in range(0 , len(s)): + freq[ord(s[i])] += 1 + + # Check if number of occurrences of + # every character in q is less than + # or equal to that in s. + for i in range(0, len(q)): + freq[ord(q[i])] -= 1 + if (freq[ord(q[i])] < 0): + return False + + return True + +# driver program +s = ""abctd"" +q = ""cat"" + +if (isPresent(s, q)): + print(""Yes"") +else: + print(""No"") + +# This code is contributed by Smitha",constant,linear +"# Python program to find +# the arrangement of +# queue at time = t + +# prints the arrangement +# at time = t +def solve(n, t, p) : + + s = list(p) + + # Checking the entire + # queue for every + # moment from time = 1 + # to time = t. + for i in range(0, t) : + + for j in range(0, n - 1) : + + # If current index + # contains 'B' and + # next index contains + # 'G' then swap + if (s[j] == 'B' and + s[j + 1] == 'G') : + + temp = s[j]; + s[j] = s[j + 1]; + s[j + 1] = temp; + j = j + 1 + + print (''.join(s)) + +# Driver code +n = 6 +t = 2 +p = ""BBGBBG"" +solve(n, t, p) + +# This code is contributed by +# Manish Shaw(manishshaw1)",constant,quadratic +"# Python3 code to check whether the +# given EMEI number is valid or not + +# Function for finding and returning +# sum of digits of a number +def sumDig( n ): + a = 0 + while n > 0: + a = a + n % 10 + n = int(n / 10) + + return a + +# Returns True if n is valid EMEI +def isValidEMEI(n): + + # Converting the number into + # String for finding length + s = str(n) + l = len(s) + + # If length is not 15 then IMEI is Invalid + if l != 15: + return False + + d = 0 + sum = 0 + for i in range(15, 0, -1): + d = (int)(n % 10) + if i % 2 == 0: + + # Doubling every alternate digit + d = 2 * d + + # Finding sum of the digits + sum = sum + sumDig(d) + n = n / 10 + return (sum % 10 == 0) + +# Driver code +n = 490154203237518 +if isValidEMEI(n): + print(""Valid IMEI Code"") +else: + print(""Invalid IMEI Code"") + +# This code is contributed by ""Sharad_Bhardwaj"".",linear,nlogn +"# Python3 program to decode a median +# string to the original string + +# function to calculate the median +# back string +def decodeMedianString(s): + + # length of string + l = len(s) + + # initialize a blank string + s1 = """" + + # Flag to check if length is + # even or odd + if(l % 2 == 0): + isEven = True + else: + isEven = False + + # traverse from first to last + for i in range(0, l, 2): + + # if len is even then add first + # character to beginning of new + # string and second character to end + if (isEven): + s1 = s[i] + s1 + s1 += s[i + 1] + else : + + # if current length is odd and + # is greater than 1 + if (l - i > 1): + + # add first character to end and + # second character to beginning + s1 += s[i] + s1 = s[i + 1] + s1 + else: + + # if length is 1, add character + # to end + s1 += s[i] + + return s1 + +# Driver Code +if __name__ == '__main__': + s = ""eekgs"" + print(decodeMedianString(s)) + +# This code is contributed by +# Sanjit_Prasad",constant,linear +"# Python program to decode a string recursively +# encoded as count followed substring + +# Returns decoded string for 'str' +def decode(Str): + integerstack = [] + stringstack = [] + temp = """" + result = """" + i = 0 + # Traversing the string + while i < len(Str): + count = 0 + + # If number, convert it into number + # and push it into integerstack. + if (Str[i] >= '0' and Str[i] <='9'): + while (Str[i] >= '0' and Str[i] <= '9'): + count = count * 10 + ord(Str[i]) - ord('0') + i += 1 + i -= 1 + integerstack.append(count) + + # If closing bracket ']', pop element until + # '[' opening bracket is not found in the + # character stack. + elif (Str[i] == ']'): + temp = """" + count = 0 + + if (len(integerstack) != 0): + count = integerstack[-1] + integerstack.pop() + + while (len(stringstack) != 0 and stringstack[-1] !='[' ): + temp = stringstack[-1] + temp + stringstack.pop() + + if (len(stringstack) != 0 and stringstack[-1] == '['): + stringstack.pop() + + # Repeating the popped string 'temo' count + # number of times. + for j in range(count): + result = result + temp + + # Push it in the character stack. + for j in range(len(result)): + stringstack.append(result[j]) + + result = """" + + # If '[' opening bracket, push it into character stack. + elif (Str[i] == '['): + if (Str[i-1] >= '0' and Str[i-1] <= '9'): + stringstack.append(Str[i]) + + else: + stringstack.append(Str[i]) + integerstack.append(1) + + else: + stringstack.append(Str[i]) + + i += 1 + + # Pop all the element, make a string and return. + while len(stringstack) != 0: + result = stringstack[-1] + result + stringstack.pop() + + return result + +# Driven code +if __name__ == '__main__': + Str = ""3[b2[ca]]"" + print(decode(Str)) + +# This code is contributed by PranchalK.",linear,linear +"def decodeString(s): + st = [] + for i in range(len(s)): + + # When ']' is encountered, we need to start decoding + if s[i] == ']': + temp = """" + while len(st) > 0 and st[-1] != '[': + + # st.top() + temp makes sure that the + # string won't be in reverse order eg, if + # the stack contains 12[abc temp = c + """" => + # temp = b + ""c"" => temp = a + ""bc"" + temp = st[-1] + temp + st.pop() + + # remove the '[' from the stack + st.pop() + num = """" + + # remove the digits from the stack + while len(st) > 0 and ord(st[-1]) >= 48 and ord(st[-1]) <= 57: + num = st[-1] + num + st.pop() + number = int(num) + repeat = """" + for j in range(number): + repeat += temp + for c in range(len(repeat)): + if len(st) > 0: + if repeat == st[-1]: + break #otherwise this thingy starts appending the same decoded words + st.append(repeat) + + else: + st.append(s[i]) + + return st[0] + + +Str = ""3[b2[ca]]"" +print(decodeString(Str)) + +# This code is contributed by mukesh07. +# And debugged by ivannakreshchenetska",linear,linear +"# Python 3 program to make a number magical + +# function to calculate the minimal changes +def calculate( s): + + # maximum digits that can be changed + ans = 6 + + # nested loops to generate all 6 + # digit numbers + for i in range(10): + for j in range(10): + for k in range(10): + for l in range(10): + for m in range(10): + for n in range(10): + if (i + j + k == l + m + n): + + # counter to count the number + # of change required + c = 0 + + # if first digit is equal + if (i != ord(s[0]) - ord('0')): + c+=1 + + # if 2nd digit is equal + if (j != ord(s[1]) - ord('0')): + c+=1 + + # if 3rd digit is equal + if (k != ord(s[2]) - ord('0')): + c+=1 + + # if 4th digit is equal + if (l != ord(s[3]) - ord('0')): + c+=1 + + # if 5th digit is equal + if (m != ord(s[4]) - ord('0')): + c+=1 + + # if 6th digit is equal + if (n != ord(s[5]) - ord('0')): + c+=1 + + # checks if less than the + # previous calculate changes + if (c < ans): + ans = c + + # returns the answer + return ans + +# driver program to test the above function +if __name__ == ""__main__"": + + # number stored in string + s = ""123456"" + + # prints the minimum operations + print(calculate(s))",constant,np +"# Python code to check if a +# given ISBN is valid or not. + +def isValidISBN(isbn): + + # check for length + if len(isbn) != 10: + return False + + # Computing weighted sum + # of first 9 digits + _sum = 0 + for i in range(9): + if 0 <= int(isbn[i]) <= 9: + _sum += int(isbn[i]) * (10 - i) + else: + return False + + # Checking last digit + if(isbn[9] != 'X' and + 0 <= int(isbn[9]) <= 9): + return False + + # If last digit is 'X', add + # 10 to sum, else add its value. + _sum += 10 if isbn[9] == 'X' else int(isbn[9]) + + # Return true if weighted sum of + # digits is divisible by 11 + return (_sum % 11 == 0) + +# Driver Code +isbn = ""007462542X"" +if isValidISBN(isbn): + print('Valid') +else: + print(""Invalid"") + +# This code is contributed +# by ""Abhishek Sharma 44""",constant,constant +"class CreditCard: + # Main Method + @staticmethod + def main(args): + number = 5196081888500645 + print(str(number) + "" is "" + + (""valid"" if CreditCard.isValid(number) else ""invalid"")) + + # Return true if the card number is valid + @staticmethod + def isValid(number): + return (CreditCard.getSize(number) >= 13 and CreditCard.getSize(number) <= 16) and (CreditCard.prefixMatched(number, 4) or CreditCard.prefixMatched(number, 5) or CreditCard.prefixMatched(number, 37) or CreditCard.prefixMatched(number, 6)) and ((CreditCard.sumOfDoubleEvenPlace(number) + CreditCard.sumOfOddPlace(number)) % 10 == 0) + + # Get the result from Step 2 + @staticmethod + def sumOfDoubleEvenPlace(number): + sum = 0 + num = str(number) + """" + i = CreditCard.getSize(number) - 2 + while (i >= 0): + sum += CreditCard.getDigit(int(str(num[i]) + """") * 2) + i -= 2 + return sum + + # Return this number if it is a single digit, otherwise, + # return the sum of the two digits + @staticmethod + def getDigit(number): + if (number < 9): + return number + return int(number / 10) + number % 10 + + # Return sum of odd-place digits in number + @staticmethod + def sumOfOddPlace(number): + sum = 0 + num = str(number) + """" + i = CreditCard.getSize(number) - 1 + while (i >= 0): + sum += int(str(num[i]) + """") + i -= 2 + return sum + + # Return true if the digit d is a prefix for number + @staticmethod + def prefixMatched(number, d): + return CreditCard.getPrefix(number, CreditCard.getSize(d)) == d + + # Return the number of digits in d + @staticmethod + def getSize(d): + num = str(d) + """" + return len(num) + + # Return the first k number of digits from + # number. If the number of digits in number + # is less than k, return number. + @staticmethod + def getPrefix(number, k): + if (CreditCard.getSize(number) > k): + num = str(number) + """" + return int(num[0:k]) + return number + +if __name__ == ""__main__"": + CreditCard.main([]) + +# This code is contributed by Aarti_Rathi",constant,linear +"# Python3 program to implement the approach + +# Python3 has no built-in swap function. +def swap(str, i, j): + ch = list(str) + temp = ch[i] + ch[i] = ch[j] + ch[j] = temp + return """".join(ch) + +# Since STRINGS are immutable in JavaScript, first we have +# to convert it to a character array in order to sort. +def sortString(str, s_index, e_index): + tempArray = list(str) + + # Sorting temp array using + tempArray = tempArray[:s_index] + sorted(tempArray[s_index: e_index]) + + # returning the new sorted string + return """".join(tempArray) + +def maximizeNumber(N, M): + # Sorting the digits of the + # number in increasing order. + N = sortString(N, 0, len(N)) + + for i in range(len(N)): + for j in range(i + 1, len(N)): + + # Copying the string into another + # temp string. + t = N + + # Swapping the j-th char(digit) + # with i-th char(digit) + + t = swap(t, j, i) + + # Sorting the temp string + # from i-th pos to end. + t = sortString(t, i + 1, len(t)) + + # Checking if the string t is + # greater than string N and less + # than or equal to the number M. + if (int(t) > int(N) and int(t) <= M): + + # If yes then, we will permanently + # swap the i-th char(or digit) + # with j-th char(digit). + N = swap(N, i, j) + + # Returns the maximized number. + return N + +# Driver Code +N = ""123"" +M = 222 +print(maximizeNumber(N, M)) + +# This code is contributed by phasing17",linear,cubic +"# Python program to find +# if a given corner string +# is present at corners. + +def isCornerPresent(str, corner) : + + n = len(str) + cl = len(corner) + + # If length of corner + # string is more, it + # cannot be present + # at corners. + if (n < cl) : + return False + + # Return true if corner + # string is present at + # both corners of given + # string. + return ((str[: cl] == corner) and + (str[n - cl :] == corner)) + +# Driver Code +str = ""geeksforgeeks"" +corner = ""geeks"" +if (isCornerPresent(str, corner)) : + print (""Yes"") +else : + print (""No"") + +# This code is contributed by +# Manish Shaw(manishshaw1)",constant,linear