code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
|---|---|---|
# Python implementation
from collections import Counter
# Function which repeats
# first repeating character
def printrepeated(string):
# Calculating frequencies
# using Counter function
freq = Counter(string)
# Traverse the string
for i in string:
if(freq[i] > 1):
print(i)
break
# Driver code
string = "geeksforgeeks"
# passing string to printrepeated function
printrepeated(string)
# this code is contributed by vikkycirus
|
linear
|
linear
|
# Python3 code to find the first repeating character in a
# string
INT_MAX = 2147483647
# Function to find left most repeating character.
def firstRep(s):
map = dict()
c = '#'
index = INT_MAX
# single traversal of string.
i = 0
while (i < len(s)):
p = s[i]
if (not (p in map.keys())):
map[p] = i
else:
if (map.get(p) < index):
index = map.get(p)
c = p
i += 1
return c
if __name__ == "__main__":
# Input string.
s = "abccdbd"
print(firstRep(s), end="")
print("\n", end="")
# This code is contributed by Aarti_Rathi
|
constant
|
linear
|
# Python program to find the first
# repeated character in a string
def firstRepeatedChar(str):
h = {} # Create empty hash
# Traverse each characters in string
# in lower case order
for ch in str:
# If character is already present
# in hash, return char
if ch in h:
return ch;
# Add ch to hash
else:
h[ch] = 0
return ''
# Driver code
print(firstRepeatedChar("geeksforgeeks"))
|
linear
|
linear
|
# Python3 program to find out the second
# most repeated word
# Function to find the word
def secMostRepeated(seq):
# Store all the words with its occurrence
occ = {}
for i in range(len(seq)):
occ[seq[i]] = occ.get(seq[i], 0) + 1
# Find the second largest occurrence
first_max = -10**8
sec_max = -10**8
for it in occ:
if (occ[it] > first_max):
sec_max = first_max
first_max = occ[it]
elif (occ[it] > sec_max and
occ[it] != first_max):
sec_max = occ[it]
# Return with occurrence equals
# to sec_max
for it in occ:
if (occ[it] == sec_max):
return it
# Driver code
if __name__ == '__main__':
seq = [ "ccc", "aaa", "ccc",
"ddd", "aaa", "aaa" ]
print(secMostRepeated(seq))
# This code is contributed by mohit kumar 29
|
linear
|
linear
|
# Efficiently check First repeated character
# in Python
# Returns -1 if all characters of str are
# unique.
# Assumptions : (1) str contains only characters
# from 'a' to 'z'
## (2) integers are stored using 32
## bits
def FirstRepeated(string):
# An integer to store presence/absence
# of 26 characters using its 32 bits.
checker = 0
pos = 0
for i in string:
val = ord(i) - ord('a');
# If bit corresponding to current
# character is already set
if ((checker & (1 << val)) > 0):
return pos
# set bit in checker
checker |= (1 << val)
pos += 1
return -1
# Driver code
string = "abcfdeacf"
i = FirstRepeated(string)
if i != -1:
print ("Char = ", string[i], " and Index = ", i)
else:
print ("No repeated Char")
# This code is contributed by Sachin Bisht
|
constant
|
linear
|
# Queries for same characters in a repeated
# string
# Print whether index i and j have same
# element or not.
def query(s, i, j):
n = len(s)
# Finding relative position of index i,j.
i %= n
j %= n
# Checking is element are same at index i, j.
print("Yes") if s[i] == s[j] else print("No")
# Driver code
if __name__ == "__main__":
X = "geeksforgeeks"
query(X, 0, 8)
query(X, 8, 13)
query(X, 6, 15)
# This code is contributed by
# sanjeev2552
|
constant
|
constant
|
# Python program to return the maximum occurring character in the input string
ASCII_SIZE = 256
def getMaxOccurringChar(str):
# Create array to keep the count of individual characters
# Initialize the count array to zero
count = [0] * ASCII_SIZE
# Utility variables
max = -1
c = ''
# Traversing through the string and maintaining the count of
# each character
for i in str:
count[ord(i)] += 1
for i in str:
if max < count[ord(i)]:
max = count[ord(i)]
c = i
return c
# Driver program to test the above function
str = "sample string"
print("Max occurring character is", getMaxOccurringChar(str))
# Although this program can be written in atmost 3 lines in Python
# the above program has been written for a better understanding of
# the reader
# Shorter version of the program
# import collections
# str = "sample string"
# print "Max occurring character is " +
# collections.Counter(str).most_common(1)[0][0]
# This code has been contributed by Bhavya Jain
|
constant
|
linear
|
# Python3 program to print all occurrences
# of every character together.
# Since only lower case characters are there
MAX_CHAR = 26
# Function to print the string
def printGrouped(string):
n = len(string)
# Initialize counts of all characters as 0
count = [0] * MAX_CHAR
# Count occurrences of all characters in string
for i in range(n):
count[ord(string[i]) - ord("a")] += 1
# Starts traversing the string
for i in range(n):
# Print the character till its count in
# hash array
while count[ord(string[i]) - ord("a")]:
print(string[i], end = "")
count[ord(string[i]) - ord("a")] -= 1
# Make this character's count value as 0.
count[ord(string[i]) - ord("a")] = 0
# Driver code
if __name__ == "__main__":
string = "geeksforgeeks"
printGrouped(string)
# This code is contributed by
# sanjeev2552
|
constant
|
linear
|
# Python3 program to print the string
# in given pattern
# Function to print the string
def printStringAlternate(string):
occ = {}
# Start traversing the string
for i in range(0, len(string)):
# Convert uppercase to lowercase
temp = string[i].lower()
# Increment occurrence count
occ[temp] = occ.get(temp, 0) + 1
# If count is odd then print the character
if occ[temp] & 1:
print(string[i], end = "")
print()
# Driver code
if __name__ == "__main__":
string = "Geeks for geeks"
string2 = "It is a long day Dear"
printStringAlternate(string)
printStringAlternate(string2)
# This code is contributed by Rituraj Jain
|
linear
|
linear
|
# Python3 program for above implementation
# Function to print the string
def printString(str, ch, count):
occ, i = 0, 0
# If given count is 0
# print the given string and return
if (count == 0):
print(str)
# Start traversing the string
for i in range(len(str)):
# Increment occ if current char
# is equal to given character
if (str[i] == ch):
occ += 1
# Break the loop if given character has
# been occurred given no. of times
if (occ == count):
break
# Print the string after the occurrence
# of given character given no. of times
if (i < len(str)- 1):
print(str[i + 1: len(str) - i + 2])
# Otherwise string is empty
else:
print("Empty string")
# Driver code
if __name__ == '__main__':
str = "geeks for geeks"
printString(str, 'e', 2)
# This code is contributed
# by 29AjayKumar
|
constant
|
linear
|
# Python3 Program to find all occurrences of the word in
# a matrix
ROW = 3
COL = 5
# check whether given cell (row, col) is a valid
# cell or not.
def isvalid(row, col, prevRow, prevCol):
# return true if row number and column number
# is in range
return (row >= 0) and (row < ROW) and (col >= 0) and \
(col < COL) and not (row== prevRow and col == prevCol)
# These arrays are used to get row and column
# numbers of 8 neighboursof a given cell
rowNum = [-1, -1, -1, 0, 0, 1, 1, 1]
colNum = [-1, 0, 1, -1, 1, -1, 0, 1]
# A utility function to do DFS for a 2D boolean
# matrix. It only considers the 8 neighbours as
# adjacent vertices
def DFS(mat, row, col,prevRow, prevCol, word,path, index, n):
# return if current character doesn't match with
# the next character in the word
if (index > n or mat[row][col] != word[index]):
return
# append current character position to path
path += word[index] + "(" + str(row)+ ", " + str(col) + ") "
# current character matches with the last character\
# in the word
if (index == n):
print(path)
return
# Recur for all connected neighbours
for k in range(8):
if (isvalid(row + rowNum[k], col + colNum[k],prevRow, prevCol)):
DFS(mat, row + rowNum[k], col + colNum[k],row, col, word, path, index + 1, n)
# The main function to find all occurrences of the
# word in a matrix
def findWords(mat,word, n):
# traverse through the all cells of given matrix
for i in range(ROW):
for j in range(COL):
# occurrence of first character in matrix
if (mat[i][j] == word[0]):
# check and print if path exists
DFS(mat, i, j, -1, -1, word, "", 0, n)
# Driver code
mat = [['B', 'N', 'E', 'Y', 'S'],
['H', 'E', 'D', 'E', 'S'],
['S', 'G', 'N', 'D', 'E']]
word = list("DES")
findWords(mat, word, len(word) - 1)
# This code is contributed by SHUBHAMSINGH10
|
quadratic
|
quadratic
|
# Python3 program to arrange given string
# Function which arrange the given string
def arrangeString(str1,x,y):
count_0=0
count_1 =0
n = len(str1)
# Counting number of 0's and 1's in the
# given string.
for i in range(n):
if str1[i] == '0':
count_0 +=1
else:
count_1 +=1
# Printing first all 0's x-times
# and decrement count of 0's x-times
# and do the similar task with '1'
while count_0>0 or count_1>0:
for i in range(0,x):
if count_0>0:
print("0",end="")
count_0 -=1
for j in range(0,y):
if count_1>0:
print("1",end="")
count_1 -=1
# Driver code
if __name__=='__main__':
str1 = "01101101101101101000000"
x = 1
y = 2
arrangeString(str1, x, y)
# This code is contributed by
# Shrikant13
|
constant
|
quadratic
|
# Finds maximum occurring digit
# without using any array/string
# Simple function to count
# occurrences of digit d in x
def countOccurrences(x, d):
count = 0; # Initialize count
# of digit d
while (x):
# Increment count if current
# digit is same as d
if (x % 10 == d):
count += 1;
x = int(x / 10);
return count;
# Returns the max occurring
# digit in x
def maxOccurring(x):
# Handle negative number
if (x < 0):
x = -x;
result = 0; # Initialize result
# which is a digit
max_count = 1; # Initialize count
# of result
# Traverse through all digits
for d in range(10):
# Count occurrences of current digit
count = countOccurrences(x, d);
# Update max_count and
# result if needed
if (count >= max_count):
max_count = count;
result = d;
return result;
# Driver Code
x = 1223355;
print("Max occurring digit is",
maxOccurring(x));
# This code is contributed by mits.
|
constant
|
constant
|
# Python3 program to bring all spaces
# in front of string using swapping technique
# Function to find spaces and move to beginning
def moveSpaceInFront(s):
# Traverse from end and swap spaces
i = len(s) - 1;
for j in range(i, -1, -1):
if (s[j] != ' '):
s = swap(s, i, j);
i -= 1;
return s;
def swap(c, i, j):
c = list(c)
c[i], c[j] = c[j], c[i]
return ''.join(c)
# Driver code
s = "Hey there, it's GeeksforGeeks";
s = moveSpaceInFront(s);
print(s);
# This code is contributed
# by Princi Singh
|
constant
|
linear
|
# Python3 program to bring all spaces
# in front of string using swapping technique
# Function to find spaces and
# move to beginning
def moveSpaceInFront(s):
# Keep copying non-space characters
i = len(s) - 1;
for j in range(i, -1, -1):
if (s[j] != ' '):
s = s[:i] + s[j] + s[i + 1:]
i -= 1;
# Move spaces to be beginning
while (i >= 0):
s = s[:i] + ' ' + s[i + 1:]
i -= 1
return s;
# Driver code
s = "Hey there, it's GeeksforGeeks";
s = moveSpaceInFront(s);
print(s);
# This code is contributed
# by Princi Singh
|
constant
|
linear
|
# Python3 program to put spaces between words
# starting with capital letters.
# Function to amend the sentence
def amendSentence(string):
string = list(string)
# Traverse the string
for i in range(len(string)):
# Convert to lowercase if its
# an uppercase character
if string[i] >= 'A' and string[i] <= 'Z':
string[i] = chr(ord(string[i]) + 32)
# Print space before it
# if its an uppercase character
if i != 0:
print(" ", end = "")
# Print the character
print(string[i], end = "")
# if lowercase character
# then just print
else:
print(string[i], end = "")
# Driver Code
if __name__ == "__main__":
string = "BruceWayneIsBatman"
amendSentence(string)
# This code is contributed by
# sanjeev2552
|
constant
|
linear
|
# Python program to Remove
# extra spaces from a string
input_string = \
' Hello Geeks . Welcome , Do you love Geeks , Geeks ? '
output_string = []
space_flag = False # Flag to check if spaces have occurred
for index in range(len(input_string)):
if input_string[index] != ' ':
if space_flag == True:
if (input_string[index] == '.'
or input_string[index] == '?'
or input_string[index] == ','):
pass
else:
output_string.append(' ')
space_flag = False
output_string.append(input_string[index])
elif input_string[index - 1] != ' ':
space_flag = True
print (''.join(output_string))
|
constant
|
linear
|
# Python 3 program to find the string which
# contain the first character of each word
# of another string.
# Function to find string which has first
# character of each word.
def firstLetterWord(str):
result = ""
# Traverse the string.
v = True
for i in range(len(str)):
# If it is space, set v as true.
if (str[i] == ' '):
v = True
# Else check if v is true or not.
# If true, copy character in output
# string and set v as false.
elif (str[i] != ' ' and v == True):
result += (str[i])
v = False
return result
# Driver Code
if __name__ == "__main__":
str = "geeks for geeks"
print(firstLetterWord(str))
# This code is contributed by ita_c
|
linear
|
linear
|
# An efficient Python3 implementation
# of above approach
charBuffer = []
def processWords(input):
""" we are splitting the input based on
spaces (s)+ : this regular expression
will handle scenarios where we have words
separated by multiple spaces """
s = input.split(" ")
for values in s:
""" charAt(0) will pick only the first
character from the string and append
to buffer """
charBuffer.append(values[0])
return charBuffer
# Driver Code
if __name__ == '__main__':
input = "geeks for geeks"
print(*processWords(input), sep = "")
# This code is contributed
# by SHUBHAMSINGH10
|
linear
|
quadratic
|
# Python 3 program to print all strings
# that can be made by placing spaces
from math import pow
def printSubsequences(str):
n = len(str)
opsize = int(pow(2, n - 1))
for counter in range(opsize):
for j in range(n):
print(str[j], end = "")
if (counter & (1 << j)):
print(" ", end = "")
print("\n", end = "")
# Driver code
if __name__ == '__main__':
str = "ABC"
printSubsequences(str)
# This code is contributed by
# Sanjit_Prasad
|
constant
|
quadratic
|
class Solution:
# Function is to check whether two strings are anagram of each other or not.
def isAnagram(self, a, b):
if sorted(a) == sorted(b):
return True
else:
return False
# {
# Driver Code Starts
if __name__ == '__main__':
a = "gram"
b = "arm"
if(Solution().isAnagram(a, b)):
print("The two strings are anagram of each other")
else:
print("The two strings are not anagram of each other")
# } Driver Code Ends
|
constant
|
nlogn
|
# Python program to check if two strings are anagrams of
# each other
NO_OF_CHARS = 256
# Function to check whether two strings are anagram of
# each other
def areAnagram(str1, str2):
# Create two count arrays and initialize all values as 0
count1 = [0] * NO_OF_CHARS
count2 = [0] * NO_OF_CHARS
# For each character in input strings, increment count
# in the corresponding count array
for i in str1:
count1[ord(i)] += 1
for i in str2:
count2[ord(i)] += 1
# If both strings are of different length. Removing this
# condition will make the program fail for strings like
# "aaca" and "aca"
if len(str1) != len(str2):
return 0
# Compare count arrays
for i in xrange(NO_OF_CHARS):
if count1[i] != count2[i]:
return 0
return 1
# Driver code
str1 = "gram"
str2 = "arm"
# Function call
if areAnagram(str1, str2):
print "The two strings are anagram of each other"
else:
print "The two strings are not anagram of each other"
# This code is contributed by Bhavya Jain
|
constant
|
linear
|
# Python program to check if two strings
# are anagrams of each other
NO_OF_CHARS = 256
# function to check if two strings
# are anagrams of each other
def areAnagram(str1,str2):
# If both strings are of different
# length. Removing this condition
# will make the program fail for
# strings like "aaca" and "aca"
if(len(str1) != len(str2)):
return False;
# Create a count array and initialize
# all values as 0
count=[0 for i in range(NO_OF_CHARS)]
i=0
# For each character in input strings,
# increment count in the corresponding
# count array
for i in range(len(str1)):
count[ord(str1[i]) - ord('a')] += 1;
count[ord(str2[i]) - ord('a')] -= 1;
# See if there is any non-zero
# value in count array
for i in range(NO_OF_CHARS):
if (count[i] != 0):
return False
return True
# Driver code
str1="gram"
str2="arm"
# Function call
if (areAnagram(str1, str2)):
print("The two strings are anagram of each other")
else:
print("The two strings are not anagram of each other")
# This code is contributed by patel2127
|
constant
|
linear
|
# Python3 implementation of the approach
# Function that returns True if a and b
# are anagarams of each other
def isAnagram(a, b):
# Check if length of both strings is same or not
if (len(a) != len(b)):
return False
# Create a HashMap containing Character as Key and
# Integer as Value. We will be storing character as
# Key and count of character as Value.
map = {}
# Loop over all character of String a and put in
# HashMap.
for i in range(len(a)):
# Check if HashMap already contain current
# character or not
if (a[i] in map):
# If contains increase count by 1 for that
# character
map[a[i]] += 1
else:
# else set that character in map and set
# count to 1 as character is encountered
# first time
map[a[i]] = 1
# Now loop over String b
for i in range(len(b)):
# Check if current character already exists in
# HashMap/map
if (b[i] in map):
# If contains reduce count of that
# character by 1 to indicate that current
# character has been already counted as
# idea here is to check if in last count of
# all characters in last is zero which
# means all characters in String a are
# present in String b.
map[b[i]] -= 1
else:
return False
# Extract all keys of HashMap/map
keys = map.keys()
# Loop over all keys and check if all keys are 0.
# If so it means it is anagram.
for key in keys:
if (map[key] != 0):
return False
# Returning True as all keys are zero
return True
# Driver code
str1 = "gram"
str2 = "arm"
# Function call
if (isAnagram(str1, str2)):
print("The two strings are anagram of each other")
else:
print("The two strings are not anagram of each other")
# This code is contributed by shinjanpatra
|
constant
|
linear
|
# Python program to search all
# anagrams of a pattern in a text
MAX=256
# This function returns true
# if contents of arr1[] and arr2[]
# are same, otherwise false.
def compare(arr1, arr2):
for i in range(MAX):
if arr1[i] != arr2[i]:
return False
return True
# This function search for all
# permutations of pat[] in txt[]
def search(pat, txt):
M = len(pat)
N = len(txt)
# countP[]: Store count of
# all characters of pattern
# countTW[]: Store count of
# current window of text
countP = [0]*MAX
countTW = [0]*MAX
for i in range(M):
(countP[ord(pat[i]) ]) += 1
(countTW[ord(txt[i]) ]) += 1
# Traverse through remaining
# characters of pattern
for i in range(M,N):
# Compare counts of current
# window of text with
# counts of pattern[]
if compare(countP, countTW):
print("Found at Index", (i-M))
# Add current character to current window
(countTW[ ord(txt[i]) ]) += 1
# Remove the first character of previous window
(countTW[ ord(txt[i-M]) ]) -= 1
# Check for the last window in text
if compare(countP, countTW):
print("Found at Index", N-M)
# Driver program to test above function
txt = "BACDGABCDA"
pat = "ABCD"
search(pat, txt)
# This code is contributed
# by Upendra Singh Bartwal
|
linear
|
linear
|
# Python 3 program to find minimum
# number of characters
# to be removed to make two
# strings anagram.
CHARS = 26
# function to calculate minimum
# numbers of characters
# to be removed to make two
# strings anagram
def remAnagram(str1, str2):
# make hash array for both string
# and calculate
# frequency of each character
count1 = [0]*CHARS
count2 = [0]*CHARS
# count frequency of each character
# in first string
i = 0
while i < len(str1):
count1[ord(str1[i])-ord('a')] += 1
i += 1
# count frequency of each character
# in second string
i =0
while i < len(str2):
count2[ord(str2[i])-ord('a')] += 1
i += 1
# traverse count arrays to find
# number of characters
# to be removed
result = 0
for i in range(26):
result += abs(count1[i] - count2[i])
return result
# Driver program to run the case
if __name__ == "__main__":
str1 = "bcadeh"
str2 = "hea"
print(remAnagram(str1, str2))
# This code is contributed by
# ChitraNayal
|
constant
|
linear
|
# Python3 program to find minimum
# number of characters to be
# removed to make two strings
# anagram.
# function to calculate minimum
# numbers of characters to be
# removed to make two strings anagram
def makeAnagram(a, b):
buffer = [0] * 26
for char in a:
buffer[ord(char) - ord('a')] += 1
for char in b:
buffer[ord(char) - ord('a')] -= 1
return sum(map(abs, buffer))
# Driver Code
if __name__ == "__main__" :
str1 = "bcadeh"
str2 = "hea"
print(makeAnagram(str1, str2))
# This code is contributed
# by Raghib Ahsan
|
constant
|
linear
|
# Python3 program to check if two
# strings are k anagram or not.
MAX_CHAR = 26
# Function to check that is
# k-anagram or not
def arekAnagrams(str1, str2, k) :
# If both strings are not of equal
# length then return false
n = len(str1)
if (len(str2)!= n) :
return False
count1 = [0] * MAX_CHAR
count2 = [0] * MAX_CHAR
# Store the occurrence of all
# characters in a hash_array
for i in range(n):
count1[ord(str1[i]) -
ord('a')] += 1
for i in range(n):
count2[ord(str2[i]) -
ord('a')] += 1
count = 0
# Count number of characters that
# are different in both strings
for i in range(MAX_CHAR):
if (count1[i] > count2[i]) :
count = count + abs(count1[i] -
count2[i])
# Return true if count is less
# than or equal to k
return (count <= k)
# Driver Code
if __name__ == '__main__':
str1 = "anagram"
str2 = "grammar"
k = 2
if (arekAnagrams(str1, str2, k)):
print("Yes")
else:
print("No")
# This code is contributed
# by SHUBHAMSINGH10
|
constant
|
linear
|
# Optimized Python3 program
# to check if two strings
# are k anagram or not.
MAX_CHAR = 26;
# Function to check if str1
# and str2 are k-anagram or not
def areKAnagrams(str1, str2, k):
# If both strings are
# not of equal length
# then return false
n = len(str1);
if (len(str2) != n):
return False;
hash_str1 = [0]*(MAX_CHAR);
# Store the occurrence of
# all characters in a hash_array
for i in range(n):
hash_str1[ord(str1[i]) - ord('a')]+=1;
# Store the occurrence of all
# characters in a hash_array
count = 0;
for i in range(n):
if (hash_str1[ord(str2[i]) - ord('a')] > 0):
hash_str1[ord(str2[i]) - ord('a')]-=1;
else:
count+=1;
if (count > k):
return False;
# Return true if count is
# less than or equal to k
return True;
# Driver code
str1 = "fodr";
str2 = "gork";
k = 2;
if (areKAnagrams(str1, str2, k) == True):
print("Yes");
else:
print("No");
# This code is contributed by mits
|
constant
|
linear
|
# Python 3 program for the above approach
import sys
# Function to check k
# anagram of two strings
def kAnagrams(str1, str2, k):
flag = 0
list1 = []
# First Condition: If both the
# strings have different length ,
# then they cannot form anagram
if (len(str1) != len(str2)):
sys.exit()
# Converting str1 to Character Array arr1
arr1 = list(str1)
# Converting str2 to Character Array arr2
arr2 = list(str2)
# Sort arr1 in increasing order
arr1.sort()
# Sort arr2 in increasing order
arr2.sort()
# Iterate till str1.length()
for i in range(len(str1)):
# Condition if arr1[i] is
# not equal to arr2[i]
# then add it to list
if (arr1[i] != arr2[i]):
list1.append(arr2[i])
# Condition to check if
# strings for K-anagram or not
if (len(list1) <= k):
flag = 1
if (flag == 1):
return True
else:
return False
# Driver Code
if __name__ == "__main__":
str1 = "fodr"
str2 = "gork"
k = 2
# Function Call
kAnagrams(str1, str2, k)
if (kAnagrams(str1, str2, k) == True):
print("Yes")
else:
print("No")
|
constant
|
linear
|
# A simple Python program to check if binary
# representations of two numbers are anagram.
SIZE = 8
def bit_anagram_check(a, b):
# Find reverse binary representation of a
# and store it in binary_a[]
global size
i = 0
binary_a = [0] * SIZE
while (a > 0):
binary_a[i] = a % 2
a //= 2
i += 1
# Find reverse binary representation of b
# and store it in binary_a[]
j = 0
binary_b = [0] * SIZE
while (b > 0):
binary_b[j] = b % 2
b //= 2
j += 1
# Sort two binary representations
binary_a.sort()
binary_b.sort()
# Compare two sorted binary representations
for i in range(SIZE):
if (binary_a[i] != binary_b[i]):
return 0
return 1
# Driver code
if __name__ == "__main__":
a = 8
b = 4
print(bit_anagram_check(a, b))
# This code is contributed by ukasp.
|
constant
|
constant
|
# Python3 program to check if binary
# representations of two numbers are anagrams.
# Check each bit in a number is set or not
# and return the total count of the set bits.
def countSetBits(n) :
count = 0
while n>0 :
count += n & 1
n >>= 1
return count
def areAnagrams(A, B) :
return countSetBits(A) == countSetBits(B)
# Driver code
if __name__ == "__main__" :
a,b = 8,4
if areAnagrams(a, b) :
print("1")
else :
print("0")
# this code is contributed by aditya942003patil
|
constant
|
constant
|
# Python3 program for finding all anagram
# pairs in the given array
from collections import defaultdict
# Utility function for
# printing anagram list
def printAnagram(store: dict) -> None:
for (k, v) in store.items():
temp_vec = v
size = len(temp_vec)
if (size > 1):
for i in range(size):
print(temp_vec[i], end = " ")
print()
# Utility function for storing
# the vector of strings into HashMap
def storeInMap(vec: list) -> None:
store = defaultdict(lambda: list)
for i in range(len(vec)):
tempString = vec[i]
tempString = ''.join(sorted(tempString))
# Check for sorted string
# if it already exists
if (tempString not in store):
temp_vec = []
temp_vec.append(vec[i])
store[tempString] = temp_vec
else:
# Push new string to
# already existing key
temp_vec = store[tempString]
temp_vec.append(vec[i])
store[tempString] = temp_vec
# Print utility function for
# printing all the anagrams
printAnagram(store)
# Driver code
if __name__ == "__main__":
# Initialize vector of strings
arr = []
arr.append("geeksquiz")
arr.append("geeksforgeeks")
arr.append("abcd")
arr.append("forgeeksgeeks")
arr.append("zuiqkeegs")
arr.append("cat")
arr.append("act")
arr.append("tca")
# Utility function for storing
# strings into hashmap
storeInMap(arr)
# This code is contributed by sanjeev2552
|
linear
|
quadratic
|
# Python3 program to count total anagram
# substring of a string
def countOfAnagramSubstring(s):
# Returns total number of anagram
# substrings in s
n = len(s)
mp = dict()
# loop for length of substring
for i in range(n):
sb = ''
for j in range(i, n):
sb = ''.join(sorted(sb + s[j]))
mp[sb] = mp.get(sb, 0)
# increase count corresponding
# to this dict array
mp[sb] += 1
anas = 0
# loop over all different dictionary
# items and aggregate substring count
for k, v in mp.items():
anas += (v*(v-1))//2
return anas
# Driver Code
s = "xyyx"
print(countOfAnagramSubstring(s))
# This code is contributed by fgaim
|
linear
|
quadratic
|
# Python3 Program to find minimum number
# of manipulations required to make
# two strings identical
# Counts the no of manipulations
# required
def countManipulations(s1, s2):
count = 0
# store the count of character
char_count = [0] * 26
for i in range(26):
char_count[i] = 0
# iterate though the first String
# and update count
for i in range(len( s1)):
char_count[ord(s1[i]) -
ord('a')] += 1
# iterate through the second string
# update char_count.
# if character is not found in
# char_count then increase count
for i in range(len(s2)):
char_count[ord(s2[i]) - ord('a')] -= 1
for i in range(26):
if char_count[i] != 0:
count += abs(char_count[i])
return count / 2
# Driver code
if __name__ == "__main__":
s1 = "ddcf"
s2 = "cedk"
print(countManipulations(s1, s2))
# This code is contributed by ita_c
|
constant
|
linear
|
# Python program to check if a given string is a rotation
# of a palindrome
# A utility function to check if a string str is palindrome
def isPalindrome(string):
# Start from leftmost and rightmost corners of str
l = 0
h = len(string) - 1
# Keep comparing characters while they are same
while h > l:
l+= 1
h-= 1
if string[l-1] != string[h + 1]:
return False
# If we reach here, then all characters were matching
return True
# Function to check if a given string is a rotation of a
# palindrome.
def isRotationOfPalindrome(string):
# If string itself is palindrome
if isPalindrome(string):
return True
# Now try all rotations one by one
n = len(string)
for i in range(n-1):
string1 = string[i + 1:n]
string2 = string[0:i + 1]
# Check if this rotation is palindrome
string1+=(string2)
if isPalindrome(string1):
return True
return False
# Driver program
print ("1" if isRotationOfPalindrome("aab") == True else "0")
print ("1" if isRotationOfPalindrome("abcde") == True else "0")
print ("1" if isRotationOfPalindrome("aaaad") == True else "0")
# This code is contributed by BHAVYA JAIN
|
linear
|
quadratic
|
# Python3 implementation of above idea
# A function to check if n is palindrome
def isPalindrome(n: int) -> bool:
# Find reverse of n
rev = 0
i = n
while i > 0:
rev = rev * 10 + i % 10
i //= 10
# If n and rev are same,
# then n is palindrome
return (n == rev)
# prints palindrome between min and max
def countPal(minn: int, maxx: int) -> None:
for i in range(minn, maxx + 1):
if isPalindrome(i):
print(i, end = " ")
# Driver Code
if __name__ == "__main__":
countPal(100, 2000)
# This code is contributed by
# sanjeev2552
|
constant
|
logn
|
# Python 3 implementation of O(n^2)
# time and O(1) space method
# to find the longest palindromic substring
class LongestPalinSubstring :
maxLength = 0
# variables to store and
res = None
# update maxLength and res
# A utility function to get the longest palindrome
# starting and expanding out from given center indices
@staticmethod
def cSubUtil( s, l, r) :
# check if the indices lie in the range of string
# and also if it is palindrome
while (l >= 0 and r < len(s) and s[l] == s[r]) :
# expand the boundary
l -= 1
r += 1
# if it's length is greater than maxLength update
# maxLength and res
if (r - l - 1 >= LongestPalinSubstring.maxLength) :
LongestPalinSubstring.res = s[l + 1:r]
LongestPalinSubstring.maxLength = r - l - 1
return
# A function which takes a string prints the LPS and
# returns the length of LPS
@staticmethod
def longestPalSubstr( str) :
LongestPalinSubstring.res = ""
LongestPalinSubstring.maxLength = 1
# for every index in the string check palindromes
# starting from that index
i = 0
while (i < len(str)) :
# check for odd length palindromes
LongestPalinSubstring.cSubUtil(str, i, i)
# check for even length palindromes
LongestPalinSubstring.cSubUtil(str, i, i + 1)
i += 1
print("Longest palindrome substring is: ", end ="")
print(LongestPalinSubstring.res)
return LongestPalinSubstring.maxLength
# Driver program to test above function
@staticmethod
def main( args) :
str1 = "forgeeksskeegfor"
print("Length is: " + str(LongestPalinSubstring.longestPalSubstr(str1)))
if __name__=="__main__":
LongestPalinSubstring.main([])
# This code is contributed by phasing17.
|
constant
|
quadratic
|
# Python3 program to Count number of ways we
# can get palindrome string from a given
# string
# function to find the substring of the
# string
def substring(s, a, b):
s1 = ""
# extract the specified position of
# the string
for i in range(a, b, 1):
s1 += s[i]
return s1
# can get palindrome string from a
# given string
def allPalindromeSubstring(s):
v = []
# moving the pivot from starting till
# end of the string
pivot = 0.0
while pivot < len(s):
# set radius to the first nearest
# element on left and right
palindromeRadius = pivot - int(pivot)
# if the position needs to be
# compared has an element and the
# characters at left and right
# matches
while ((pivot + palindromeRadius) < len(s) and
(pivot - palindromeRadius) >= 0 and
(s[int(pivot - palindromeRadius)] ==
s[int(pivot + palindromeRadius)])):
v.append(s[int(pivot - palindromeRadius):
int(pivot + palindromeRadius + 1)])
# increasing the radius by 1 to point
# to the next elements in left and right
palindromeRadius += 1
pivot += 0.5
return v
# Driver Code
if __name__ == "__main__":
v = allPalindromeSubstring("hellolle")
print(len(v))
print(v)
v = allPalindromeSubstring("geeksforgeeks")
print(len(v))
print(v)
# This code is contributed by
# sanjeev2552
|
linear
|
cubic
|
# Python program Online algorithm for checking palindrome
# in a stream
# d is the number of characters in input alphabet
d = 256
# q is a prime number used for evaluating Rabin Karp's
# Rolling hash
q = 103
def checkPalindromes(string):
# Length of input string
N = len(string)
# A single character is always a palindrome
print string[0] + " Yes"
# Return if string has only one character
if N == 1:
return
# Initialize first half reverse and second half for
# as firstr and second characters
firstr = ord(string[0]) % q
second = ord(string[1]) % q
h = 1
i = 0
j = 0
# Now check for palindromes from second character
# onward
for i in xrange(1,N):
# If the hash values of 'firstr' and 'second'
# match, then only check individual characters
if firstr == second:
# Check if str[0..i] is palindrome using
# simple character by character match
for j in xrange(0,i/2):
if string[j] != string[i-j]:
break
j += 1
if j == i/2:
print string[i] + " Yes"
else:
print string[i] + " No"
else:
print string[i] + " No"
# Calculate hash values for next iteration.
# Don't calculate hash for next characters if
# this is the last character of string
if i != N-1:
# If i is even (next i is odd)
if i % 2 == 0:
# Add next character after first half at
# beginning of 'firstr'
h = (h*d) % q
firstr = (firstr + h*ord(string[i/2]))%q
# Add next character after second half at
# the end of second half.
second = (second*d + ord(string[i+1]))%q
else:
# If next i is odd (next i is even) then we
# need not to change firstr, we need to remove
# first character of second and append a
# character to it.
second = (d*(second + q - ord(string[(i+1)/2])*h)%q
+ ord(string[i+1]))%q
# Driver program
txt = "aabaacaabaa"
checkPalindromes(txt)
# This code is contributed by Bhavya Jain
|
constant
|
quadratic
|
# Python3 program to print all palindromic
# partitions of a given string.
def checkPalindrome(string):
# Returns true if str is palindrome,
# else false
length = len(string)
length -= 1
for i in range(length):
if string[i] != string[length]:
return False
length -= 1
return True
def printSolution(partitions):
for i in range(len(partitions)):
for j in range(len(partitions[i])):
print(partitions[i][j], end = " ")
print()
def addStrings(v, s, temp, index):
# Goes through all indexes and
# recursively add remaining partitions
# if current string is palindrome.
length = len(s)
string = ""
current = temp[:]
if index == 0:
temp = []
for i in range(index, length):
string += s[i]
if checkPalindrome(string):
temp.append(string)
if i + 1 < length:
addStrings(v, s, temp[:], i + 1)
else:
v.append(temp)
temp = current
def partition(s, v):
# Generates all palindromic partitions
# of 's' and stores the result in 'v'.
temp = []
addStrings(v, s, temp[:], 0)
printSolution(v)
# Driver Code
if __name__ == "__main__":
s = "geeks"
partitions = []
partition(s, partitions)
# This code is contributed by
# vibhu4agarwal
|
linear
|
quadratic
|
# Python3 code to Count Palindromic
# Subsequence in a given String
# Function return the total
# palindromic subsequence
def countPS(str):
N = len(str)
# Create a 2D array to store the count
# of palindromic subsequence
cps = [[0 for i in range(N + 2)]for j in range(N + 2)]
# palindromic subsequence of length 1
for i in range(N):
cps[i][i] = 1
# check subsequence of length L
# is palindrome or not
for L in range(2, N + 1):
for i in range(N):
k = L + i - 1
if (k < N):
if (str[i] == str[k]):
cps[i][k] = (cps[i][k - 1] +
cps[i + 1][k] + 1)
else:
cps[i][k] = (cps[i][k - 1] +
cps[i + 1][k] -
cps[i + 1][k - 1])
# return total palindromic subsequence
return cps[0][N - 1]
# Driver program
str = "abcb"
print("Total palindromic subsequence are : ", countPS(str))
# This code is contributed by Anant Agarwal.
|
quadratic
|
quadratic
|
# Python 3 program to counts Palindromic
# Subsequence in a given String using recursion
str = "abcb"
# Function return the total
# palindromic subsequence
def countPS(i, j):
if(i > j):
return 0
if(dp[i][j] != -1):
return dp[i][j]
if(i == j):
dp[i][j] = 1
return dp[i][j]
else if (str[i] == str[j]):
dp[i][j] = (countPS(i + 1, j) +
countPS(i, j - 1) + 1)
return dp[i][j]
else:
dp[i][j] = (countPS(i + 1, j) +
countPS(i, j - 1) -
countPS(i + 1, j - 1))
return dp[i][j]
# Driver code
if __name__ == "__main__":
dp = [[-1 for x in range(1000)]
for y in range(1000)]
n = len(str)
print("Total palindromic subsequence are :",
countPS(0, n - 1))
# This code is contributed by ita_c
|
quadratic
|
quadratic
|
# Python 3 program for getting minimum character
# to be added at front to make string palindrome
# function for checking string is
# palindrome or not
def ispalindrome(s):
l = len(s)
i = 0
j = l - 1
while i <= j:
if(s[i] != s[j]):
return False
i += 1
j -= 1
return True
# Driver code
if __name__ == "__main__":
s = "BABABAA"
cnt = 0
flag = 0
while(len(s) > 0):
# if string becomes palindrome then break
if(ispalindrome(s)):
flag = 1
break
else:
cnt += 1
# erase the last element of the string
s = s[:-1]
# print the number of insertion at front
if(flag):
print(cnt)
# This code is contributed by ita_c
|
constant
|
quadratic
|
# Python3 program for getting minimum
# character to be added at the front
# to make string palindrome
# Returns vector lps for given string str
def computeLPSArray(string):
M = len(string)
lps = [None] * M
length = 0
lps[0] = 0 # lps[0] is always 0
# the loop calculates lps[i]
# for i = 1 to M-1
i = 1
while i < M:
if string[i] == string[length]:
length += 1
lps[i] = length
i += 1
else: # (str[i] != str[len])
# This is tricky. Consider the example.
# AAACAAAA and i = 7. The idea is
# similar to search step.
if length != 0:
length = lps[length - 1]
# Also, note that we do not
# increment i here
else: # if (len == 0)
lps[i] = 0
i += 1
return lps
# Method returns minimum character
# to be added at front to make
# string palindrome
def getMinCharToAddedToMakeStringPalin(string):
revStr = string[::-1]
# Get concatenation of string,
# special character and reverse string
concat = string + "$" + revStr
# Get LPS array of this
# concatenated string
lps = computeLPSArray(concat)
# By subtracting last entry of lps
# vector from string length, we
# will get our result
return len(string) - lps[-1]
# Driver Code
if __name__ == "__main__":
string = "AACECAAAA"
print(getMinCharToAddedToMakeStringPalin(string))
# This code is contributed by Rituraj Jain
|
linear
|
linear
|
# Python3 program to get largest palindrome changing
# atmost K digits
# Returns maximum possible
# palindrome using k changes
def maximumPalinUsingKChanges(strr, k):
palin = strr[::]
# Initialize l and r by leftmost and
# rightmost ends
l = 0
r = len(strr) - 1
# first try to make palindrome
while (l <= r):
# Replace left and right character by
# maximum of both
if (strr[l] != strr[r]):
palin[l] = palin[r] =
max(strr[l], strr[r])
# print(strr[l],strr[r])
k -= 1
l += 1
r -= 1
# If k is negative then we can't make
# palindrome
if (k < 0):
return "Not possible"
l = 0
r = len(strr) - 1
while (l <= r):
# At mid character, if K>0 then change
# it to 9
if (l == r):
if (k > 0):
palin[l] = '9'
# If character at lth (same as rth) is
# less than 9
if (palin[l] < '9'):
# If none of them is changed in the
# previous loop then subtract 2 from K
# and convert both to 9
if (k >= 2 and palin[l] == strr[l] and
palin[r] == strr[r]):
k -= 2
palin[l] = palin[r] = '9'
# If one of them is changed in the previous
# loop then subtract 1 from K (1 more is
# subtracted already) and make them 9
elif (k >= 1 and (palin[l] != strr[l] or
palin[r] != strr[r])):
k -= 1
palin[l] = palin[r] = '9'
l += 1
r -= 1
return palin
# Driver code
st = "43435"
strr = [i for i in st]
k = 3
a = maximumPalinUsingKChanges(strr, k)
print("".join(a))
# This code is contributed by mohit kumar 29
|
linear
|
linear
|
# A recursive Python program
# to check whether a given
# number is palindrome or not
# A recursive function that
# check a str[s..e] is
# palindrome or not.
def isPalRec(st, s, e) :
# If there is only one character
if (s == e):
return True
# If first and last
# characters do not match
if (st[s] != st[e]) :
return False
# If there are more than
# two characters, check if
# middle substring is also
# palindrome or not.
if (s < e + 1) :
return isPalRec(st, s + 1, e - 1);
return True
def isPalindrome(st) :
n = len(st)
# An empty string is
# considered as palindrome
if (n == 0) :
return True
return isPalRec(st, 0, n - 1);
# Driver Code
st = "geeg"
if (isPalindrome(st)) :
print "Yes"
else :
print "No"
# This code is contributed
# by Nikita Tiwari.
|
linear
|
linear
|
def isPalindrome(s, i):
if(i > len(s)/2):
return True
ans = False
if((s[i] is s[len(s) - i - 1]) and isPalindrome(s, i + 1)):
ans = True
return ans
str = "geeg"
if (isPalindrome(str, 0)):
print("Yes")
else:
print("No")
# This code is contributed by akashish__
|
linear
|
linear
|
# Python 3 implementation to find maximum
# length substring which is not palindrome
# utility function to check whether
# a string is palindrome or not
def isPalindrome(str):
# Check for palindrome.
n = len(str)
for i in range(n // 2):
if (str[i] != str[n - i - 1]):
return False
# palindrome string
return True
# function to find maximum length
# substring which is not palindrome
def maxLengthNonPalinSubstring(str):
n = len(str)
ch = str[0]
# to check whether all characters
# of the string are same or not
i = 1
for i in range(1, n):
if (str[i] != ch):
break
# All characters are same, we can't
# make a non-palindromic string.
if (i == n):
return 0
# If string is palindrome, we can make
# it non-palindrome by removing any
# corner character
if (isPalindrome(str)):
return n - 1
# Complete string is not a palindrome.
return n
# Driver Code
if __name__ == "__main__":
str = "abba"
print("Maximum length =",
maxLengthNonPalinSubstring(str))
# This code is contributed by ita_c
|
linear
|
linear
|
# Python3 program to query the number of
# palindromic substrings of a string in a range
M = 50
# Utility method to construct the dp array
def constructDP(dp, string):
l = len(string)
# declare 2D array isPalin, isPalin[i][j]
# will be 1 if str(i..j) is palindrome
# and initialize it with zero
isPalin = [[0 for i in range(l + 1)]
for j in range(l + 1)]
# loop for starting index of range
for i in range(l - 1, -1, -1):
# initialize value for one
# character strings as 1
isPalin[i][i], dp[i][i] = 1, 1
# loop for ending index of range
for j in range(i + 1, l):
# isPalin[i][j] will be 1 if ith and jth
# characters are equal and mid substring
# str(i+1..j-1) is also a palindrome
isPalin[i][j] = (string[i] == string[j] and
(i + 1 > j - 1 or isPalin[i + 1][j - 1]))
# dp[i][j] will be addition of number
# of palindromes from i to j-1 and i+1
# to j subtracting palindromes from i+1
# to j-1 (as counted twice) plus 1 if
# str(i..j) is also a palindrome
dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] -
dp[i + 1][j - 1] + isPalin[i][j])
# Method returns count of palindromic
# substring in range (l, r)
def countOfPalindromeInRange(dp, l, r):
return dp[l][r]
# Driver code
if __name__ == "__main__":
string = "xyaabax"
dp = [[0 for i in range(M)]
for j in range(M)]
constructDP(dp, string)
l, r = 3, 5
print(countOfPalindromeInRange(dp, l, r))
# This code is contributed by Rituraj Jain
|
quadratic
|
quadratic
|
# Python3 program to find minimum number
# of insertions to make a string
# palindrome
import math as mt
# Function will return number of
# characters to be added
def minInsertion(tr1):
# To store string length
n = len(str1)
# To store number of characters
# occurring odd number of times
res = 0
# To store count of each
# character
count = [0 for i in range(26)]
# To store occurrence of each
# character
for i in range(n):
count[ord(str1[i]) - ord('a')] += 1
# To count characters with odd
# occurrence
for i in range(26):
if (count[i] % 2 == 1):
res += 1
# As one character can be odd return
# res - 1 but if string is already
# palindrome return 0
if (res == 0):
return 0
else:
return res - 1
# Driver Code
str1 = "geeksforgeeks"
print(minInsertion(str1))
# This code is contributed by
# Mohit kumar 29
|
constant
|
linear
|
# Python3 program to find n=th even
# length string.
import math as mt
# Function to find nth even length
# Palindrome
def evenlength(n):
# string r to store resultant
# palindrome. Initialize same as s
res = n
# In this loop string r stores
# reverse of string s after the
# string s in consecutive manner .
for j in range(len(n) - 1, -1, -1):
res += n[j]
return res
# Driver code
n = "10"
# Function call
print(evenlength(n))
# This code is contributed by
# Mohit kumar 29
|
linear
|
linear
|
# code to make 'ab' free string
def abFree(s):
# Traverse from end. Keep track of count
# b's. For every 'a' encountered, add b_count
# to result and double b_count.
b_count = 0
res = 0
for i in range(len(s)):
if s[~i] == 'a':
res = (res + b_count)
b_count = (b_count * 2)
else:
b_count += 1
return res
# driver code
s = 'abbaa'
print(abFree(s))
s = 'aab'
print(abFree(s))
s ='ababab'
print(abFree(s))
|
linear
|
linear
|
# Python3 implementation of program to find the maximum length
# that can be removed
# Function to find the length of longest sub-string that
# can me make removed
# arr --> pair type of array whose first field store
# character in and second field stores
# corresponding index of that character
def longestNull(S):
arr=[]
# store {'@',-1} in arr , here this value will
# work as base index
arr.append(['@', -1])
maxlen = 0 # Initialize result
# one by one iterate characters of String
for i in range(len(S)):
# make pair of char and index , then store
# them into arr
arr.append([S[i], i])
# now if last three elements of arr[] are making
# sub-string"100" or not
while (len(arr)>=3 and
arr[len(arr)-3][0]=='1' and
arr[len(arr)-2][0]=='0' and
arr[len(arr)-1][0]=='0'):
# if above condition is true then delete
# sub-string"100" from arr[]
arr.pop()
arr.pop()
arr.pop()
# index of current last element in arr[]
tmp = arr[-1]
# This is important, here 'i' is the index of
# current character inserted into arr[]
# and 'tmp' is the index of last element in arr[]
# after continuous deletion of sub-String
# "100" from arr[] till we make it null, difference
# of these to 'i-tmp' gives the length of current
# sub-string that can be make null by continuous
# deletion of sub-string"100"
maxlen = max(maxlen, i - tmp[1])
return maxlen
# Driver code
print(longestNull("1011100000100"))
# This code is contributed by mohit kumar 29
|
linear
|
linear
|
# Python 3 program to find minimum number of
# flip to make binary string alternate
# Utility method to flip a character
def flip( ch):
return '1' if (ch == '0') else '0'
# Utility method to get minimum flips when
# alternate string starts with expected char
def getFlipWithStartingCharcter(str, expected):
flipCount = 0
for i in range(len( str)):
# if current character is not expected,
# increase flip count
if (str[i] != expected):
flipCount += 1
# flip expected character each time
expected = flip(expected)
return flipCount
# method return minimum flip to make binary
# string alternate
def minFlipToMakeStringAlternate(str):
# return minimum of following two
# 1) flips when alternate string starts with 0
# 2) flips when alternate string starts with 1
return min(getFlipWithStartingCharcter(str, '0'),
getFlipWithStartingCharcter(str, '1'))
# Driver code to test above method
if __name__ == "__main__":
str = "0001010111"
print(minFlipToMakeStringAlternate(str))
|
constant
|
linear
|
# An efficient Python 3 program to
# find 2's complement
# Function to find two's complement
def findTwoscomplement(str):
n = len(str)
# Traverse the string to get first
# '1' from the last of string
i = n - 1
while(i >= 0):
if (str[i] == '1'):
break
i -= 1
# If there exists no '1' concatenate 1
# at the starting of string
if (i == -1):
return '1'+str
# Continue traversal after the
# position of first '1'
k = i - 1
while(k >= 0):
# Just flip the values
if (str[k] == '1'):
str = list(str)
str[k] = '0'
str = ''.join(str)
else:
str = list(str)
str[k] = '1'
str = ''.join(str)
k -= 1
# return the modified string
return str
# Driver code
if __name__ == '__main__':
str = "00000101"
print(findTwoscomplement(str))
# This code is contributed by
# Sanjit_Prasad
|
constant
|
linear
|
# Python 3 program to count all
# distinct binary strings with
# two consecutive 1's
# Returns count of n length
# binary strings with
# consecutive 1's
def countStrings(n):
# Count binary strings without
# consecutive 1's.
# See the approach discussed on be
# ( http://goo.gl/p8A3sW )
a = [0] * n
b = [0] * n
a[0] = b[0] = 1
for i in range(1, n):
a[i] = a[i - 1] + b[i - 1]
b[i] = a[i - 1]
# Subtract a[n-1]+b[n-1] from 2^n
return (1 << n) - a[n - 1] - b[n - 1]
# Driver code
print(countStrings(5))
# This code is contributed
# by Nikita tiwari.
|
linear
|
linear
|
# Recursive Python program to generate all
# binary strings formed by replacing
# each wildcard character by 0 or 1
# Recursive function to generate all binary
# strings formed by replacing each wildcard
# character by 0 or 1
def _print(string, index):
if index == len(string):
print(''.join(string))
return
if string[index] == "?":
# replace '?' by '0' and recurse
string[index] = '0'
_print(string, index + 1)
# replace '?' by '1' and recurse
string[index] = '1'
_print(string, index + 1)
# NOTE: Need to backtrack as string
# is passed by reference to the
# function
string[index] = '?'
else:
_print(string, index + 1)
# Driver code
if __name__ == "__main__":
string = "1??0?101"
string = list(string)
_print(string, 0)
# This code is contributed by
# sanjeev2552
# Note: function name _print is used because
# print is already a predefined function in Python
|
quadratic
|
np
|
# Iterative Python program to generate all binary
# strings formed by replacing each wildcard
# character by 0 or 1
# Iterative function to generate all binary strings
# formed by replacing each wildcard character by 0
# or 1
def Print(Str):
q = []
q.append(Str)
while(len(q) > 0):
Str = q[0]
# find position of first occurrence of wildcard
try:
index = Str.index('?')
except ValueError:
index = -1
# If no matches were found,
# find returns -1
if(index != -1):
# replace '?' by '0' and push string into queue
s1=Str.replace('?','0',1)
q.append(s1)
# replace '?' by '1' and push string into queue
s2=Str.replace('?','1',1)
q.append(s2)
else:
# If no wildcard characters are left,
# print the string.
print(Str)
q.pop(0)
# Driver code
Str = "1??0?101"
Print(Str)
# This code is contributed by Pushpesh Raj
|
np
|
quadratic
|
#we store processed strings in all (array)
#we see if string as "?", if so, replace it with 0 and 1
#and send it back to recursive func until base case is reached
#which is no wildcard left
res = []
def genBin(s):
if '?' in s:
s1 = s.replace('?','0',1) #only replace once
s2 = s.replace('?','1',1) #only replace once
genBin(s1)
genBin(s2)
else: res.append(s)
# Driver code
genBin("1??0?101")
print(res)
# This code is contributed by
# divay pandey
|
np
|
quadratic
|
# The function that adds two-bit sequences and returns the addition
def addBitStrings(str1, str2):
ans = ''
i = len(str1) - 1
j = len(str2) - 1
carry = 0
while i >= 0 or j >= 0 or carry:
if i >= 0:
carry += ord(str1[i]) - ord('0')
i = i - 1
else:
carry += 0
if j >= 0:
carry += ord(str2[j]) - ord('0')
j = j - 1
else:
carry += 0
ans = chr(ord('0') + carry % 2) + ans
carry = carry // 2
return ans
# Driver program to test above functions
str1 = '1100011'
str2 = '10'
print('Sum is ', addBitStrings(str1, str2))
# This code is contributed by ajaymakavan.
|
constant
|
linear
|
# Python program to count
# all distinct binary strings
# without two consecutive 1's
def countStrings(n):
a=[0 for i in range(n)]
b=[0 for i in range(n)]
a[0] = b[0] = 1
for i in range(1,n):
a[i] = a[i-1] + b[i-1]
b[i] = a[i-1]
return a[n-1] + b[n-1]
# Driver program to test
# above functions
print(countStrings(3))
# This code is contributed
# by Anant Agarwal.
|
linear
|
linear
|
class Subset_sum :
@staticmethod
def countStrings( n) :
a = 1
b = 1
i = 1
while (i < n) :
# Here we have used the temp variable because
# we want to assign the older value of a to b
temp = a + b
b = a
a = temp
i += 1
return a + b
# Driver program to test above function
@staticmethod
def main( args) :
print(Subset_sum.countStrings(3))
if __name__=="__main__":
Subset_sum.main([])
# This code is contributed by aadityaburujwale.
|
constant
|
linear
|
# Python 3program to check if a
# string is of the form a^nb^n.
# Returns true str is of the
# form a^nb^n.
def isAnBn(str):
n = len(str)
# After this loop 'i' has
# count of a's
for i in range(n):
if (str[i] != 'a'):
break
# Since counts of a's and b's should
# be equal, a should appear exactly
# n/2 times
if (i * 2 != n):
return False
# Rest of the characters must
# be all 'b'
for j in range(i, n):
if (str[j] != 'b'):
return False
return True
# Driver code
if __name__ == "__main__":
str = "abab"
print("Yes") if isAnBn(str) else print("No")
# This code is contributed
# by ChitraNayal
|
constant
|
linear
|
# Python3 code to check
# a^nb^n pattern
def isanbn(str):
n=len(str)
# if length of str is odd return No
if n&1:
return "No"
# check first half is 'a' and other half is full of 'b'
for i in range(int(n/2)):
if str[i]!='a' or str[n-i-1]!='b':
return "No"
return "Yes"
# Driver code
input_str = "ab"
# Function call
print(isanbn(input_str))
|
constant
|
linear
|
# Python3 implementation to find the binary
# representation of next greater integer
# function to find the required
# binary representation
def nextGreater(num1):
l = len(num1);
num = list(num1);
# examine bits from the right
i = l-1;
while(i >= 0):
# if '0' is encountered, convert
# it to '1' and then break
if (num[i] == '0'):
num[i] = '1';
break;
# else convert '1' to '0'
else:
num[i] = '0';
i-=1;
# if the binary representation
# contains only the set bits
num1 = ''.join(num);
if (i < 0):
num1 = '1' + num1;
# final binary representation
# of the required integer
return num1;
# Driver Code
num = "10011";
print("Binary representation of next number = ",nextGreater(num));
# This code is contributed by mits
|
linear
|
linear
|
# Python3 program to find next permutation in a
# binary string.
# Function to find the next greater number
# with same number of 1's and 0's
def nextGreaterWithSameDigits(bnum):
l = len(bnum)
bnum = list(bnum)
for i in range(l - 2, 0, -1):
# locate first 'i' from end such that
# bnum[i]=='0' and bnum[i+1]=='1'
# swap these value and break
if (bnum[i] == '0' and bnum[i + 1] == '1'):
ch = bnum[i]
bnum[i] = bnum[i + 1]
bnum[i + 1] = ch
break
# if no swapping performed
if (i == 0):
return "no greater number"
# Since we want the smallest next value,
# shift all 1's at the end in the binary
# substring starting from index 'i+2'
j = i + 2
k = l - 1
while (j < k):
if (bnum[j] == '1' and bnum[k] == '0'):
ch = bnum[j]
bnum[j] = bnum[k]
bnum[k] = ch
j += 1
k -= 1
# special case while swapping if '0'
# occurs then break
else if (bnum[i] == '0'):
break
else:
j += 1
# required next greater number
return bnum
# Driver code
bnum = "10010"
print("Binary representation of next greater number = ",*nextGreaterWithSameDigits(bnum),sep="")
# This code is contributed by shubhamsingh10
|
constant
|
linear
|
# Python Program to find the length of
# substring with maximum difference of
# zeros and ones in binary string.
# Returns the length of substring with
# maximum difference of zeroes and ones
# in binary string
def findLength(string, n):
current_sum = 0
max_sum = 0
# traverse a binary string from left
# to right
for i in range(n):
# add current value to the current_sum
# according to the Character
# if it's '0' add 1 else -1
current_sum += (1 if string[i] == '0' else -1)
if current_sum < 0:
current_sum = 0
# update maximum sum
max_sum = max(current_sum, max_sum)
# return -1 if string does not contain
# any zero that means all ones
# otherwise max_sum
return max_sum if max_sum else 0
# Driven Program
s = "11000010001"
n = 11
print(findLength(s, n))
# This code is contributed by Ansu Kumari.
|
linear
|
linear
|
# Python3 regex program to check for valid string
import re
# Method to check for valid string
def checkString(str):
# regular expression for invalid string
regex = "10+1"
x = re.search("10+1", str)
return x is None
#Driver method
str = "00011111111100000"
if checkString(str):
print("VALID")
else:
print("NOT VALID")
#this code is contributed by phasing17
|
constant
|
linear
|
# Python 3 program to find min flips in
# binary string to make all characters equal
# To find min number of flips in
# binary string
def findFlips(str, n):
last = ' '
res = 0
for i in range( n) :
# If last character is not equal
# to str[i] increase res
if (last != str[i]):
res += 1
last = str[i]
# To return min flips
return res // 2
# Driver Code
if __name__ == "__main__":
str = "00011110001110"
n = len(str)
print(findFlips(str, n))
# This code is contributed by ita_c
|
constant
|
linear
|
# Python Solution for above problem:
# This function adds two binary
# strings return the resulting string
def add_binary_nums(x, y):
max_len = max(len(x), len(y))
x = x.zfill(max_len)
y = y.zfill(max_len)
# initialize the result
result = ''
# initialize the carry
carry = 0
# Traverse the string
for i in range(max_len - 1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1 # Compute the carry.
if carry !=0 : result = '1' + result
return result.zfill(max_len)
# Driver code
print(add_binary_nums('1101', '100'))
# This code is contributed
# by Anand Khatri
|
linear
|
linear
|
# Python 3 program to convert
# string into binary string
# utility function
def strToBinary(s):
bin_conv = []
for c in s:
# convert each char to
# ASCII value
ascii_val = ord(c)
# Convert ASCII value to binary
binary_val = bin(ascii_val)
bin_conv.append(binary_val[2:])
return (' '.join(bin_conv))
# Driver Code
if __name__ == '__main__':
s = 'geeks'
print (strToBinary(s))
# This code is contributed
# by Vikas Chitturi
|
linear
|
linear
|
# Python3 program to Generate all binary string
# without consecutive 1's of size K
# A utility function generate all string without
# consecutive 1'sof size K
def generateAllStringsUtil(K, str, n):
# print binary string without consecutive 1's
if (n == K):
# terminate binary string
print(*str[:n], sep = "", end = " ")
return
# if previous character is '1' then we put
# only 0 at end of string
# example str = "01" then new string be "000"
if (str[n-1] == '1'):
str[n] = '0'
generateAllStringsUtil (K, str, n + 1)
# if previous character is '0' than we put
# both '1' and '0' at end of string
# example str = "00" then new string "001" and "000"
if (str[n-1] == '0'):
str[n] = '0'
generateAllStringsUtil(K, str, n + 1)
str[n] = '1'
generateAllStringsUtil(K, str, n + 1)
# function generate all binary string without
# consecutive 1's
def generateAllStrings(K):
# Base case
if (K <= 0):
return
# One by one stores every
# binary string of length K
str = [0] * K
# Generate all Binary string starts with '0'
str[0] = '0'
generateAllStringsUtil (K, str, 1)
# Generate all Binary string starts with '1'
str[0] = '1'
generateAllStringsUtil (K, str, 1)
# Driver code
K = 3
generateAllStrings (K)
# This code is contributed by SHUBHAMSINGH10
|
linear
|
np
|
def All_Binary_Strings(arr,num,r):
if(r == num):
for i in range(num):
print(arr[i],end="")
print(end=" ")
return
elif(arr[r-1]):
arr[r] = 0
All_Binary_Strings(arr, num, r + 1)
else:
arr[r] = 0
All_Binary_Strings(arr,num,r+1)
arr[r] = 1
All_Binary_Strings(arr,num,r+1)
def Print(a,num):
a[0] = 0
All_Binary_Strings(a,num,1)
a[0] = 1
All_Binary_Strings(a,num,1)
# driver's code
n = 2
a = [False for i in range(n)]
Print(a,n)
# This code is contributed by shinjanpatra
|
linear
|
np
|
def All_Binary_Strings(str,num):
Len = len(str)
if(Len == num):
print(str,end = " ")
return
elif(str[Len - 1]=='1'):
All_Binary_Strings(str+'0',num)
else:
All_Binary_Strings(str+'0',num)
All_Binary_Strings(str+'1',num)
def Print(num):
word = ""
word += '0'
All_Binary_Strings(word,num)
word = '1'
All_Binary_Strings(word,num)
# Driver's code
n = 4
Print(n)
# This code is contributed by shinjanpatra.
|
linear
|
np
|
# Python 3 implementation to check
# whether given binary number is
# evenly divisible by 2^k or not
# function to check whether
# given binary number is
# evenly divisible by 2^k or not
def isDivisible(str, k):
n = len(str)
c = 0
# count of number of 0 from last
for i in range(0, k):
if (str[n - i - 1] == '0'):
c += 1
# if count = k, number is evenly
# divisible, so returns true else
# false
return (c == k)
# Driver program to test above
# first example
str1 = "10101100"
k = 2
if (isDivisible(str1, k)):
print("Yes")
else:
print("No")
# Second example
str2 = "111010100"
k = 2
if (isDivisible(str2, k)):
print("Yes")
else:
print("No")
# This code is contributed by Smitha
|
constant
|
constant
|
# Python3 Program to find ith character in
# a binary string.
# Function to store binary Representation
def binary_conversion(s, m):
while(m):
temp = m % 2
s += str(temp)
m = m // 2
return s[::-1]
# Function to find ith character
def find_character(n, m, i):
s = ""
# Function to change decimal to binary
s = binary_conversion(s, m)
s1 = ""
for x in range(n):
for j in range(len(s)):
if s[j] == "1":
s1 += "10"
else:
s1 += "01"
# Assign s1 string in s string
s = s1
s1 = ""
e = ord(s[i])
r = ord('0')
return e-r
# Driver code
m, n, i = 5, 2, 8
print(find_character(n,m,i))
# This code is contributed by mohit kumar 29
|
linear
|
quadratic
|
# python program to count substrings
# with odd decimal value
import math
# function to count number of substrings
# with odd decimal representation
def countSubstr( s):
n = len(s)
# auxiliary array to store count
# of 1's before ith index
auxArr= [0 for i in range(n)]
if (s[0] == '1'):
auxArr[0] = 1
# store count of 1's before
# i-th index
for i in range(0,n):
if (s[i] == '1'):
auxArr[i] = auxArr[i-1]+1
else:
auxArr[i] = auxArr[i-1]
# variable to store answer
count = 0
# traverse the string reversely to
# calculate number of odd substrings
# before i-th index
for i in range(n-1,-1,-1):
if (s[i] == '1'):
count += auxArr[i]
return count
# Driver method
s = "1101"
print (countSubstr(s))
# This code is contributed by Gitanjali.
|
linear
|
linear
|
# Python3 program to generate n-bit Gray codes
import math as mt
# This function generates all n bit Gray
# codes and prints the generated codes
def generateGrayarr(n):
# base case
if (n <= 0):
return
# 'arr' will store all generated codes
arr = list()
# start with one-bit pattern
arr.append("0")
arr.append("1")
# Every iteration of this loop generates
# 2*i codes from previously generated i codes.
i = 2
j = 0
while(True):
if i >= 1 << n:
break
# Enter the previously generated codes
# again in arr[] in reverse order.
# Nor arr[] has double number of codes.
for j in range(i - 1, -1, -1):
arr.append(arr[j])
# append 0 to the first half
for j in range(i):
arr[j] = "0" + arr[j]
# append 1 to the second half
for j in range(i, 2 * i):
arr[j] = "1" + arr[j]
i = i << 1
# print contents of arr[]
for i in range(len(arr)):
print(arr[i])
# Driver Code
generateGrayarr(3)
# This code is contributed
# by Mohit kumar 29
|
np
|
np
|
# Python3 program to generate
# n-bit Gray codes
# This function generates all n
# bit Gray codes and prints the
# generated codes
def generateGray(n):
# Base case
if (n <= 0):
return ["0"]
if (n == 1):
return [ "0", "1" ]
# Recursive case
recAns = generateGray(n - 1)
mainAns = []
# Append 0 to the first half
for i in range(len(recAns)):
s = recAns[i]
mainAns.append("0" + s)
# Append 1 to the second half
for i in range(len(recAns) - 1, -1, -1):
s = recAns[i]
mainAns.append("1" + s)
return mainAns
# Function to generate the
# Gray code of N bits
def generateGrayarr(n):
arr = generateGray(n)
# Print contents of arr
print(*arr, sep = "\n")
# Driver Code
generateGrayarr(3)
# This code is contributed by avanitrachhadiya2155
|
np
|
np
|
# Python3 implementation of the above approach
def GreyCode(n):
# power of 2
for i in range(1 << n):
# Generating the decimal
# values of gray code then using
# bitset to convert them to binary form
val = (i ^ (i >> 1))
# Converting to binary string
s = bin(val)[2::]
print(s.zfill(n), end = " ")
# Driver Code
n = 4
# Function call
GreyCode(n)
# This code is contributed by phasing17
|
linear
|
np
|
# Python 3 program to print all N-bit binary
# function to generate n digit numbers
def printRec(number, extraOnes, remainingPlaces):
# if number generated
if (0 == remainingPlaces):
print(number, end=" ")
return
# Append 1 at the current number and
# reduce the remaining places by one
printRec(number + "1", extraOnes + 1,
remainingPlaces - 1)
# If more ones than zeros, append 0 to
# the current number and reduce the
# remaining places by one
if (0 < extraOnes):
printRec(number + "0", extraOnes - 1,
remainingPlaces - 1)
def printNums(n):
str = ""
printRec(str, 0, n)
# Driver Code
if __name__ == '__main__':
n = 4
# Function call
printNums(n)
# This code is contributed by
# Surendra_Gangwar
|
linear
|
linear
|
# Python3 program to print
# all N-bit binary
# Function to get the binary
# representation of the number N
def getBinaryRep(N, num_of_bits):
r = "";
num_of_bits -= 1
# loop for each bit
while (num_of_bits >= 0):
if (N & (1 << num_of_bits)):
r += ("1");
else:
r += ("0");
num_of_bits -= 1
return r;
def NBitBinary(N):
r = []
first = 1 << (N - 1);
last = first * 2;
# generate numbers in the range
# of (2^N)-1 to 2^(N-1) inclusive
for i in range (last - 1,
first - 1, -1):
zero_cnt = 0;
one_cnt = 0;
t = i;
num_of_bits = 0;
# longest prefix check
while (t):
if (t & 1):
one_cnt += 1
else:
zero_cnt += 1
num_of_bits += 1
t = t >> 1;
# if counts of 1 is greater
# than counts of zero
if (one_cnt >= zero_cnt):
# do sub-prefixes check
all_prefix_match = True;
msk = (1 << num_of_bits) - 2;
prefix_shift = 1;
while (msk):
prefix = ((msk & i) >>
prefix_shift);
prefix_one_cnt = 0;
prefix_zero_cnt = 0;
while (prefix):
if (prefix & 1):
prefix_one_cnt += 1
else:
prefix_zero_cnt += 1
prefix = prefix >> 1;
if (prefix_zero_cnt >
prefix_one_cnt):
all_prefix_match = False;
break;
prefix_shift += 1
msk = msk & (msk << 1);
if (all_prefix_match):
r.append(getBinaryRep(i,
num_of_bits));
return r
# Driver code
if __name__ == "__main__":
n = 4;
# Function call
results = NBitBinary(n);
for i in range (len(results)):
print (results[i],
end = " ")
print ()
# This code is contributed by Chitranayal
|
linear
|
quadratic
|
# Python3 program to add n binary strings
# This function adds two binary strings and
# return result as a third string
def addBinaryUtil(a, b):
result = ""; # Initialize result
s = 0; # Initialize digit sum
# Traverse both strings
# starting from last characters
i = len(a) - 1;
j = len(b) - 1;
while (i >= 0 or j >= 0 or s == 1):
# Compute sum of last digits and carry
s += (ord(a[i]) - ord('0')) if(i >= 0) else 0;
s += (ord(b[j]) - ord('0')) if(j >= 0) else 0;
# If current digit sum is 1 or 3,
# add 1 to result
result = chr(s % 2 + ord('0')) + result;
# Compute carry
s //= 2;
# Move to next digits
i -= 1;
j -= 1;
return result;
# function to add n binary strings
def addBinary(arr, n):
result = "";
for i in range(n):
result = addBinaryUtil(result, arr[i]);
return result;
# Driver code
arr = ["1", "10", "11"];
n = len(arr);
print(addBinary(arr, n));
# This code is contributed by mits
|
linear
|
linear
|
# Python3 program to generate power
# set in lexicographic order.
# str : Stores input string
# n : Length of str.
# curr : Stores current permutation
# index : Index in current permutation, curr
def permuteRec(string, n, index = -1, curr = ""):
# base case
if index == n:
return
if len(curr) > 0:
print(curr)
for i in range(index + 1, n):
curr += string[i]
permuteRec(string, n, i, curr)
# backtracking
curr = curr[:len(curr) - 1]
# Generates power set in lexicographic order
def powerSet(string):
string = ''.join(sorted(string))
permuteRec(string, len(string))
# Driver Code
if __name__ == "__main__":
string = "cab"
powerSet(string)
# This code is contributed by vibhu4agarwal
|
constant
|
quadratic
|
# Python3 program to print nth permutation
# with using next_permute()
# next_permutation method implementation
def next_permutation(L):
n = len(L)
i = n - 2
while i >= 0 and L[i] >= L[i + 1]:
i -= 1
if i == -1:
return False
j = i + 1
while j < n and L[j] > L[i]:
j += 1
j -= 1
L[i], L[j] = L[j], L[i]
left = i + 1
right = n - 1
while left < right:
L[left], L[right] = L[right], L[left]
left += 1
right -= 1
return True
# Function to print nth permutation
# using next_permute()
def nPermute(string, n):
string = list(string)
new_string = []
# Sort the string in lexicographically
# ascending order
string.sort()
j = 2
# Keep iterating until
# we reach nth position
while next_permutation(string):
new_string = string
# check for nth iteration
if j == n:
break
j += 1
# print string after nth iteration
print(''.join(new_string))
# Driver Code
if __name__ == "__main__":
string = "GEEKSFORGEEKS"
n = 100
nPermute(string, n)
# This code is contributed by
# sanjeev2552
|
constant
|
nlogn
|
# A simple Python3 program to find lexicographically
# minimum rotation of a given string
# This function return lexicographically minimum
# rotation of str
def minLexRotation(str_) :
# Find length of given string
n = len(str_)
# Create an array of strings to store all rotations
arr = [0] * n
# Create a concatenation of string with itself
concat = str_ + str_
# One by one store all rotations of str in array.
# A rotation is obtained by getting a substring of concat
for i in range(n) :
arr[i] = concat[i : n + i]
# Sort all rotations
arr.sort()
# Return the first rotation from the sorted array
return arr[0]
# Driver Code
print(minLexRotation("GEEKSFORGEEKS"))
print(minLexRotation("GEEKSQUIZ"))
print(minLexRotation("BCABDADAB"))
# This code is contributed by divyamohan123
|
linear
|
quadratic
|
# Python program to print all distinct
# subsequences of a string.
# Finds and stores result in st for a given
# string s.
def generate(st, s):
if len(s) == 0:
return
# If current string is not already present.
if s not in st:
st.add(s)
# Traverse current string, one by one
# remove every character and recur.
for i in range(len(s)):
t = list(s).copy()
t.remove(s[i])
t = ''.join(t)
generate(st, t)
return
# Driver Code
if __name__ == "__main__":
s = "xyz"
st = set()
generate(st, s)
for i in st:
print(i)
# This code is contributed by
# sanjeev2552
|
linear
|
quadratic
|
# Python 3 code to find the lexicographically
# smallest string
def lexSmallest(a, n):
# Sort strings using above compare()
for i in range(0,n):
for j in range(i+1,n):
if(a[i]+a[j]>a[j]+a[i]):
s=a[i]
a[i]=a[j]
a[j]=s
# Concatenating sorted strings
answer = ""
for i in range( n):
answer += a[i]
return answer
# Driver code
if __name__ == "__main__":
a = [ "c", "cb", "cba" ]
n = len(a)
print(lexSmallest(a, n))
# This code is contributed by vibhu karnwal
|
linear
|
quadratic
|
# Python Program to create concatenation of all
# substrings in lexicographic order.
def lexicographicSubConcat(s):
n = len(s);
# Creating an array to store substrings
sub_count = (n * (n + 1))//2;
arr = [0]*sub_count;
# finding all substrings of string
index = 0;
for i in range(n):
for j in range(1,n - i + 1):
arr[index] = s[i:i + j];
index += 1;
# Sort all substrings in lexicographic
# order
arr.sort();
# Concatenating all substrings
res = "";
for i in range(sub_count):
res += arr[i];
return res;
s = "abc";
print(lexicographicSubConcat(s));
# This code is contributed by Princi Singh
|
linear
|
cubic
|
# Python3 for constructing smallest palindrome
# function for printing palindrome
def constructPalin(string, l):
string = list(string)
i = -1
j = l
# iterate till i<j
while i < j:
i += 1
j -= 1
# continue if str[i]==str[j]
if (string[i] == string[j] and
string[i] != '*'):
continue
# update str[i]=str[j]='a' if both are '*'
elif (string[i] == string[j] and
string[i] == '*'):
string[i] = 'a'
string[j] = 'a'
continue
# update str[i]=str[j] if only str[i]='*'
elif string[i] == '*':
string[i] = string[j]
continue
# update str[j]=str[i] if only str[j]='*'
elif string[j] == '*':
string[j] = string[i]
continue
# else print not possible and return
print("Not Possible")
return ""
return ''.join(string)
# Driver Code
if __name__ == "__main__":
string = "bca*xc**b"
l = len(string)
print(constructPalin(string, l))
# This code is contributed by
# sanjeev2552
|
constant
|
linear
|
# Python 3 program to find Lexicographically
# smallest string whose hamming distance
# from the given string is exactly K
# function to find Lexicographically
# smallest string with hamming distance k
def findString(str, n, k):
# If k is 0, output input string
if (k == 0):
print(str)
return
# Copying input string into output
# string
str2 = str
p = 0
# Traverse all the character of the
# string
for i in range(0, n, 1):
# If current character is not 'a'
if (str2[i] != 'a'):
# copy character 'a' to
# output string
str2 = str2.replace(str2[i], 'a')
p += 1
# If hamming distance became k,
# break;
if (p == k):
break
# If k is less than p
if (p < k):
# Traversing string in reverse
# order
i = n - 1
while(i >= 0):
if (str[i] == 'a'):
str2 = str2.replace(str2[i], 'b')
p += 1
if (p == k):
break
i -= 1
print(str2)
# Driver Code
if __name__ == '__main__':
str = "pqrs"
n = len(str)
k = 2
findString(str, n, k)
# This code is contributed by
# Surendra_Gangwar
|
linear
|
linear
|
# Python 3 program to find lexicographically
# next string
def nextWord(s):
# If string is empty.
if (s == " "):
return "a"
# Find first character from right
# which is not z.
i = len(s) - 1
while (s[i] == 'z' and i >= 0):
i -= 1
# If all characters are 'z', append
# an 'a' at the end.
if (i == -1):
s = s + 'a'
# If there are some non-z characters
else:
s = s.replace(s[i], chr(ord(s[i]) + 1), 1)
return s
# Driver code
if __name__ == '__main__':
str = "samez"
print(nextWord(str))
# This code is contributed by
# Sanjit_Prasad
|
constant
|
linear
|
# Python3 program to find lexicographically largest
# subsequence where every character appears at
# least k times.
# Find lexicographically largest subsequence of
# s[0..n-1] such that every character appears
# at least k times. The result is filled in t[]
def subsequence(s, t, n, k):
last = 0
cnt = 0
new_last = 0
size = 0
string = 'zyxwvutsrqponmlkjihgfedcba'
# Starting from largest character 'z' to 'a'
for ch in string:
cnt = 0
for i in range(last, n):
if s[i] == ch:
cnt += 1
# If frequency is greater than k
if cnt >= k:
# From the last point we leave
for i in range(last, n):
# check if string contain ch
if s[i] == ch:
# If yes, append to output string
t[size] = ch
new_last = i
size += 1
# Update the last point.
last = new_last
# Driver Code
if __name__ == "__main__":
s = ['b', 'a', 'n', 'a', 'n', 'a']
n = len(s)
k = 2
t = [''] * n
subsequence(s, t, n - 1, k)
t = ''.join(t)
print(t)
# This code is contributed by
# sanjeev2552
|
linear
|
linear
|
# Python3 implementation of lexicographically first
# alternate vowel and consonant string
SIZE = 26
# 'ch' is vowel or not
def isVowel(ch):
if (ch == 'a' or ch == 'e' or
ch == 'i' or ch == 'o' or
ch == 'u'):
return True
return False
# create alternate vowel and consonant string
# str1[0...l1-1] and str2[start...l2-1]
def createAltStr(str1, str2, start, l):
finalStr = ""
i = 0
j = start
# first adding character of vowel/consonant
# then adding character of consonant/vowel
while j < l:
finalStr += str1[i] + str2[j]
i += 1
j += 1
return finalStr
# function to find the required lexicographically
# first alternate vowel and consonant string
def findAltStr(string):
# hash table to store frequencies
# of each character in 'str'
char_freq = [0] * SIZE # initialize all elements
# of char_freq[] to 0
nv = 0
nc = 0
vstr = ""
cstr = ""
l = len(string)
for i in range(l):
ch = string[i]
# count vowels
if isVowel(ch):
nv += 1
# count consonants
else:
nc += 1
# update frequency of 'ch' in
# char_freq[]
char_freq[ord(ch) - 97] += 1
# no such string can be formed
if abs(nv - nc) >= 2:
return "no such string"
# form the vowel string 'vstr' and
# consonant string 'cstr' which contains
# characters in lexicographical order
for i in range(SIZE):
ch = chr(i + 97)
for j in range(1, char_freq[i] + 1):
if isVowel(ch):
vstr += ch
else:
cstr += ch
# remove first character of vowel string
# then create alternate string with
# cstr[0...nc-1] and vstr[1...nv-1]
if nv > nc:
return vstr[0] + createAltStr(cstr,
vstr, 1, nv)
# remove first character of consonant string
# then create alternate string with
# vstr[0...nv-1] and cstr[1...nc-1]
if nc > nv:
return cstr[0] + createAltStr(vstr,
cstr, 1, nc)
# if both vowel and consonant
# strings are of equal length
# start creating string with consonant
if cstr[0] < vstr[0]:
return createAltStr(cstr, vstr, 0, nv)
# start creating string with vowel
return createAltStr(vstr, cstr, 0, nc)
# Driver Code
if __name__ == "__main__":
string = "aeroplane"
print(findAltStr(string))
# This code is contributed by
# sanjeev2552
|
constant
|
linear
|
# Python3 program to find the string
# in lexicographic order which is
# in between given two strings
# Function to find the lexicographically
# next string
def lexNext(s, n):
# Iterate from last character
for i in range(n - 1, -1, -1):
# If not 'z', increase by one
if s[i] != 'z':
k = ord(s[i])
s[i] = chr(k + 1)
return ''.join(s)
# if 'z', change it to 'a'
s[i] = 'a'
# Driver Code
if __name__ == "__main__":
S = "abcdeg"
T = "abcfgh"
n = len(S)
S = list(S)
res = lexNext(S, n)
# If not equal, print the
# resultant string
if res != T:
print(res)
else:
print(-1)
# This code is contributed by
# sanjeev2552
|
constant
|
linear
|
# Python3 program to print n-th permutation
MAX_CHAR = 26
MAX_FACT = 20
fact = [None] * (MAX_FACT)
# Utility for calculating factorials
def precomputeFactorials():
fact[0] = 1
for i in range(1, MAX_FACT):
fact[i] = fact[i - 1] * i
# Function for nth permutation
def nPermute(string, n):
precomputeFactorials()
# length of given string
length = len(string)
# Count frequencies of all
# characters
freq = [0] * (MAX_CHAR)
for i in range(0, length):
freq[ord(string[i]) - ord('a')] += 1
# out string for output string
out = [None] * (MAX_CHAR)
# iterate till sum equals n
Sum, k = 0, 0
# We update both n and sum in
# this loop.
while Sum != n:
Sum = 0
# check for characters present in freq[]
for i in range(0, MAX_CHAR):
if freq[i] == 0:
continue
# Remove character
freq[i] -= 1
# calculate sum after fixing
# a particular char
xsum = fact[length - 1 - k]
for j in range(0, MAX_CHAR):
xsum = xsum // fact[freq[j]]
Sum += xsum
# if sum > n fix that char as
# present char and update sum
# and required nth after fixing
# char at that position
if Sum >= n:
out[k] = chr(i + ord('a'))
n -= Sum - xsum
k += 1
break
# if sum < n, add character back
if Sum < n:
freq[i] += 1
# if sum == n means this char will provide
# its greatest permutation as nth permutation
i = MAX_CHAR-1
while k < length and i >= 0:
if freq[i]:
out[k] = chr(i + ord('a'))
freq[i] -= 1
i += 1
k += 1
i -= 1
# print result
print(''.join(out[:k]))
# Driver Code
if __name__ == "__main__":
n = 2
string = "geeksquiz"
nPermute(string, n)
# This code is contributed by Rituraj Jain
|
linear
|
linear
|
# Python program to find lexicographic
# rank of a string
# A utility function to find factorial
# of n
def fact(n):
f = 1
while n >= 1:
f = f * n
n = n - 1
return f
# A utility function to count smaller
# characters on right of arr[low]
def findSmallerInRight(st, low, high):
countRight = 0
i = low + 1
while i <= high:
if st[i] < st[low]:
countRight = countRight + 1
i = i + 1
return countRight
# A function to find rank of a string
# in all permutations of characters
def findRank(st):
ln = len(st)
mul = fact(ln)
rank = 1
i = 0
while i < ln:
mul = mul // (ln - i)
# count number of chars smaller
# than str[i] from str[i + 1] to
# str[len-1]
countRight = findSmallerInRight(st, i, ln-1)
rank = rank + countRight * mul
i = i + 1
return rank
# Driver code
if __name__ == '__main__':
st = "string"
# Function call
print(findRank(st))
# This code is contributed by Nikita Tiwari.
|
constant
|
quadratic
|
# A O(n) solution for finding rank of string
MAX_CHAR = 256
# All elements of count[] are initialized with 0
count = [0]*(MAX_CHAR + 1)
# A utility function to find factorial of n
def fact(n):
return 1 if(n <= 1) else (n * fact(n - 1))
# Construct a count array where value at every index
# contains count of smaller characters in whole string
def populateAndIncreaseCount(str):
for i in range(len(str)):
count[ord(str[i])] += 1
for i in range(1, MAX_CHAR):
count[i] += count[i - 1]
# Removes a character ch from count[] array
# constructed by populateAndIncreaseCount()
def updatecount(ch):
for i in range(ord(ch), MAX_CHAR):
count[i] -= 1
# A function to find rank of a string in all permutations
# of characters
def findRank(str):
len1 = len(str)
mul = fact(len1)
rank = 1
# Populate the count array such that count[i]
# contains count of characters which are present
# in str and are smaller than i
populateAndIncreaseCount(str)
for i in range(len1):
mul = mul//(len1 - i)
# count number of chars smaller than str[i]
# from str[i+1] to str[len-1]
rank += count[ord(str[i]) - 1] * mul
# Reduce count of characters greater than str[i]
updatecount(str[i])
return rank
# Driver code
if __name__ == '__main__':
str = "string"
print(findRank(str))
# This is code is contributed by chandan_jnu
|
constant
|
linear
|
# Python3 Program for Bad Character Heuristic
# of Boyer Moore String Matching Algorithm
NO_OF_CHARS = 256
def badCharHeuristic(string, size):
'''
The preprocessing function for
Boyer Moore's bad character heuristic
'''
# Initialize all occurrence as -1
badChar = [-1]*NO_OF_CHARS
# Fill the actual value of last occurrence
for i in range(size):
badChar[ord(string[i])] = i;
# return initialized list
return badChar
def search(txt, pat):
'''
A pattern searching function that uses Bad Character
Heuristic of Boyer Moore Algorithm
'''
m = len(pat)
n = len(txt)
# create the bad character list by calling
# the preprocessing function badCharHeuristic()
# for given pattern
badChar = badCharHeuristic(pat, m)
# s is shift of the pattern with respect to text
s = 0
while(s <= n-m):
j = m-1
# Keep reducing index j of pattern while
# characters of pattern and text are matching
# at this shift s
while j>=0 and pat[j] == txt[s+j]:
j -= 1
# If the pattern is present at current shift,
# then index j will become -1 after the above loop
if j<0:
print("Pattern occur at shift = {}".format(s))
'''
Shift the pattern so that the next character in text
aligns with the last occurrence of it in pattern.
The condition s+m < n is necessary for the case when
pattern occurs at the end of text
'''
s += (m-badChar[ord(txt[s+m])] if s+m<n else 1)
else:
'''
Shift the pattern so that the bad character in text
aligns with the last occurrence of it in pattern. The
max function is used to make sure that we get a positive
shift. We may get a negative shift if the last occurrence
of bad character in pattern is on the right side of the
current character.
'''
s += max(1, j-badChar[ord(txt[s+j])])
# Driver program to test above function
def main():
txt = "ABAAABCD"
pat = "ABC"
search(txt, pat)
if __name__ == '__main__':
main()
# This code is contributed by Atul Kumar
# (www.facebook.com/atul.kr.007)
|
constant
|
quadratic
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.