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):
pr... | 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 m... | 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:
... | 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... | 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 s... | 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")
... | 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 = ''
# ... | 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 a... | 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 ... | 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)):
# Increme... | 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) an... | 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:
... | 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 %... | 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);
... | 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... | 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... | 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 =... | 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 ... | 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:
... | 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)):
... | 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"
... | 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
... | 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 lik... | 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. ... | 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... | 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
# freq... | 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 ... | 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] * ... | 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):
re... | 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)):
... | 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... | 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) :
... | 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):
... | 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 =... | 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
... | 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... | 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)
# p... | 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... | 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 pal... | 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 characte... | 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 -= ... | 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)]
# palindromi... | 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... | 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
... | 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 =... | 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 palindro... | 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... | 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... | 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
... | 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 =... | 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 i... | 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 =... | 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 lo... | 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):
... | 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
# ... | 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] ... | 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))
... | 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]
... | 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) ... | 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:
c... | 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 ... | 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
... | 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
... | 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"
# Drive... | 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
... | 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
#... | 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
... | 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")
e... | 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[... | 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 = ''
#... | 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)
b... | 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
... | 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,... | 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 = ""
wor... | 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... | 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 = ""
# Fu... | 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... | 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
... | 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)
... | 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
... | 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 place... | 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:
... | 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;
... | 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) >... | 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 ... | 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
... | 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
... | 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... | 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)... | 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
... | 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)
re... | 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', appen... | 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
ne... | 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
# st... | 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':
... | 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):
pre... | 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):
countRi... | 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 s... | 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
# F... | constant | quadratic |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.