code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
// C++ program to find position of a number // in a series of numbers with 4 and 7 as the // only digits. #include <iostream> #include <algorithm> using namespace std; int findpos(string n) { int i = 0, pos = 0; while (n[i] != '\0') { // check all digit position switch (n[i]) { // if number is left then pos*2+1 case '4': pos = pos * 2 + 1; break; // if number is right then pos*2+2 case '7': pos = pos * 2 + 2; break; } i++; } return pos; } // Driver code int main() { // given a number which is constructed // by 4 and 7 digit only string n = "774"; cout << findpos(n); return 0; }
constant
linear
// C++++ program to find winner in an election. #include "bits/stdc++.h" using namespace std; /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ void findWinner(vector<string>& votes) { // Insert all votes in a hashmap unordered_map<string, int> mapObj; for (auto& str : votes) { mapObj[str]++; } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; string winner; for (auto& entry : mapObj) { string key = entry.first; int val = entry.second; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner > key) winner = key; } cout << winner << endl; } // Driver code int main() { vector<string> votes = { "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john" }; findWinner(votes); return 0; }
linear
linear
// CPP program to check if a query string // is present is given set. #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 256; bool isPresent(string s, string q) { // Count occurrences of all characters // in s. int freq[MAX_CHAR] = { 0 }; for (int i = 0; i < s.length(); i++) freq[s[i]]++; // Check if number of occurrences of // every character in q is less than // or equal to that in s. for (int i = 0; i < q.length(); i++) { freq[q[i]]--; if (freq[q[i]] < 0) return false; } return true; } // driver program int main() { string s = "abctd"; string q = "cat"; if (isPresent(s, q)) cout << "Yes"; else cout << "No"; return 0; }
constant
linear
// CPP program to find the arrangement // of queue at time = t #include <bits/stdc++.h> using namespace std; // prints the arrangement at time = t void solve(int n, int t, string s) { // Checking the entire queue for // every moment from time = 1 to // time = t. for (int i = 0; i < t; i++) for (int j = 0; j < n - 1; j++) /*If current index contains 'B' and next index contains 'G' then swap*/ if (s[j] == 'B' && s[j + 1] == 'G') { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j++; } cout << s; } // Driver function for the program int main() { int n = 6, t = 2; string s = "BBGBBG"; solve(n, t, s); return 0; }
constant
quadratic
// C++ program to check whether the // given EMEI number is valid or not. #include<bits/stdc++.h> using namespace std; // Function for finding and returning // sum of digits of a number int sumDig(int n) { int a = 0; while (n > 0) { a = a + n % 10; n = n / 10; } return a; } bool isValidIMEI(long n) { // Converting the number into // String for finding length string s = to_string(n); int len = s.length(); if (len != 15) return false; int sum = 0; for(int i = len; i >= 1; i--) { int d = (int)(n % 10); // Doubling every alternate digit if (i % 2 == 0) d = 2 * d; // Finding sum of the digits sum += sumDig(d); n = n / 10; } return (sum % 10 == 0); } // Driver code int main() { // 15 digits cannot be stored // in 'int' data type long n = 490154203237518L; if (isValidIMEI(n)) cout << "Valid IMEI Code"; else cout << "Invalid IMEI Code"; return 0; } // This code is contributed by Yash_R
linear
nlogn
// C++ program to decode a median string // to the original string #include <bits/stdc++.h> using namespace std; // function to calculate the median back string string decodeMedianString(string s) { // length of string int l = s.length(); // initialize a blank string string s1 = ""; // Flag to check if length is even or odd bool isEven = (l % 2 == 0)? true : false; // traverse from first to last for (int i = 0; i < l; i += 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 program int main() { string s = "eekgs"; cout << decodeMedianString(s); return 0; }
constant
linear
// CPP program to check if a // given ISBN is valid or not #include <bits/stdc++.h> using namespace std; bool isValidISBN(string& isbn) { // length must be 10 int n = isbn.length(); if (n != 10) return false; // Computing weighted sum // of first 9 digits int sum = 0; for (int i = 0; i < 9; i++) { int digit = isbn[i] - '0'; if (0 > digit || 9 < digit) return false; sum += (digit * (10 - i)); } // Checking last digit. char last = isbn[9]; if (last != 'X' && (last < '0' || last > '9')) return false; // If last digit is 'X', add 10 // to sum, else add its value. sum += ((last == 'X') ? 10 : (last - '0')); // Return true if weighted sum // of digits is divisible by 11. return (sum % 11 == 0); } // Driver code int main() { string isbn = "007462542X"; if (isValidISBN(isbn)) cout << "Valid"; else cout << "Invalid"; return 0; }
constant
constant
// C++ program to check if a given credit // card is valid or not. #include <iostream> using namespace std; // Return this number if it is a single digit, otherwise, // return the sum of the two digits int getDigit(int number) { if (number < 9) return number; return number / 10 + number % 10; } // Return the number of digits in d int getSize(long d) { string num = to_string(d); return num.length(); } // Return the first k number of digits from // number. If the number of digits in number // is less than k, return number. long getPrefix(long number, int k) { if (getSize(number) > k) { string num = to_string(number); return stol(num.substr(0, k)); } return number; } // Return true if the digit d is a prefix for number bool prefixMatched(long number, int d) { return getPrefix(number, getSize(d)) == d; } // Get the result from Step 2 int sumOfDoubleEvenPlace(long int number) { int sum = 0; string num = to_string(number) ; for (int i = getSize(number) - 2; i >= 0; i -= 2) sum += getDigit(int(num[i] - '0') * 2); return sum; } // Return sum of odd-place digits in number int sumOfOddPlace(long number) { int sum = 0; string num = to_string(number) ; for (int i = getSize(number) - 1; i >= 0; i -= 2) sum += num[i] - '0'; return sum; } // Return true if the card number is valid bool isValid(long int number) { return (getSize(number) >= 13 && getSize(number) <= 16) && (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 37) || prefixMatched(number, 6)) && ((sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0); } // Driver Code int main() { long int number = 5196081888500645L; cout << number << " is " << (isValid(number) ? "valid" : "invalid"); return 0; } // This code is contributed by yuvraj_chandra
constant
linear
// CPP program to Maximize the given number. #include <bits/stdc++.h> using namespace std; // Function to maximize the number N with // limit as M. string maximizeNumber(string N, int M) { // Sorting the digits of the // number in increasing order. sort(N.begin(), N.end()); for (int i = 0; i < N.size(); i++) { for (int j = i + 1; j < N.size(); j++) { // Copying the string into another // temp string. string t = N; // Swapping the j-th char(digit) // with i-th char(digit) swap(t[j], t[i]); // Sorting the temp string // from i-th pos to end. sort(t.begin() + i + 1, t.end()); // Checking if the string t is // greater than string N and less // than or equal to the number M. if (stoll(t) > stoll(N) && stoll(t) <= M) // If yes then, we will permanently // swap the i-th char(or digit) // with j-th char(digit). swap(N[i], N[j]); } } // Returns the maximized number. return N; } // Driver function int main() { string N = "123"; int M = 222; cout << maximizeNumber(N, M); return 0; } // This code is contributed by KaaL-EL.
linear
cubic
// CPP program to find if a given corner string // is present at corners. #include <bits/stdc++.h> using namespace std; bool isCornerPresent(string str, string corner) { int n = str.length(); int cl = corner.length(); // 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.substr(0, cl).compare(corner) == 0 && str.substr(n-cl, cl).compare(corner) == 0); } // Driver code int main() { string str = "geeksforgeeks"; string corner = "geeks"; if (isCornerPresent(str, corner)) cout << "Yes"; else cout << "No"; return 0; }
constant
linear
# 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 <stdio.h> #include <stdlib.h> #include <stdbool.h> #define ROW 4 #define COL 5 // A Trie node typedef struct Node { bool isEndOfCol; struct Node *child[2]; // Only two children needed for 0 and 1 } Node; // A utility function to allocate memory for a new Trie node Node* newNode() { Node* temp = (Node *)malloc( sizeof( Node ) ); temp->isEndOfCol = 0; temp->child[0] = temp->child[1] = NULL; return temp; } // Inserts a new matrix row to Trie. If row is already // present, then returns 0, otherwise insets the row and // return 1 bool insert( Node** root, int (*M)[COL], int row, int col ) { // base case if ( *root == NULL ) *root = newNode(); // Recur if there are more entries in this row if ( col < COL ) return insert ( &( (*root)->child[ M[row][col] ] ), M, row, col+1 ); else // If all entries of this row are processed { // unique row found, return 1 if ( !( (*root)->isEndOfCol ) ) return (*root)->isEndOfCol = 1; // duplicate row found, return 0 return 0; } } // A utility function to print a row void printRow( int (*M)[COL], int row ) { int i; for( i = 0; i < COL; ++i ) printf( "%d ", M[row][i] ); printf("\n"); } // The main function that prints all unique rows in a // given matrix. void findUniqueRows( int (*M)[COL] ) { Node* root = NULL; // create an empty Trie int i; // Iterate through all rows for ( i = 0; i < ROW; ++i ) // insert row to TRIE if ( insert(&root, M, i, 0) ) // unique row found, print it printRow( M, i ); } // Driver program to test above functions int main() { int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0} }; findUniqueRows( M ); return 0; }
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<<i) if val : # Create new node if needed if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right if not val: # Create new node if needed if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left # Store value at leaf node self.temp.data = pre_xor # Find the maximum xor ending with last number # in prefix XOR and return the XOR of this def query(self, xor): self.temp = self.root for i in range(31, -1, -1): # Find the current bit in prefix xor val = xor & (1<<i) # Traverse the trie, first look for opposite bit # and then look for same bit if val: if self.temp.left: self.temp = self.temp.left elif self.temp.right: self.temp = self.temp.right else: if self.temp.right: self.temp = self.temp.right elif self.temp.left: self.temp = self.temp.left return xor ^ self.temp.data # Returns maximum XOR value of subarray def maxSubArrayXOR(self, n, Arr): # Insert 0 in the trie self.insert(0) # Initialize result and pre_xor result = -float('inf') pre_xor = 0 # Traverse all input array element for i in range(n): # Update current prefix xor and # insert it into Trie pre_xor = pre_xor ^ Arr[i] self.insert(pre_xor) # Query for current prefix xor # in Trie and update result result = max(result, self.query(pre_xor)) return result # Driver code if __name__ == "__main__": Arr = [8, 1, 2, 12] n = len(Arr) trie = Trie() print("Max subarray XOR is", end = ' ') print(trie.maxSubArrayXOR(n, Arr)) # This code is contributed by chaudhary_19
linear
linear
# Python implementation of Binary Indexed Tree # Returns sum of arr[0..index]. This function assumes # that the array is preprocessed and partial sums of # array elements are stored in BITree[]. def getsum(BITTree,i): s = 0 #initialize result # index in BITree[] is 1 more than the index in arr[] i = i+1 # Traverse ancestors of BITree[index] while i > 0: # Add current element of BITree to sum s += BITTree[i] # Move index to parent node in getSum View i -= i & (-i) return s # Updates a node in Binary Index Tree (BITree) at given index # in BITree. The given value 'val' is added to BITree[i] and # all of its ancestors in tree. def updatebit(BITTree , n , i ,v): # index in BITree[] is 1 more than the index in arr[] i += 1 # Traverse all ancestors and add 'val' while i <= n: # Add 'val' to current node of BI Tree BITTree[i] += v # Update index to that of parent in update View i += i & (-i) # Constructs and returns a Binary Indexed Tree for given # array of size n. def construct(arr, n): # Create and initialize BITree[] as 0 BITTree = [0]*(n+1) # Store the actual values in BITree[] using update() for i in range(n): updatebit(BITTree, n, i, arr[i]) # Uncomment below lines to see contents of BITree[] #for i in range(1,n+1): # print BITTree[i], return BITTree # Driver code to test above methods freq = [2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9] BITTree = construct(freq,len(freq)) print("Sum of elements in arr[0..5] is " + str(getsum(BITTree,5))) freq[3] += 6 updatebit(BITTree, len(freq), 3, 6) print("Sum of elements in arr[0..5]"+ " after update is " + str(getsum(BITTree,5))) # This code is contributed by Raju Varshney
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<bits/stdc++.h> 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<int, Node*> 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 <iNPair, vector<iNPair>, greater<iNPair>> 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[prev]\ and arr[mid]<=arr[nex]: return mid # if not selecting the unsorted part of array elif arr[mid]<arr[start]: end = mid-1 elif 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
<script> // Python 3 program for // moving negative numbers to left // while maintaining the order class Solution{ rotateSubArray(arr, l, r){ let temp = arr[r] for(let j = r;j > l-1;j--){ arr[j] = arr[j-1] } arr[l] = temp return arr } moveNegative(arr){ let last_negative_index = -1 for(let i=0;i<arr.length;i++){ if(arr[i] < 0){ last_negative_index += 1 let temp = arr[i]; arr[i] = arr[last_negative_index]; arr[last_negative_index] = temp; // Done to manage order too if(i - last_negative_index >= 2) this.rotateSubArray(arr, last_negative_index+1, i) } } return arr } } // Driver Code let arr = [5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1] let ob = new Solution() ob.moveNegative(arr) for(let i of arr){ document.write(i,' ') } // This code is contributed by shinjanpatra </script>
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<high): if(arr[low] < 0): low += 1 elif(arr[high] > 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