code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
---|---|---|
# Python program to implement Manacher's Algorithm
def findLongestPalindromicString(text):
N = len(text)
if N == 0:
return
N = 2*N+1 # Position count
L = [0] * N
L[0] = 0
L[1] = 1
C = 1 # centerPosition
R = 2 # centerRightPosition
i = 0 # currentRightPosition
iMirror = 0 # currentLeftPosition
maxLPSLength = 0
maxLPSCenterPosition = 0
start = -1
end = -1
diff = -1
# Uncomment it to print LPS Length array
# printf("%d %d ", L[0], L[1]);
for i in range(2,N):
# get currentLeftPosition iMirror for currentRightPosition i
iMirror = 2*C-i
L[i] = 0
diff = R - i
# If currentRightPosition i is within centerRightPosition R
if diff > 0:
L[i] = min(L[iMirror], diff)
# Attempt to expand palindrome centered at currentRightPosition i
# Here for odd positions, we compare characters and
# if match then increment LPS Length by ONE
# If even position, we just increment LPS by ONE without
# any character comparison
try:
while ((i + L[i]) < N and (i - L[i]) > 0) and \
(((i + L[i] + 1) % 2 == 0) or \
(text[(i + L[i] + 1) // 2] == text[(i - L[i] - 1) // 2])):
L[i]+=1
except Exception as e:
pass
if L[i] > maxLPSLength: # Track maxLPSLength
maxLPSLength = L[i]
maxLPSCenterPosition = i
# If palindrome centered at currentRightPosition i
# expand beyond centerRightPosition R,
# adjust centerPosition C based on expanded palindrome.
if i + L[i] > R:
C = i
R = i + L[i]
# Uncomment it to print LPS Length array
# printf("%d ", L[i]);
start = (maxLPSCenterPosition - maxLPSLength) // 2
end = start + maxLPSLength - 1
print ("LPS of string is " + text + " : ",text[start:end+1])
# Driver program
text1 = "babcbabcbaccba"
findLongestPalindromicString(text1)
text2 = "abaaba"
findLongestPalindromicString(text2)
text3 = "abababa"
findLongestPalindromicString(text3)
text4 = "abcbabcbabcba"
findLongestPalindromicString(text4)
text5 = "forgeeksskeegfor"
findLongestPalindromicString(text5)
text6 = "caba"
findLongestPalindromicString(text6)
text7 = "abacdfgdcaba"
findLongestPalindromicString(text7)
text8 = "abacdfgdcabba"
findLongestPalindromicString(text8)
text9 = "abacdedcaba"
findLongestPalindromicString(text9)
# This code is contributed by BHAVYA JAIN | linear | linear |
# Python 3 program to print the
# string in 'plus' pattern
max = 100
# Function to make a cross
# in the matrix
def carveCross(str):
n = len(str)
if (n % 2 == 0) :
''' As, it is not possible to make
the cross exactly in the middle of
the matrix with an even length string.'''
print("Not possible. Please enter "
, "odd length string.\n")
else :
# declaring a 2D array i.e a matrix
arr = [[ False for x in range(max)]
for y in range(max)]
m = n // 2
''' Now, we will fill all the
elements of the array with 'X'''
for i in range( n) :
for j in range(n) :
arr[i][j] = 'X'
'''Now, we will place the characters
of the string in the matrix, such
that a cross is formed in it.'''
for i in range(n):
''' here the characters of the
string will be added in the
middle column of our array.'''
arr[i][m] = str[i]
for i in range(n):
# here the characters of the
# string will be added in the
# middle row of our array.
arr[m][i] = str[i]
# Now finally, we will print
# the array
for i in range(n):
for j in range(n):
print( arr[i][j] , end=" ")
print()
# Driver Code
if __name__ == "__main__":
str = "PICTURE"
carveCross(str)
# This code is contributed
# by ChitraNayal | constant | quadratic |
# Python3 program to implement
# wildcard pattern matching
# algorithm
# Function that matches input
# txt with given wildcard pattern
def stringmatch(txt, pat, n, m):
# empty pattern can only
# match with empty sting
# Base case
if (m == 0):
return (n == 0)
# step 1
# initialize markers :
i = 0
j = 0
index_txt = -1
index_pat = -1
while(i < n - 2):
# For step - (2, 5)
if (j < m and txt[i] == pat[j]):
i += 1
j += 1
# For step - (3)
elif(j < m and pat[j] == '?'):
i += 1
j += 1
# For step - (4)
elif(j < m and pat[j] == '*'):
index_txt = i
index_pat = j
j += 1
# For step - (5)
elif(index_pat != -1):
j = index_pat + 1
i = index_txt + 1
index_txt += 1
# For step - (6)
else:
return False
# For step - (7)
while (j < m and pat[j] == '*'):
j += 1
# Final Check
if(j == m):
return True
return False
# Driver code
strr = "baaabab"
pattern = "*****ba*****ab"
# char pattern[] = "ba*****ab"
# char pattern[] = "ba * ab"
# char pattern[] = "a * ab"
if (stringmatch(strr, pattern, len(strr),
len(pattern))):
print("Yes")
else:
print( "No")
pattern2 = "a*****ab";
if (stringmatch(strr, pattern2, len(strr),
len(pattern2))):
print("Yes")
else:
print( "No")
# This code is contributed
# by sahilhelangia | constant | linear |
# Python3 program to replace c1 with c2
# and c2 with c1
def replace(s, c1, c2):
l = len(s)
# loop to traverse in the string
for i in range(l):
# check for c1 and replace
if (s[i] == c1):
s = s[0:i] + c2 + s[i + 1:]
# check for c2 and replace
elif (s[i] == c2):
s = s[0:i] + c1 + s[i + 1:]
return s
# Driver Code
if __name__ == '__main__':
s = "grrksfoegrrks"
c1 = 'e'
c2 = 'r'
print(replace(s, c1, c2))
# This code is contributed
# by PrinciRaj1992 | constant | linear |
# Python program for implementation of
# Aho-Corasick algorithm for string matching
# defaultdict is used only for storing the final output
# We will return a dictionary where key is the matched word
# and value is the list of indexes of matched word
from collections import defaultdict
# For simplicity, Arrays and Queues have been implemented using lists.
# If you want to improve performance try using them instead
class AhoCorasick:
def __init__(self, words):
# Max number of states in the matching machine.
# Should be equal to the sum of the length of all keywords.
self.max_states = sum([len(word) for word in words])
# Maximum number of characters.
# Currently supports only alphabets [a,z]
self.max_characters = 26
# OUTPUT FUNCTION IS IMPLEMENTED USING out []
# Bit i in this mask is 1 if the word with
# index i appears when the machine enters this state.
# Lets say, a state outputs two words "he" and "she" and
# in our provided words list, he has index 0 and she has index 3
# so value of out[state] for this state will be 1001
# It has been initialized to all 0.
# We have taken one extra state for the root.
self.out = [0]*(self.max_states+1)
# FAILURE FUNCTION IS IMPLEMENTED USING fail []
# There is one value for each state + 1 for the root
# It has been initialized to all -1
# This will contain the fail state value for each state
self.fail = [-1]*(self.max_states+1)
# GOTO FUNCTION (OR TRIE) IS IMPLEMENTED USING goto [[]]
# Number of rows = max_states + 1
# Number of columns = max_characters i.e 26 in our case
# It has been initialized to all -1.
self.goto = [[-1]*self.max_characters for _ in range(self.max_states+1)]
# Convert all words to lowercase
# so that our search is case insensitive
for i in range(len(words)):
words[i] = words[i].lower()
# All the words in dictionary which will be used to create Trie
# The index of each keyword is important:
# "out[state] & (1 << i)" is > 0 if we just found word[i]
# in the text.
self.words = words
# Once the Trie has been built, it will contain the number
# of nodes in Trie which is total number of states required <= max_states
self.states_count = self.__build_matching_machine()
# Builds the String matching machine.
# Returns the number of states that the built machine has.
# States are numbered 0 up to the return value - 1, inclusive.
def __build_matching_machine(self):
k = len(self.words)
# Initially, we just have the 0 state
states = 1
# Convalues for goto function, i.e., fill goto
# This is same as building a Trie for words[]
for i in range(k):
word = self.words[i]
current_state = 0
# Process all the characters of the current word
for character in word:
ch = ord(character) - 97 # Ascii value of 'a' = 97
# Allocate a new node (create a new state)
# if a node for ch doesn't exist.
if self.goto[current_state][ch] == -1:
self.goto[current_state][ch] = states
states += 1
current_state = self.goto[current_state][ch]
# Add current word in output function
self.out[current_state] |= (1<<i)
# For all characters which don't have
# an edge from root (or state 0) in Trie,
# add a goto edge to state 0 itself
for ch in range(self.max_characters):
if self.goto[0][ch] == -1:
self.goto[0][ch] = 0
# Failure function is computed in
# breadth first order using a queue
queue = []
# Iterate over every possible input
for ch in range(self.max_characters):
# All nodes of depth 1 have failure
# function value as 0. For example,
# in above diagram we move to 0
# from states 1 and 3.
if self.goto[0][ch] != 0:
self.fail[self.goto[0][ch]] = 0
queue.append(self.goto[0][ch])
# Now queue has states 1 and 3
while queue:
# Remove the front state from queue
state = queue.pop(0)
# For the removed state, find failure
# function for all those characters
# for which goto function is not defined.
for ch in range(self.max_characters):
# If goto function is defined for
# character 'ch' and 'state'
if self.goto[state][ch] != -1:
# Find failure state of removed state
failure = self.fail[state]
# Find the deepest node labeled by proper
# suffix of String from root to current state.
while self.goto[failure][ch] == -1:
failure = self.fail[failure]
failure = self.goto[failure][ch]
self.fail[self.goto[state][ch]] = failure
# Merge output values
self.out[self.goto[state][ch]] |= self.out[failure]
# Insert the next level node (of Trie) in Queue
queue.append(self.goto[state][ch])
return states
# Returns the next state the machine will transition to using goto
# and failure functions.
# current_state - The current state of the machine. Must be between
# 0 and the number of states - 1, inclusive.
# next_input - The next character that enters into the machine.
def __find_next_state(self, current_state, next_input):
answer = current_state
ch = ord(next_input) - 97 # Ascii value of 'a' is 97
# If goto is not defined, use
# failure function
while self.goto[answer][ch] == -1:
answer = self.fail[answer]
return self.goto[answer][ch]
# This function finds all occurrences of all words in text.
def search_words(self, text):
# Convert the text to lowercase to make search case insensitive
text = text.lower()
# Initialize current_state to 0
current_state = 0
# A dictionary to store the result.
# Key here is the found word
# Value is a list of all occurrences start index
result = defaultdict(list)
# Traverse the text through the built machine
# to find all occurrences of words
for i in range(len(text)):
current_state = self.__find_next_state(current_state, text[i])
# If match not found, move to next state
if self.out[current_state] == 0: continue
# Match found, store the word in result dictionary
for j in range(len(self.words)):
if (self.out[current_state] & (1<<j)) > 0:
word = self.words[j]
# Start index of word is (i-len(word)+1)
result[word].append(i-len(word)+1)
# Return the final result dictionary
return result
# Driver code
if __name__ == "__main__":
words = ["he", "she", "hers", "his"]
text = "ahishers"
# Create an Object to initialize the Trie
aho_chorasick = AhoCorasick(words)
# Get the result
result = aho_chorasick.search_words(text)
# Print the result
for word in result:
for i in result[word]:
print("Word", word, "appears from", i, "to", i+len(word)-1)
# This code is contributed by Md Azharuddin | linear | linear |
# Python program to calculate number of times
# the pattern occurred in given string
# Returns count of occurrences of "1(0+)1"
def countPattern(s):
length = len(s)
oneSeen = False
count = 0 # Initialize result
for i in range(length):
# Check if encountered '1' forms a valid
# pattern as specified
if (s[i] == '1' and oneSeen):
if (s[i - 1] == '0'):
count += 1
# if 1 encountered for first time
# set oneSeen to 1
if (s[i] == '1' and oneSeen == 0):
oneSeen = True
# Check if there is any other character
# other than '0' or '1'. If so then set
# oneSeen to 0 to search again for new
# pattern
if (s[i] != '0' and s[i] != '1'):
oneSeen = False
return count
# Driver code
s = "100001abc101"
print(countPattern(s))
# This code is contributed by Sachin Bisht | constant | linear |
# Python3 program to find if a string follows
# order defined by a given pattern
CHAR_SIZE = 256
# Returns true if characters of str follow
# order defined by a given ptr.
def checkPattern(Str, pat):
# Initialize all orders as -1
label = [-1] * CHAR_SIZE
# Assign an order to pattern characters
# according to their appearance in pattern
order = 1
for i in range(len(pat)):
# Give the pattern characters order
label[ord(pat[i])] = order
# Increment the order
order += 1
# Now one by one check if string
# characters follow above order
last_order = -1
for i in range(len(Str)):
if (label[ord(Str[i])] != -1):
# If order of this character is less
# than order of previous, return false
if (label[ord(Str[i])] < last_order):
return False
# Update last_order for next iteration
last_order = label[ord(Str[i])]
# return that str followed pat
return True
# Driver Code
if __name__ == '__main__':
Str = "engineers rock"
pattern = "gsr"
print(checkPattern(Str, pattern))
# This code is contributed by himanshu77 | constant | linear |
# Python code for finding count
# of string in a given 2D
# character array.
# utility function to search
# complete string from any
# given index of 2d array
def internalSearch(ii, needle, row, col, hay,
row_max, col_max):
found = 0
if (row >= 0 and row <= row_max and
col >= 0 and col <= col_max and
needle[ii] == hay[row][col]):
match = needle[ii]
ii += 1
hay[row][col] = 0
if (ii == len(needle)):
found = 1
else:
# through Backtrack searching
# in every directions
found += internalSearch(ii, needle, row,
col + 1, hay, row_max, col_max)
found += internalSearch(ii, needle, row,
col - 1, hay, row_max, col_max)
found += internalSearch(ii, needle, row + 1,
col, hay, row_max, col_max)
found += internalSearch(ii, needle, row - 1,
col, hay, row_max, col_max)
hay[row][col] = match
return found
# Function to search the string in 2d array
def searchString(needle, row, col,strr,
row_count, col_count):
found = 0
for r in range(row_count):
for c in range(col_count):
found += internalSearch(0, needle, r, c,
strr, row_count - 1, col_count - 1)
return found
# Driver code
needle = "MAGIC"
inputt = ["BBABBM","CBMBBA","IBABBG",
"GOZBBI","ABBBBC","MCIGAM"]
strr = [0] * len(inputt)
for i in range(len(inputt)):
strr[i] = list(inputt[i])
print("count: ", searchString(needle, 0, 0, strr,
len(strr), len(strr[0])))
# This code is contributed by SHUBHAMSINGH10 | quadratic | quadratic |
# Python3 program to check if we can
# break a into four distinct strings.
# Return if the given string can be
# split or not.
def check(s):
# We can always break a of size 10 or
# more into four distinct strings.
if (len(s) >= 10):
return True
# Brute Force
for i in range(1, len(s)):
for j in range(i + 1, len(s)):
for k in range(j + 1, len(s)):
# Making 4 from the given
s1 = s[0:i]
s2 = s[i:j - i]
s3 = s[j: k - j]
s4 = s[k: len(s) - k]
# Checking if they are distinct or not.
if (s1 != s2 and s1 != s3 and s1 != s4 and
s2 != s3 and s2 != s4 and s3 != s4):
return True
return False
# Driver Code
if __name__ == '__main__':
str = "aaabb"
print("Yes") if(check(str)) else print("NO")
# This code is contributed
# by SHUBHAMSINGH10 | linear | np |
# Python 3 program to split an alphanumeric
# string using STL
def splitString(str):
alpha = ""
num = ""
special = ""
for i in range(len(str)):
if (str[i].isdigit()):
num = num+ str[i]
elif((str[i] >= 'A' and str[i] <= 'Z') or
(str[i] >= 'a' and str[i] <= 'z')):
alpha += str[i]
else:
special += str[i]
print(alpha)
print(num )
print(special)
# Driver code
if __name__ == "__main__":
str = "geeks01$$for02geeks03!@!!"
splitString(str)
# This code is contributed by ita_c | linear | linear |
# Python3 program to split a numeric
# string in an Increasing
# sequence if possible
# Function accepts a string and
# checks if string can be split.
def split(Str) :
Len = len(Str)
# if there is only 1 number
# in the string then
# it is not possible to split it
if (Len == 1) :
print("Not Possible")
return
s1, s2 = "", ""
for i in range((Len // 2) + 1) :
flag = 0
# storing the substring from
# 0 to i+1 to form initial
# number of the increasing sequence
s1 = Str[0 : i + 1]
num1 = int(s1)
num2 = num1 + 1
# convert string to integer
# and add 1 and again convert
# back to string s2
s2 = str(num2)
k = i + 1
while (flag == 0) :
l = len(s2)
# if s2 is not a substring
# of number than not possible
if (k + l > Len) :
flag = 1
break
# if s2 is the next substring
# of the numeric string
if ((Str[k : k + l] == s2)) :
flag = 0
# Increase num2 by 1 i.e the
# next number to be looked for
num2 += 1
k = k + l
# check if string is fully
# traversed then break
if (k == Len) :
break
s2 = str(num2)
l = len(s2)
if (k + 1 > len) :
# If next string doesnot occurs
# in a given numeric string
# then it is not possible
flag = 1
break
else :
flag = 1
# if the string was fully traversed
# and conditions were satisfied
if (flag == 0) :
print("Possible", s1)
break
# if conditions failed to hold
elif (flag == 1 and i > (Len // 2) - 1) :
print("Not Possible")
break
# Driver code
Str = "99100"
# Call the split function
# for splitting the string
split(Str)
# This code is contributed by divyesh072019. | linear | quadratic |
# Python3 Program to find number of way
# to split string such that each partition
# starts with distinct character with
# maximum number of partitions.
# Returns the number of we can split
# the string
def countWays(s):
count = [0] * 26;
# Finding the frequency of each
# character.
for x in s:
count[ord(x) -
ord('a')] = (count[ord(x) -
ord('a')]) + 1;
# making frequency of first character
# of string equal to 1.
count[ord(s[0]) - ord('a')] = 1;
# Finding the product of frequency
# of occurrence of each character.
ans = 1;
for i in range(26):
if (count[i] != 0):
ans *= count[i];
return ans;
# Driver Code
if __name__ == '__main__':
s = "acbbcc";
print(countWays(s));
# This code is contributed by Rajput-Ji | constant | linear |
# Python3 program to check if a can be splitted
# into two strings such that one is divisible by 'a'
# and other is divisible by 'b'.
# Finds if it is possible to partition str
# into two parts such that first part is
# divisible by a and second part is divisible
# by b.
def findDivision(str, a, b):
lenn = len(str)
# Create an array of size lenn+1 and
# initialize it with 0.
# Store remainders from left to right
# when divided by 'a'
lr = [0] * (lenn + 1)
lr[0] = (int(str[0]))%a
for i in range(1, lenn):
lr[i] = ((lr[i - 1] * 10) % a + \
int(str[i])) % a
# Compute remainders from right to left
# when divided by 'b'
rl = [0] * (lenn + 1)
rl[lenn - 1] = int(str[lenn - 1]) % b
power10 = 10
for i in range(lenn - 2, -1, -1):
rl[i] = (rl[i + 1] + int(str[i]) * power10) % b
power10 = (power10 * 10) % b
# Find a point that can partition a number
for i in range(0, lenn - 1):
# If split is not possible at this point
if (lr[i] != 0):
continue
# We can split at i if one of the following
# two is true.
# a) All characters after str[i] are 0
# b) after str[i] is divisible by b, i.e.,
# str[i+1..n-1] is divisible by b.
if (rl[i + 1] == 0):
print("YES")
for k in range(0, i + 1):
print(str[k], end = "")
print(",", end = " ")
for i in range(i + 1, lenn):
print(str[k], end = "")
return
print("NO")
# Driver code
str = "123"
a, b = 12, 3
findDivision(str, a, b)
# This code is contributed by SHUBHAMSINGH10 | linear | linear |
# Python program to check if a string can be splitted
# into two strings such that one is divisible by 'a'
# and other is divisible by 'b'.
# Finds if it is possible to partition str
# into two parts such that first part is
# divisible by a and second part is divisible
# by b.
def findDivision(S, a, b):
for i in range(len(S)-1):
firstPart = S[0: i + 1]
secondPart = S[i + 1:]
if (int(firstPart) % a == 0
and int(secondPart) % b == 0):
return firstPart + " " + secondPart
return "-1"
# Driver code
Str = "125"
a,b = 12,3
result = findDivision(Str, a, b)
if (result == "-1"):
print("NO")
else:
print("YES")
print(result)
# This code is contributed by shinjanpatra | constant | linear |
# Python3 code to implement the approach
# This code kind of uses sliding window technique. First
# checking if string[0] and string[0..n-1] is divisible if
# yes then return else run a loop from 1 to n-1 and check if
# taking this (0-i)index number and (i+1 to n-1)index number
# on our two declared variables if they are divisible by given two numbers respectively
# in any iteration return them simply
def stringPartition(s, a, b):
# code here
n = len(s)
# if length is 1 not possible
if (n == 1):
return "-1"
else:
# Checking if number formed bt S[0] and S[1->n-1] is divisible
a1 = int(s[0])
a2 = int(s[1])
multiplyer = 10
for i in range(2, n):
a2 = a2 * multiplyer + int(s[i])
i = 1
if (a1 % a == 0 and a2 % b == 0):
k1 = '1' * (s[0])
k2 = ""
for j in range(1, n):
k2 += s[j]
return k1 + " " + k2 # return the numbers formed as string
# from here by using sliding window technique we
# will iterate and check for every i that if the
# two current numbers formed are divisible if yes
# return else form the two new numbers for next
# iteration using sliding window technique
q1 = 10
q2 = 1
for i in range(1, n - 1):
q2 *= 10
while (i < n - 1):
x = s[i]
ad = int(x)
a1 = a1 * q1 + ad
a2 = a2 - q2 * ad
if (a1 % a == 0 and a2 % b == 0):
k1 = ""
k2 = ""
for j in range(i + 1):
k1 += s[j]
for j in range(i + 1, n):
k2 += s[j]
return k1 + " " + k2
q2 //= 10
i += 1
return "-1"
# Driver code
str = "123"
a = 12
b = 3
result = stringPartition(str, a, b)
if (result == "-1"):
print("NO")
else:
print("YES")
print(result)
# This code is contributed by phasing17 | constant | linear |
# Python3 program to count ways to divide
# a string in two parts a and b such that
# b/pow(10, p) == a
def calculate( N ):
length = len(N)
l = int((length) / 2)
count = 0
for i in range(l + 1):
print(i)
# substring representing int a
s = N[0: 0 + i]
# no of digits in a
l1 = len(s)
print(s,l1)
# consider only most significant
# l1 characters of remaining
# string for int b
t = N[i: l1 + i]
# if any of a or b contains
# leading 0s discard this
try:
if s[0] == '0' or t[0] == '0':
continue
except:
continue
# if both are equal
if s == t:
count+=1
print(i,N[i],count)
return count
# driver code to test above function
N = str("2202200")
print(calculate(N))
# This code is contributed by "Sharad_Bhardwaj". | linear | quadratic |
# Python program to print n equal parts of string
# Function to print n equal parts of string
def divideString(string, n):
str_size = len(string)
# Check if string can be divided in n equal parts
if str_size % n != 0:
print ("Invalid Input: String size is not divisible by n")
return
# Calculate the size of parts to find the division points
part_size = str_size/n
k = 0
for i in string:
if k % part_size == 0:
print ()
print (i,end='')
k += 1
# Driver program to test the above function
# Length of string is 28
string = "a_simple_divide_string_quest"
# Print 4 equal parts of the string
divideString(string, 4)
# This code is contributed by Bhavya Jain | constant | linear |
# Python code for the same approach
def divide(Str,n):
if (len(Str) % n != 0):
print("Invalid Input: String size",end="")
print(" is not divisible by n")
return
parts = len(Str) // n
start = 0
while (start < len(Str)):
print(Str[start: start + parts])
start += parts
# if(start < len(Str)) cout << endl; to ignore
# final new line
# driver code
Str = "a_simple_divide_string_quest"
divide(Str, 4)
# This code is contributed By shinjanpatra | linear | linear |
# Python program to find minimum breaks needed
# to break a string in dictionary words.
import sys
class TrieNode:
def __init__(self):
self.endOfTree = False
self.children = [None for i in range(26)]
root = TrieNode()
minWordBreak = sys.maxsize
# If not present, inserts a key into the trie
# If the key is the prefix of trie node, just
# marks leaf node
def insert(key):
global root,minWordBreak
length = len(key)
pcrawl = root
for i in range(length):
index = ord(key[i])- ord('a')
if(pcrawl.children[index] == None):
pcrawl.children[index] = TrieNode()
pcrawl = pcrawl.children[index]
# mark last node as leaf
pcrawl.endOfTree = True
# function break the string into minimum cut
# such the every substring after breaking
# in the dictionary.
def _minWordBreak(key):
global minWordBreak
minWordBreak = sys.maxsize
minWordBreakUtil(root, key, 0, sys.maxsize, 0)
def minWordBreakUtil(node,key,start,min_Break,level):
global minWordBreak,root
pCrawl = node
# base case, update minimum Break
if (start == len(key)):
min_Break = min(min_Break, level - 1)
if(min_Break<minWordBreak):
minWordBreak = min_Break
return
# traverse given key(pattern)
for i in range(start,len(key)):
index = ord(key[i]) - ord('a')
if (pCrawl.children[index]==None):
return
# if we find a condition were we can
# move to the next word in a trie
# dictionary
if (pCrawl.children[index].endOfTree):
minWordBreakUtil(root, key, i + 1,min_Break, level + 1)
pCrawl = pCrawl.children[index]
# Driver code
keys=["cat", "mat", "ca", "ma", "at", "c", "dog", "og", "do" ]
for i in range(len(keys)):
insert(keys[i])
_minWordBreak("catmatat")
print(minWordBreak)
# This code is contributed by shinjanpatra | linear | quadratic |
class Solution(object):
def wordBreak(self, s, wordDict):
"""
Author : @amitrajitbose
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
"""CREATING THE TRIE CLASS"""
class TrieNode(object):
def __init__(self):
self.children = [] # will be of size = 26
self.isLeaf = False
def getNode(self):
p = TrieNode() # new trie node
p.children = []
for i in range(26):
p.children.append(None)
p.isLeaf = False
return p
def insert(self, root, key):
key = str(key)
pCrawl = root
for i in key:
index = ord(i)-97
if(pCrawl.children[index] == None):
# node has to be initialised
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isLeaf = True # marking end of word
def search(self, root, key):
# print("Searching %s" %key) #DEBUG
pCrawl = root
for i in key:
index = ord(i)-97
if(pCrawl.children[index] == None):
return False
pCrawl = pCrawl.children[index]
if(pCrawl and pCrawl.isLeaf):
return True
def checkWordBreak(strr, root):
n = len(strr)
if(n == 0):
return True
for i in range(1, n+1):
if(root.search(root, strr[:i]) and checkWordBreak(strr[i:], root)):
return True
return False
"""IMPLEMENT SOLUTION"""
root = TrieNode().getNode()
for w in wordDict:
root.insert(root, w)
out = checkWordBreak(s, root)
if(out):
return "Yes"
else:
return "No"
print(Solution().wordBreak("thequickbrownfox",
["the", "quick", "fox", "brown"]))
print(Solution().wordBreak("bedbathandbeyond", [
"bed", "bath", "bedbath", "and", "beyond"]))
print(Solution().wordBreak("bedbathandbeyond", [
"teddy", "bath", "bedbath", "and", "beyond"]))
print(Solution().wordBreak("bedbathandbeyond", [
"bed", "bath", "bedbath", "and", "away"])) | quadratic | quadratic |
# A recursive program to print all possible
# partitions of a given string into dictionary
# words
# A utility function to check whether a word
# is present in dictionary or not. An array of
# strings is used for dictionary. Using array
# of strings for dictionary is definitely not
# a good idea. We have used for simplicity of
# the program
def dictionaryContains(word):
dictionary = {"mobile", "samsung", "sam", "sung", "man",
"mango", "icecream", "and", "go", "i", "love", "ice", "cream"}
return word in dictionary
# Prints all possible word breaks of given string
def wordBreak(string):
# Last argument is prefix
wordBreakUtil(string, len(string), "")
# Result store the current prefix with spaces
# between words
def wordBreakUtil(string, n, result):
# Process all prefixes one by one
for i in range(1, n + 1):
# Extract substring from 0 to i in prefix
prefix = string[:i]
# If dictionary contains this prefix, then
# we check for remaining string. Otherwise
# we ignore this prefix (there is no else for
# this if) and try next
if dictionaryContains(prefix):
# If no more elements are there, print it
if i == n:
# Add this element to previous prefix
result += prefix
print(result)
return
wordBreakUtil(string[i:], n - i, result+prefix+" ")
# Driver Code
if __name__ == "__main__":
print("First Test:")
wordBreak("iloveicecreamandmango")
print("\nSecond Test:")
wordBreak("ilovesamsungmobile")
# This code is contributed by harshitkap00r | quadratic | np |
# Python3 program to
# mark balanced and
# unbalanced parenthesis.
def identifyParenthesis(a):
st = []
# run the loop upto
# end of the string
for i in range (len(a)):
# if a[i] is opening
# bracket then push
# into stack
if (a[i] == '('):
st.append(a[i])
# if a[i] is closing bracket ')'
elif (a[i] == ')'):
# If this closing bracket
# is unmatched
if (len(st) == 0):
a = a.replace(a[i], "-1", 1)
else:
# replace all opening brackets with 0
# and closing brackets with 1
a = a.replace(a[i], "1", 1)
a = a.replace(st[-1], "0", 1)
st.pop()
# if stack is not empty
# then pop out all
# elements from it and
# replace -1 at that
# index of the string
while (len(st) != 0):
a = a.replace(st[-1], 1, "-1");
st.pop()
# print final string
print(a)
# Driver code
if __name__ == "__main__":
st = "(a))"
identifyParenthesis(st)
# This code is contributed by Chitranayal | linear | linear |
# Python 3 code to calculate the minimum cost
# to make the given parentheses balanced
def costToBalance(s):
if (len(s) == 0):
print(0)
# To store absolute count of
# balanced and unbalanced parenthesis
ans = 0
# o(open bracket) stores count of '(' and
# c(close bracket) stores count of ')'
o = 0
c = 0
for i in range(len(s)):
if (s[i] == '('):
o += 1
if (s[i] == ')'):
c += 1
if (o != c):
return -1
a = [0 for i in range(len(s))]
if (s[0] == '('):
a[0] = 1
else:
a[0] = -1
if (a[0] < 0):
ans += abs(a[0])
for i in range(1, len(s)):
if (s[i] == '('):
a[i] = a[i - 1] + 1
else:
a[i] = a[i - 1] - 1
if (a[i] < 0):
ans += abs(a[i])
return ans
# Driver code
if __name__ == '__main__':
s = ")))((("
print(costToBalance(s))
s = "))(("
print(costToBalance(s))
# This code is contributed by
# Surendra_Gangwar | linear | linear |
# Python 3 code to check balanced
# parentheses with O(1) space.
# Function1 to match closing bracket
def matchClosing(X, start, end,
open, close):
c = 1
i = start + 1
while (i <= end):
if (X[i] == open):
c += 1
elif (X[i] == close):
c -= 1
if (c == 0):
return i
i += 1
return i
# Function1 to match opening bracket
def matchingOpening(X, start, end,
open, close):
c = -1
i = end - 1
while (i >= start):
if (X[i] == open):
c += 1
elif (X[i] == close):
c -= 1
if (c == 0):
return i
i -= 1
return -1
# Function to check balanced
# parentheses
def isBalanced(X, n):
for i in range(n):
# Handling case of opening
# parentheses
if (X[i] == '('):
j = matchClosing(X, i, n - 1, '(', ')')
elif (X[i] == '{'):
j = matchClosing(X, i, n - 1, '{', '}')
elif (X[i] == '['):
j = matchClosing(X, i, n - 1, '[', ']')
# Handling case of closing
# parentheses
else :
if (X[i] == ')'):
j = matchingOpening(X, 0, i, '(', ')')
elif (X[i] == '}'):
j = matchingOpening(X, 0, i, '{', '}')
elif (X[i] == ']'):
j = matchingOpening(X, 0, i, '[', ']')
# If corresponding matching opening
# parentheses doesn't lie in given
# interval return 0
if (j < 0 or j >= i):
return False
# else continue
continue
# If corresponding closing parentheses
# doesn't lie in given interval, return 0
if (j >= n or j < 0):
return False
# if found, now check for each opening and
# closing parentheses in this interval
start = i
end = j
for k in range(start + 1, end) :
if (X[k] == '(') :
x = matchClosing(X, k, end, '(', ')')
if (not(k < x and x < end)):
return False
elif (X[k] == ')'):
x = matchingOpening(X, start, k, '(', ')')
if (not(start < x and x < k)):
return False
if (X[k] == '{'):
x = matchClosing(X, k, end, '{', '}')
if (not(k < x and x < end)):
return False
elif (X[k] == '}'):
x = matchingOpening(X, start, k, '{', '}')
if (not(start < x and x < k)):
return False
if (X[k] == '['):
x = matchClosing(X, k, end, '[', ']')
if (not(k < x and x < end)):
return False
elif (X[k] == ']'):
x = matchingOpening(X, start, k, '[', ']')
if (not(start < x and x < k)):
return False
return True
# Driver Code
if __name__ == "__main__":
X = "[()]()"
n = 6
if (isBalanced(X, n)):
print("Yes")
else:
print("No")
Y = "[[()]])"
n = 7
if (isBalanced(Y, n)):
print("Yes")
else:
print("No")
# This code is contributed by ita_c | constant | cubic |
# Python3 program to check for
# balanced brackets.
# function to check if
# brackets are balanced
def areBracketsBalanced(expr):
stack = []
# Traversing the Expression
for char in expr:
if char in ["(", "{", "["]:
# Push the element in the stack
stack.append(char)
else:
# IF current character is not opening
# bracket, then it must be closing.
# So stack cannot be empty at this point.
if not stack:
return False
current_char = stack.pop()
if current_char == '(':
if char != ")":
return False
if current_char == '{':
if char != "}":
return False
if current_char == '[':
if char != "]":
return False
# Check Empty Stack
if stack:
return False
return True
# Driver Code
if __name__ == "__main__":
expr = "{()}[]"
# Function call
if areBracketsBalanced(expr):
print("Balanced")
else:
print("Not Balanced")
# This code is contributed by AnkitRai01 and improved
# by Raju Pitta | linear | linear |
# Python3 program to find length of
# the longest balanced subsequence
def maxLength(s, n):
dp = [[0 for i in range(n)]
for i in range(n)]
# Considering all balanced
# substrings of length 2
for i in range(n - 1):
if (s[i] == '(' and s[i + 1] == ')'):
dp[i][i + 1] = 2
# Considering all other substrings
for l in range(2, n):
i = -1
for j in range(l, n):
i += 1
if (s[i] == '(' and s[j] == ')'):
dp[i][j] = 2 + dp[i + 1][j - 1]
for k in range(i, j):
dp[i][j] = max(dp[i][j], dp[i][k] +
dp[k + 1][j])
return dp[0][n - 1]
# Driver Code
s = "()(((((()"
n = len(s)
print(maxLength(s, n))
# This code is contributed
# by sahishelangia | quadratic | quadratic |
# Python3 program to find length of
# the longest balanced subsequence
def maxLength(s, n):
# As it's subsequence - assuming first
# open brace would map to a first close
# brace which occurs after the open brace
# to make subsequence balanced and second
# open brace would map to second close
# brace and so on.
# Variable to count all the open brace
# that does not have the corresponding
# closing brace.
invalidOpenBraces = 0;
# To count all the close brace that does
# not have the corresponding open brace.
invalidCloseBraces = 0;
# Iterating over the String
for i in range(n):
if( s[i] == '(' ):
# Number of open braces that
# hasn't been closed yet.
invalidOpenBraces += 1
else:
if(invalidOpenBraces == 0):
# Number of close braces that
# cannot be mapped to any open
# brace.
invalidCloseBraces += 1
else:
# Mapping the ith close brace
# to one of the open brace.
invalidOpenBraces -= 1
return (
n - (
invalidOpenBraces + invalidCloseBraces))
# Driver Code
s = "()(((((()"
n = len(s)
print(maxLength(s, n)) | constant | linear |
# Python3 program to determine whether
# given expression is balanced/ parenthesis
# expression or not.
# Function to check if two brackets are
# matching or not.
def isMatching(a, b):
if ((a == '{' and b == '}') or
(a == '[' and b == ']') or
(a == '(' and b == ')') or
a == 'X'):
return 1
return 0
# Recursive function to check if given
# expression is balanced or not.
def isBalanced(s, ele, ind):
# Base case.
# If the string is balanced then all the
# opening brackets had been popped and
# stack should be empty after string is
# traversed completely.
if (ind == len(s)):
if len(ele) == 0:
return True
else:
return False
# Variable to store element at the top
# of the stack.
# char topEle;
# Variable to store result of
# recursive call.
# int res;
# Case 1: When current element is an
# opening bracket then push that
# element in the stack.
if (s[ind] == '{' or s[ind] == '(' or
s[ind] == '['):
ele.append(s[ind])
return isBalanced(s, ele, ind + 1)
# Case 2: When current element is a closing
# bracket then check for matching bracket
# at the top of the stack.
elif (s[ind] == '}' or s[ind] == ')' or
s[ind] == ']'):
# If stack is empty then there is no matching
# opening bracket for current closing bracket
# and the expression is not balanced.
if (len(ele) == 0):
return 0
topEle = ele[-1]
ele.pop()
# Check bracket is matching or not.
if (isMatching(topEle, s[ind]) == 0):
return 0
return isBalanced(s, ele, ind + 1)
# Case 3: If current element is 'X' then check
# for both the cases when 'X' could be opening
# or closing bracket.
elif (s[ind] == 'X'):
tmp = ele
tmp.append(s[ind])
res = isBalanced(s, tmp, ind + 1)
if (res):
return 1
if (len(ele) == 0):
return 0
ele.pop()
return isBalanced(s, ele, ind + 1)
# Driver Code
s = "{(X}[]"
ele = []
# Check if the length of the given string is even
if(len(s)%2==0):
if (isBalanced(s, ele, 0)): print("Balanced")
else: print("Not Balanced")
# If the length is not even, then the string is not balanced
else: print("Not Balanced")
# This code is contributed by divyeshrabadiya07 | linear | np |
# Python3 program to evaluate value
# of an expression.
import math as mt
def evaluateBoolExpr(s):
n = len(s)
# Traverse all operands by jumping
# a character after every iteration.
for i in range(0, n - 2, 2):
# If operator next to current
# operand is AND.'''
if (s[i + 1] == "A"):
if (s[i + 2] == "0" or s[i] == "0"):
s[i + 2] = "0"
else:
s[i + 2] = "1"
# If operator next to current
# operand is OR.
else if (s[i + 1] == "B"):
if (s[i + 2] == "1" or s[i] == "1"):
s[i + 2] = "1"
else:
s[i + 2] = "0"
# If operator next to current operand
# is XOR (Assuming a valid input)
else:
if (s[i + 2] == s[i]):
s[i + 2] = "0"
else:
s[i + 2] = "1"
return ord(s[n - 1]) - ord("0")
# Driver code
s = "1C1B1B0A0"
string=[s[i] for i in range(len(s))]
print(evaluateBoolExpr(string))
# This code is contributed
# by mohit kumar 29 | linear | linear |
# Python code to implement the approach
def maxDepth(s):
count = 0
st = []
for i in range(len(s)):
if (s[i] == '('):
st.append(i) # pushing the bracket in the stack
elif (s[i] == ')'):
if (count < len(st)):
count = len(st)
# keeping track of the parenthesis and storing
# it before removing it when it gets balanced
st.pop()
return count
# Driver program
s = "( ((X)) (((Y))) )"
print(maxDepth(s))
# This code is contributed by shinjanpatra | constant | linear |
# A Python program to find the maximum depth of nested
# parenthesis in a given expression
# function takes a string and returns the
# maximum depth nested parenthesis
def maxDepth(S):
current_max = 0
max = 0
n = len(S)
# Traverse the input string
for i in range(n):
if S[i] == '(':
current_max += 1
if current_max > max:
max = current_max
else if S[i] == ')':
if current_max > 0:
current_max -= 1
else:
return -1
# finally check for unbalanced string
if current_max != 0:
return -1
return max
# Driver program
s = "( ((X)) (((Y))) )"
print (maxDepth(s))
# This code is contributed by BHAVYA JAIN | constant | linear |
# Python3 Program to find all combinations of Non-
# overlapping substrings formed from given
# string
# find all combinations of non-overlapping
# substrings formed by input string str
# index – index of the next character to
# be processed
# out - output string so far
def findCombinations(string, index, out):
if index == len(string):
print(out)
for i in range(index, len(string), 1):
# append substring formed by str[index,
# i] to output string
findCombinations(string, i + 1, out + "(" +
string[index:i + 1] + ")")
# Driver Code
if __name__ == "__main__":
# input string
string = "abcd"
findCombinations(string, 0, "")
# This code is contributed by
# sanjeev2552 | quadratic | quadratic |
# Method to find an equal index
def findIndex(str):
l = len(str)
open = [0] * (l + 1)
close = [0] * (l + 1)
index = -1
open[0] = 0
close[l] = 0
if (str[0]=='('):
open[1] = 1
if (str[l - 1] == ')'):
close[l - 1] = 1
# Store the number of
# opening brackets
# at each index
for i in range(1, l):
if (str[i] == '('):
open[i + 1] = open[i] + 1
else:
open[i + 1] = open[i]
# Store the number
# of closing brackets
# at each index
for i in range(l - 2, -1, -1):
if ( str[i] == ')'):
close[i] = close[i + 1] + 1
else:
close[i] = close[i + 1]
# check if there is no
# opening or closing brackets
if (open[l] == 0):
return len
if (close[0] == 0):
return 0
# check if there is any
# index at which both
# brackets are equal
for i in range(l + 1):
if (open[i] == close[i]):
index = i
return index
# Driver Code
str = "(()))(()()())))"
print(findIndex(str))
# This code is contributed
# by ChitraNayal | linear | linear |
# Method to find an equal index
def findIndex(str):
cnt_close = 0
l = len(str)
for i in range(1, l):
if(str[i] == ')'):
cnt_close = cnt_close + 1
for i in range(1, l):
if(cnt_close == i):
return i
# If no opening brackets
return l
# Driver Code
str = "(()))(()()())))"
print(findIndex(str))
# This code is contributed by Aditya Kumar (adityakumar129) | constant | linear |
# Python3 program to check if two expressions
# evaluate to same.
MAX_CHAR = 26;
# Return local sign of the operand. For example,
# in the expr a-b-(c), local signs of the operands
# are +a, -b, +c
def adjSign(s, i):
if (i == 0):
return True;
if (s[i - 1] == '-'):
return False;
return True;
# Evaluate expressions into the count vector of
# the 26 alphabets.If add is True, then add count
# to the count vector of the alphabets, else remove
# count from the count vector.
def eval(s, v, add):
# stack stores the global sign
# for operands.
stk = []
stk.append(True);
# + means True
# global sign is positive initially
i = 0;
while (i < len(s)):
if (s[i] == '+' or s[i] == '-'):
i += 1
continue;
if (s[i] == '('):
# global sign for the bracket is
# pushed to the stack
if (adjSign(s, i)):
stk.append(stk[-1]);
else:
stk.append(not stk[-1]);
# global sign is popped out which
# was pushed in for the last bracket
elif (s[i] == ')'):
stk.pop();
else:
# global sign is positive (we use different
# values in two calls of functions so that
# we finally check if all vector elements
# are 0.
if (stk[-1]):
v[ord(s[i]) - ord('a')] += (1 if add else -1) if adjSign(s, i) else (-1 if add else 1)
# global sign is negative here
else:
v[ord(s[i]) - ord('a')] += (-1 if add else 1) if adjSign(s, i) else (1 if add else -1)
i += 1
# Returns True if expr1 and expr2 represent
# same expressions
def areSame(expr1, expr2):
# Create a vector for all operands and
# initialize the vector as 0.
v = [0 for i in range(MAX_CHAR)];
# Put signs of all operands in expr1
eval(expr1, v, True);
# Subtract signs of operands in expr2
eval(expr2, v, False);
# If expressions are same, vector must
# be 0.
for i in range(MAX_CHAR):
if (v[i] != 0):
return False;
return True;
# Driver Code
if __name__=='__main__':
expr1 = "-(a+b+c)"
expr2 = "-a-b-c";
if (areSame(expr1, expr2)):
print("Yes");
else:
print("No");
# This code is contributed by rutvik_56. | linear | linear |
# Python3 Program to check whether valid
# expression is redundant or not
# Function to check redundant brackets
# in a balanced expression
def checkRedundancy(Str):
# create a stack of characters
st = []
# Iterate through the given expression
for ch in Str:
# if current character is close
# parenthesis ')'
if (ch == ')'):
top = st[-1]
st.pop()
# If immediate pop have open parenthesis
# '(' duplicate brackets found
flag = True
while (top != '('):
# Check for operators in expression
if (top == '+' or top == '-' or
top == '*' or top == '/'):
flag = False
# Fetch top element of stack
top = st[-1]
st.pop()
# If operators not found
if (flag == True):
return True
else:
st.append(ch) # append open parenthesis '(',
# operators and operands to stack
return False
# Function to check redundant brackets
def findRedundant(Str):
ans = checkRedundancy(Str)
if (ans == True):
print("Yes")
else:
print("No")
# Driver code
if __name__ == '__main__':
Str = "((a+b))"
findRedundant(Str)
# This code is contributed by PranchalK | linear | linear |
# Python3 program to find sum of given
# array of string type in integer form
# Function to find the sum of given array
def calculateSum(arr, n):
# if string is empty
if (n == 0):
return 0
s = arr[0]
# stoi function to convert
# string into integer
value = int(s)
sum = value
for i in range(2 , n, 2):
s = arr[i]
# stoi function to convert
# string into integer
value = int(s)
# Find operator
operation = arr[i - 1][0]
# If operator is equal to '+',
# add value in sum variable
# else subtract
if (operation == '+'):
sum += value
else:
sum -= value
return sum
# Driver Function
arr = ["3", "+", "4", "-","7", "+", "13"]
n = len(arr)
print(calculateSum(arr, n))
# This code is contributed by Smitha | constant | linear |
# Python3 implementation to print the bracket number
# function to print the bracket number
def printBracketNumber(exp, n):
# used to print the bracket number
# for the left bracket
left_bnum = 1
# used to obtain the bracket number
# for the right bracket
right_bnum = list()
# traverse the given expression 'exp'
for i in range(n):
# if current character is a left bracket
if exp[i] == '(':
# print 'left_bnum',
print(left_bnum, end = " ")
# push 'left_bnum' on to the stack 'right_bnum'
right_bnum.append(left_bnum)
# increment 'left_bnum' by 1
left_bnum += 1
# else if current character is a right bracket
elif exp[i] == ')':
# print the top element of stack 'right_bnum'
# it will be the right bracket number
print(right_bnum[-1], end = " ")
# pop the top element from the stack
right_bnum.pop()
# Driver Code
if __name__ == "__main__":
exp = "(a+(b*c))+(d/e)"
n = len(exp)
printBracketNumber(exp, n)
# This code is contributed by
# sanjeev2552 | linear | linear |
# Python program to find index of closing
# bracket for a given opening bracket.
from collections import deque
def getIndex(s, i):
# If input is invalid.
if s[i] != '[':
return -1
# Create a deque to use it as a stack.
d = deque()
# Traverse through all elements
# starting from i.
for k in range(i, len(s)):
# Pop a starting bracket
# for every closing bracket
if s[k] == ']':
d.popleft()
# Push all starting brackets
elif s[k] == '[':
d.append(s[i])
# If deque becomes empty
if not d:
return k
return -1
# Driver code to test above method.
def test(s, i):
matching_index = getIndex(s, i)
print(s + ", " + str(i) + ": " + str(matching_index))
def main():
test("[ABC[23]][89]", 0) # should be 8
test("[ABC[23]][89]", 4) # should be 7
test("[ABC[23]][89]", 9) # should be 12
test("[ABC[23]][89]", 1) # No matching bracket
if __name__ == "__main__":
main() | linear | linear |
# Python3 program to construct string from binary tree
# A binary tree node has data, pointer to left
# child and a pointer to right child
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to construct string from binary tree
def treeToString(root: Node, string: list):
# base case
if root is None:
return
# push the root data as character
string.append(str(root.data))
# if leaf node, then return
if not root.left and not root.right:
return
# for left subtree
string.append('(')
treeToString(root.left, string)
string.append(')')
# only if right child is present to
# avoid extra parenthesis
if root.right:
string.append('(')
treeToString(root.right, string)
string.append(')')
# Driver Code
if __name__ == "__main__":
# Let us construct below tree
# 1
# / \
# 2 3
# / \ \
# 4 5 6
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(6)
string = []
treeToString(root, string)
print(''.join(string))
# This code is contributed by
# sanjeev2552 | linear | linear |
# Python3 program to conStruct a
# binary tree from the given String
# Helper class that allocates a new node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# This function is here just to test
def preOrder(node):
if (node == None):
return
print(node.data, end=' ')
preOrder(node.left)
preOrder(node.right)
# function to return the index of
# close parenthesis
def findIndex(Str, si, ei):
if (si > ei):
return -1
# Inbuilt stack
s = []
for i in range(si, ei + 1):
# if open parenthesis, push it
if (Str[i] == '('):
s.append(Str[i])
# if close parenthesis
elif (Str[i] == ')'):
if (s[-1] == '('):
s.pop(-1)
# if stack is empty, this is
# the required index
if len(s) == 0:
return i
# if not found return -1
return -1
# function to conStruct tree from String
def treeFromString(Str, si, ei):
# Base case
if (si > ei):
return None
# new root
root = newNode(ord(Str[si]) - ord('0'))
index = -1
# if next char is '(' find the
# index of its complement ')'
if (si + 1 <= ei and Str[si + 1] == '('):
index = findIndex(Str, si + 1, ei)
# if index found
if (index != -1):
# call for left subtree
root.left = treeFromString(Str, si + 2,
index - 1)
# call for right subtree
root.right = treeFromString(Str, index + 2,
ei - 1)
return root
# Driver Code
if __name__ == '__main__':
Str = "4(2(3)(1))(6(5))"
root = treeFromString(Str, 0, len(Str) - 1)
preOrder(root)
# This code is contributed by pranchalK | linear | quadratic |
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
def preOrder(node):
if (node == None):
return
print(node.data, end=" ")
preOrder(node.left)
preOrder(node.right)
def treeFromStringHelper(si, ei, arr, root):
if si[0] >= ei:
return None
if arr[si[0]] == "(":
if arr[si[0]+1] != ")":
if root.left is None:
if si[0] >= ei:
return
new_root = newNode(arr[si[0]+1])
root.left = new_root
si[0] += 2
treeFromStringHelper(si, ei, arr, new_root)
else:
si[0] += 2
if root.right is None:
if si[0] >= ei:
return
if arr[si[0]] != "(":
si[0] += 1
return
new_root = newNode(arr[si[0]+1])
root.right = new_root
si[0] += 2
treeFromStringHelper(si, ei, arr, new_root)
else:
return
if arr[si[0]] == ")":
if si[0] >= ei:
return
si[0] += 1
return
return
def treeFromString(string):
root = newNode(string[0])
if len(string) > 1:
si = [1]
ei = len(string)-1
treeFromStringHelper(si, ei, string, root)
return root
# Driver Code
if __name__ == '__main__':
Str = "4(2(3)(1))(6(5))"
root = treeFromString(Str)
preOrder(root)
# This code is contributed by dheerajalimchandani | linear | quadratic |
# Simple Python3 program to convert
# all substrings from decimal to given base.
import math
def substringConversions(s, k, b):
l = len(s);
for i in range(l):
if((i + k) < l + 1):
# Saving substring in sub
sub = s[i : i + k];
# Evaluating decimal for current
# substring and printing it.
sum, counter = 0, 0;
for i in range(len(sub) - 1, -1, -1):
sum = sum + ((ord(sub[i]) - ord('0')) *
pow(b, counter));
counter += 1;
print(sum , end = " ");
# Driver code
s = "12212";
b, k = 3, 3;
substringConversions(s, b, k);
# This code is contributed
# by Princi Singh | linear | quadratic |
# Simple Python3 program to convert all
# substrings from decimal to given base.
import math as mt
def substringConversions(str1, k, b):
for i in range(0, len(str1) - k + 1):
# Saving substring in sub
sub = str1[i:k + i]
# Evaluating decimal for current
# substring and printing it.
Sum = 0
counter = 0
for i in range(len(sub) - 1, -1, -1):
Sum = (Sum + ((ord(sub[i]) - ord('0')) *
pow(b, counter)))
counter += 1
print(Sum, end = " ")
# Driver code
str1 = "12212"
b = 3
k = 3
substringConversions(str1, b, k)
# This code is contributed by
# Mohit Kumar 29 | linear | linear |
# Python3 program to demonstrate above steps
# of binary fractional to decimal conversion
# Function to convert binary fractional
# to decimal
def binaryToDecimal(binary, length) :
# Fetch the radix point
point = binary.find('.')
# Update point if not found
if (point == -1) :
point = length
intDecimal = 0
fracDecimal = 0
twos = 1
# Convert integral part of binary
# to decimal equivalent
for i in range(point-1, -1, -1) :
# Subtract '0' to convert
# character into integer
intDecimal += ((ord(binary[i]) -
ord('0')) * twos)
twos *= 2
# Convert fractional part of binary
# to decimal equivalent
twos = 2
for i in range(point + 1, length):
fracDecimal += ((ord(binary[i]) -
ord('0')) / twos);
twos *= 2.0
# Add both integral and fractional part
ans = intDecimal + fracDecimal
return ans
# Driver code :
if __name__ == "__main__" :
n = "110.101"
print(binaryToDecimal(n, len(n)))
n = "101.1101"
print(binaryToDecimal(n, len(n)))
# This code is contributed
# by aishwarya.27 | linear | linear |
# Python3 program to convert fractional
# decimal to binary number
# Function to convert decimal to binary
# upto k-precision after decimal point
def decimalToBinary(num, k_prec) :
binary = ""
# Fetch the integral part of
# decimal number
Integral = int(num)
# Fetch the fractional part
# decimal number
fractional = num - Integral
# Conversion of integral part to
# binary equivalent
while (Integral) :
rem = Integral % 2
# Append 0 in binary
binary += str(rem);
Integral //= 2
# Reverse string to get original
# binary equivalent
binary = binary[ : : -1]
# Append point before conversion
# of fractional part
binary += '.'
# Conversion of fractional part
# to binary equivalent
while (k_prec) :
# Find next bit in fraction
fractional *= 2
fract_bit = int(fractional)
if (fract_bit == 1) :
fractional -= fract_bit
binary += '1'
else :
binary += '0'
k_prec -= 1
return binary
# Driver code
if __name__ == "__main__" :
n = 4.47
k = 3
print(decimalToBinary(n, k))
n = 6.986
k = 5
print(decimalToBinary(n, k))
# This code is contributed by Ryuga | linear | linear |
# Python3 implementation to convert
# a sentence into its equivalent
# mobile numeric keypad sequence
# Function which computes the
# sequence
def printSequence(arr, input):
# length of input string
n = len(input)
output = ""
for i in range(n):
# checking for space
if(input[i] == ' '):
output = output + "0"
else:
# calculating index for each
# character
position = ord(input[i]) - ord('A')
output = output + arr[position]
# output sequence
return output
# Driver code
str = ["2", "22", "222",
"3", "33", "333",
"4", "44", "444",
"5", "55", "555",
"6", "66", "666",
"7", "77", "777", "7777",
"8", "88", "888",
"9", "99", "999", "9999"]
input = "GEEKSFORGEEKS"
print(printSequence(str, input))
# This code is contributed by upendra bartwal | linear | linear |
# Python Program for above implementation
# Function to check is it possible to convert
# first string into another string or not.
def isItPossible(str1, str2, m, n):
# To Check Length of Both String is Equal or Not
if (m != n):
return False
# To Check Frequency of A's and B's are
# equal in both strings or not.
if str1.count('A') != str2.count('A') \
or str1.count('B') != str2.count('B'):
return False
# Start traversing
for i in range(m):
if (str1[i] != '#'):
for j in range(n):
# To Check no two elements cross each other.
if ((str2[j] != str1[i]) and str2[j] != '#'):
return False
if (str2[j] == str1[i]):
str2[j] = '#'
# To Check Is it Possible to Move
# towards Left or not.
if (str1[i] == 'A' and i < j):
return False
# To Check Is it Possible to Move
# towards Right or not.
if (str1[i] == 'B' and i > j):
return False
break
return True
# Drivers code
str1 = "A#B#"
str2 = "A##B"
m = len(str1)
n = len(str2)
str1 = list(str1)
str2 = list(str2)
if(isItPossible(str1, str2, m, n)):
print("Yes")
else:
print("No")
# This code is contributed by ankush_953 | linear | quadratic |
# Python 3 Program to convert str1 to
# str2 in exactly k operations
# Returns true if it is possible to convert
# str1 to str2 using k operations.
def isConvertible(str1, str2, k):
# Case A (i)
if ((len(str1) + len(str2)) < k):
return True
# finding common length of both string
commonLength = 0
for i in range(0, min(len(str1),
len(str2)), 1):
if (str1[i] == str2[i]):
commonLength += 1
else:
break
# Case A (ii)-
if ((k - len(str1) - len(str2) + 2 *
commonLength) % 2 == 0):
return True
# Case B-
return False
# Driver Code
if __name__ == '__main__':
str1 = "geek"
str2 = "geek"
k = 7
if (isConvertible(str1, str2, k)):
print("Yes")
else:
print("No")
str1 = "geeks"
str2 = "geek"
k = 5
if (isConvertible(str1, str2, k)):
print("Yes")
else:
print("No")
# This code is contributed by
# Sanjit_Prasad | constant | linear |
# Python3 program to convert
# decimal number to roman numerals
ls=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
dict={1:"I",4:"IV",5:"V",9:"IX",10:"X",40:"XL",50:"L",90:"XC",100:"C",400:"CD",500:"D",900:"CM",1000:"M"}
ls2=[]
# Function to convert decimal to Roman Numerals
def func(no,res):
for i in range(0,len(ls)):
if no in ls:
res=dict[no]
rem=0
break
if ls[i]<no:
quo=no//ls[i]
rem=no%ls[i]
res=res+dict[ls[i]]*quo
break
ls2.append(res)
if rem==0:
pass
else:
func(rem,"")
# Driver code
if __name__ == "__main__":
func(3549, "")
print("".join(ls2))
# This code is contributed by
# VIKAS CHOUDHARY(vikaschoudhary344) | constant | linear |
# Python3 program for above approach
# Function to calculate roman equivalent
def intToRoman(num):
# Storing roman values of digits from 0-9
# when placed at different places
m = ["", "M", "MM", "MMM"]
c = ["", "C", "CC", "CCC", "CD", "D",
"DC", "DCC", "DCCC", "CM "]
x = ["", "X", "XX", "XXX", "XL", "L",
"LX", "LXX", "LXXX", "XC"]
i = ["", "I", "II", "III", "IV", "V",
"VI", "VII", "VIII", "IX"]
# Converting to roman
thousands = m[num // 1000]
hundreds = c[(num % 1000) // 100]
tens = x[(num % 100) // 10]
ones = i[num % 10]
ans = (thousands + hundreds +
tens + ones)
return ans
# Driver code
if __name__ == "__main__":
number = 3549
print(intToRoman(number))
# This code is contributed by rutvik_56 | constant | linear |
# Python 3 program to convert Decimal
# number to Roman numbers.
import math
def integerToRoman(A):
romansDict = \
{
1: "I",
5: "V",
10: "X",
50: "L",
100: "C",
500: "D",
1000: "M",
5000: "G",
10000: "H"
}
div = 1
while A >= div:
div *= 10
div //= 10
res = ""
while A:
# main significant digit extracted
# into lastNum
lastNum = (A // div)
if lastNum <= 3:
res += (romansDict[div] * lastNum)
elif lastNum == 4:
res += (romansDict[div] +
romansDict[div * 5])
elif 5 <= lastNum <= 8:
res += (romansDict[div * 5] +
(romansDict[div] * (lastNum - 5)))
elif lastNum == 9:
res += (romansDict[div] +
romansDict[div * 10])
A = math.floor(A % div)
div //= 10
return res
# Driver code
print("Roman Numeral of Integer is:"
+ str(integerToRoman(3549))) | constant | linear |
# Python program to convert Roman Numerals
# to Numbers
# This function returns value of each Roman symbol
def value(r):
if (r == 'I'):
return 1
if (r == 'V'):
return 5
if (r == 'X'):
return 10
if (r == 'L'):
return 50
if (r == 'C'):
return 100
if (r == 'D'):
return 500
if (r == 'M'):
return 1000
return -1
def romanToDecimal(str):
res = 0
i = 0
while (i < len(str)):
# Getting value of symbol s[i]
s1 = value(str[i])
if (i + 1 < len(str)):
# Getting value of symbol s[i + 1]
s2 = value(str[i + 1])
# Comparing both values
if (s1 >= s2):
# Value of current symbol is greater
# or equal to the next symbol
res = res + s1
i = i + 1
else:
# Value of current symbol is greater
# or equal to the next symbol
res = res + s2 - s1
i = i + 2
else:
res = res + s1
i = i + 1
return res
# Driver code
print("Integer form of Roman Numeral is"),
print(romanToDecimal("MCMIV")) | constant | linear |
# Program to convert Roman
# Numerals to Numbers
roman = {}
roman['I'] = 1
roman['V'] = 5
roman['X'] = 10
roman['L'] = 50
roman['C'] = 100
roman['D'] = 500
roman['M'] = 1000
# This function returns value
# of a Roman symbol
def romanToInt(s):
sum = 0
n = len(s)
i = 0
while i < n :
# If present value is less than next value,
# subtract present from next value and add the
# resultant to the sum variable.
# print(roman[s[i]],roman[s[i+1]])
if (i != n - 1 and roman[s[i]] < roman[s[i + 1]]):
sum += roman[s[i + 1]] - roman[s[i]]
i += 2
continue
else:
sum += roman[s[i]]
i += 1
return sum
# Driver Code
# Considering inputs given are valid
input = "MCMIV"
print(f"Integer form of Roman Numeral is {romanToInt(input)}")
# This code is contributed by shinjanpatra | constant | constant |
def romanToInt(s):
translations = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
number = 0
s = s.replace("IV", "IIII").replace("IX", "VIIII")
s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
for char in s:
number += translations[char]
print(number)
romanToInt('MCMIV') | constant | constant |
# Python3 program to check if a string can
# be converted to another string by
# performing operations
# function to check if a string can be
# converted to another string by
# performing following operations
def check(s1,s2):
# calculates length
n = len(s1)
m = len(s2)
dp=([[False for i in range(m+1)]
for i in range(n+1)])
# mark 1st position as true
dp[0][0] = True
# traverse for all DPi, j
for i in range(len(s1)):
for j in range(len(s2)+1):
# if possible for to convert i
# characters of s1 to j characters
# of s2
if (dp[i][j]):
# if upper_case(s1[i])==s2[j]
# is same
if ((j < len(s2) and
(s1[i].upper()== s2[j]))):
dp[i + 1][j + 1] = True
# if not upper then deletion is
# possible
if (s1[i].isupper()==False):
dp[i + 1][j] = True
return (dp[n][m])
# driver code
if __name__=='__main__':
s1 = "daBcd"
s2 = "ABC"
if (check(s1, s2)):
print("YES")
else:
print("NO")
# this code is contributed by
# sahilshelangia | quadratic | quadratic |
# Python code to
# transform string
# def to change
# character's case
def change_case(s) :
a = list(s)
l = len(s)
for i in range(0, l) :
# If character is
# lowercase change
# to uppercase
if(a[i] >= 'a' and
a[i] <= 'z') :
a[i] = s[i].upper()
# If character is uppercase
# change to lowercase
elif(a[i] >= 'A' and
a[i] <= 'Z') :
a[i] = s[i].lower()
return a
# def to delete vowels
def delete_vowels(s) :
temp = ""
a = list(s)
l = len(s)
for i in range(0, l) :
# If character
# is consonant
if(a[i] != 'a' and a[i] != 'e' and
a[i] != 'i' and a[i] != 'o' and
a[i] != 'u' and a[i] != 'A' and
a[i] != 'E' and a[i] != 'O' and
a[i] != 'U' and a[i] != 'I') :
temp = temp + a[i]
return temp
# def to insert "#"
def insert_hash(s) :
temp = ""
a = list(s)
l = len(s)
for i in range(0, l) :
# If character is
# not special
if((a[i] >= 'a' and
a[i] <= 'z') or
(a[i] >= 'A' and
a[i] <= 'Z')) :
temp = temp + '#' + a[i]
else :
temp = temp + a[i]
return temp
# def to
# transform string
def transformSting(a) :
b = delete_vowels(a)
c = change_case(b)
d = insert_hash(c)
print (d)
# Driver Code
a = "SunshinE!!"
# Calling def
transformSting(a)
# This code is contributed by
# Manish Shaw(manishshaw1) | linear | linear |
# Python implementation of above approach
# A utility function to reverse string str[low..high]
def Reverse(string: list, low: int, high: int):
while low < high:
string[low], string[high] = string[high], string[low]
low += 1
high -= 1
# Cycle leader algorithm to move all even
# positioned elements at the end.
def cycleLeader(string: list, shift: int, len: int):
i = 1
while i < len:
j = i
item = string[j + shift]
while True:
# odd index
if j & 1:
j = len // 2 + j // 2
# even index
else:
j //= 2
# keep the back-up of element at new position
string[j + shift], item = item, string[j + shift]
if j == i:
break
i *= 3
# The main function to transform a string. This function
# mainly uses cycleLeader() to transform
def moveNumberToSecondHalf(string: list):
k, lenFirst = 0, 0
lenRemaining = len(string)
shift = 0
while lenRemaining:
k = 0
# Step 1: Find the largest prefix
# subarray of the form 3^k + 1
while pow(3, k) + 1 <= lenRemaining:
k += 1
lenFirst = pow(3, k - 1) + 1
lenRemaining -= lenFirst
# Step 2: Apply cycle leader algorithm
# for the largest subarrau
cycleLeader(string, shift, lenFirst)
# Step 4.1: Reverse the second half of first subarray
Reverse(string, shift // 2, shift - 1)
# Step 4.2: Reverse the first half of second sub-string
Reverse(string, shift, shift + lenFirst // 2 - 1)
# Step 4.3 Reverse the second half of first sub-string
# and first half of second sub-string together
Reverse(string, shift // 2, shift + lenFirst // 2 - 1)
# Increase the length of first subarray
shift += lenFirst
# Driver Code
if __name__ == "__main__":
string = "a1b2c3d4e5f6g7"
string = list(string)
moveNumberToSecondHalf(string)
print(''.join(string))
# This code is contributed by
# sanjeev2552 | constant | quadratic |
# Python3 program to count the distinct
# transformation of one string to other.
def countTransformation(a, b):
n = len(a)
m = len(b)
# If b = "" i.e., an empty string. There
# is only one way to transform (remove all
# characters)
if m == 0:
return 1
dp = [[0] * (n) for _ in range(m)]
# Fill dp[][] in bottom up manner
# Traverse all character of b[]
for i in range(m):
# Traverse all characters of a[] for b[i]
for j in range(i, n):
# Filling the first row of the dp
# matrix.
if i == 0:
if j == 0:
if a[j] == b[i]:
dp[i][j] = 1
else:
dp[i][j] = 0
else if a[j] == b[i]:
dp[i][j] = dp[i][j - 1] + 1
else:
dp[i][j] = dp[i][j - 1]
# Filling other rows
else:
if a[j] == b[i]:
dp[i][j] = (dp[i][j - 1] +
dp[i - 1][j - 1])
else:
dp[i][j] = dp[i][j - 1]
return dp[m - 1][n - 1]
# Driver Code
if __name__ == "__main__":
a = "abcccdf"
b = "abccdf"
print(countTransformation(a, b))
# This code is contributed by vibhu4agarwal | quadratic | quadratic |
# Class to define a node
# structure of the tree
class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# Function to convert ternary
# expression to a Binary tree
# It returns the root node
# of the tree
def convert_expression(expression, i):
if i >= len(expression):
return None
# Create a new node object
# for the expression at
# ith index
root = Node(expression[i])
i += 1
# if current character of
# ternary expression is '?'
# then we add next character
# as a left child of
# current node
if (i < len(expression) and
expression[i] is "?"):
root.left = convert_expression(expression, i + 1)
# else we have to add it
# as a right child of
# current node expression[0] == ':'
elif i < len(expression):
root.right = convert_expression(expression, i + 1)
return root
# Function to print the tree
# in a pre-order traversal pattern
def print_tree(root):
if not root:
return
print(root.data, end=' ')
print_tree(root.left)
print_tree(root.right)
# Driver Code
if __name__ == "__main__":
string_expression = "a?b?c:d:e"
root_node = convert_expression(string_expression, 0)
print_tree(root_node)
# This code is contributed
# by Kanav Malhotra | linear | linear |
# Python Program to convert prefix to Infix
def prefixToInfix(prefix):
stack = []
# read prefix in reverse order
i = len(prefix) - 1
while i >= 0:
if not isOperator(prefix[i]):
# symbol is operand
stack.append(prefix[i])
i -= 1
else:
# symbol is operator
str = "(" + stack.pop() + prefix[i] + stack.pop() + ")"
stack.append(str)
i -= 1
return stack.pop()
def isOperator(c):
if c == "*" or c == "+" or c == "-" or c == "/" or c == "^" or c == "(" or c == ")":
return True
else:
return False
# Driver code
if __name__=="__main__":
str = "*-A/BC-/AKL"
print(prefixToInfix(str))
# This code is contributed by avishekarora | linear | linear |
# Write Python3 code here
# -*- coding: utf-8 -*-
# Example Input
s = "*-A/BC-/AKL"
# Stack for storing operands
stack = []
operators = set(['+', '-', '*', '/', '^'])
# Reversing the order
s = s[::-1]
# iterating through individual tokens
for i in s:
# if token is operator
if i in operators:
# pop 2 elements from stack
a = stack.pop()
b = stack.pop()
# concatenate them as operand1 +
# operand2 + operator
temp = a+b+i
stack.append(temp)
# else if operand
else:
stack.append(i)
# printing final output
print(*stack) | linear | linear |
# Python3 Program to convert postfix to prefix
# function to check if
# character is operator or not
def isOperator(x):
if x == "+":
return True
if x == "-":
return True
if x == "/":
return True
if x == "*":
return True
return False
# Convert postfix to Prefix expression
def postToPre(post_exp):
s = []
# length of expression
length = len(post_exp)
# reading from right to left
for i in range(length):
# check if symbol is operator
if (isOperator(post_exp[i])):
# pop two operands from stack
op1 = s[-1]
s.pop()
op2 = s[-1]
s.pop()
# concat the operands and operator
temp = post_exp[i] + op2 + op1
# Push string temp back to stack
s.append(temp)
# if symbol is an operand
else:
# push the operand to the stack
s.append(post_exp[i])
ans = ""
for i in s:
ans += i
return ans
# Driver Code
if __name__ == "__main__":
post_exp = "AB+CD-"
# Function call
print("Prefix : ", postToPre(post_exp))
# This code is contributed by AnkitRai01 | linear | linear |
# Python3 program to find infix for
# a given postfix.
def isOperand(x):
return ((x >= 'a' and x <= 'z') or
(x >= 'A' and x <= 'Z'))
# Get Infix for a given postfix
# expression
def getInfix(exp) :
s = []
for i in exp:
# Push operands
if (isOperand(i)) :
s.insert(0, i)
# We assume that input is a
# valid postfix and expect
# an operator.
else:
op1 = s[0]
s.pop(0)
op2 = s[0]
s.pop(0)
s.insert(0, "(" + op2 + i +
op1 + ")")
# There must be a single element in
# stack now which is the required
# infix.
return s[0]
# Driver Code
if __name__ == '__main__':
exp = "ab*c+"
print(getInfix(exp.strip()))
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10) | linear | linear |
# Python 3 program for space optimized
# solution of Word Wrap problem.
import sys
# Function to find space optimized
# solution of Word Wrap problem.
def solveWordWrap(arr, n, k):
dp = [0] * n
# Array in which ans[i] store index
# of last word in line starting with
# word arr[i].
ans = [0] * n
# If only one word is present then
# only one line is required. Cost
# of last line is zero. Hence cost
# of this line is zero. Ending point
# is also n-1 as single word is
# present.
dp[n - 1] = 0
ans[n - 1] = n - 1
# Make each word first word of line
# by iterating over each index in arr.
for i in range(n - 2, -1, -1):
currlen = -1
dp[i] = sys.maxsize
# Keep on adding words in current
# line by iterating from starting
# word upto last word in arr.
for j in range(i, n):
# Update number of characters
# in current line. arr[j] is
# number of characters in
# current word and 1
# represents space character
# between two words.
currlen += (arr[j] + 1)
# If limit of characters
# is violated then no more
# words can be added to
# current line.
if (currlen > k):
break
# If current word that is
# added to line is last
# word of arr then current
# line is last line. Cost of
# last line is 0. Else cost
# is square of extra spaces
# plus cost of putting line
# breaks in rest of words
# from j+1 to n-1.
if (j == n - 1):
cost = 0
else:
cost = ((k - currlen) *
(k - currlen) + dp[j + 1])
# Check if this arrangement gives
# minimum cost for line starting
# with word arr[i].
if (cost < dp[i]):
dp[i] = cost
ans[i] = j
# Print starting index and ending index
# of words present in each line.
i = 0
while (i < n):
print(i + 1 , ans[i] + 1, end = " ")
i = ans[i] + 1
# Driver Code
if __name__ == "__main__":
arr = [3, 2, 2, 5 ]
n = len(arr)
M = 6
solveWordWrap(arr, n, M)
# This code is contributed by ita_c | linear | quadratic |
# Python 3 program to print shortest possible
# path to type all characters of given string
# using a remote
# Function to print shortest possible path
# to type all characters of given string
# using a remote
def printPath(str):
i = 0
# start from character 'A' present
# at position (0, 0)
curX = 0
curY = 0
while (i < len(str)):
# find coordinates of next character
nextX = int((ord(str[i]) - ord('A')) / 5)
nextY = (ord(str[i]) - ord('B') + 1) % 5
# Move Up if destination is above
while (curX > nextX):
print("Move Up")
curX -= 1
# Move Left if destination is to the left
while (curY > nextY):
print("Move Left")
curY -= 1
# Move down if destination is below
while (curX < nextX):
print("Move Down")
curX += 1
# Move Right if destination is to the right
while (curY < nextY):
print("Move Right")
curY += 1
# At this point, destination is reached
print("Press OK")
i += 1
# Driver code
if __name__ == '__main__':
str = "COZY"
printPath(str)
# This code is contributed by
# Sanjit_Prasad | constant | quadratic |
# Python program to check whether second string
# can be formed from first string
def canMakeStr2(s1, s2):
# Create a count array and count
# frequencies characters in s1
count = {s1[i] : 0 for i in range(len(s1))}
for i in range(len(s1)):
count[s1[i]] += 1
# Now traverse through str2 to check
# if every character has enough counts
for i in range(len(s2)):
if (count.get(s2[i]) == None or count[s2[i]] == 0):
return False
count[s2[i]] -= 1
return True
# Driver Code
s1 = "geekforgeeks"
s2 = "for"
if canMakeStr2(s1, s2):
print("Yes")
else:
print("No") | constant | linear |
# python code to find the reverse
# alphabetical order from a given
# position
# Function which take the given string and the
# position from which the reversing shall be
# done and returns the modified string
def compute(st, n):
# Creating a string having reversed
# alphabetical order
reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba"
l = len(st)
# The string up to the point specified in the
# question, the string remains unchanged and
# from the point up to the length of the
# string, we reverse the alphabetical order
answer = ""
for i in range(0, n):
answer = answer + st[i];
for i in range(n, l):
answer = (answer +
reverseAlphabet[ord(st[i]) - ord('a')]);
return answer;
# Driver function
st = "pneumonia"
n = 4
answer = compute(st, n - 1)
print(answer)
# This code is contributed by Sam007. | constant | linear |
# A Python program to find last
# index of character x in given
# string.
# Returns last index of x if it
# is present. Else returns -1.
def findLastIndex(str, x):
index = -1
for i in range(0, len(str)):
if str[i] == x:
index = i
return index
# Driver program
# String in which char is to be found
str = "geeksforgeeks"
# char whose index is to be found
x = 'e'
index = findLastIndex(str, x)
if index == -1:
print("Character not found")
else:
print('Last index is', index)
# This code is contributed by shrikant13. | constant | linear |
# Simple Python3 program to find last
# index of character x in given string.
# Returns last index of x if it is
# present. Else returns -1.
def findLastIndex(str, x):
# Traverse from right
for i in range(len(str) - 1, -1,-1):
if (str[i] == x):
return i
return -1
# Driver code
str = "geeksforgeeks"
x = 'e'
index = findLastIndex(str, x)
if (index == -1):
print("Character not found")
else:
print("Last index is " ,index)
# This code is contributed by Smitha | constant | linear |
# python program to find position
# of a number in a series of
# numbers with 4 and 7 as the
# only digits.
def findpos(n):
i = 0
j = len(n)
pos = 0
while (i<j):
# check all digit position
# if number is left then
# pos*2+1
if(n[i] == '4'):
pos = pos * 2 + 1
# if number is right then
# pos*2+2
if(n[i] == '7'):
pos = pos * 2 + 2
i= i+1
return pos
# Driver code
# given a number which is constructed
# by 4 and 7 digit only
n = "774"
print(findpos(n))
# This code is contributed by Sam007 | constant | linear |
# Python3 program to find winner in an election.
from collections import defaultdict
''' 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. '''
def findWinner(votes):
# Insert all votes in a hashmap
mapObj = defaultdict(int)
for st in votes:
mapObj[st] += 1
# Traverse through map to find the
# candidate with maximum votes.
maxValueInMap = 0
winner = ""
for entry in mapObj:
key = entry
val = mapObj[entry]
if (val > maxValueInMap):
maxValueInMap = val
winner = key
# If there is a tie, pick lexicographically
# smaller.
else if (val == maxValueInMap and
winner > key):
winner = key
print(winner)
# Driver code
if __name__ == "__main__":
votes = ["john", "johnny", "jackie",
"johnny", "john", "jackie",
"jamie", "jamie", "john",
"johnny", "jamie", "johnny",
"john"]
findWinner(votes)
# This code is contributed by ukasp | linear | linear |
# Python 3 program to check if a query
# string is present is given set.
MAX_CHAR = 256
def isPresent(s, q):
# Count occurrences of all characters
# in s.
freq = [0] * MAX_CHAR
for i in range(0 , len(s)):
freq[ord(s[i])] += 1
# Check if number of occurrences of
# every character in q is less than
# or equal to that in s.
for i in range(0, len(q)):
freq[ord(q[i])] -= 1
if (freq[ord(q[i])] < 0):
return False
return True
# driver program
s = "abctd"
q = "cat"
if (isPresent(s, q)):
print("Yes")
else:
print("No")
# This code is contributed by Smitha | constant | linear |
# Python program to find
# the arrangement of
# queue at time = t
# prints the arrangement
# at time = t
def solve(n, t, p) :
s = list(p)
# Checking the entire
# queue for every
# moment from time = 1
# to time = t.
for i in range(0, t) :
for j in range(0, n - 1) :
# If current index
# contains 'B' and
# next index contains
# 'G' then swap
if (s[j] == 'B' and
s[j + 1] == 'G') :
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
j = j + 1
print (''.join(s))
# Driver code
n = 6
t = 2
p = "BBGBBG"
solve(n, t, p)
# This code is contributed by
# Manish Shaw(manishshaw1) | constant | quadratic |
# Python3 code to check whether the
# given EMEI number is valid or not
# Function for finding and returning
# sum of digits of a number
def sumDig( n ):
a = 0
while n > 0:
a = a + n % 10
n = int(n / 10)
return a
# Returns True if n is valid EMEI
def isValidEMEI(n):
# Converting the number into
# String for finding length
s = str(n)
l = len(s)
# If length is not 15 then IMEI is Invalid
if l != 15:
return False
d = 0
sum = 0
for i in range(15, 0, -1):
d = (int)(n % 10)
if i % 2 == 0:
# Doubling every alternate digit
d = 2 * d
# Finding sum of the digits
sum = sum + sumDig(d)
n = n / 10
return (sum % 10 == 0)
# Driver code
n = 490154203237518
if isValidEMEI(n):
print("Valid IMEI Code")
else:
print("Invalid IMEI Code")
# This code is contributed by "Sharad_Bhardwaj". | linear | nlogn |
# Python3 program to decode a median
# string to the original string
# function to calculate the median
# back string
def decodeMedianString(s):
# length of string
l = len(s)
# initialize a blank string
s1 = ""
# Flag to check if length is
# even or odd
if(l % 2 == 0):
isEven = True
else:
isEven = False
# traverse from first to last
for i in range(0, l, 2):
# if len is even then add first
# character to beginning of new
# string and second character to end
if (isEven):
s1 = s[i] + s1
s1 += s[i + 1]
else :
# if current length is odd and
# is greater than 1
if (l - i > 1):
# add first character to end and
# second character to beginning
s1 += s[i]
s1 = s[i + 1] + s1
else:
# if length is 1, add character
# to end
s1 += s[i]
return s1
# Driver Code
if __name__ == '__main__':
s = "eekgs"
print(decodeMedianString(s))
# This code is contributed by
# Sanjit_Prasad | constant | linear |
# Python program to decode a string recursively
# encoded as count followed substring
# Returns decoded string for 'str'
def decode(Str):
integerstack = []
stringstack = []
temp = ""
result = ""
i = 0
# Traversing the string
while i < len(Str):
count = 0
# If number, convert it into number
# and push it into integerstack.
if (Str[i] >= '0' and Str[i] <='9'):
while (Str[i] >= '0' and Str[i] <= '9'):
count = count * 10 + ord(Str[i]) - ord('0')
i += 1
i -= 1
integerstack.append(count)
# If closing bracket ']', pop element until
# '[' opening bracket is not found in the
# character stack.
elif (Str[i] == ']'):
temp = ""
count = 0
if (len(integerstack) != 0):
count = integerstack[-1]
integerstack.pop()
while (len(stringstack) != 0 and stringstack[-1] !='[' ):
temp = stringstack[-1] + temp
stringstack.pop()
if (len(stringstack) != 0 and stringstack[-1] == '['):
stringstack.pop()
# Repeating the popped string 'temo' count
# number of times.
for j in range(count):
result = result + temp
# Push it in the character stack.
for j in range(len(result)):
stringstack.append(result[j])
result = ""
# If '[' opening bracket, push it into character stack.
elif (Str[i] == '['):
if (Str[i-1] >= '0' and Str[i-1] <= '9'):
stringstack.append(Str[i])
else:
stringstack.append(Str[i])
integerstack.append(1)
else:
stringstack.append(Str[i])
i += 1
# Pop all the element, make a string and return.
while len(stringstack) != 0:
result = stringstack[-1] + result
stringstack.pop()
return result
# Driven code
if __name__ == '__main__':
Str = "3[b2[ca]]"
print(decode(Str))
# This code is contributed by PranchalK. | linear | linear |
def decodeString(s):
st = []
for i in range(len(s)):
# When ']' is encountered, we need to start decoding
if s[i] == ']':
temp = ""
while len(st) > 0 and st[-1] != '[':
# st.top() + temp makes sure that the
# string won't be in reverse order eg, if
# the stack contains 12[abc temp = c + "" =>
# temp = b + "c" => temp = a + "bc"
temp = st[-1] + temp
st.pop()
# remove the '[' from the stack
st.pop()
num = ""
# remove the digits from the stack
while len(st) > 0 and ord(st[-1]) >= 48 and ord(st[-1]) <= 57:
num = st[-1] + num
st.pop()
number = int(num)
repeat = ""
for j in range(number):
repeat += temp
for c in range(len(repeat)):
if len(st) > 0:
if repeat == st[-1]:
break #otherwise this thingy starts appending the same decoded words
st.append(repeat)
else:
st.append(s[i])
return st[0]
Str = "3[b2[ca]]"
print(decodeString(Str))
# This code is contributed by mukesh07.
# And debugged by ivannakreshchenetska | linear | linear |
# Python 3 program to make a number magical
# function to calculate the minimal changes
def calculate( s):
# maximum digits that can be changed
ans = 6
# nested loops to generate all 6
# digit numbers
for i in range(10):
for j in range(10):
for k in range(10):
for l in range(10):
for m in range(10):
for n in range(10):
if (i + j + k == l + m + n):
# counter to count the number
# of change required
c = 0
# if first digit is equal
if (i != ord(s[0]) - ord('0')):
c+=1
# if 2nd digit is equal
if (j != ord(s[1]) - ord('0')):
c+=1
# if 3rd digit is equal
if (k != ord(s[2]) - ord('0')):
c+=1
# if 4th digit is equal
if (l != ord(s[3]) - ord('0')):
c+=1
# if 5th digit is equal
if (m != ord(s[4]) - ord('0')):
c+=1
# if 6th digit is equal
if (n != ord(s[5]) - ord('0')):
c+=1
# checks if less than the
# previous calculate changes
if (c < ans):
ans = c
# returns the answer
return ans
# driver program to test the above function
if __name__ == "__main__":
# number stored in string
s = "123456"
# prints the minimum operations
print(calculate(s)) | constant | np |
# Python code to check if a
# given ISBN is valid or not.
def isValidISBN(isbn):
# check for length
if len(isbn) != 10:
return False
# Computing weighted sum
# of first 9 digits
_sum = 0
for i in range(9):
if 0 <= int(isbn[i]) <= 9:
_sum += int(isbn[i]) * (10 - i)
else:
return False
# Checking last digit
if(isbn[9] != 'X' and
0 <= int(isbn[9]) <= 9):
return False
# If last digit is 'X', add
# 10 to sum, else add its value.
_sum += 10 if isbn[9] == 'X' else int(isbn[9])
# Return true if weighted sum of
# digits is divisible by 11
return (_sum % 11 == 0)
# Driver Code
isbn = "007462542X"
if isValidISBN(isbn):
print('Valid')
else:
print("Invalid")
# This code is contributed
# by "Abhishek Sharma 44" | constant | constant |
class CreditCard:
# Main Method
@staticmethod
def main(args):
number = 5196081888500645
print(str(number) + " is " +
("valid" if CreditCard.isValid(number) else "invalid"))
# Return true if the card number is valid
@staticmethod
def isValid(number):
return (CreditCard.getSize(number) >= 13 and CreditCard.getSize(number) <= 16) and (CreditCard.prefixMatched(number, 4) or CreditCard.prefixMatched(number, 5) or CreditCard.prefixMatched(number, 37) or CreditCard.prefixMatched(number, 6)) and ((CreditCard.sumOfDoubleEvenPlace(number) + CreditCard.sumOfOddPlace(number)) % 10 == 0)
# Get the result from Step 2
@staticmethod
def sumOfDoubleEvenPlace(number):
sum = 0
num = str(number) + ""
i = CreditCard.getSize(number) - 2
while (i >= 0):
sum += CreditCard.getDigit(int(str(num[i]) + "") * 2)
i -= 2
return sum
# Return this number if it is a single digit, otherwise,
# return the sum of the two digits
@staticmethod
def getDigit(number):
if (number < 9):
return number
return int(number / 10) + number % 10
# Return sum of odd-place digits in number
@staticmethod
def sumOfOddPlace(number):
sum = 0
num = str(number) + ""
i = CreditCard.getSize(number) - 1
while (i >= 0):
sum += int(str(num[i]) + "")
i -= 2
return sum
# Return true if the digit d is a prefix for number
@staticmethod
def prefixMatched(number, d):
return CreditCard.getPrefix(number, CreditCard.getSize(d)) == d
# Return the number of digits in d
@staticmethod
def getSize(d):
num = str(d) + ""
return len(num)
# Return the first k number of digits from
# number. If the number of digits in number
# is less than k, return number.
@staticmethod
def getPrefix(number, k):
if (CreditCard.getSize(number) > k):
num = str(number) + ""
return int(num[0:k])
return number
if __name__ == "__main__":
CreditCard.main([])
# This code is contributed by Aarti_Rathi | constant | linear |
# Python3 program to implement the approach
# Python3 has no built-in swap function.
def swap(str, i, j):
ch = list(str)
temp = ch[i]
ch[i] = ch[j]
ch[j] = temp
return "".join(ch)
# Since STRINGS are immutable in JavaScript, first we have
# to convert it to a character array in order to sort.
def sortString(str, s_index, e_index):
tempArray = list(str)
# Sorting temp array using
tempArray = tempArray[:s_index] + sorted(tempArray[s_index: e_index])
# returning the new sorted string
return "".join(tempArray)
def maximizeNumber(N, M):
# Sorting the digits of the
# number in increasing order.
N = sortString(N, 0, len(N))
for i in range(len(N)):
for j in range(i + 1, len(N)):
# Copying the string into another
# temp string.
t = N
# Swapping the j-th char(digit)
# with i-th char(digit)
t = swap(t, j, i)
# Sorting the temp string
# from i-th pos to end.
t = sortString(t, i + 1, len(t))
# Checking if the string t is
# greater than string N and less
# than or equal to the number M.
if (int(t) > int(N) and int(t) <= M):
# If yes then, we will permanently
# swap the i-th char(or digit)
# with j-th char(digit).
N = swap(N, i, j)
# Returns the maximized number.
return N
# Driver Code
N = "123"
M = 222
print(maximizeNumber(N, M))
# This code is contributed by phasing17 | linear | cubic |
# Python program to find
# if a given corner string
# is present at corners.
def isCornerPresent(str, corner) :
n = len(str)
cl = len(corner)
# If length of corner
# string is more, it
# cannot be present
# at corners.
if (n < cl) :
return False
# Return true if corner
# string is present at
# both corners of given
# string.
return ((str[: cl] == corner) and
(str[n - cl :] == corner))
# Driver Code
str = "geeksforgeeks"
corner = "geeks"
if (isCornerPresent(str, corner)) :
print ("Yes")
else :
print ("No")
# This code is contributed by
# Manish Shaw(manishshaw1) | constant | linear |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.