text
stringlengths
1
636
code
stringlengths
8
1.89k
Build the segment tree for range max query
build ( A , 0 , N - 1 , 0 ) ; NEW_LINE
Loop through the array with a starting point as i for the required subarray till the longest subarray is found
for i in range ( N ) : NEW_LINE INDENT start = i ; NEW_LINE end = N - 1 ; NEW_LINE max_index = i ; NEW_LINE DEDENT
Performing the binary search to find the endpoint for the selected range
while ( start <= end ) : NEW_LINE
Find the mid for binary search
mid = ( start + end ) // 2 ; NEW_LINE
Find the max element in the range [ i , mid ] using Segment Tree
max_element = query ( 0 , N - 1 , i , mid , 0 ) ; NEW_LINE
Total sum of subarray after increments
expected_sum = ( mid - i + 1 ) * max_element ; NEW_LINE
Actual sum of elements before increments
actual_sum = preSum [ mid + 1 ] - preSum [ i ] ; NEW_LINE
Check if such increment is possible If true , then current i is the actual starting point of the required longest subarray
if ( expected_sum - actual_sum <= K ) : NEW_LINE
Now for finding the endpoint for this range Perform the Binary search again with the updated start
start = mid + 1 ; NEW_LINE
Store max end point for the range to give longest subarray
max_index = max ( max_index , mid ) ; NEW_LINE
If false , it means that the selected range is invalid
else : NEW_LINE
Perform the Binary Search again with the updated end
end = mid - 1 ; NEW_LINE
Store the length of longest subarray
res = max ( res , max_index - i + 1 ) ; NEW_LINE
Return result
return res ; NEW_LINE
Driver code
if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 0 , 4 , 6 , 7 ] ; K = 6 ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( longestSubArray ( arr , N , K ) ) ; NEW_LINE DEDENT
Function to return the count of the required numbers
def countNums ( l , r ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE DEDENT
Last digit of the current number
lastDigit = ( i % 10 ) ; NEW_LINE
If the last digit is equal to any of the given digits
if ( ( lastDigit % 10 ) == 2 or ( lastDigit % 10 ) == 3 or ( lastDigit % 10 ) == 9 ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT return cnt ; NEW_LINE
Driver code
if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 11 ; r = 33 ; NEW_LINE print ( countNums ( l , r ) ) ; NEW_LINE DEDENT
Function to return the minimum value of k that satisfies the given condition
def findMinimumK ( a , n , s ) : NEW_LINE
Find the maximum element
maximum = a [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT maximum = max ( maximum , a [ i ] ) NEW_LINE DEDENT
Lowest answer can be 1 and the highest answer can be ( maximum + 1 )
low = 1 NEW_LINE high = maximum + 1 NEW_LINE ans = high NEW_LINE
Binary search
while ( low <= high ) : NEW_LINE
Get the mid element
mid = ( low + high ) // 2 NEW_LINE sum = 0 NEW_LINE
Calculate the sum after dividing the array by new K which is mid
for i in range ( n ) : NEW_LINE INDENT sum += ( a [ i ] // mid ) NEW_LINE DEDENT
Search in the second half
if ( sum > s ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT
First half
else : NEW_LINE INDENT ans = min ( ans , mid ) NEW_LINE high = mid - 1 NEW_LINE DEDENT return ans NEW_LINE
Driver code
a = [ 10 , 7 , 8 , 10 , 12 , 19 ] NEW_LINE n = len ( a ) NEW_LINE s = 27 NEW_LINE print ( findMinimumK ( a , n , s ) ) NEW_LINE
Python3 program to find Sum of GCD over all subarrays
from math import gcd as __gcd , log , floor NEW_LINE
Build Sparse Table
def buildSparseTable ( a , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT SparseTable [ i ] [ 0 ] = a [ i ] NEW_LINE DEDENT DEDENT
Building the Sparse Table for GCD [ L , R ] Queries
for j in range ( 1 , 20 ) : NEW_LINE INDENT for i in range ( n - ( 1 << j ) + 1 ) : NEW_LINE INDENT SparseTable [ i ] [ j ] = __gcd ( SparseTable [ i ] [ j - 1 ] , SparseTable [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT
Utility Function to calculate GCD in range [ L , R ]
def queryForGCD ( L , R ) : NEW_LINE
Calculating where the answer is stored in our Sparse Table
j = floor ( log ( R - L + 1 , 2 ) ) NEW_LINE returnValue = __gcd ( SparseTable [ L ] [ j ] , SparseTable [ R - ( 1 << j ) + 1 ] [ j ] ) NEW_LINE return returnValue NEW_LINE
Utility Function to find next - farther position where gcd is same
def nextPosition ( tempGCD , startPointer , prevEndPointer , n ) : NEW_LINE INDENT high = n - 1 NEW_LINE low = prevEndPointer NEW_LINE mid = prevEndPointer NEW_LINE nextPos = prevEndPointer NEW_LINE DEDENT
BinarySearch for Next Position for EndPointer
while ( high >= low ) : NEW_LINE INDENT mid = ( ( high + low ) >> 1 ) NEW_LINE if ( queryForGCD ( startPointer , mid ) == tempGCD ) : NEW_LINE INDENT nextPos = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return nextPos + 1 NEW_LINE
Utility function to calculate sum of gcd
def calculateSum ( a , n ) : NEW_LINE INDENT buildSparseTable ( a , n ) NEW_LINE tempAns = 0 NEW_LINE for i in range ( n ) : NEW_LINE DEDENT
Initializing all the values
endPointer = i NEW_LINE startPointer = i NEW_LINE prevEndPointer = i NEW_LINE tempGCD = a [ i ] NEW_LINE while ( endPointer < n ) : NEW_LINE
Finding the next position for endPointer
endPointer = nextPosition ( tempGCD , startPointer , prevEndPointer , n ) NEW_LINE
Adding the suitable sum to our answer
tempAns += ( ( endPointer - prevEndPointer ) * tempGCD ) NEW_LINE
Changing prevEndPointer
prevEndPointer = endPointer NEW_LINE if ( endPointer < n ) : NEW_LINE
Recalculating tempGCD
tempGCD = __gcd ( tempGCD , a [ endPointer ] ) NEW_LINE return tempAns NEW_LINE
Driver code
if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE a = [ 2 , 2 , 2 , 3 , 5 , 5 ] NEW_LINE print ( calculateSum ( a , n ) ) NEW_LINE DEDENT
Standard Lomuto partition function
def partition ( arr , low , high ) : NEW_LINE INDENT pivot = arr [ high ] NEW_LINE i = ( low - 1 ) NEW_LINE for j in range ( low , high ) : NEW_LINE INDENT if arr [ j ] <= pivot : NEW_LINE INDENT i += 1 NEW_LINE arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE DEDENT DEDENT arr [ i + 1 ] , arr [ high ] = arr [ high ] , arr [ i + 1 ] NEW_LINE return ( i + 1 ) NEW_LINE DEDENT
Implementation of QuickSelect
def kthSmallest ( a , left , right , k ) : NEW_LINE INDENT while left <= right : NEW_LINE DEDENT
Partition a [ left . . right ] around a pivot and find the position of the pivot
pivotIndex = partition ( a , left , right ) NEW_LINE
If pivot itself is the k - th smallest element
if pivotIndex == k - 1 : NEW_LINE INDENT return a [ pivotIndex ] NEW_LINE DEDENT
If there are more than k - 1 elements on left of pivot , then k - th smallest must be on left side .
elif pivotIndex > k - 1 : NEW_LINE INDENT right = pivotIndex - 1 NEW_LINE DEDENT
Else k - th smallest is on right side .
else : NEW_LINE INDENT left = pivotIndex + 1 NEW_LINE DEDENT return - 1 NEW_LINE
Driver Code
arr = [ 10 , 4 , 5 , 8 , 11 , 6 , 26 ] NEW_LINE n = len ( arr ) NEW_LINE k = 5 NEW_LINE print ( " K - th ▁ smallest ▁ element ▁ is " , kthSmallest ( arr , 0 , n - 1 , k ) ) NEW_LINE
Function to find pair with largest sum which is less than K in the array
def Max_Sum ( arr , n , k ) : NEW_LINE
To store the break point
p = n NEW_LINE
Sort the given array
arr . sort ( ) NEW_LINE
Find the break point
for i in range ( 0 , n ) : NEW_LINE
No need to look beyond i 'th index
if ( arr [ i ] >= k ) : NEW_LINE INDENT p = i NEW_LINE break NEW_LINE DEDENT maxsum = 0 NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE
Find the required pair
for i in range ( 0 , p ) : NEW_LINE INDENT for j in range ( i + 1 , p ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] < k and arr [ i ] + arr [ j ] > maxsum ) : NEW_LINE INDENT maxsum = arr [ i ] + arr [ j ] NEW_LINE a = arr [ i ] NEW_LINE b = arr [ j ] NEW_LINE DEDENT DEDENT DEDENT
Print the required answer
print ( a , b ) NEW_LINE
Driver code
arr = [ 5 , 20 , 110 , 100 , 10 ] NEW_LINE k = 85 NEW_LINE n = len ( arr ) NEW_LINE
Function call
Max_Sum ( arr , n , k ) NEW_LINE
Function that returns true if str [ i ... j ] is a palindrome
def isPalindrome ( str , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( str [ i ] != str [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT
Function to return the length of the longest palindromic sub - string such that it starts and ends with the character ch
def maxLenPalindrome ( str , n , ch ) : NEW_LINE INDENT maxLen = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE DEDENT
If current character is a valid starting index
if ( str [ i ] == ch ) : NEW_LINE
Instead of finding the ending index from the beginning , find the index from the end This is because if the current sub - string is a palindrome then there is no need to check the sub - strings of smaller length and we can skip to the next iteration of the outer loop
for j in range ( n - 1 , i + 1 , - 1 ) : NEW_LINE
If current character is a valid ending index
if ( str [ j ] == ch ) : NEW_LINE
If str [ i ... j ] is a palindrome then update the length of the maximum palindrome so far
if ( isPalindrome ( str , i , j ) ) : NEW_LINE INDENT maxLen = max ( maxLen , j - i + 1 ) ; NEW_LINE break ; NEW_LINE DEDENT return maxLen ; NEW_LINE
Driver code
str = " lapqooqpqpl " ; NEW_LINE n = len ( str ) ; NEW_LINE ch = ' p ' ; NEW_LINE print ( maxLenPalindrome ( str , n , ch ) ) ; NEW_LINE
Function to find the starting and the ending index of the sub - array with equal number of alphabets and numeric digits
def findSubArray ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE maxsize = - 1 NEW_LINE startindex = 0 NEW_LINE for i in range ( n ) : NEW_LINE DEDENT
If its an alphabet
if ( arr [ i ] . isalpha ( ) ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT
Else its a number
else : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT
Pick a starting poas i
for i in range ( n - 1 ) : NEW_LINE INDENT if arr [ i ] == '1' : NEW_LINE INDENT sum = 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum = - 1 NEW_LINE DEDENT DEDENT
Consider all sub - arrays starting from i
for j in range ( i + 1 , n ) : NEW_LINE INDENT if arr [ j ] == 0 : NEW_LINE INDENT sum -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum += 1 NEW_LINE DEDENT DEDENT
If this is a 0 sum sub - array then compare it with maximum size sub - array calculated so far
if ( sum == 0 and maxsize < j - i + 1 ) : NEW_LINE INDENT maxsize = j - i + 1 NEW_LINE startindex = i NEW_LINE DEDENT
If no valid sub - array found
if ( maxsize == - 1 ) : NEW_LINE INDENT print ( maxsize , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( startindex , ( startindex + maxsize - 1 ) ) NEW_LINE DEDENT
Driver code
arr = [ ' A ' , ' B ' , ' X ' , '4' , '6' , ' X ' , ' a ' ] NEW_LINE size = len ( arr ) NEW_LINE findSubArray ( arr , size ) NEW_LINE
Python 3 implementation of the approach
MAX = 26 NEW_LINE
Function to sort the given string using counting sort
def countingsort ( s ) : NEW_LINE
Array to store the count of each character
count = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT count [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT index = 0 NEW_LINE
Insert characters in the string in increasing order
for i in range ( MAX ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < count [ i ] ) : NEW_LINE INDENT s = s . replace ( s [ index ] , chr ( 97 + i ) ) NEW_LINE index += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT
Function that returns true if str can be generated from any permutation of the two strings selected from the given vector
def isPossible ( v , str1 ) : NEW_LINE
Sort the given string
countingsort ( str1 ) ; NEW_LINE
Select two strings at a time from given vector
for i in range ( len ( v ) - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , len ( v ) , 1 ) : NEW_LINE DEDENT
Get the concatenated string
temp = v [ i ] + v [ j ] NEW_LINE
Sort the resultant string
countingsort ( temp ) NEW_LINE
If the resultant string is equal to the given string str
if ( temp == str1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT
No valid pair found
return True NEW_LINE
Driver code
if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " amazon " NEW_LINE v = [ " fds " , " oxq " , " zoa " , " epw " , " amn " ] NEW_LINE if ( isPossible ( v , str1 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Maximum distinct characters possible
MAX = 256 NEW_LINE
To store the frequency of the characters
freq = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE
Function to pre - calculate the frequency array
def preCalculate ( string , n ) : NEW_LINE
Only the first character has frequency 1 till index 0
freq [ ord ( string [ 0 ] ) ] [ 0 ] = 1 NEW_LINE
Starting from the second character of the string
for i in range ( 1 , n ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE DEDENT
For every possible character
for j in range ( MAX ) : NEW_LINE
Current character under consideration
charToUpdate = chr ( j ) NEW_LINE
If it is equal to the character at the current index
if charToUpdate == ch : NEW_LINE INDENT freq [ j ] [ i ] = freq [ j ] [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ j ] [ i ] = freq [ j ] [ i - 1 ] NEW_LINE DEDENT
Function to return the frequency of the given character in the sub - string str [ l ... r ]
def getFrequency ( ch , l , r ) : NEW_LINE INDENT if l == 0 : NEW_LINE INDENT return freq [ ord ( ch ) ] [ r ] NEW_LINE DEDENT else : NEW_LINE INDENT return ( freq [ ord ( ch ) ] [ r ] - freq [ ord ( ch ) ] [ l - 1 ] ) NEW_LINE DEDENT DEDENT
Function to return the first non - repeating character in range [ l . . r ]
def firstNonRepeating ( string , n , l , r ) : NEW_LINE INDENT t = [ " " ] * 2 NEW_LINE DEDENT
Starting from the first character
for i in range ( l , r ) : NEW_LINE
Current character
ch = string [ i ] NEW_LINE
If frequency of the current character is 1 then return the character
if getFrequency ( ch , l , r ) == 1 : NEW_LINE INDENT t [ 0 ] = ch NEW_LINE return t [ 0 ] NEW_LINE DEDENT
All the characters of the sub - string are repeating
return " - 1" NEW_LINE
Driver Code
if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GeeksForGeeks " NEW_LINE n = len ( string ) NEW_LINE queries = [ ( 0 , 3 ) , ( 2 , 3 ) , ( 5 , 12 ) ] NEW_LINE q = len ( queries ) NEW_LINE DEDENT