text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Check if two people starting from different points ever meet | Python3 program to find if two people starting from different positions ever meet or not . ; If speed of a person at a position before other person is smaller , then return false . ; Making sure that x1 is greater ; checking if relative speed is a factor of... | def everMeet ( x1 , x2 , v1 , v2 ) : NEW_LINE INDENT if ( x1 < x2 and v1 <= v2 ) : NEW_LINE INDENT return False ; NEW_LINE if ( x1 > x2 and v1 >= v2 ) : NEW_LINE INDENT return False ; NEW_LINE if ( x1 < x2 ) : NEW_LINE INDENT swap ( x1 , x2 ) NEW_LINE swap ( v1 , v2 ) NEW_LINE return ( ( x1 - x2 ) % ( v1 - v2 ) == 0 ) ... |
Count of distinct GCDs among all the non | Python 3 program for the above approach ; Function to calculate the number of distinct GCDs among all non - empty subsequences of an array ; variables to store the largest element in array and the required count ; Map to store whether a number is present in A ; calculate large... | from math import gcd NEW_LINE def distinctGCDs ( arr , N ) : NEW_LINE INDENT M = - 1 NEW_LINE ans = 0 NEW_LINE Mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT M = max ( M , arr [ i ] ) NEW_LINE Mp [ arr [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 1 , M + 1 , 1 ) : NEW_LINE INDENT currGcd = 0 NEW_LINE for j in... |
Find ceil of a / b without using ceil ( ) function | Python3 program to find math . ceil ( a / b ) without using math . ceil ( ) function ; taking input 1 ; example of perfect division taking input 2 | import math NEW_LINE a = 4 ; NEW_LINE b = 3 ; NEW_LINE val = ( a + b - 1 ) / b ; NEW_LINE print ( " The β ceiling β value β of β 4/3 β is β " , math . floor ( val ) ) ; NEW_LINE a = 6 ; NEW_LINE b = 3 ; NEW_LINE val = ( a + b - 1 ) / b ; NEW_LINE print ( " The β ceiling β value β of β 6/3 β is β " , math . floor ( val ... |
Sum of range in a series of first odd then even natural numbers | Python 3 program to find sum in the given range in the sequence 1 3 5 7 ... . . N 2 4 6. . . N - 1 ; Function that returns sum in the range 1 to x in the sequence 1 3 5 7. ... . N 2 4 6. . . N - 1 ; number of odd numbers ; number of extra even numbers re... | import math NEW_LINE def sumTillX ( x , n ) : NEW_LINE INDENT odd = math . ceil ( n / 2.0 ) NEW_LINE if ( x <= odd ) : NEW_LINE INDENT return x * x ; NEW_LINE DEDENT even = x - odd ; NEW_LINE return ( ( odd * odd ) + ( even * even ) + even ) ; NEW_LINE DEDENT def rangeSum ( N , L , R ) : NEW_LINE INDENT return ( sumTil... |
Twin Prime Numbers between 1 and n | Python program to illustrate ... To print total number of twin prime using Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is ... | def printTwinPrime ( n ) : NEW_LINE INDENT prime = [ True for i in range ( n + 2 ) ] NEW_LINE p = 2 NEW_LINE while ( p * p <= n + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , n + 2 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT fo... |
Cube Free Numbers smaller than n | Python3 Program to print all cube free numbers smaller than or equal to n . ; Returns true if n is a cube free number , else returns false . ; check for all possible divisible cubes ; Print all cube free numbers smaller than n . ; Driver program | import math NEW_LINE def isCubeFree ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , int ( n ** ( 1 / 3 ) + 1 ) ) : NEW_LINE INDENT if ( n % ( i * i * i ) == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def printCubeFree (... |
Decimal Equivalent of Gray Code and its Inverse | Function to convert given decimal number of gray code into its inverse in decimal form ; Taking xor until n becomes zero ; Driver Code | def inversegrayCode ( n ) : NEW_LINE INDENT inv = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT inv = inv ^ n ; NEW_LINE n = n >> 1 ; NEW_LINE DEDENT return inv ; NEW_LINE DEDENT n = 15 ; NEW_LINE print ( inversegrayCode ( n ) ) ; NEW_LINE |
Product of unique prime factors of a number | Python program to find product of unique prime factors of a number ; A function to print all prime factors of a given number n ; Handle prime factor 2 explicitly so that can optimally handle other prime factors . ; n must be odd at this point . So we can skip one element ( ... | import math NEW_LINE def productPrimeFactors ( n ) : NEW_LINE INDENT product = 1 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT product *= 2 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = n / 2 NEW_LINE DEDENT DEDENT for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_L... |
Maximizing Probability of one type from N containers | Returns the Maximum probability for Drawing 1 copy of number A from N containers with N copies each of numbers A and B ; Pmax = N / ( N + 1 ) ; 1. N = 1 ; 2. N = 2 ; 3. N = 10 | def calculateProbability ( N ) : NEW_LINE INDENT probability = N / ( N + 1 ) NEW_LINE return probability NEW_LINE DEDENT N = 1 NEW_LINE probabilityMax = calculateProbability ( N ) NEW_LINE print ( " Maximum β Probability β for β N β = β " , N , " is , β % .4f " % probabilityMax ) NEW_LINE N = 2 NEW_LINE probabilityMax ... |
Program to implement standard deviation of grouped data | Python Program to implement standard deviation of grouped data . ; Function to find mean of grouped data . ; Function to find standard deviation of grouped data . ; Formula to find standard deviation of grouped data . ; Declare and initialize the lower limit of ... | import math NEW_LINE def mean ( mid , freq , n ) : NEW_LINE INDENT sum = 0 NEW_LINE freqSum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum = sum + mid [ i ] * freq [ i ] NEW_LINE freqSum = freqSum + freq [ i ] NEW_LINE DEDENT return sum / freqSum NEW_LINE DEDENT def groupedSD ( lower_limit , upper_limit , ... |
Average of first n even natural numbers | Function to find average of sum of first n even numbers ; sum of first n even numbers ; calculating Average ; driver code | def avg_of_even_num ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum = sum + 2 * i NEW_LINE DEDENT return sum / n NEW_LINE DEDENT n = 9 NEW_LINE print ( avg_of_even_num ( n ) ) NEW_LINE |
Average of first n even natural numbers | Return the average of sum of first n even numbers ; Driven Program | def avg_of_even_num ( n ) : NEW_LINE INDENT return n + 1 NEW_LINE DEDENT n = 8 NEW_LINE print ( avg_of_even_num ( n ) ) NEW_LINE |
Sum of square of first n odd numbers | Python3 code to find sum of square of first n odd numbers ; driver code | def squareSum ( n ) : NEW_LINE INDENT return int ( n * ( 4 * n * n - 1 ) / 3 ) NEW_LINE DEDENT ans = squareSum ( 8 ) NEW_LINE print ( ans ) NEW_LINE |
Check whether given three numbers are adjacent primes | Function checks whether given number is prime or not . ; Check if n is a multiple of 2 ; If not , then just check the odds ; Return next prime number ; Start with next number ; Breaks after finding next prime number ; Check given three numbers are adjacent primes ... | def isPrime ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 3 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 2 NEW_LINE DEDENT return True NEW_LINE DEDENT def nextPrime ( start ) : NEW_LINE INDENT nxt ... |
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | Python3 Program to find sum of series 1 + 2 + 2 + 3 + . . . + n ; Function that find sum of series . ; Driver method ; Function call | import math NEW_LINE def sumOfSeries ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum = sum + i * i NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 10 NEW_LINE print ( sumOfSeries ( n ) ) NEW_LINE |
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | Python3 Program to find sum of series 1 + 2 + 2 + 3 + . . . + n ; Function that find sum of series . ; Driver method | import math NEW_LINE def sumOfSeries ( n ) : NEW_LINE INDENT return ( ( n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ) NEW_LINE DEDENT n = 10 NEW_LINE print ( sumOfSeries ( n ) ) NEW_LINE |
Maximum binomial coefficient term value | Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Return maximum binomial coefficient term value . ; if n is even ; if n is odd ; Driver Code | def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for x in range ( k + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT C ... |
Smallest n digit number divisible by given three numbers | Python3 code to find smallest n digit number which is divisible by x , y and z . ; LCM for x , y , z ; returns smallest n digit number divisible by x , y and z ; find the LCM ; find power of 10 for least number ; reminder after ; If smallest number itself divid... | from fractions import gcd NEW_LINE import math NEW_LINE def LCM ( x , y , z ) : NEW_LINE INDENT ans = int ( ( x * y ) / ( gcd ( x , y ) ) ) NEW_LINE return int ( ( z * ans ) / ( gcd ( ans , z ) ) ) NEW_LINE DEDENT def findDivisible ( n , x , y , z ) : NEW_LINE INDENT lcm = LCM ( x , y , z ) NEW_LINE ndigitnumber = math... |
Sum of squares of first n natural numbers | Return the sum of square of first n natural numbers ; Driven Program | def squaresum ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) / 2 ) * ( 2 * n + 1 ) / 3 NEW_LINE DEDENT n = 4 NEW_LINE print ( squaresum ( n ) ) ; NEW_LINE |
Program to calculate distance between two points | Python3 program to calculate distance between two points ; Function to calculate distance ; Calculating distance ; Drivers Code | import math NEW_LINE def distance ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT return math . sqrt ( math . pow ( x2 - x1 , 2 ) + math . pow ( y2 - y1 , 2 ) * 1.0 ) NEW_LINE DEDENT print ( " % .6f " % distance ( 3 , 4 , 4 , 3 ) ) NEW_LINE |
Check if a large number is divisibility by 15 | to find sum ; function to check if a large number is divisible by 15 ; length of string ; check divisibility by 5 ; Sum of digits ; if divisible by 3 ; Driver Code | def accumulate ( s ) : NEW_LINE INDENT acc = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT acc += ord ( s [ i ] ) - 48 ; NEW_LINE DEDENT return acc ; NEW_LINE DEDENT def isDivisible ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE if ( s [ n - 1 ] != '5' and s [ n - 1 ] != '0' ) : NEW_LINE INDENT return F... |
Shortest path with exactly k edges in a directed and weighted graph | Define number of vertices in the graph and inifinite value ; A naive recursive function to count walks from u to v with k edges ; Base cases ; Initialize result ; Go to all adjacents of u and recur ; Driver Code ; Let us create the graph shown in abo... | V = 4 NEW_LINE INF = 999999999999 NEW_LINE def shortestPath ( graph , u , v , k ) : NEW_LINE INDENT if k == 0 and u == v : NEW_LINE INDENT return 0 NEW_LINE DEDENT if k == 1 and graph [ u ] [ v ] != INF : NEW_LINE INDENT return graph [ u ] [ v ] NEW_LINE DEDENT if k <= 0 : NEW_LINE INDENT return INF NEW_LINE DEDENT res... |
Shortest path with exactly k edges in a directed and weighted graph | Define number of vertices in the graph and inifinite value ; A Dynamic programming based function to find the shortest path from u to v with exactly k edges . ; Table to be filled up using DP . The value sp [ i ] [ j ] [ e ] will store weight of the ... | V = 4 NEW_LINE INF = 999999999999 NEW_LINE def shortestPath ( graph , u , v , k ) : NEW_LINE INDENT global V , INF NEW_LINE sp = [ [ None ] * V for i in range ( V ) ] NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT sp [ i ] [ j ] = [ None ] * ( k + 1 ) NEW_LINE DEDENT DEDENT for e... |
Multistage Graph ( Shortest Path ) | Returns shortest distance from 0 to N - 1. ; dist [ i ] is going to store shortest distance from node i to node N - 1. ; Calculating shortest path for rest of the nodes ; Initialize distance from i to destination ( N - 1 ) ; Check all nodes of next stages to find shortest distance f... | def shortestDist ( graph ) : NEW_LINE INDENT global INF NEW_LINE dist = [ 0 ] * N NEW_LINE dist [ N - 1 ] = 0 NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT dist [ i ] = INF NEW_LINE for j in range ( N ) : NEW_LINE INDENT if graph [ i ] [ j ] == INF : NEW_LINE INDENT continue NEW_LINE DEDENT dist [ i ]... |
Reverse Level Order Traversal | A binary tree node ; Function to print reverse level order traversal ; Print nodes at a given level ; Compute the height of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node ; Compute the height of each subtree ; Use the larger one ; L... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def reverseLevelOrder ( root ) : NEW_LINE INDENT h = height ( root ) NEW_LINE for i in reversed ( range ( 1 , h + 1 ) ) : NEW_LINE INDENT printGi... |
Minimize the number of weakly connected nodes | Set of nodes which are traversed in each launch of the DFS ; Function traversing the graph using DFS approach and updating the set of nodes ; Building a undirected graph ; Computes the minimum number of disconnected components when a bi - directed graph is converted to a ... | node = set ( ) NEW_LINE Graph = [ [ ] for i in range ( 10001 ) ] NEW_LINE def dfs ( visit , src ) : NEW_LINE INDENT visit [ src ] = True NEW_LINE node . add ( src ) NEW_LINE llen = len ( Graph [ src ] ) NEW_LINE for i in range ( llen ) : NEW_LINE INDENT if ( not visit [ Graph [ src ] [ i ] ] ) : NEW_LINE INDENT dfs ( v... |
Karp 's minimum mean (or average) weight cycle algorithm | a struct to represent edges ; vector to store edges @ SuppressWarnings ( " unchecked " ) ; calculates the shortest path ; initializing all distances as - 1 ; shortest distance From first vertex to in tself consisting of 0 edges ; filling up the dp table ; Retur... | class edge : NEW_LINE INDENT def __init__ ( self , u , w ) : NEW_LINE INDENT self . From = u NEW_LINE self . weight = w NEW_LINE DEDENT DEDENT def addedge ( u , v , w ) : NEW_LINE INDENT edges [ v ] . append ( edge ( u , w ) ) NEW_LINE DEDENT V = 4 NEW_LINE edges = [ [ ] for i in range ( V ) ] NEW_LINE def shortestpath... |
Frequency of maximum occurring subsequence in given string | Python3 program for the above approach ; Function to find the frequency ; freq stores frequency of each english lowercase character ; dp [ i ] [ j ] stores the count of subsequence with ' a ' + i and ' a ' + j character ; Increment the count of subsequence j ... | import numpy NEW_LINE def findCount ( s ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE dp = [ [ 0 ] * 26 ] * 26 NEW_LINE freq = numpy . zeros ( 26 ) NEW_LINE dp = numpy . zeros ( [ 26 , 26 ] ) NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT for j in range ( 26 ) : NEW_LINE INDENT dp [ j ] [ ord ( s [ i ] ) ... |
Create an array such that XOR of subarrays of length K is X | Function to construct the array ; Creating a list of size K , initialised with 0 ; Initialising the first element with the given XOR ; Driver code | def constructArray ( N , K , X ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in range ( 0 , K ) : NEW_LINE INDENT ans . append ( 0 ) NEW_LINE DEDENT ans [ 0 ] = X NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT print ( ans [ i % K ] , end = " β " ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE K = 2 NEW_LINE X = 4 NEW_LINE ... |
Two player game in which a player can remove all occurrences of a number | Python3 implementation for two player game in which a player can remove all occurrences of a number ; Function that print whether player1 can wins or loses ; Storing the number of occurrence of elements in unordered map ; Variable to check if th... | from collections import defaultdict NEW_LINE def game ( v , n ) : NEW_LINE INDENT m = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( v [ i ] not in m ) : NEW_LINE INDENT m [ v [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ v [ i ] ] += 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE check ... |
Count of elements which form a loop in an Array according to given constraints | Python3 program to number of elements which form a cycle in an array ; Function to count number of elements forming a cycle ; Array to store parent node of traversal . ; Array to determine whether current node is already counted in the cyc... | import math NEW_LINE mod = 1000000007 NEW_LINE def solve ( A , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE parent = [ - 1 ] * n NEW_LINE vis = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = i NEW_LINE if ( parent [ j ] == - 1 ) : NEW_LINE INDENT while ( parent [ j ] == - 1 ) : NEW_LINE INDENT parent [ j ] = i... |
Find farthest node from each node in Tree | Add edge between U and V in tree ; Edge from U to V ; Edge from V to U ; DFS to find the first End Node of diameter ; Calculating level of nodes ; Go in opposite direction of parent ; Function to clear the levels of the nodes ; Set all value of lvl [ ] to 0 for next dfs ; Set... | def AddEdge ( u , v ) : NEW_LINE INDENT global adj NEW_LINE adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def findFirstEnd ( u , p ) : NEW_LINE INDENT global lvl , adj , end1 , maxi NEW_LINE lvl [ u ] = 1 + lvl [ p ] NEW_LINE if ( lvl [ u ] > maxi ) : NEW_LINE INDENT maxi = lvl [ u ] NEW_LI... |
Sum and Product of all even digit sum Nodes of a Singly Linked List | Node of Linked List ; Function to insert a node at the beginning of the singly Linked List ; Insert the data ; Link old list to the new node ; Move head to pothe new node ; Function to find the digit sum for a number ; Return the sum ; Function to fi... | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE D... |
Shortest Palindromic Substring | Function return the shortest palindromic substring ; One by one consider every character as center point of even and length palindromes ; Find the longest odd length palindrome with center point as i ; Find the even length palindrome with center points as i - 1 and i . ; Smallest substr... | def ShortestPalindrome ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT l = i NEW_LINE r = i NEW_LINE ans1 = " " NEW_LINE ans2 = " " NEW_LINE while ( ( l >= 0 ) and ( r < n ) and ( s [ l ] == s [ r ] ) ) : NEW_LINE INDENT ans1 += s [ l ] NEW_LINE l -= 1 NEW_LINE r +... |
Find numbers which are multiples of first array and factors of second array | Python3 implementation of the approach ; Function to return the LCM of two numbers ; Function to print the required numbers ; To store the lcm of array a [ ] elements and the gcd of array b [ ] elements ; Finding LCM of first array ; Finding ... | from math import gcd NEW_LINE def lcm ( x , y ) : NEW_LINE INDENT temp = ( x * y ) // gcd ( x , y ) ; NEW_LINE return temp ; NEW_LINE DEDENT def findNumbers ( a , n , b , m ) : NEW_LINE INDENT lcmA = 1 ; __gcdB = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT lcmA = lcm ( lcmA , a [ i ] ) ; NEW_LINE DEDENT for i i... |
Probability such that two subset contains same number of elements | Python3 implementation of the above approach ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of ; Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize result ; If y is odd , m... | import math NEW_LINE def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k NEW_LINE DEDENT for i in range ( 0 , k ) : NEW_LINE INDENT res = res * ( n - i ) NEW_LINE res = res // ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def power ( x , y ) : NEW_LINE INDE... |
How to learn Pattern printing easily ? | Python3 implementation of the approach | N = 4 NEW_LINE print ( " Value β of β N : β " , N ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT min = i if i < j else j NEW_LINE print ( N - min + 1 , end = " β " ) NEW_LINE DEDENT for j in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT min = i if i < j else j NEW... |
Largest perfect square number in an Array | Python3 program to find the largest perfect square number among n numbers ; Function to check if a number is perfect square number or not ; takes the sqrt of the number ; checks if it is a perfect square number ; Function to find the largest perfect square number in the array... | from math import sqrt NEW_LINE def checkPerfectSquare ( n ) : NEW_LINE INDENT d = sqrt ( n ) NEW_LINE if d * d == n : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def largestPerfectSquareNumber ( a , n ) : NEW_LINE INDENT maxi = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( checkP... |
Maximum number of parallelograms that can be made using the given length of line segments | Function to find the maximum number of parallelograms can be made ; Finding the length of the frequency array ; Increasing the occurrence of each segment ; To store the count of parallelograms ; Counting parallelograms that can ... | def convert ( n , a ) : NEW_LINE INDENT z = max ( a ) + 1 NEW_LINE ff = [ 0 ] * z NEW_LINE for i in range ( n ) : NEW_LINE INDENT ff [ a [ i ] ] += 1 NEW_LINE DEDENT cc = 0 NEW_LINE for i in range ( z ) : NEW_LINE INDENT cc += ff [ i ] // 4 NEW_LINE ff [ i ] = ff [ i ] % 4 NEW_LINE DEDENT vv = 0 NEW_LINE for i in range... |
Count pairs ( i , j ) such that ( i + j ) is divisible by A and B both | Python3 implementation of above approach ; Function to find the LCM ; Function to count the pairs ; Driver code | from math import gcd NEW_LINE def find_LCM ( x , y ) : NEW_LINE INDENT return ( x * y ) // gcd ( x , y ) NEW_LINE DEDENT def CountPairs ( n , m , A , B ) : NEW_LINE INDENT cnt = 0 NEW_LINE lcm = find_LCM ( A , B ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT cnt += ( m + ( i % lcm ) ) // lcm NEW_LINE DEDENT ... |
Sorting without comparison of elements | Represents node of a doubly linked list ; Count of elements in given range ; Count frequencies of all elements ; Traverse through range . For every element , print it its count times . ; Driver Code | def sortArr ( arr , n , min_no , max_no ) : NEW_LINE INDENT m = max_no - min_no + 1 NEW_LINE c = [ 0 ] * m NEW_LINE for i in range ( n ) : NEW_LINE INDENT c [ arr [ i ] - min_no ] += 1 NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( ( c [ i ] ) ) : NEW_LINE INDENT print ( ( i + min_no ) , end = ... |
Find Binary permutations of given size not present in the Array | Python 3 program for the above approach ; Function to find a Binary String of same length other than the Strings present in the array ; Map all the strings present in the array ; Find all the substring that can be made ; If num already exists then increa... | from math import pow NEW_LINE def findMissingBinaryString ( nums , N ) : NEW_LINE INDENT s = set ( ) NEW_LINE counter = 0 NEW_LINE for x in nums : NEW_LINE INDENT s . add ( x ) NEW_LINE DEDENT total = int ( pow ( 2 , N ) ) NEW_LINE ans = " " NEW_LINE for i in range ( total ) : NEW_LINE INDENT num = " " NEW_LINE j = N -... |
Queries to find number of connected grid components of given sizes in a Matrix | Python 3 implementation for the above approach ; stores information about which cell are already visited in a particular BFS ; Stores the final result grid ; Stores the count of cells in the largest connected component ; Function checks if... | n = 6 NEW_LINE m = 6 NEW_LINE dx = [ 0 , 1 , - 1 , 0 ] NEW_LINE dy = [ 1 , 0 , 0 , - 1 ] NEW_LINE visited = [ [ False for i in range ( m ) ] for j in range ( n ) ] NEW_LINE result = [ [ 0 for i in range ( m ) ] for j in range ( n ) ] NEW_LINE COUNT = 0 NEW_LINE def is_valid ( x , y , matrix ) : NEW_LINE INDENT if ( x <... |
Minimum value of X such that sum of arr [ i ] | Function to check if there exists an X that satisfies the given conditions ; Find the required value of the given expression ; Function to find the minimum value of X using binary search . ; Boundaries of the Binary Search ; Find the middle value ; Check for the middle va... | def check ( a , b , k , n , x ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + pow ( max ( a [ i ] - x , 0 ) , b [ i ] ) NEW_LINE DEDENT if ( sum <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def findMin ( a , b , n... |
Count of indices pairs such that product of elements at these indices is equal to absolute difference of indices | Function to count the number of pairs ( i , j ) such that arr [ i ] * arr [ j ] is equal to abs ( i - j ) ; Stores the resultant number of pairs ; Iterate over the range [ 0 , N ) ; Now , iterate from the ... | def getPairsCount ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT s = arr [ i ] - ( i % arr [ i ] ) NEW_LINE for j in range ( s , n ) : NEW_LINE INDENT if ( i < j and ( arr [ i ] * arr [ j ] ) == abs ( i - j ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT retur... |
Find frequency of each character with positions in given Array of Strings | Function to print every occurence of every characters in every string ; Iterate over the vector arr [ ] ; Traverse the string arr [ i ] ; Push the pair of { i + 1 , j + 1 } in mp [ arr [ i ] [ j ] ] ; Print the occurences of every character ; D... | def printOccurences ( arr , N ) : NEW_LINE INDENT mp = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( len ( arr [ i ] ) ) : NEW_LINE INDENT mp [ ord ( arr [ i ] [ j ] ) - ord ( ' a ' ) ] . append ( ( i + 1 , j + 1 ) ) NEW_LINE DEDENT DEDENT for i in range ( 26 ) : NEW_LIN... |
Count of subarrays with X as the most frequent element , for each value of X from 1 to N | Function to calculate the number of subarrays where X ( 1 <= X <= N ) is the most frequent element ; array to store the final answers ; Array to store current frequencies ; Variable to store the current most frequent element ; Up... | def mostFrequent ( arr , N ) : NEW_LINE INDENT ans = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT count = [ 0 ] * N NEW_LINE best = 0 NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT count [ arr [ j ] - 1 ] += 1 NEW_LINE if ( count [ arr [ j ] - 1 ] > count [ best - 1 ] or ( count [ arr [ j ] - 1 ] == c... |
Count array elements whose highest power of 2 less than or equal to that number is present in the given array | Python program for the above approach ; Function to count array elements whose highest power of 2 is less than or equal to that number is present in the given array ; Stores the resultant count of array eleme... | from math import log2 NEW_LINE def countElement ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE m = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT m [ arr [ i ] ] = m . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT lg = int ( log2 ( arr [ i ] ) ) NEW_LINE p = pow ( 2 , lg ) NEW_... |
Maximum number of intersections possible for any of the N given segments | Python 3 program for the above approach ; Function to find the maximum number of intersections one segment has with all the other given segments ; Stores the resultant maximum count ; Stores the starting and the ending points ; Sort arrays point... | from bisect import bisect_left , bisect_right NEW_LINE def lower_bound ( a , low , high , element ) : NEW_LINE INDENT while ( low < high ) : NEW_LINE INDENT middle = low + ( high - low ) // 2 NEW_LINE if ( element > a [ middle ] ) : NEW_LINE INDENT low = middle + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = middle N... |
Program to find the Nth Composite Number | Function to find the Nth Composite Numbers using Sieve of Eratosthenes ; Sieve of prime numbers ; ; Iterate over the range [ 2 , 1000005 ] ; If IsPrime [ p ] is true ; Iterate over the range [ p * p , 1000005 ] ; Stores the list of composite numbers ; Iterate over the range [... | def NthComposite ( N ) : NEW_LINE INDENT IsPrime = [ True ] * 1000005 NEW_LINE DEDENT / * Initialize the array to true * / NEW_LINE INDENT for p in range ( 2 , 1000005 ) : NEW_LINE INDENT if p * p > 1000005 : NEW_LINE INDENT break NEW_LINE DEDENT if ( IsPrime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , 1... |
Intersection point of two Linked Lists | Set 3 | Structure of a node of a Linked List ; ; Function to find the intersection point of the two Linked Lists ; Traverse the first linked list and multiply all values by - 1 ; Update a . data ; Update a ; Traverse the second Linked List and find the value of the first node h... | class Node : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . next = None NEW_LINE DEDENT DEDENT / * Constructor * / def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . next = None NEW_LINE DEDENT def intersectingNode ( headA , headB ) : NEW_LINE INDENT... |
Modify array of strings by replacing characters repeating in the same or remaining strings | Function to remove duplicate characters across the strings ; Stores distinct characters ; Size of the array ; Stores the list of modified strings ; Traverse the array ; Stores the modified string ; Iterate over the characters o... | def removeDuplicateCharacters ( arr ) : NEW_LINE INDENT cset = set ( [ ] ) NEW_LINE n = len ( arr ) NEW_LINE out = [ ] NEW_LINE for st in arr : NEW_LINE INDENT out_curr = " " NEW_LINE for ch in st : NEW_LINE INDENT if ( ch in cset ) : NEW_LINE INDENT continue NEW_LINE DEDENT out_curr += ch NEW_LINE cset . add ( ch ) NE... |
Sum of array elements which are prime factors of a given number | Function to check if a number is prime or not ; Corner cases ; Check if n is a multiple of 2 or 3 ; Above condition allows to check only for every 6 th number , starting from 5 ; If n is a multiple of i and i + 2 ; Function to find the sum of array eleme... | def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2... |
Minimum number of array elements from either ends required to be subtracted from X to reduce X to 0 | Python3 Program to implement the above approach ; Function to count the minimum number of operations required to reduce x to 0 ; If sum of the array is less than x ; Stores the count of operations ; Two pointers to tra... | import math NEW_LINE def minOperations ( nums , x ) : NEW_LINE INDENT if sum ( nums ) < x : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans = math . inf NEW_LINE l , r = len ( nums ) - 1 , len ( nums ) NEW_LINE x -= sum ( nums ) NEW_LINE while l >= 0 : NEW_LINE INDENT if x <= 0 : NEW_LINE INDENT x += nums [ l ] NEW_LINE... |
Number of subarrays having even product | Function to count subarrays with even product ; Total number of subarrays ; Counter variables ; Traverse the array ; If current element is odd ; Update count of subarrays with odd product up to index i ; Print count of subarrays with even product ; Driver code ; Input ; Length ... | def evenproduct ( arr , length ) : NEW_LINE INDENT total_subarray = length * ( length + 1 ) // 2 NEW_LINE total_odd = 0 NEW_LINE count_odd = 0 NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT count_odd = 0 NEW_LINE DEDENT else : NEW_LINE INDENT count_odd += 1 NEW_LINE tot... |
Check if all rows of a Binary Matrix have all ones placed adjacently or not | Function to check if all 1 s are placed adjacently in an array or not ; Base Case ; Stores the sum of XOR of all pair of adjacent elements ; Calculate sum of XOR of all pair of adjacent elements ; Check for corner cases ; Return true ; Functi... | def checkGroup ( arr ) : NEW_LINE INDENT if len ( arr ) <= 2 : NEW_LINE INDENT return True NEW_LINE DEDENT corner = arr [ 0 ] + arr [ - 1 ] NEW_LINE xorSum = 0 NEW_LINE for i in range ( len ( arr ) - 1 ) : NEW_LINE INDENT xorSum += ( arr [ i ] ^ arr [ i + 1 ] ) NEW_LINE DEDENT if not corner : NEW_LINE INDENT if xorSum ... |
Print all numbers up to N having product of digits equal to K | Function to find the product of digits of a number ; Stores the product of digits of a number ; Return the product ; Function to print all numbers upto N having product of digits equal to K ; Stores whether any number satisfying the given conditions exists... | def productOfDigits ( N ) : NEW_LINE INDENT product = 1 ; NEW_LINE while ( N != 0 ) : NEW_LINE INDENT product = product * ( N % 10 ) ; NEW_LINE N = N // 10 ; NEW_LINE DEDENT return product ; NEW_LINE DEDENT def productOfDigitsK ( N , K ) : NEW_LINE INDENT flag = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDE... |
Minimize difference between maximum and minimum array elements by removing a K | Function to minimize difference between maximum and minimum array elements by removing a K - length subarray ; Size of array ; Stores the maximum and minimum in the suffix subarray [ i . . N - 1 ] ; Traverse the array ; Stores the maximum ... | def minimiseDifference ( arr , K ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE maxSuffix = [ 0 for i in range ( N + 1 ) ] NEW_LINE minSuffix = [ 0 for i in range ( N + 1 ) ] NEW_LINE maxSuffix [ N ] = - 1e9 NEW_LINE minSuffix [ N ] = 1e9 NEW_LINE maxSuffix [ N - 1 ] = arr [ N - 1 ] NEW_LINE minSuffix [ N - 1 ] = arr [ N... |
Minimize segments required to be removed such that at least one segment intersects with all remaining segments | Pyhton3 program for the above approach ; Function to find the minimum number of segments required to be deleted ; Stores the start and end points ; Traverse segments and fill the startPoints and endPoints ; ... | from bisect import bisect_left , bisect_right NEW_LINE def minSegments ( segments , n ) : NEW_LINE INDENT startPoints = [ 0 for i in range ( n ) ] NEW_LINE endPoints = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT startPoints [ i ] = segments [ i ] [ 0 ] NEW_LINE endPoints [ i ] = segments ... |
Longest substring where all the characters appear at least K times | Set 3 | Function to find the length of the longest substring ; Store the required answer ; Create a frequency map of the characters of the string ; Store the length of the string ; Traverse the string , s ; Increment the frequency of the current chara... | def longestSubstring ( s , k ) : NEW_LINE INDENT ans = 0 NEW_LINE freq = [ 0 ] * 26 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT unique = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] != 0 ) : NEW_LINE INDENT un... |
Print matrix elements using DFS traversal | Direction vectors ; Function to check if current position is valid or not ; Check if the cell is out of bounds ; Check if the cell is visited or not ; Utility function to prmatrix elements using DFS Traversal ; Mark the current cell visited ; Print element at the cell ; Trave... | dRow = [ - 1 , 0 , 1 , 0 ] NEW_LINE dCol = [ 0 , 1 , 0 , - 1 ] NEW_LINE def isValid ( row , col , COL , ROW ) : NEW_LINE INDENT global vis NEW_LINE if ( row < 0 or col < 0 or col > COL - 1 or row > ROW - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( vis [ row ] [ col ] == True ) : NEW_LINE INDENT return False... |
Print matrix elements using DFS traversal | Direction vectors ; Function to check if curruent position is valid or not ; Check if the cell is out of bounds ; Check if the cell is visited ; Function to print the matrix elements ; Stores if a position in the matrix been visited or not ; Initialize stack to implement DFS ... | dRow = [ - 1 , 0 , 1 , 0 ] NEW_LINE dCol = [ 0 , 1 , 0 , - 1 ] NEW_LINE vis = [ ] NEW_LINE def isValid ( row , col , COL , ROW ) : NEW_LINE INDENT global vis NEW_LINE if ( row < 0 or col < 0 or col > COL - 1 or row > ROW - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( vis [ row ] [ col ] == True ) : NEW_LINE ... |
Segregate 1 s and 0 s in separate halves of a Binary String | Function to count the minimum number of operations required to segregate all 1 s and 0 s in a binary string ; Stores the count of unequal pair of adjacent characters ; If an unequal pair of adjacent characters occurs ; For odd count ; For even count ; Given ... | def minOps ( s , N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( s [ i ] != s [ i - 1 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT if ( ans % 2 == 1 ) : NEW_LINE INDENT print ( ( ans - 1 ) // 2 ) NEW_LINE return NEW_LINE DEDENT print ( ans // 2 ) NEW_LINE DEDENT str = "01... |
Find index of the element differing in parity with all other array elements | Function to print the array element which differs in parity with the remaining array elements ; Multimaps to store even and odd numbers along with their indices ; Traverse the array ; If array element is even ; Otherwise ; If only one even el... | def OddOneOut ( arr , N ) : NEW_LINE INDENT e , o = { } , { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT e [ arr [ i ] ] = i NEW_LINE DEDENT else : NEW_LINE INDENT o [ arr [ i ] ] = i NEW_LINE DEDENT DEDENT if ( len ( e ) == 1 ) : NEW_LINE INDENT print ( list ( e . value... |
Count indices where the maximum in the prefix array is less than that in the suffix array | Function to print the count of indices in which the maximum in prefix arrays is less than that in the suffix array ; If size of array is 1 ; pre [ ] : Prefix array suf [ ] : Suffix array ; Stores the required count ; Find the ma... | def count ( a , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT pre = [ 0 ] * ( n - 1 ) NEW_LINE suf = [ 0 ] * ( n - 1 ) NEW_LINE max = a [ 0 ] NEW_LINE ans = 0 NEW_LINE pre [ 0 ] = a [ 0 ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( a [ i ] > max ) : NEW_L... |
Length of the longest subsequence such that XOR of adjacent elements is equal to K | Function to find maximum length of subsequence ; Stores maximum length of subsequence ; HashMap to store the longest length of subsequence ending at an integer , say X ; Stores the maximum length of subsequence ending at index i ; Base... | def xorSubsequence ( a , n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE map = { } NEW_LINE dp = [ 0 ] * n NEW_LINE map [ a [ 0 ] ] = 1 NEW_LINE dp [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] ^ k in map ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , map [ a [ i ] ^ k ] + 1 ) NEW_LINE DEDENT a... |
Sum of subtree depths for every node of a given Binary Tree | Binary tree node ; Constructor to set the data of the newly created tree node ; Function to allocate a new node with the given data and null in its left and right pointers ; DFS function to calculate the sum of depths of all subtrees depth sum ; Store total ... | class TreeNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE def newNode ( data ) : NEW_LINE INDENT Node = TreeNode ( data ) NEW_LINE return ( Node ) NEW_LINE DEDENT def sumofsubtree ( ... |
Minimum time required to fill given N slots | Function to return the minimum time to fill all the slots ; Stores visited slots ; Checks if a slot is visited or not ; Insert all filled slots ; Iterate until queue is not empty ; Iterate through all slots in the queue ; Front index ; If previous slot is present and not vi... | def minTime ( arr , N , K ) : NEW_LINE INDENT q = [ ] NEW_LINE vis = [ False ] * ( N + 1 ) NEW_LINE time = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT q . append ( arr [ i ] ) NEW_LINE vis [ arr [ i ] ] = True NEW_LINE DEDENT while ( len ( q ) > 0 ) : NEW_LINE INDENT for i in range ( len ( q ) ) : NEW_LINE INDENT... |
Count of integers having difference with its reverse equal to D | Maximum digits in N ; Utility function to find count of N such that N + D = reverse ( N ) ; If d is a multiple of 9 , no such value N found ; Divide D by 9 check reverse of number and its sum ; B [ i ] : Stores power of ( 10 , i ) ; Calculate power ( 10 ... | MAXL = 17 ; NEW_LINE N = 0 ; NEW_LINE v = 0 ; NEW_LINE def findN ( D ) : NEW_LINE INDENT global N ; NEW_LINE global v ; NEW_LINE if ( D % 9 != 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT D //= 9 ; NEW_LINE B = [ 0 ] * MAXL ; NEW_LINE B [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , MAXL ) : NEW_LINE INDENT B [ i ] = B ... |
Search for an element in a Mountain Array | Function to find the index of the peak element in the array ; Stores left most index in which the peak element can be found ; Stores right most index in which the peak element can be found ; Stores mid of left and right ; If element at mid is less than element at ( mid + 1 ) ... | def findPeak ( arr ) : NEW_LINE INDENT left = 0 NEW_LINE right = len ( arr ) - 1 NEW_LINE while ( left < right ) : NEW_LINE INDENT mid = left + ( right - left ) // 2 NEW_LINE if ( arr [ mid ] < arr [ ( mid + 1 ) ] ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid NEW_LINE DEDENT DEDE... |
Rearrange given array to obtain positive prefix sums at exactly X indices | Function to rearrange the array according to the given condition ; Using 2 nd operation making all values positive ; Sort the array ; Assign K = N - K ; Count number of zeros ; If number of zeros if greater ; Using 2 nd operation convert it int... | def rearrange ( a , n , x ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT a [ i ] = abs ( a [ i ] ) NEW_LINE DEDENT a = sorted ( a ) NEW_LINE x = n - x ; NEW_LINE z = a . count ( 0 ) NEW_LINE if ( x > n - z ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT for i in range ( 0 , n , 2 ) : NE... |
Maximize product of a strictly increasing or decreasing subarray | Function to find the maximum product of subarray in the array , arr [ ] ; Maximum positive product ending at the i - th index ; Minimum negative product ending at the current index ; Maximum product up to i - th index ; Check if an array element is posi... | def maxSubarrayProduct ( arr , n ) : NEW_LINE INDENT max_ending_here = 1 NEW_LINE min_ending_here = 1 NEW_LINE max_so_far = 0 NEW_LINE flag = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT max_ending_here = max_ending_here * arr [ i ] NEW_LINE min_ending_here = min ( min_ending... |
Number of connected components of a graph ( using Disjoint Set Union ) | Stores the parent of each vertex ; Function to find the topmost parent of vertex a ; If current vertex is the topmost vertex ; Otherwise , set topmost vertex of its parent as its topmost vertex ; Function to connect the component having vertex a w... | parent = [ 0 ] * ( 1000000 ) NEW_LINE def root ( a ) : NEW_LINE INDENT if ( a == parent [ a ] ) : NEW_LINE INDENT return a NEW_LINE DEDENT parent [ a ] = root ( parent [ a ] ) NEW_LINE return parent [ a ] NEW_LINE DEDENT def connect ( a , b ) : NEW_LINE INDENT a = root ( a ) NEW_LINE b = root ( b ) NEW_LINE if ( a != b... |
Remove all zero | Function to remove the rows or columns from the matrix which contains all 0 s elements ; Stores count of rows ; col [ i ] : Stores count of 0 s in current column ; row [ i ] : Stores count of 0 s in current row ; Traverse the matrix ; Stores count of 0 s in current row ; Update col [ j ] ; Update coun... | def removeZeroRowCol ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE col = [ 0 ] * ( n + 1 ) NEW_LINE row = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT col [ j ] += ( arr [ i ] [ j ] == 1 ) NEW_LINE count += ( arr [ i ] [ j ] == 1 ) NEW_... |
Find a pair of overlapping intervals from a given Set | Function to find a pair ( i , j ) such that i - th interval lies within the j - th interval ; Store interval and index of the interval in the form of { { l , r } , index } ; Traverse the array , arr [ ] [ ] ; Stores l - value of the interval ; Stores r - value of ... | def findOverlapSegement ( N , a , b ) : NEW_LINE INDENT tup = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = a [ i ] NEW_LINE y = b [ i ] NEW_LINE tup . append ( ( ( x , y ) , i ) ) NEW_LINE DEDENT tup . sort ( ) NEW_LINE curr = tup [ 0 ] [ 0 ] [ 1 ] NEW_LINE currPos = tup [ 0 ] [ 1 ] NEW_LINE for i in range (... |
Replace each node of a Binary Tree with the sum of all the nodes present in its diagonal | Structure of a tree node ; Function to replace each node with the sum of nodes at the same diagonal ; IF root is NULL ; Replace nodes ; Traverse the left subtree ; Traverse the right subtree ; Function to find the sum of all the ... | class TreeNode : NEW_LINE INDENT def __init__ ( self , val = 0 , left = None , right = None ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def replaceDiag ( root , d , diagMap ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return NEW_LINE DEDENT ... |
Count maximum concatenation of pairs from given array that are divisible by 3 | Function to count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; Stores count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; Check if an e... | def countDivBy3InArray ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE taken = [ False ] * len ( arr ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if taken [ i ] : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( i + 1 , len ( arr ) ) : NEW_LINE INDENT if taken [ j ] : NEW_LINE INDENT continue NEW_LIN... |
Longest increasing sequence possible by the boundary elements of an Array | Function to find longest strictly increasing sequence using boundary elements ; Maintains rightmost element in the sequence ; Pointer to start of array ; Pointer to end of array ; Stores the required sequence ; Traverse the array ; If arr [ i ]... | def findMaxLengthSequence ( N , arr ) : NEW_LINE INDENT rightmost_element = - 1 NEW_LINE i = 0 NEW_LINE j = N - 1 NEW_LINE sequence = [ ] NEW_LINE while ( i <= j ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] ) : NEW_LINE INDENT if ( arr [ j ] > rightmost_element ) : NEW_LINE INDENT sequence . append ( arr [ j ] ) NEW_... |
Maximum average of subtree values in a given Binary Tree | Structure of the Tree node ; Stores the result ; Function for finding maximum subtree average ; Checks if current node is not None and doesn 't have any children ; Stores sum of its subtree in index 0 and count number of nodes in index 1 ; Traverse all children... | class TreeNode : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . children = [ ] NEW_LINE DEDENT DEDENT ans = 0.0 NEW_LINE def MaxAverage ( root ) : NEW_LINE INDENT global ans NEW_LINE if ( root != None and len ( root . children ) == 0 ) : NEW_LINE INDENT ans = max ( ans , ... |
Check if a Binary String can be converted to another by reversing substrings consisting of even number of 1 s | Function to check if string A can be transformed to string B by reversing substrings of A having even number of 1 s ; Store the size of string A ; Store the size of string B ; Store the count of 1 s in A and ... | def canTransformStrings ( A , B ) : NEW_LINE INDENT n1 = len ( A ) ; NEW_LINE n2 = len ( B ) ; NEW_LINE count1A = 0 ; NEW_LINE count1B = 0 ; NEW_LINE odd1A = 0 ; odd1B = 0 ; NEW_LINE even1A = 0 ; even1B = 0 ; NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT if ( A [ i ] == '1' ) : NEW_LINE INDENT count1A += 1 ; NEW_LIN... |
Smallest element present in every subarray of all possible lengths | Function to print the common elements for all subarray lengths ; Function to find and store the minimum element present in all subarrays of all lengths from 1 to n ; Skip lengths for which answer [ i ] is - 1 ; Initialize minimum as the first element ... | def printAnswer ( answer , N ) : NEW_LINE INDENT for i in range ( N + 1 ) : NEW_LINE INDENT print ( answer [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def updateAnswerArray ( answer , N ) : NEW_LINE INDENT i = 0 NEW_LINE while ( answer [ i ] == - 1 ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT minimum = answer [ i ] NEW_... |
Minimize remaining array element by removing pairs and replacing them by their absolute difference | function to find the smallest element left in the array by the given operations ; Base Case ; If this subproblem has occurred previously ; Including i - th array element into the first subset ; If i - th array element i... | def smallestLeft ( arr , total , sum , i , dp ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT return abs ( total - 2 * sum ) NEW_LINE DEDENT if ( dp [ i ] [ sum ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ sum ] NEW_LINE DEDENT X = smallestLeft ( arr , total , sum + arr [ i - 1 ] , i - 1 , dp ) NEW_LINE Y = small... |
Minimize remaining array element by removing pairs and replacing them by their absolute difference | Function to find minimize the remaining array element by removing pairs and replacing them by their absolute difference ; Stores sum of array elements ; Traverse the array ; Update totalSum ; Stores half of totalSum ; d... | def SmallestElementLeft ( arr , N ) : NEW_LINE INDENT totalSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT totalSum += arr [ i ] NEW_LINE DEDENT req = totalSum // 2 NEW_LINE dp = [ False for i in range ( req + 1 ) ] NEW_LINE memset ( dp , false , sizeof ( dp ) ) ; NEW_LINE dp [ 0 ] = True NEW_LINE reach = 0 NEW... |
Replace even | Function to count the minimum number of substrings of str1 such that replacing even - indexed characters of those substrings converts the str1 to str2 ; Stores length of str1 ; Stores minimum count of operations to convert str1 to str2 ; Traverse both the given string ; If current character in both the s... | def minOperationsReq ( str11 , str22 ) : NEW_LINE INDENT str1 = list ( str11 ) NEW_LINE str2 = list ( str22 ) NEW_LINE N = len ( str1 ) NEW_LINE cntOp = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( str1 [ i ] == str2 [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT ptr = i NEW_LINE while ( ptr < N and str1 ... |
Check if GCD of all Composite Numbers in an array divisible by K is a Fibonacci Number or not | Python3 program for the above approach ; Function to check if a number is composite or not ; Corner cases ; Check if the number is divisible by 2 or 3 or not ; Check if n is a multiple of any other prime number ; Function to... | import math NEW_LINE def isComposite ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n <= 3 : NEW_LINE INDENT return False NEW_LINE DEDENT if n % 2 == 0 or n % 3 == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT i = 5 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( ( n % i == 0 ) o... |
Longest subarray in which all elements are a factor of K | Function to find the length of the longest subarray in which all elements are a factor of K ; Stores length of the longest subarray in which all elements are a factor of K ; Stores length of the current subarray ; Traverse the array arr [ ] ; If A [ i ] is a fa... | def find_longest_subarray ( A , N , K ) : NEW_LINE INDENT MaxLen = 0 NEW_LINE Len = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( K % A [ i ] == 0 ) : NEW_LINE INDENT Len += 1 NEW_LINE MaxLen = max ( MaxLen , Len ) NEW_LINE DEDENT else : NEW_LINE INDENT Len = 0 NEW_LINE DEDENT DEDENT return MaxLen NEW_LINE DED... |
Length of smallest meeting that can be attended | Python3 program to implement the above approach ; Function to find the minimum time to attend exactly one meeting ; Stores minimum time to attend exactly one meeting ; Sort entrance [ ] array ; Sort exit [ ] time ; Traverse meeting [ ] [ ] ; Stores start time of current... | from bisect import bisect_left , bisect_right NEW_LINE import sys NEW_LINE def minTime ( meeting , n , entrance , m , exit , p ) : NEW_LINE INDENT ans = sys . maxsize NEW_LINE entrance = sorted ( entrance ) NEW_LINE exit = sorted ( exit ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT u = meeting [ i ] [ 0 ] NEW_LINE ... |
Divide array into two arrays which does not contain any pair with sum K | Function to split the given array into two separate arrays satisfying given condition ; Stores resultant arrays ; Traverse the array ; If a [ i ] is smaller than or equal to k / 2 ; Print first array ; Print second array ; Driver Code ; Given K ;... | def splitArray ( a , n , k ) : NEW_LINE INDENT first = [ ] NEW_LINE second = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] <= k // 2 ) : NEW_LINE INDENT first . append ( a [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT second . append ( a [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( first ) ... |
Find all the queens attacking the king in a chessboard | Function to find the queen closest to king in an attacking position ; Function to find all the queens attacking the king in the chessboard ; Iterating over the coordinates of the queens ; If king is horizontally on the right of current queen ; If no attacker is p... | def dis ( ans , attacker ) : NEW_LINE INDENT return ( abs ( ans [ 0 ] - attacker [ 0 ] ) + abs ( ans [ 1 ] - attacker [ 1 ] ) ) NEW_LINE DEDENT def findQueens ( queens , king ) : NEW_LINE INDENT sol = [ ] NEW_LINE attackers = [ [ 0 for x in range ( 8 ) ] for y in range ( 8 ) ] NEW_LINE for i in range ( len ( queens ) )... |
Count numbers in a given range whose count of prime factors is a Prime Number | Python3 program to implement the above approach ; Function to find the smallest prime factor of all the numbers in range [ 0 , MAX ] ; Stores smallest prime factor of all the numbers in the range [ 0 , MAX ] ; No smallest prime factor of 0 ... | MAX = 1001 NEW_LINE def sieve ( ) : NEW_LINE INDENT global MAX NEW_LINE spf = [ 0 ] * MAX NEW_LINE spf [ 0 ] = spf [ 1 ] = - 1 NEW_LINE for i in range ( 2 , MAX ) : NEW_LINE INDENT spf [ i ] = i NEW_LINE DEDENT for i in range ( 4 , MAX , 2 ) : NEW_LINE INDENT spf [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , MAX ) : N... |
Maximum number of Perfect Numbers present in a subarray of size K | Function to check a number is Perfect Number or not ; Stores sum of divisors ; Find all divisors and add them ; If sum of divisors is equal to N ; Function to return maximum sum of a subarray of size K ; If k is greater than N ; Compute sum of first wi... | def isPerfect ( N ) : NEW_LINE INDENT sum = 1 NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( i == N // i ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT else : NEW_LINE INDENT sum += i + N // i NEW_LINE DEDENT DEDENT DEDENT ... |
Count greater elements on the left side of every array element | Function to print the count of greater elements on left of each array element ; Function to get the count of greater elements on left of each array element ; Store distinct array elements in sorted order ; Stores the count of greater elements on the left ... | def display ( countLeftGreater , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( countLeftGreater [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def countGreater ( arr , N ) : NEW_LINE INDENT St = set ( ) NEW_LINE countLeftGreater = [ 0 ] * ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT St . a... |
Count characters to be shifted from the start or end of a string to obtain another string | Function to find the minimum cost to convert string A to string B ; Length of string ; Initialize maxlen as 0 ; Traverse the string A ; Stores the length of substrings of string A ; Traversing string B for each character of A ; ... | def minCost ( A , B ) : NEW_LINE INDENT n = len ( A ) ; NEW_LINE i = 0 ; NEW_LINE maxlen = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT length = 0 ; NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( A [ i ] == B [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE length += 1 ; NEW_LINE if ( i == n ) : NEW_LINE INDENT br... |
Lexicographic rank of a string among all its substrings | Function to find lexicographic rank of among all its substring ; Length of string ; Traverse the given string and store the indices of each character ; Extract the index ; Store it in the vector ; Traverse the alphaIndex array lesser than the index of first char... | def lexicographicRank ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE alphaIndex = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT x = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE alphaIndex [ x ] . append ( i ) NEW_LINE DEDENT rank = - 1 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT... |
Find H | Function to find the H - index ; Set the range for binary search ; Check if current citations is possible ; Check to the right of mid ; Update h - index ; Since current value is not possible , check to the left of mid ; Print the h - index ; citations | def hIndex ( citations , n ) : NEW_LINE INDENT hindex = 0 NEW_LINE low = 0 NEW_LINE high = n - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( citations [ mid ] >= ( mid + 1 ) ) : NEW_LINE INDENT low = mid + 1 NEW_LINE hindex = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hi... |
Check if all strings of an array can be made same by interchanging characters | Function to check if all strings are equal after swap operations ; Stores the frequency of characters ; Stores the length of string ; Traverse the array ; Traverse each string ; Check if frequency of character is divisible by N ; Driver Cod... | def checkEqual ( arr , N ) : NEW_LINE INDENT hash = [ 0 ] * 256 NEW_LINE M = len ( arr [ 0 ] ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT hash [ ord ( arr [ i ] [ j ] ) ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 256 ) : NEW_LINE INDENT if ( hash [ i ] % N != 0 ) : NEW_LIN... |
Maximize sum of remaining elements after every removal of the array half with greater sum | Function to find the maximum sum ; Base Case ; Create a key to map the values ; Check if mapped key is found in the dictionary ; Traverse the array ; Store left prefix sum ; Store right prefix sum ; Compare the left and right va... | def maxweight ( s , e , pre , dp ) : NEW_LINE INDENT if s == e : NEW_LINE INDENT return 0 NEW_LINE DEDENT key = ( s , e ) NEW_LINE if key in dp : NEW_LINE INDENT return dp [ key ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( s , e ) : NEW_LINE INDENT left = pre [ i ] - pre [ s - 1 ] NEW_LINE right = pre [ e ] - pr... |
Find K smallest leaf nodes from a given Binary Tree | Binary tree node ; Function to create new node ; Utility function which calculates smallest three nodes of all leaf nodes ; Check if current root is a leaf node ; Traverse the left and right subtree ; Function to find the K smallest nodes of the Binary Tree ; Sortin... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def st... |
Check if all the pairs of an array are coprime with each other | Python3 implementation of the above approach ; Function to check if all the pairs of the array are coprime with each other or not ; Check if GCD of the pair is not equal to 1 ; All pairs are non - coprime Return false ; ; Driver code | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( b , a % b ) NEW_LINE DEDENT DEDENT def allCoprime ( A , n ) : NEW_LINE INDENT all_coprime = True NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT... |
Smallest power of 2 consisting of N digits | Python3 program of the above approach ; Function to return smallest power of 2 with N digits ; Driver Code | from math import log2 , ceil NEW_LINE def smallestNum ( n ) : NEW_LINE INDENT power = log2 ( 10 ) NEW_LINE print ( power ) ; NEW_LINE return ceil ( ( n - 1 ) * power ) NEW_LINE DEDENT n = 4 NEW_LINE print ( smallestNum ( n ) ) NEW_LINE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.