code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
|---|---|---|
# Python 3 program to check if
# a string can be made
# valid by removing at most 1 character.
# Assuming only lower case characters
CHARS = 26
# To check a string S can be converted to a “valid”
# string by removing less than or equal to one
# character.
def isValidString(str):
freq = [0]*CHARS
# freq[] : stores the frequency of each
# character of a string
for i in range(len(str)):
freq[ord(str[i])-ord('a')] += 1
# Find first character with non-zero frequency
freq1 = 0
count_freq1 = 0
for i in range(CHARS):
if (freq[i] != 0):
freq1 = freq[i]
count_freq1 = 1
break
# Find a character with frequency different
# from freq1.
freq2 = 0
count_freq2 = 0
for j in range(i+1,CHARS):
if (freq[j] != 0):
if (freq[j] == freq1):
count_freq1 += 1
else:
count_freq2 = 1
freq2 = freq[j]
break
# If we find a third non-zero frequency
# or count of both frequencies become more
# than 1, then return false
for k in range(j+1,CHARS):
if (freq[k] != 0):
if (freq[k] == freq1):
count_freq1 += 1
if (freq[k] == freq2):
count_freq2 += 1
# If we find a third non-zero freq
else:
return False
# If counts of both frequencies is more than 1
if (count_freq1 > 1 and count_freq2 > 1):
return False
# Return true if we reach here
return True
# Driver code
if __name__ == "__main__":
str= "abcbc"
if (isValidString(str)):
print("YES")
else:
print("NO")
# this code is contributed by
# ChitraNayal
|
constant
|
linear
|
# Python program to check if a string can be made
# valid by removing at most 1 character using hashmap.
# To check a string S can be converted to a variation
# string
def checkForVariation(strr):
if(len(strr) == 0):
return True
mapp = {}
# Run loop form 0 to length of string
for i in range(len(strr)):
if strr[i] in mapp:
mapp[strr[i]] += 1
else:
mapp[strr[i]] = 1
# declaration of variables
first = True
second = True
val1 = 0
val2 = 0
countOfVal1 = 0
countOfVal2 = 0
for itr in mapp:
i = itr
# if first is true than countOfVal1 increase
if(first):
val1 = i
first = False
countOfVal1 += 1
continue
if(i == val1):
countOfVal1 += 1
continue
# if second is true than countOfVal2 increase
if(second):
val2 = i
countOfVal2 += 1
second = False
continue
if(i == val2):
countOfVal2 += 1
continue
if(countOfVal1 > 1 and countOfVal2 > 1):
return False
else:
return True
# Driver code
print(checkForVariation("abcbc"))
# This code is contributed by rag2127
|
linear
|
nlogn
|
# Python program
from collections import Counter
# To check a string S can be
# converted to a variation
# string
def checkForVariation(strr):
freq = Counter(strr)
# Converting these values to list
valuelist = list(freq.values())
# Counting frequencies again
ValueCounter = Counter(valuelist)
if(len(ValueCounter) == 1):
return True
elif(len(ValueCounter) == 2 and
min(ValueCounter.values()) == 1):
return True
# If no conditions satisfied return false
return False
# Driver code
string = "abcbc"
# passing string to checkForVariation Function
print(checkForVariation(string))
# This code is contributed by vikkycirus
|
linear
|
linear
|
# Python3 program to get number of ways to increase
# LCS by 1
M = 26
# Method returns total ways to increase LCS length by 1
def waysToIncreaseLCSBy1(str1, str2):
m = len(str1)
n = len(str2)
# Fill positions of each character in vector
# vector<int> position[M];
position = [[] for i in range(M)]
for i in range(1, n+1, 1):
position[ord(str2[i-1])-97].append(i)
# Initializing 2D array by 0 values
lcsl = [[0 for i in range(n+2)] for j in range(m+2)]
lcsr = [[0 for i in range(n+2)] for j in range(m+2)]
# Filling LCS array for prefix substrings
for i in range(1, m+1, 1):
for j in range(1, n+1,1):
if (str1[i-1] == str2[j-1]):
lcsl[i][j] = 1 + lcsl[i-1][j-1]
else:
lcsl[i][j] = max(lcsl[i-1][j],
lcsl[i][j-1])
# Filling LCS array for suffix substrings
for i in range(m, 0, -1):
for j in range(n, 0, -1):
if (str1[i-1] == str2[j-1]):
lcsr[i][j] = 1 + lcsr[i+1][j+1]
else:
lcsr[i][j] = max(lcsr[i+1][j],
lcsr[i][j+1])
# Looping for all possible insertion positions
# in first string
ways = 0
for i in range(0, m+1,1):
# Trying all possible lower case characters
for C in range(0, 26,1):
# Now for each character, loop over same
# character positions in second string
for j in range(0, len(position[C]),1):
p = position[C][j]
# If both, left and right substrings make
# total LCS then increase result by 1
if (lcsl[i][p-1] + lcsr[i+1][p+1] == lcsl[m][n]):
ways += 1
return ways
# Driver code to test above methods
str1 = "abcabc"
str2 = "abcd"
print(waysToIncreaseLCSBy1(str1, str2))
# This code is contributed by ankush_953
|
quadratic
|
quadratic
|
# Python3 implementation to find the character in
# first that is present at minimum index
# in second String
# function to find the minimum index character
def printMinIndexChar(Str, patt):
# to store the index of character having
# minimum index
minIndex = 10**9
# lengths of the two Strings
m =len(Str)
n =len(patt)
# traverse 'patt'
for i in range(n):
# for each character of 'patt' traverse 'Str'
for j in range(m):
# if patt[i] is found in 'Str', check if
# it has the minimum index or not. If yes,
# then update 'minIndex' and break
if (patt[i] == Str[j] and j < minIndex):
minIndex = j
break
# print the minimum index character
if (minIndex != 10**9):
print("Minimum Index Character = ",Str[minIndex])
# if no character of 'patt' is present in 'Str'
else:
print("No character present")
# Driver code
Str = "geeksforgeeks"
patt = "set"
printMinIndexChar(Str, patt)
# This code is contributed by mohit kumar 29
|
constant
|
quadratic
|
# Python3 implementation to
# find the character in first
# string that is present at
# minimum index in second string
import sys
# Function to find the
# minimum index character
def printMinIndexChar(st, patt):
# unordered_map 'um'
# implemented as hash table
um = {}
# to store the index of
# character having minimum index
minIndex = sys.maxsize
# Lengths of the two strings
m = len(st)
n = len(patt)
# Store the first index of
# each character of 'str'
for i in range (m):
if (st[i] not in um):
um[st[i]] = i
# traverse the string 'patt'
for i in range(n):
# If patt[i] is found in 'um',
# check if it has the minimum
# index or not accordingly
# update 'minIndex'
if (patt[i] in um and
um[patt[i]] < minIndex):
minIndex = um[patt[i]]
# Print the minimum index character
if (minIndex != sys.maxsize):
print ("Minimum Index Character = ",
st[minIndex])
# If no character of 'patt'
# is present in 'str'
else:
print ("No character present")
# Driver program to test above
if __name__ == "__main__":
st = "geeksforgeeks"
patt = "set"
printMinIndexChar(st, patt)
# This code is contributed by Chitranayal
|
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
|
# Simple Python3 program to find pairs with
# distance equal to English alphabet distance
# Function to count pairs
def countPairs(str1):
result = 0;
n = len(str1)
for i in range(0, n):
for j in range(i + 1, n):
# Increment count if characters
# are at same distance
if (abs(ord(str1[i]) -
ord(str1[j])) == abs(i - j)):
result += 1;
return result;
# Driver code
if __name__ == "__main__":
str1 = "geeksforgeeks";
print(countPairs(str1));
# This code is contributed
# by Sairahul099
|
linear
|
quadratic
|
# An optimized C++ program to find pairs with
# distance equal to English alphabet distance
MAX_CHAR = 26
# Function to count pairs with distance
# equal to English alphabet distance
def countPairs(str1):
result = 0;
n = len(str1)
for i in range(0, n):
# This loop runs at most 26 times
for j in range(1, MAX_CHAR + 1):
if((i + j) < n):
if ((abs(ord(str1[i + j]) -
ord(str1[i])) == j)):
result += 1;
return result
# Driver code
if __name__ == "__main__":
str1 = "geeksforgeeks";
print(countPairs(str1))
# This code is contributed
# by Sairahul099
|
linear
|
quadratic
|
# Python3 program to count the
# number of pairs
MAX = 256
# Function to count the number
# of equal pairs
def countPairs(s):
# Hash table
cnt = [0 for i in range(0, MAX)]
# Traverse the string and count
# occurrence
for i in range(len(s)):
cnt[ord(s[i]) - 97] += 1
# Stores the answer
ans = 0
# Traverse and check the occurrence
# of every character
for i in range(0, MAX):
ans += cnt[i] * cnt[i]
return ans
# Driver code
if __name__=="__main__":
s = "geeksforgeeks"
print(countPairs(s))
# This code is contributed
# by Sairahul099
|
linear
|
linear
|
# Python3 Program to count strings with
# adjacent characters.
def countStrs(n):
# Initializing arr[n+1][27] to 0
dp = [[0 for j in range(27)]
for i in range(n + 1)]
# Initialing 1st row all 1 from 0 to 25
for i in range(0, 26):
dp[1][i] = 1
# Begin evaluating from i=2 since
# 1st row is set
for i in range(2, n + 1):
for j in range(0, 26):
# j=0 is 'A' which can make strings
# of length i using strings of length
# i-1 and starting with 'B'
if(j == 0):
dp[i][j] = dp[i - 1][j + 1];
else:
dp[i][j] = (dp[i - 1][j - 1] +
dp[i - 1][j + 1])
# Our result is sum of last row.
sum = 0
for i in range(0, 26):
sum = sum + dp[n][i]
return sum
# Driver's Code
if __name__ == "__main__":
n = 3
print("Total strings are : ", countStrs(n))
# This code is contributed by Sairahul Jella
|
linear
|
linear
|
# Python3 program to print Number of Words,
# Vowels and Frequency of Each Character
# A method to count the number of
# uppercase character, vowels and number of words
def words(str):
wcount = vcount = ucount = i = 0
while i < len(str):
ch = str[i]
# condition checking for word count
if (ch == " " or ch == "."):
wcount += 1
# condition checking for vowels
# in lower case
if(ch == "a" or ch == "e" or
ch == "i" or ch == 'o' or ch == "u"):
vcount += 1
# condition checking for vowels in uppercase
if (ch == "A" or ch == "E" or
ch == "I" or ch == 'O' or ch == "U"):
vcount += 1
# condition checking for upper case characters
if (ord(ch) >= 65 and ord(ch) <= 90):
ucount += 1
i += 1
print("number of words = ", wcount)
print("number of vowels = ", vcount)
print("number of upper case characters = ",
ucount)
# a method to print the frequency
# of each character.
def frequency(str):
i = 1
# checking each and every
# ascii code character
while i < 127:
ch1 = chr(i)
c = 0
j = 0
while j < len(str):
ch2 = str[j]
if(ch1 == ch2):
c += 1
j += 1
# condition to print the frequency
if c > 0:
print("Character:", ch1 +
" Frequency:", c)
i += 1
# Driver Code
# sample string to check the code
s = "Geeks for Geeks."
# function calling
words(s)
frequency(s)
# This code is contributed by Animesh_Gupta
|
constant
|
linear
|
# Python3 program to Find longest subsequence where
# every character appears at-least k times
MAX_CHARS = 26
def longestSubseqWithK(s, k):
n = len(s)
# Count frequencies of all characters
freq = [0]*MAX_CHARS
for i in range(n):
freq[ord(s[i]) - ord('a')]+=1
# Traverse given string again and print
# all those characters whose frequency
# is more than or equal to k.
for i in range(n ):
if (freq[ord(s[i]) - ord('a')] >= k):
print(s[i],end="")
# Driver code
if __name__ == "__main__":
s = "geeksforgeeks"
k = 2
longestSubseqWithK(s, k)
|
linear
|
linear
|
# Python3 program to Find longest subsequence where every
# character appears at-least k times
def longestSubseqWithK(Str, k):
n = len(Str)
hm = {}
# Count frequencies of all characters
for i in range(n):
c = Str[i]
if(c in hm):
hm += 1
else:
hm = 1
# Traverse given string again and print
# all those characters whose frequency
# is more than or equal to k.
for i in range(n):
c = Str[i]
if (hm >= k):
print(c,end="")
# Driver code
Str = "geeksforgeeks"
k = 2
longestSubseqWithK(Str, k)
# This code is contributed by shinjanpatra
|
linear
|
nlogn
|
# Recursive Python program to check
# if a string is subsequence
# of another string
# Returns true if str1[] is a
# subsequence of str2[].
def isSubSequence(string1, string2, m, n):
# Base Cases
if m == 0:
return True
if n == 0:
return False
# If last characters of two
# strings are matching
if string1[m-1] == string2[n-1]:
return isSubSequence(string1, string2, m-1, n-1)
# If last characters are not matching
return isSubSequence(string1, string2, m, n-1)
# Driver program to test the above function
string1 = "gksrek"
string2 = "geeksforgeeks"
if isSubSequence(string1, string2, len(string1), len(string2)):
print ("Yes")
else:
print ("No")
# This code is contributed by BHAVYA JAIN
|
linear
|
linear
|
# Iterative JavaScript program to check
# If a string is subsequence of another string
# Returns true if s1 is subsequence of s2
def issubsequence(s1, s2):
n,m = len(s1),len(s2)
i,j = 0,0
while (i < n and j < m):
if (s1[i] == s2[j]):
i += 1
j += 1
# If i reaches end of s1,that mean we found all
# characters of s1 in s2,
# so s1 is subsequence of s2, else not
return i == n
# driver code
s1 = "gksrek"
s2 = "geeksforgeeks"
if (issubsequence(s1, s2)):
print("gksrek is subsequence of geekforgeeks")
else:
print("gksrek is not a subsequence of geekforgeeks")
# This code is contributed by shinjanpatra
|
constant
|
linear
|
# Python 3 program to count
# subsequences of the form
# a ^ i b ^ j c ^ k
# Returns count of subsequences
# of the form a ^ i b ^ j c ^ k
def countSubsequences(s):
# Initialize counts of different
# subsequences caused by different
# combination of 'a'
aCount = 0
# Initialize counts of different
# subsequences caused by different
# combination of 'a' and different
# combination of 'b'
bCount = 0
# Initialize counts of different
# subsequences caused by different
# combination of 'a', 'b' and 'c'.
cCount = 0
# Traverse all characters
# of given string
for i in range(len(s)):
# If current character is 'a',
# then there are following
# possibilities :
# a) Current character begins
# a new subsequence.
# b) Current character is part
# of aCount subsequences.
# c) Current character is not
# part of aCount subsequences.
if (s[i] == 'a'):
aCount = (1 + 2 * aCount)
# If current character is 'b', then
# there are following possibilities :
# a) Current character begins a
# new subsequence of b's with
# aCount subsequences.
# b) Current character is part
# of bCount subsequences.
# c) Current character is not
# part of bCount subsequences.
else if (s[i] == 'b'):
bCount = (aCount + 2 * bCount)
# If current character is 'c', then
# there are following possibilities :
# a) Current character begins a
# new subsequence of c's with
# bCount subsequences.
# b) Current character is part
# of cCount subsequences.
# c) Current character is not
# part of cCount subsequences.
else if (s[i] == 'c'):
cCount = (bCount + 2 * cCount)
return cCount
# Driver code
if __name__ == "__main__":
s = "abbc"
print(countSubsequences(s))
# This code is contributed
# by ChitraNayal
|
constant
|
linear
|
# Python 3 program to count subsequences
# of a string divisible by n.
# Returns count of subsequences of
# str divisible by n.
def countDivisibleSubseq(str, n):
l = len(str)
# division by n can leave only n remainder
# [0..n-1]. dp[i][j] indicates number of
# subsequences in string [0..i] which leaves
# remainder j after division by n.
dp = [[0 for x in range(l)]
for y in range(n)]
# Filling value for first digit in str
dp[int(str[0]) % n][0] += 1
for i in range(1, l):
# start a new subsequence with index i
dp[int(str[i]) % n][i] += 1
for j in range(n):
# exclude i'th character from all the
# current subsequences of string [0...i-1]
dp[j][i] += dp[j][i-1]
# include i'th character in all the current
# subsequences of string [0...i-1]
dp[(j * 10 + int(str[i])) % n][i] += dp[j][i-1]
return dp[0][l-1]
# Driver code
if __name__ == "__main__":
str = "1234"
n = 4
print(countDivisibleSubseq(str, n))
# This code is contributed by ita_c
|
quadratic
|
quadratic
|
# Python 3 Program to find the "GFG"
# subsequence in the given string
MAX = 100
# Print the count of "GFG" subsequence
# in the string
def countSubsequence(s, n):
cntG = 0
cntF = 0
result = 0
C=0
# Traversing the given string
for i in range(n):
if (s[i] == 'G'):
# If the character is 'G', increment
# the count of 'G', increase the result
# and update the array.
cntG += 1
result += C
continue
# If the character is 'F', increment
# the count of 'F' and update the array.
if (s[i] == 'F'):
cntF += 1
C += cntG
continue
# Ignore other character.
else:
continue
print(result)
# Driver Code
if __name__ == '__main__':
s = "GFGFG"
n = len(s)
countSubsequence(s, n)
# This code is contributed by
# Sanjit_Prasad
|
constant
|
linear
|
# Python3 program to print
# distinct subsequences of
# a given string
import math
# Create an empty set
# to store the subsequences
sn = []
global m
m = 0
# Function for generating
# the subsequences
def subsequences(s, op, i, j):
# Base Case
if(i == m):
op[j] = None
temp = "".join([i for i in op if i])
# Insert each generated
# subsequence into the set
sn.append(temp)
return
# Recursive Case
else:
# When a particular
# character is taken
op[j] = s[i]
subsequences(s, op,
i + 1, j + 1)
# When a particular
# character isn't taken
subsequences(s, op,
i + 1, j)
return
# Driver Code
str = "ggg"
m = len(str)
n = int(math.pow(2, m) + 1)
# Output array for storing
# the generating subsequences
# in each call
op = [None for i in range(n)]
# Function Call
subsequences(str, op, 0, 0)
# Output will be the number
# of elements in the set
print(len(set(sn)))
# This code is contributed by avanitrachhadiya2155
|
linear
|
np
|
# Python3 program to count number of
# distinct subsequences of a given string
MAX_CHAR = 256
def countSub(ss):
# create an array to store index of last
last = [-1 for i in range(MAX_CHAR + 1)]
# length of input string
n = len(ss)
# dp[i] is going to store count of
# discount subsequence of length of i
dp = [-2 for i in range(n + 1)]
# empty substring has only
# one subsequence
dp[0] = 1
# Traverse through all lengths
# from 1 to n
for i in range(1, n + 1):
# number of subsequence with
# substring str[0...i-1]
dp[i] = 2 * dp[i - 1]
# if current character has appeared
# before, then remove all subsequences
# ending with previous occurrence.
if last[ord(ss[i - 1])] != -1:
dp[i] = dp[i] - dp[last[ord(ss[i - 1])]]
last[ord(ss[i - 1])] = i - 1
return dp[n]
# Driver code
print(countSub("gfg"))
# This code is contributed
# by mohit kumar 29
|
linear
|
linear
|
# Python3 program for above approach
# Returns count of distinct
# subsequences of str.
def countSub(s):
Map = {}
# Iterate from 0 to length of s
for i in range(len(s)):
Map[s[i]] = -1
allCount = 0
levelCount = 0
# Iterate from 0 to length of s
for i in range(len(s)):
c = s[i]
# Check if i equal to 0
if (i == 0):
allCount = 1
Map = 1
levelCount = 1
continue
# Replace levelCount with
# allCount + 1
levelCount = allCount + 1
# If map is less than 0
if (Map < 0):
allCount = allCount + levelCount
else:
allCount = allCount + levelCount - Map
Map = levelCount
# Return answer
return allCount
# Driver Code
List = [ "abab", "gfg" ]
for s in List:
cnt = countSub(s)
withEmptyString = cnt + 1
print("With empty string count for",
s, "is", withEmptyString)
print("Without empty string count for",
s, "is", cnt)
# This code is contributed by rag2127
|
constant
|
linear
|
# Python 3 program to find LCS
# with permutations allowed
# Function to calculate longest string
# str1 --> first string
# str2 --> second string
# count1[] --> hash array to calculate frequency
# of characters in str1
# count[2] --> hash array to calculate frequency
# of characters in str2
# result --> resultant longest string whose
# permutations are sub-sequence
# of given two strings
def longestString(str1, str2):
count1 = [0] * 26
count2 = [0] * 26
# calculate frequency of characters
for i in range( len(str1)):
count1[ord(str1[i]) - ord('a')] += 1
for i in range(len(str2)):
count2[ord(str2[i]) - ord('a')] += 1
# Now traverse hash array
result = ""
for i in range(26):
# append character ('a'+i) in
# resultant string 'result' by
# min(count1[i],count2i]) times
for j in range(1, min(count1[i],
count2[i]) + 1):
result = result + chr(ord('a') + i)
print(result)
# Driver Code
if __name__ == "__main__":
str1 = "geeks"
str2 = "cake"
longestString(str1, str2)
# This code is contributed by ita_c
|
constant
|
linear
|
# A simple recursive Python
# program to find shortest
# uncommon subsequence.
MAX = 1005
# A recursive function to
# find the length of shortest
# uncommon subsequence
def shortestSeq(S, T, m, n):
# S String is empty
if m == 0:
return MAX
# T String is empty
if(n <= 0):
return 1
# Loop to search for
# current character
for k in range(n):
if(T[k] == S[0]):
break
# char not found in T
if(k == n):
return 1
# Return minimum of following
# two Not including current
# char in answer Including
# current char
return min(shortestSeq(S[1 : ], T, m - 1, n),
1 + shortestSeq((S[1 : ]), T[k + 1 : ],
m - 1, n - k - 1))
# Driver code
S = "babab"
T = "babba"
m = len(S)
n = len(T)
ans = shortestSeq(S, T, m, n)
if(ans >= MAX):
ans =- 1
print("Length of shortest subsequence is:", ans)
# This code is contributed by avanitrachhadiya2155
|
quadratic
|
cubic
|
# A dynamic programming based Python program
# to find shortest uncommon subsequence.
MAX = 1005
# Returns length of shortest common subsequence
def shortestSeq(S: list, T: list):
m = len(S)
n = len(T)
# declaring 2D array of m + 1 rows and
# n + 1 columns dynamically
dp = [[0 for i in range(n + 1)]
for j in range(m + 1)]
# T string is empty
for i in range(m + 1):
dp[i][0] = 1
# S string is empty
for i in range(n + 1):
dp[0][i] = MAX
for i in range(1, m + 1):
for j in range(1, n + 1):
ch = S[i - 1]
k = j - 1
while k >= 0:
if T[k] == ch:
break
k -= 1
# char not present in T
if k == -1:
dp[i][j] = 1
else:
dp[i][j] = min(dp[i - 1][j],
dp[i - 1][k] + 1)
ans = dp[m][n]
if ans >= MAX:
ans = -1
return ans
# Driver Code
if __name__ == "__main__":
S = "babab"
T = "babba"
print("Length of shortest subsequence is:",
shortestSeq(S, T))
# This code is contributed by
# sanjeev2552
|
quadratic
|
cubic
|
# A dynamic programming based Python3 program print
# shortest supersequence of two strings
# returns shortest supersequence of X and Y
def printShortestSuperSeq(m, n, x, y):
# dp[i][j] contains length of shortest
# supersequence for X[0..i-1] and Y[0..j-1]
dp = [[0 for i in range(n + 1)]
for j in range(m + 1)]
# Fill table in bottom up manner
for i in range(m + 1):
for j in range(n + 1):
# Below steps follow recurrence relation
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
elif x[i - 1] == y[j - 1]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j],
dp[i][j - 1])
# Following code is used to print
# shortest supersequence
# dp[m][n] stores the length of the
# shortest supersequence of X and Y
# string to store the shortest supersequence
string = ""
# Start from the bottom right corner and
# add the characters to the output string
i = m
j = n
while i * j > 0:
# If current character in X and Y are same,
# then current character is part of
# shortest supersequence
if x[i - 1] == y[j - 1]:
# Put current character in result
string = x[i - 1] + string
# reduce values of i, j and index
i -= 1
j -= 1
# If current character in X and Y are different
elif dp[i - 1][j] > dp[i][j - 1]:
# Put current character of Y in result
string = y[j - 1] + string
# reduce values of j and index
j -= 1
else:
# Put current character of X in result
string = x[i - 1] + string
# reduce values of i and index
i -= 1
# If Y reaches its end, put remaining characters
# of X in the result string
while i > 0:
string = x[i - 1] + string
i -= 1
# If X reaches its end, put remaining characters
# of Y in the result string
while j > 0:
string = y[j - 1] + string
j -= 1
return string
# Driver Code
if __name__ == "__main__":
x = "GXTXAYB"
y = "AGGTAB"
m = len(x)
n = len(y)
# Take the smaller string as x and larger one as y
if m > n:
x, y = y, x
m, n = n, m
print(*printShortestSuperSeq(m, n, x, y))
# This code is contributed by
# sanjeev2552
|
quadratic
|
quadratic
|
# Space optimized Python
# implementation of LCS problem
# Returns length of LCS for
# X[0..m-1], Y[0..n-1]
def lcs(X, Y):
# Find lengths of two strings
m = len(X)
n = len(Y)
L = [[0 for i in range(n+1)] for j in range(2)]
# Binary index, used to index current row and
# previous row.
bi = bool
for i in range(m):
# Compute current binary index
bi = i&1
for j in range(n+1):
if (i == 0 or j == 0):
L[bi][j] = 0
elif (X[i] == Y[j - 1]):
L[bi][j] = L[1 - bi][j - 1] + 1
else:
L[bi][j] = max(L[1 - bi][j],
L[bi][j - 1])
# Last filled entry contains length of LCS
# for X[0..n-1] and Y[0..m-1]
return L[bi][n]
# Driver Code
X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is", lcs(X, Y))
# This code is contributed by Soumen Ghosh.
|
linear
|
quadratic
|
# Python3 program to find largest word in Dictionary
# by deleting some characters of given string
# Returns true if str1[] is a subsequence of str2[].
# m is length of str1 and n is length of str2
def isSubSequence(str1, str2):
m = len(str1);
n = len(str2);
j = 0; # For index of str1 (or subsequence
# Traverse str2 and str1, and compare current
# character of str2 with first unmatched char
# of str1, if matched then move ahead in str1
i = 0;
while (i < n and j < m):
if (str1[j] == str2[i]):
j += 1;
i += 1;
# If all characters of str1 were found in str2
return (j == m);
# Returns the longest string in dictionary which is a
# subsequence of str.
def findLongestString(dict1, str1):
result = "";
length = 0;
# Traverse through all words of dictionary
for word in dict1:
# If current word is subsequence of str and is largest
# such word so far.
if (length < len(word) and isSubSequence(word, str1)):
result = word;
length = len(word);
# Return longest string
return result;
# Driver program to test above function
dict1 = ["ale", "apple", "monkey", "plea"];
str1 = "abpcplea" ;
print(findLongestString(dict1, str1));
# This code is conribued by mits
|
constant
|
quadratic
|
# Python3 program to find largest word in Dictionary
# by deleting some characters of given string
res=""
def check(d,s):
global res
i = 0
j = 0
while(i < len(d) and j < len(s)):
if(d[i] == s[j]):
i += 1
j += 1
else:
j += 1
if(i == len(d) and len(res) < len(d)):
res = d
def LongestWord(d, S):
# sort the dictionary word
# for smallest lexicographical order
d.sort()
for c in d :
check(c,S)
return res
# Driver program
dict = [ "ale", "apple", "monkey", "plea" ]
str = "abpcplea"
print(LongestWord(dict, str))
# This code is contributed by shinjanpatra
|
constant
|
quadratic
|
# Python3 program to check if
# a string is perfect reversible or not
# This function basically checks
# if string is palindrome or not
def isReversible(str):
i = 0; j = len(str) - 1;
# iterate from left and right
while (i < j):
if (str[i] != str[j]):
return False;
i += 1;
j -= 1;
return True;
# Driver Code
str = "aba";
if (isReversible(str)):
print("YES");
else:
print("NO");
# This code is contributed by Princi Singh
|
constant
|
linear
|
# Python3 Program to reverse an equation
# Function to reverse order of words
def reverseEquation(s):
# Reverse String
result=""
for i in range(len(s)):
# A space marks the end of the word
if(s[i]=='+' or s[i]=='-' or s[i]=='/' or s[i]=='*'):
# insert the word at the beginning
# of the result String
result = s[i] + result
# insert the symbol
else:
result = s[i] + result
return result
# Driver Code
s = "a+b*c-d/e"
print(reverseEquation(s))
# This code is contributed by simranjenny84
|
linear
|
linear
|
# Python3 program for Left
# Rotation and Right
# Rotation of a String
# In-place rotates s towards left by d
def leftrotate(s, d):
tmp = s[d : ] + s[0 : d]
return tmp
# In-place rotates s
# towards right by d
def rightrotate(s, d):
return leftrotate(s, len(s) - d)
# Driver code
if __name__=="__main__":
str1 = "GeeksforGeeks"
print(leftrotate(str1, 2))
str2 = "GeeksforGeeks"
print(rightrotate(str2, 2))
# This code is contributed by Rutvik_56
|
constant
|
linear
|
# Python3 program for Left
# Rotation and Right
# Rotation of a String
def leftrotate(str1, n):
# extended string
temp = str1 + str1
l = len(str1)
# Return string
return temp[n :l+n]
def rightrotate(str1, n):
return leftrotate(str1, len(str1)-n)
return temp[l-n : l1-n ]
# Driver code
if __name__=="__main__":
str1 = "GeeksforGeeks"
print(leftrotate(str1, 2))
str2 = "GeeksforGeeks"
print(rightrotate(str2, 2))
# This code is contributed by sam snehil
|
linear
|
linear
|
# A simple Python3 program to generate
# all rotations of a given string
# Print all the rotated strings.
def printRotatedString(str):
lenn = len(str)
# Generate all rotations
# one by one and print
temp = [0] * (lenn)
for i in range(lenn):
j = i # Current index in str
k = 0 # Current index in temp
# Copying the second part from
# the point of rotation.
while (j < len(str)):
temp[k] = str[j]
k += 1
j += 1
# Copying the first part from
# the point of rotation.
j = 0
while (j < i) :
temp[k] = str[j]
j += 1
k += 1
print(*temp, sep = "")
# Driver Code
if __name__ == '__main__':
str = "geeks"
printRotatedString(str)
# This code is contributed
# by SHUBHAMSINGH10
|
linear
|
quadratic
|
# An efficient Python3 program to print
# all rotations of a string.
# Print all the rotated string.
def printRotatedString(string) :
n = len(string)
# Concatenate str with itself
temp = string + string
# Print all substrings of size n.
# Note that size of temp is 2n
for i in range(n) :
for j in range(n) :
print(temp[i + j], end = "")
print()
# Driver Code
if __name__ == "__main__" :
string = "geeks"
printRotatedString(string)
# This code is contributed by Ryuga
|
linear
|
quadratic
|
# Python 3 program to determine minimum
# number of rotations required to yield
# same string.
# Returns count of rotations to get the
# same string back.
def findRotations(str):
# tmp is the concatenated string.
tmp = str + str
n = len(str)
for i in range(1, n + 1):
# substring from i index of
# original string size.
substring = tmp[i: i+n]
# if substring matches with
# original string then we will
# come out of the loop.
if (str == substring):
return i
return n
# Driver code
if __name__ == '__main__':
str = "abc"
print(findRotations(str))
# This code is contributed
# by 29AjayKumar.
|
linear
|
quadratic
|
# Python program to determine minimum number
# of rotations required to yield same
# string.
# Returns count of rotations to get the
# same string back.
def findRotations(Str):
ans = 0 # to store the answer
n = len(Str) # length of the String
# All the length where we can partition
for i in range(1 , len(Str) - 1):
# right part + left part = rotated String
# we are checking whether the rotated String is equal to
# original String
if(Str[i: n] + Str[0: i] == Str):
ans = i
break
if(ans == 0):
return n
return ans
# Driver code
Str = "abc"
print(findRotations(Str))
# This code is contributed by shinjanpatra
|
constant
|
quadratic
|
# Python 3 program to determine minimum
# number of rotations required to yield
# same string.
# input
string = 'aaaa'
check = ''
for r in range(1, len(string)+1):
# checking the input after each rotation
check = string[r:] + string[:r]
# following if statement checks if input is
# equals to check , if yes it will print r and
# break out of the loop
if check == string:
print(r)
break
# This code is contributed
# by nagasowmyanarayanan.
|
linear
|
quadratic
|
# Python program to check if
# two strings are rotations
# of each other
def isRotation(a: str, b: str) -> bool:
n = len(a)
m = len(b)
if (n != m):
return False
# create lps[] that
# will hold the longest
# prefix suffix values
# for pattern
lps = [0 for _ in range(n)]
# length of the previous
# longest prefix suffix
length = 0
i = 1
# lps[0] is always 0
lps[0] = 0
# the loop calculates
# lps[i] for i = 1 to n-1
while (i < n):
if (a[i] == b[length]):
length += 1
lps[i] = length
i += 1
else:
if (length == 0):
lps[i] = 0
i += 1
else:
length = lps[length - 1]
i = 0
# Match from that rotating
# point
for k in range(lps[n - 1], m):
if (b[k] != a[i]):
return False
i += 1
return True
# Driver code
if __name__ == "__main__":
s1 = "ABACD"
s2 = "CDABA"
print("1" if isRotation(s1, s2) else "0")
# This code is contributed by sanjeev2552
|
linear
|
linear
|
# Python3 program to count
# all rotation divisible
# by 4.
# Returns count of all
# rotations divisible
# by 4
def countRotations(n) :
l = len(n)
# For single digit number
if (l == 1) :
oneDigit = (int)(n[0])
if (oneDigit % 4 == 0) :
return 1
return 0
# At-least 2 digit number
# (considering all pairs)
count = 0
for i in range(0, l - 1) :
twoDigit = (int)(n[i]) * 10 + (int)(n[i + 1])
if (twoDigit % 4 == 0) :
count = count + 1
# Considering the number
# formed by the pair of
# last digit and 1st digit
twoDigit = (int)(n[l - 1]) * 10 + (int)(n[0])
if (twoDigit % 4 == 0) :
count = count + 1
return count
# Driver program
n = "4834"
print("Rotations: " ,
countRotations(n))
# This code is contributed by Nikita tiwari.
|
constant
|
linear
|
# Python3 program to check if all rows
# of a matrix are rotations of each other
MAX = 1000
# Returns true if all rows of mat[0..n-1][0..n-1]
# are rotations of each other.
def isPermutedMatrix(mat, n) :
# Creating a string that contains
# elements of first row.
str_cat = ""
for i in range(n) :
str_cat = str_cat + "-" + str(mat[0][i])
# Concatenating the string with itself
# so that substring search operations
# can be performed on this
str_cat = str_cat + str_cat
# Start traversing remaining rows
for i in range(1, n) :
# Store the matrix into vector
# in the form of strings
curr_str = ""
for j in range(n) :
curr_str = curr_str + "-" + str(mat[i][j])
# Check if the current string is present
# in the concatenated string or not
if (str_cat.find(curr_str)) :
return True
return False
# Driver code
if __name__ == "__main__" :
n = 4
mat = [[1, 2, 3, 4],
[4, 1, 2, 3],
[3, 4, 1, 2],
[2, 3, 4, 1]]
if (isPermutedMatrix(mat, n)):
print("Yes")
else :
print("No")
# This code is contributed by Ryuga
|
linear
|
cubic
|
# Python program to reverse a string using recursion
# Function to print reverse of the passed string
def reverse(string):
if len(string) == 0:
return
temp = string[0]
reverse(string[1:])
print(temp, end='')
# Driver program to test above function
string = "Geeks for Geeks"
reverse(string)
# A single line statement to reverse string in python
# string[::-1]
# This code is contributed by Bhavya Jain
|
linear
|
quadratic
|
# Python3 program to print reverse
# of words in a string.
def wordReverse(str):
i = len(str)-1
start = end = i+1
result = ''
while i >= 0:
if str[i] == ' ':
start = i+1
while start != end:
result += str[start]
start += 1
result += ' '
end = i
i -= 1
start = 0
while start != end:
result += str[start]
start += 1
return result
# Driver Code
str = 'I AM A GEEK'
print(wordReverse(str))
# This code is contributed
# by SamyuktaSHegde
|
linear
|
linear
|
# Python code for the same approach
def reverse_words(s):
left, i, n = 0, 0, len(s)
while (s[i] == ' '):
i += 1
left = i
while (i < n):
if (i + 1 == n or s[i] == ' '):
j = i - 1
if (i + 1 == n):
j += 1
while (left < j):
s = s[0:left] + s[j] + s[left+1:j] + s[left] + s[j+1:]
left += 1
j -= 1
left = i + 1
if (i > left and s[left] == ' '):
left = i
i += 1
s = s[::-1]
return s
# driver code
Str = "I AM A GEEK"
Str = reverse_words(Str)
print(Str)
# This code is contributed by shinjanpatra
|
constant
|
linear
|
# Python3 program to reverse string without
# affecting it's special character
def rev(s, l, r) :
while l<r :
temp = s[l]
s[l] = s[r]
s[r] = temp
l += 1
r -= 1
# creating character array of size
# equal to length of string
def reverse(s):
temp = ['']*len(s)
x = 0
for i in range(len(s)) :
if s[i] >= 'a' and s[i] <= 'z' or s[i] >= 'A' and s[i] <= 'Z' :
# storing elements in array
temp[x] = s[i]
x += 1
# reversing the character array
rev(temp, 0, x)
lst = list(s)
x = 0
for i in range(len(s)) :
if s[i] >= 'a' and s[i] <= 'z' or s[i] >= 'A' and s[i] <= 'Z' :
# updating the origional string
lst[i] = temp[x]
x += 1
revStr = ""
for i in range(len(s)) :
revStr += lst[i]
print("reverse string is :",revStr);
# Driver Code
if __name__ == "__main__" :
s="Ab,c,de!$"
reverse(s)
# This code is contributed by aditya942003patil
|
linear
|
linear
|
def reverseString(text):
index = -1
# Loop from last index until half of the index
for i in range(len(text)-1, int(len(text)/2), -1):
# match character is alphabet or not
if text[i].isalpha():
temp = text[i]
while True:
index += 1
if text[index].isalpha():
text[i] = text[index]
text[index] = temp
break
return text
# Driver code
string = "a!!!b.c.d,e'f,ghi"
print ("Input string: ", string)
string = reverseSting(list(string))
print ("Output string: ", "".join(string))
# This code is contributed by shiva9610
|
constant
|
linear
|
# Python3 program to reverse a string preserving
# spaces.
# Function to reverse the string
# and preserve the space position
def reverses(st):
# Mark spaces in result
n = len(st)
result = [0] * n
for i in range(n):
if (st[i] == ' '):
result[i] = ' '
# Traverse input string from beginning
# and put characters in result from end
j = n - 1
for i in range(len(st)):
# Ignore spaces in input string
if (st[i] != ' '):
# Ignore spaces in result.
if (result[j] == ' '):
j -= 1
result[j] = st[i]
j -= 1
return ''.join(result)
# Driver code
if __name__ == "__main__":
st = "internship at geeks for geeks"
print(reverses(st))
# This code is contributed by ukasp
|
linear
|
linear
|
# Python3 program to implement
# the above approach
def preserveSpace(Str):
n = len(Str)
Str = list(Str)
# Initialize two pointers
# as two corners
start = 0
end = n - 1
# Move both pointers
# toward each other
while(start < end):
# If character at start
# or end is space,
# ignore it
if(Str[start] == ' '):
start += 1
continue
elif(Str[end] == ' '):
end -= 1
continue
# If both are not
# spaces, do swap
else:
Str[start], Str[end] = (Str[end],
Str[start])
start += 1
end -= 1
print(''.join(Str))
# Driver code
Str = "internship at geeks for geeks"
preserveSpace(Str);
# This code is contributed by avanitrachhadiya2155
|
constant
|
linear
|
# Python3 Program for removing characters
# from reversed string where vowels are
# present in original string
# Function for replacing the string
def replaceOriginal(s, n):
# initialize a string of length n
r = [' '] * n
# Traverse through all characters of string
for i in range(n):
# assign the value to string r
# from last index of string s
r[i] = s[n - 1 - i]
# if s[i] is a consonant then
# print r[i]
if (s[i] != 'a' and s[i] != 'e' and
s[i] != 'i' and s[i] != 'o' and
s[i] != 'u'):
print(r[i], end = "")
print()
# Driver Code
if __name__ == "__main__":
s = "geeksforgeeks"
n = len(s)
replaceOriginal(s, n)
# This code is contributed by
# sanjeev2552
|
linear
|
linear
|
# Python3 program to reverse order of vowels
# utility function to check for vowel
def isVowel(c):
if (c == 'a' or c == 'A' or c == 'e' or
c == 'E' or c == 'i' or c == 'I' or
c == 'o' or c == 'O' or c == 'u' or c == 'U'):
return True
return False
# Function to reverse order of vowels
def reverserVowel(string):
j = 0
vowel = [0] * len(string)
string = list(string)
# Storing the vowels separately
for i in range(len(string)):
if isVowel(string[i]):
vowel[j] = string[i]
j += 1
# Placing the vowels in the reverse
# order in the string
for i in range(len(string)):
if isVowel(string[i]):
j -= 1
string[i] = vowel[j]
return ''.join(string)
# Driver Code
if __name__ == "__main__":
string = "hello world"
print(reverserVowel(string))
# This code is contributed by
# sanjeev2552
|
linear
|
linear
|
# Python3 program to reverse order of vowels
# utility function to check for vowel
def isVowel(c):
return (c=='a' or c=='A' or c=='e' or
c=='E' or c=='i' or c=='I' or
c=='o' or c=='O' or c=='u' or
c=='U')
# Function to reverse order of vowels
def reverseVowel(str):
# Start two indexes from two corners
# and move toward each other
i = 0
j = len(str) - 1
while (i < j):
if not isVowel(str[i]):
i += 1
continue
if (not isVowel(str[j])):
j -= 1
continue
# swapping
str[i], str[j] = str[j], str[i]
i += 1
j -= 1
return str
# Driver function
if __name__ == "__main__":
str = "hello world"
print(*reverseVowel(list(str)), sep = "")
# This code is contributed by SHUBHAMSINGH10
|
constant
|
linear
|
# Python3 program to reverse string
# according to the number of words
# Reverse the letters of the word
def reverse(string, start, end):
# Temporary variable to store character
temp = ''
while start <= end:
# Swapping the first and last character
temp = string[start]
string[start] = string[end]
string[end] = temp
start += 1
end -= 1
# This function forms the required string
def reverseletter(string, start, end):
wstart, wend = start, start
while wend < end:
if string[wend] == " ":
wend += 1
continue
# Checking the number of words
# present in string to reverse
while wend <= end and string[wend] != " ":
wend += 1
wend -= 1
# Reverse the letter
# of the words
reverse(string, wstart, wend)
wend += 1
# Driver Code
if __name__ == "__main__":
string = "Ashish Yadav Abhishek Rajput Sunil Pundir"
string = list(string)
reverseletter(string, 0, len(string) - 1)
print(''.join(string))
# This code is contributed by
# sanjeev2552
|
constant
|
linear
|
# Python3 program to reverse each word
# in a linked list
# Node of a linked list
class Node:
def __init__(self, next = None, data = None):
self.next = next
self.data = data
# Function to create newNode
# in a linked list
def newNode(c) :
temp = Node()
temp.c = c
temp.next = None
return temp
# reverse each node data
def reverse_word(str) :
s = ""
i = 0
while(i < len(str) ):
s = str[i] + s
i = i + 1
return s
def reverse( head) :
ptr = head
# iterate each node and call reverse_word
# for each node data
while (ptr != None):
ptr.c = reverse_word(ptr.c)
ptr = ptr.next
return head
# printing linked list
def printList( head) :
while (head != None):
print( head.c ,end = " ")
head = head.next
# Driver program
head = newNode("Geeksforgeeks")
head.next = newNode("a")
head.next.next = newNode("computer")
head.next.next.next = newNode("science")
head.next.next.next.next = newNode("portal")
head.next.next.next.next.next = newNode("for")
head.next.next.next.next.next.next = newNode("geeks")
print( "List before reverse: ")
printList(head)
head = reverse(head)
print( "\n\nList after reverse: ")
printList(head)
# This code is contributed by Arnab Kundu
|
constant
|
linear
|
# Python3 code to check if
# cyclic order is possible
# among strings under given
# constraints
M = 26
# Utility method for a depth
# first search among vertices
def dfs(g, u, visit):
visit[u] = True
for i in range(len(g[u])):
if(not visit[g[u][i]]):
dfs(g, g[u][i], visit)
# Returns true if all vertices
# are strongly connected i.e.
# can be made as loop
def isConnected(g, mark, s):
# Initialize all vertices
# as not visited
visit = [False for i in range(M)]
# Perform a dfs from s
dfs(g, s, visit)
# Now loop through
# all characters
for i in range(M):
# I character is marked
# (i.e. it was first or last
# character of some string)
# then it should be visited
# in last dfs (as for looping,
# graph should be strongly
# connected) */
if(mark[i] and (not visit[i])):
return False
# If we reach that means
# graph is connected
return True
# return true if an order among
# strings is possible
def possibleOrderAmongString(arr, N):
# Create an empty graph
g = {}
# Initialize all vertices
# as not marked
mark = [False for i in range(M)]
# Initialize indegree and
# outdegree of every
# vertex as 0.
In = [0 for i in range(M)]
out = [0 for i in range(M)]
# Process all strings
# one by one
for i in range(N):
# Find first and last
# characters
f = (ord(arr[i][0]) -
ord('a'))
l = (ord(arr[i][-1]) -
ord('a'))
# Mark the characters
mark[f] = True
mark[l] = True
# Increase indegree
# and outdegree count
In[l] += 1
out[f] += 1
if f not in g:
g[f] = []
# Add an edge in graph
g[f].append(l)
# If for any character
# indegree is not equal to
# outdegree then ordering
# is not possible
for i in range(M):
if(In[i] != out[i]):
return False
return isConnected(g, mark,
ord(arr[0][0]) -
ord('a'))
# Driver code
arr = ["ab", "bc",
"cd", "de",
"ed", "da"]
N = len(arr)
if(possibleOrderAmongString(arr, N) ==
False):
print("Ordering not possible")
else:
print("Ordering is possible")
# This code is contributed by avanitrachhadiya2155
|
linear
|
linear
|
# Python3 program to sort an Array of
# Strings according to their lengths
# Function to print the sorted array of string
def printArraystring(string, n):
for i in range(n):
print(string[i], end = " ")
# Function to Sort the array of string
# according to lengths. This function
# implements Insertion Sort.
def sort(s, n):
for i in range(1, n):
temp = s[i]
# Insert s[j] at its correct position
j = i - 1
while j >= 0 and len(temp) < len(s[j]):
s[j + 1] = s[j]
j -= 1
s[j + 1] = temp
# Driver code
if __name__ == "__main__":
arr = ["GeeksforGeeks", "I", "from", "am"]
n = len(arr)
# Function to perform sorting
sort(arr, n)
# Calling the function to print result
printArraystring(arr, n)
# This code is contributed by
# sanjeev2552
|
constant
|
quadratic
|
from functools import cmp_to_key
# Function to check the small string
def compare(s1,s2):
return len(s1) - len(s2)
# Function to print the sorted array of string
def printArraystring(str,n):
for i in range(n):
print(str[i],end = " ")
# Driver function
arr = ["GeeksforGeeks", "I", "from", "am"]
n = len(arr)
# Function to perform sorting
arr.sort(key = cmp_to_key(compare))
# Calling the function to print result
printArraystring(arr, n)
# This code is contributed by shinjanpatra.
|
constant
|
nlogn
|
# Python code for the above approach
def printsorted(arr):
# Sorting using sorted function
# providing key as len
print(*sorted(arr, key=len))
# Driver code
arr = ["GeeksforGeeks", "I", "from", "am"]
# Passing list to printsorted function
printsorted(arr)
# this code is contributed by vikkycirus
|
constant
|
nlogn
|
# Python3 program to sort an array of strings
# using Trie
MAX_CHAR = 26
class Trie:
# index is set when node is a leaf
# node, otherwise -1;
# to make new trie
def __init__(self):
self.child = [None for i in range(MAX_CHAR)]
self.index = -1
# def to insert in trie
def insert(root,str,index):
node = root
for i in range(len(str)):
# taking ascii value to find index of
# child node
ind = ord(str[i]) - ord('a')
# making new path if not already
if (node.child[ind] == None):
node.child[ind] = Trie()
# go to next node
node = node.child[ind]
# Mark leaf (end of word) and store
# index of word in arr[]
node.index = index
# function for preorder traversal
def preorder(node, arr):
if (node == None):
return False
for i in range(MAX_CHAR):
if (node.child[i] != None):
# if leaf node then print key
if (node.child[i].index != -1):
print(arr[node.child[i].index])
preorder(node.child[i], arr)
def printSorted(arr,n):
root = Trie()
# insert all keys of dictionary into trie
for i in range(n):
insert(root, arr[i], i)
# print keys in lexicographic order
preorder(root, arr)
# Driver code
arr = [ "abc", "xy", "bcd" ]
n = len(arr)
printSorted(arr, n)
# This code is contributed by shinjanpatra
|
linear
|
linear
|
# Python3 program to sort a string
# of characters
# function to print string in
# sorted order
def sortString(str) :
str = ''.join(sorted(str))
print(str)
# Driver Code
s = "geeksforgeeks"
sortString(s)
# This code is contributed by Smitha
|
constant
|
nlogn
|
# Python 3 program to sort a string
# of characters
MAX_CHAR = 26
# function to print string in sorted order
def sortString(str):
# Hash array to keep count of characters.
# Initially count of all characters is
# initialized to zero.
charCount = [0 for i in range(MAX_CHAR)]
# Traverse string and increment
# count of characters
for i in range(0, len(str), 1):
# 'a'-'a' will be 0, 'b'-'a' will be 1,
# so for location of character in count
# array we will do str[i]-'a'.
charCount[ord(str[i]) - ord('a')] += 1
# Traverse the hash array and print
# characters
for i in range(0, MAX_CHAR, 1):
for j in range(0, charCount[i], 1):
print(chr(ord('a') + i), end = "")
# Driver Code
if __name__ == '__main__':
s = "geeksforgeeks"
sortString(s)
# This code is contributed by
# Sahil_Shelangia
|
constant
|
linear
|
# Python program to sort
# a string in descending
# order using library function
def descOrder(s):
s.sort(reverse = True)
str1 = ''.join(s)
print(str1)
def main():
s = list('geeksforgeeks')
# function call
descOrder(s)
if __name__=="__main__":
main()
# This code is contributed by
# prabhat kumar singh
|
constant
|
constant
|
# Python program to sort a string of characters
# in descending order
MAX_CHAR = 26;
# function to print string in sorted order
def sortString(str):
# Hash array to keep count of characters.
# Initially count of all charters is
# initialized to zero.
charCount = [0]*MAX_CHAR;
# Traverse string and increment
# count of characters
for i in range(len(str)):
# 'a'-'a' will be 0, 'b'-'a' will be 1,
# so for location of character in count
# array we will do str[i]-'a'.
charCount[ord(str[i]) - ord('a')]+=1;
# Traverse the hash array and print
# characters
for i in range(MAX_CHAR - 1,-1, -1):
for j in range(charCount[i]):
print(chr(97+i),end="");
# Driver program to test above function
s = "alkasingh";
sortString(s);
# This code is contributed by Princi Singh
|
constant
|
linear
|
# Python 3 implementation to print array
# of strings in sorted order without
# copying one string into another
# function to print strings in sorted order
def printInSortedOrder(arr, n):
index = [0] * n
# Initially the index of the strings
# are assigned to the 'index[]'
for i in range(n):
index[i] = i
# selection sort technique is applied
for i in range(n - 1):
min = i
for j in range(i + 1, n):
# with the help of 'index[]'
# strings are being compared
if (arr[index[min]] > arr[index[j]]):
min = j
# index of the smallest string is placed
# at the ith index of 'index[]'
if (min != i):
index[min], index[i] = index[i], index[min]
# printing strings in sorted order
for i in range(n):
print(arr[index[i]], end = " ")
# Driver Code
if __name__ == "__main__":
arr = ["geeks", "quiz", "geeks", "for"]
n = 4
printInSortedOrder(arr, n)
# This code is contributed by ita_c
|
linear
|
quadratic
|
# Python3 implementation to sort
# the given string without using
# any sorting technique
# Function to sort the given string
# without using any sorting technique
def sortString(str, n):
# To store the final sorted string
new_str = ""
# for each character 'i'
for i in range(ord('a'), ord('z') + 1):
# if character 'i' is present at a particular
# index then add character 'i' to 'new_str'
for j in range(n):
if (str[j] == chr(i)):
new_str += str[j]
# required final sorted string
return new_str
# Driver Code
str = "geeksforgeeks"
n = len(str)
print(sortString(str, n))
# This code is contributed by Anant Agarwal.
|
constant
|
linear
|
# Python 3 implementation to sort the given
# string without using any sorting technique
def sortString(st, n):
# A character array to store the no.of occurrences of each character
# between 'a' to 'z'
arr = [0] * 26
# to store the final sorted string
new_str = ""
# To store each occurrence of character by relative indexing
for i in range(n):
arr[ord(st[i]) - ord('a')] += 1
# To traverse the character array and append it to new_str
for i in range(26):
while(arr[i] > 0):
new_str += chr(i+ord('a'))
arr[i] -= 1
return new_str
# Driver program to test above
if __name__ == "__main__":
st = "geeksforgeeks"
n = len(st)
print(sortString(st, n))
# This code is contributed by ukasp.
|
constant
|
linear
|
# Python3 program for above implementation
MAX_CHAR = 26
# Function to return string in lexicographic
# order followed by integers sum
def arrangeString(string):
char_count = [0] * MAX_CHAR
s = 0
# Traverse the string
for i in range(len(string)):
# Count occurrence of uppercase alphabets
if string[i] >= "A" and string[i] <= "Z":
char_count[ord(string[i]) - ord("A")] += 1
# Store sum of integers
else:
s += ord(string[i]) - ord("0")
res = ""
# Traverse for all characters A to Z
for i in range(MAX_CHAR):
ch = chr(ord("A") + i)
# Append the current character
# in the string no. of times it
# occurs in the given string
while char_count[i]:
res += ch
char_count[i] -= 1
# Append the sum of integers
if s > 0:
res += str(s)
# return resultant string
return res
# Driver code
if __name__ == "__main__":
string = "ACCBA10D2EW30"
print(arrangeString(string))
# This code is contributed by
# sanjeev2552
|
linear
|
linear
|
# Python3 program to print
# all permutations of a
# string in sorted order.
from collections import defaultdict
# Calculating factorial
# of a number
def factorial(n):
f = 1
for i in range (1, n + 1):
f = f * i
return f
# Method to find total
# number of permutations
def calculateTotal(temp, n):
f = factorial(n)
# Building Map to store
# frequencies of all
# characters.
hm = defaultdict (int)
for i in range (len(temp)):
hm[temp[i]] += 1
# Traversing map and
# finding duplicate elements.
for e in hm:
x = hm[e]
if (x > 1):
temp5 = factorial(x)
f //= temp5
return f
def nextPermutation(temp):
# Start traversing from
# the end and find position
# 'i-1' of the first character
# which is greater than its successor
for i in range (len(temp) - 1, 0, -1):
if (temp[i] > temp[i - 1]):
break
# Finding smallest character
# after 'i-1' and greater
# than temp[i-1]
min = i
x = temp[i - 1]
for j in range (i + 1, len(temp)):
if ((temp[j] < temp[min]) and
(temp[j] > x)):
min = j
# Swapping the above
# found characters.
temp[i - 1], temp[min] = (temp[min],
temp[i - 1])
# Sort all digits from
# position next to 'i-1'
# to end of the string
temp[i:].sort()
# Print the String
print (''.join(temp))
def printAllPermutations(s):
# Sorting String
temp = list(s)
temp.sort()
# Print first permutation
print (''.join( temp))
# Finding the total permutations
total = calculateTotal(temp,
len(temp))
for i in range (1, total):
nextPermutation(temp)
# Driver Code
if __name__ == "__main__":
s = "AAB"
printAllPermutations(s)
# This code is contributed by Chitranayal
|
linear
|
quadratic
|
# Python program to get minimum cost to sort
# strings by reversal operation
# Returns minimum cost for sorting arr[]
# using reverse operation. This function
# returns -1 if it is not possible to sort.
def ReverseStringMin(arr, reverseCost, n):
# dp[i][j] represents the minimum cost to
# make first i strings sorted.
# j = 1 means i'th string is reversed.
# j = 0 means i'th string is not reversed.
dp = [[float("Inf")] * 2 for i in range(n)]
# initializing dp array for first string
dp[0][0] = 0
dp[0][1] = reverseCost[0]
# getting array of reversed strings
rev_arr = [i[::-1] for i in arr]
# looping for all strings
for i in range(1, n):
# Looping twice, once for string and once
# for reversed string
for j in range(2):
# getting current string and current
# cost according to j
curStr = arr[i] if j==0 else rev_arr[i]
curCost = 0 if j==0 else reverseCost[i]
# Update dp value only if current string
# is lexicographically larger
if (curStr >= arr[i - 1]):
dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost)
if (curStr >= rev_arr[i - 1]):
dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost)
# getting minimum from both entries of last index
res = min(dp[n-1][0], dp[n-1][1])
return res if res != float("Inf") else -1
# Driver code
def main():
arr = ["aa", "ba", "ac"]
reverseCost = [1, 3, 1]
n = len(arr)
dp = [float("Inf")] * n
res = ReverseStringMin(arr, reverseCost,n)
if res != -1 :
print ("Minimum cost to sort sorting is" , res)
else :
print ("Sorting not possible")
if __name__ == '__main__':
main()
#This code is contributed by Neelam Yadav
|
linear
|
linear
|
# Python program for printing
# all numbers containing 1,2 and 3
def printNumbers(numbers):
# convert all numbers
# to strings
numbers = map(str, numbers)
result = []
for num in numbers:
# check if each number
# in the list has 1,2 and 3
if ('1' in num and
'2' in num and
'3' in num):
result.append(num)
# if there are no
# valid numbers
if not result:
result = ['-1']
return sorted(result)
# Driver Code
numbers = [123, 1232, 456,
234, 32145]
result = printNumbers(numbers)
print ', '.join(num for num in result)
# This code is contributed
# by IshitaTripathi
|
linear
|
nlogn
|
# Python3 program to implement binary search
# in a sparse array
def sparseSearch(arr , key , low , high):
left = 0; right = 0
while low <= high:
mid = low + (high - low) // 2
if arr[mid] == '':
left = mid - 1
right = mid + 1
while True:
# Check for out of bounds
if left < low and right > high:
return -1
elif left >= low and arr[left] != '':
# Search left
mid = left
break
elif right <= high and arr[right] != '':
# Search right
mid = right
break
left -= 1
right += 1
if arr[mid] == key:
print('Found string {} at index {}'.format
(arr[mid] , mid))
return mid
# Classical Binary search
# search left
elif arr[mid] > key:
high = mid - 1
# search right
elif arr[mid] < key:
low = mid + 1
return -1
if __name__ == '__main__':
arr = ["for", "geeks", "", "", "", "", "ide",
"practice", "", "", "", "quiz"]
key = 'geeks'
low = 0
high = len(arr) - 1
sparseSearch(arr , key , low , high)
# This is Code contributed by
# Ashwin Viswanathan
# Additional Updates by Meghna Natraj
|
logn
|
logn
|
# Python3 Program to find maximum
# lowercase alphabets present
# between two uppercase alphabets
MAX_CHAR = 26
# Function which computes the
# maximum number of distinct
# lowercase alphabets between
# two uppercase alphabets
def maxLower(str):
n = len(str)
# Ignoring lowercase characters
# in the beginning.
i = 0
for i in range(n):
if str[i] >= 'A' and str[i] <= 'Z':
i += 1
break
# We start from next of first capital
# letter and traverse through
# remaining character.
maxCount = 0
count = []
for j in range(MAX_CHAR):
count.append(0)
for j in range(i, n):
# If character is in uppercase,
if str[j] >= 'A' and str[j] <= 'Z':
# Count all distinct lower
# case characters
currCount = 0
for k in range(MAX_CHAR):
if count[k] > 0:
currCount += 1
# Update maximum count
maxCount = max(maxCount, currCount)
# Reset count array
for y in count:
y = 0
# If character is in lowercase
if str[j] >= 'a' and str[j] <= 'z':
count[ord(str[j]) - ord('a')] += 1
return maxCount
# Driver function
str = "zACaAbbaazzC";
print(maxLower(str))
# This code is contributed by Upendra Bartwal
|
constant
|
linear
|
# Python3 Program to find maximum
# lowercase alphabets present
# between two uppercase alphabets
# Function which computes the
# maximum number of distinct
# lowercase alphabets between
# two uppercase alphabets
def maxLower(str):
n = len(str);
# Ignoring lowercase characters
# in the beginning.
i = 0;
for i in range(n):
if (str[i] >= 'A' and
str[i] <= 'Z'):
i += 1;
break;
# We start from next of first
# capital letter and traverse
# through remaining character.
maxCount = 3;
s = set()
for i in range(n):
# If character is in
# uppercase,
if (str[i] >= 'A' and
str[i] <= 'Z'):
# Update maximum count if
# lowercase character before
# this is more.
maxCount = max(maxCount,
len(s));
# clear the set
s.clear();
# If character is in
# lowercase
if (str[i] >= 'a' and
str[i] <= 'z'):
s.add(str[i]);
return maxCount;
# Driver Code
if __name__ == '__main__':
str = "zACaAbbaazzC";
print(maxLower(str));
# This code is contributed by 29AjayKumar
|
linear
|
linear
|
# Python3 program to Convert characters
# of a string to opposite case
str = "GeEkSfOrGeEkS"
x=""
for i in str:
if(i.isupper()):
x+=i.lower()
else:
x+=i.upper()
print(x)
|
constant
|
linear
|
# Python3 program to Convert characters
# of a string to opposite case
str = "GeEkSfOrGeEkS"
x=""
upperalphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
loweralphabets="abcdefghijklmnopqrstuvwxyz"
for i in str:
if i in upperalphabets:
x+=loweralphabets[upperalphabets.index(i)]
else:
x+=upperalphabets[loweralphabets.index(i)]
print(x)
|
constant
|
linear
|
# Python3 program to convert a
# sentence to gOOGLE cASE.
def convert(str):
# empty strings
w = ""
z = "";
# convert input string
# to upper case
str = str.upper() + " ";
for i in range(len(str)):
# checki if character is not
# a space and adding it to
# string w
ch = str[i];
if (ch != ' '):
w = w + ch;
else:
# converting first character
# to lower case and subsequent
# initial letter of another
# word to lower case
z = (z + (w[0]).lower() +
w[1:len(w)] + " ");
w = "";
return z;
# Driver code
if __name__ == '__main__':
str = "I got intern at geeksforgeeks";
print(convert(str));
# This code is contributed by 29AjayKumar
|
linear
|
linear
|
# Python program to convert given
# sentence to camel case.
import math
# Function to remove spaces
# and convert into camel case
def convert( s):
n = len(s)
s1 = ""
s1 = s1 + s[0].lower()
i = 1
while i < n:
# check for spaces in the sentence
if (s[i] == ' ' and i <= n):
# conversion into upper case
s1 = s1 + " " + (s[i + 1]).lower()
i = i + 1
# If not space, copy character
else:
s1 = s1 + (s[i]).upper()
# increase index of string by s1
i = i + 1
# return string to main
return s1
# Driver code
str = "I get intern at geeksforgeeks"
print(convert(str))
# This code is contributed by Gitanjali.
|
constant
|
linear
|
# Python program to convert
# given sentence to camel case.
# Function to remove spaces
# and convert into camel case
def convert(s):
if(len(s) == 0):
return
s1 = ''
s1 += s[0].upper()
for i in range(1, len(s)):
if (s[i] == ' '):
s1 += s[i + 1].upper()
i += 1
elif(s[i - 1] != ' '):
s1 += s[i]
print(s1)
# Driver Code
def main():
s = "I get intern at geeksforgeeks"
convert(s)
if __name__=="__main__":
main()
# This code is contributed
# prabhat kumar singh
|
constant
|
linear
|
# Python code to print all permutations
# with respect to cases
# function to generate permutations
def permute(ip, op):
# base case
if len(ip) == 0:
print(op, end=" ")
return
# pick lower and uppercase
ch = ip[0].lower()
ch2 = ip[0].upper()
ip = ip[1:]
permute(ip, op+ch)
permute(ip, op+ch2)
# driver code
def main():
ip = "AB"
permute(ip, "")
main()
# This Code is Contributed by Vivek Maddeshiya
|
linear
|
np
|
# Python code to print all permutations
# with respect to cases
# Function to generate permutations
def permute(inp):
n = len(inp)
# Number of permutations is 2^n
mx = 1 << n
# Converting string to lower case
inp = inp.lower()
# Using all subsequences and permuting them
for i in range(mx):
# If j-th bit is set, we convert it to upper case
combination = [k for k in inp]
for j in range(n):
if (((i >> j) & 1) == 1):
combination[j] = inp[j].upper()
temp = ""
# Printing current combination
for i in combination:
temp += i
print temp,
# Driver code
permute("ABC")
# This code is contributed by Sachin Bisht
|
linear
|
quadratic
|
# Python3 program to get toggle case of a string
x = 32;
# tOGGLE cASE = swaps CAPS to lower
# case and lower case to CAPS
def toggleCase(a):
for i in range(len(a)):
# Bitwise EXOR with 32
a = a[:i] + chr(ord(a[i]) ^ 32) + a[i + 1:];
return a;
# Driver Code
str = "CheRrY";
print("Toggle case: ", end = "");
str = toggleCase(str);
print(str);
print("Original string: ", end = "");
str = toggleCase(str);
print(str);
# This code is contributed by 29AjayKumar
|
constant
|
linear
|
# Python3 code for above approach
def idToShortURL(id):
map = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
shortURL = ""
# for each digit find the base 62
while(id > 0):
shortURL += map[id % 62]
id //= 62
# reversing the shortURL
return shortURL[len(shortURL): : -1]
def shortURLToId(shortURL):
id = 0
for i in shortURL:
val_i = ord(i)
if(val_i >= ord('a') and val_i <= ord('z')):
id = id*62 + val_i - ord('a')
elif(val_i >= ord('A') and val_i <= ord('Z')):
id = id*62 + val_i - ord('A') + 26
else:
id = id*62 + val_i - ord('0') + 52
return id
if (__name__ == "__main__"):
id = 12345
shortURL = idToShortURL(id)
print("Short URL from 12345 is : ", shortURL)
print("ID from", shortURL, "is : ", shortURLToId(shortURL))
|
constant
|
linear
|
# Python program to print the first non-repeating character
string = "geeksforgeeks"
index = -1
fnc = ""
for i in string:
if string.count(i) == 1:
fnc += i
break
else:
index += 1
if index == 1:
print("Either all characters are repeating or string is empty")
else:
print("First non-repeating character is", fnc)
|
constant
|
quadratic
|
# python3 implementation
def FirstNonRepeat(s):
for i in s:
if (s.find(i, (s.find(i)+1))) == -1:
print("First non-repeating character is", i)
break
return
# __main__
s = 'geeksforgeeks'
FirstNonRepeat(s)
|
constant
|
quadratic
|
# Python program to print the first non-repeating character
NO_OF_CHARS = 256
# Returns an array of size 256 containing count
# of characters in the passed char array
def getCharCountArray(string):
count = [0] * NO_OF_CHARS
for i in string:
count[ord(i)] += 1
return count
# The function returns index of first non-repeating
# character in a string. If all characters are repeating
# then returns -1
def firstNonRepeating(string):
count = getCharCountArray(string)
index = -1
k = 0
for i in string:
if count[ord(i)] == 1:
index = k
break
k += 1
return index
# Driver program to test above function
string = "geeksforgeeks"
index = firstNonRepeating(string)
if index == 1:
print("Either all characters are repeating or string is empty")
else:
print("First non-repeating character is", string[index])
# This code is contributed by Bhavya Jain
|
constant
|
linear
|
# Python3 program to find first non-repeating
# character
import sys
NO_OF_CHARS = 256
# The function returns index of the first
# non-repeating character in a string. If
# all characters are repeating then
# returns sys.maxsize :
def firstNonRepeating(Str):
arr = [[] for i in range(NO_OF_CHARS)]
for i in range(NO_OF_CHARS):
arr[i] = [0, 0]
for i in range(len(Str)):
arr[ord(Str[i])][0] += 1
arr[ord(Str[i])][1] = i
res = sys.maxsize
for i in range(NO_OF_CHARS):
# If this character occurs only
# once and appears before the
# current result, then update the
# result
if (arr[i][0] == 1):
res = min(res, arr[i][1])
return res
# Driver program to test above functionS
Str = "geeksforgeeks"
index = firstNonRepeating(Str)
if (index == sys.maxsize):
print("Either all characters are repeating or string is empty")
else:
print("First non-repeating character is ", Str[index])
# This code is contributed by shinjanpatra
|
constant
|
linear
|
# this function return the index of first non-repeating
# character if found, or else it returns -1
import sys
def firstNonRepeating(Str):
fi = [-1 for i in range(256)]
# sets all repeating characters to -2 and non-repeating characters
# contain the index where they occur
for i in range(len(Str)):
if(fi[ord(Str[i])] == -1):
fi[ord(Str[i])] = i
else:
fi[ord(Str[i])] = -2
res = sys.maxsize
for i in range(256):
# If this character is not -1 or -2 then it
# means that this character occurred only once
# so find the min index of all characters that
# occur only once, that's our first index
if(fi[i] >= 0):
res = min(res, fi[i])
# if res remains INT_MAX, it means there are no
# characters that repeat only once or the string is empty
if(res == sys.maxsize):
return -1
else:
return res
Str = "geeksforgeeks"
firstIndex = firstNonRepeating(Str)
if (firstIndex == -1):
print("Either all characters are repeating or string is empty")
else:
print("First non-repeating character is " + str(Str[firstIndex]))
# This code is contributed by shinjanpatra
|
constant
|
linear
|
# Python implementation
from collections import Counter
# Function which repeats
# first Nonrepeating character
def printNonrepeated(string):
# Calculating frequencies
# using Counter function
freq = Counter(string)
# Traverse the string
for i in string:
if(freq[i] == 1):
print("First non-repeating character is " + i)
break
# Driver code
string = "geeksforgeeks"
# passing string to printNonrepeated function
printNonrepeated(string)
# this code is contributed by vikkycirus
|
constant
|
linear
|
# Python program to print all permutations with repetition
# of characters
def toString(List):
return ''.join(List)
# The main function that recursively prints all repeated
# permutations of the given string. It uses data[] to store
# all permutations one by one
def allLexicographicRecur (string, data, last, index):
length = len(string)
# One by one fix all characters at the given index and
# recur for the subsequent indexes
for i in range(length):
# Fix the ith character at index and if this is not
# the last index then recursively call for higher
# indexes
data[index] = string[i]
# If this is the last index then print the string
# stored in data[]
if index==last:
print (toString(data))
else:
allLexicographicRecur(string, data, last, index+1)
# This function sorts input string, allocate memory for data
# (needed for allLexicographicRecur()) and calls
# allLexicographicRecur() for printing all permutations
def allLexicographic(string):
length = len(string)
# Create a temp array that will be used by
# allLexicographicRecur()
data = [""] * (length+1)
# Sort the input string so that we get all output strings in
# lexicographically sorted order
string = sorted(string)
# Now print all permutations
allLexicographicRecur(string, data, length-1, 0)
# Driver program to test the above functions
string = "ABC"
print ("All permutations with repetition of " + string + " are:")
allLexicographic(string)
# This code is contributed to Bhavya Jain
|
linear
|
np
|
# A Python program to find first non-repeating character from
# a stream of characters
MAX_CHAR = 256
def findFirstNonRepeating():
# inDLL[x] contains pointer to a DLL node if x is present
# in DLL. If x is not present, then inDLL[x] is NULL
inDLL = [] * MAX_CHAR
# repeated[x] is true if x is repeated two or more times.
# If x is not seen so far or x is seen only once. then
# repeated[x] is false
repeated = [False] * MAX_CHAR
# Let us consider following stream and see the process
stream = "geekforgeekandgeeksandquizfor"
for i in range(len(stream)):
x = stream[i]
print ("Reading " + x + " from stream")
# We process this character only if it has not occurred
# or occurred only once. repeated[x] is true if x is
# repeated twice or more.s
if not repeated[ord(x)]:
# If the character is not in DLL, then add this
# at the end of DLL
if not x in inDLL:
inDLL.append(x)
else:
inDLL.remove(x)
repeated[ord(x)] = True
if len(inDLL) != 0:
print ("First non-repeating character so far is ")
print (str(inDLL[0]))
# Driver program
findFirstNonRepeating()
# This code is contributed by BHAVYA JAIN
|
constant
|
linear
|
# Python3 program to check if a can be converted to
# a that has repeated subs of length k.
# Returns True if S can be converted to a
# with k repeated subs after replacing k
# characters.
def check( S, k):
# Length of must be a multiple of k
n = len(S)
if (n % k != 0):
return False
# Map to store s of length k and their counts
mp = {}
for i in range(0, n, k):
mp[S[i:k]] = mp.get(S[i:k], 0) + 1
# If is already a repetition of k subs,
# return True.
if (len(mp) == 1):
return True
# If number of distinct subs is not 2, then
# not possible to replace a .
if (len(mp) != 2):
return False
# One of the two distinct must appear exactly once.
# Either the first entry appears once, or it appears
# n/k-1 times to make other sub appear once.
for i in mp:
if i == (n//k - 1) or mp[i] == 1:
return True
return False
# Driver code
if check("abababcd", 2):
print("Yes")
else:
print("No")
# This code is contributed by mohit kumar 29
|
linear
|
linear
|
# Python3 program to find smallest possible
# length of a string of only three characters
# A memoized function find result recursively.
# a, b and c are counts of 'a's, 'b's and
# 'c's in str
def length(a, b, c):
global DP
#print(a, b, c)
# If this subproblem is already
# evaluated
if a < 0 or b < 0 or c < 0:
return 0
if (DP[a][b] != -1):
return DP[a][b]
# If there is only one type
# of character
if (a == 0 and b == 0):
DP[a][b] = c
return c
if (a == 0 and c == 0):
DP[a][b] = b
return b
if (b == 0 and c == 0):
DP[a][b] = a
return a
# If only two types of characters
# are present
if (a == 0):
DP[a][b] = length(a + 1, b - 1,
c - 1)
return DP[a][b]
if (b == 0):
DP[a][b] = length(a - 1, b + 1,
c - 1)
return DP[a][b]
if (c == 0):
DP[a][b] = length(a - 1, b - 1,
c + 1)
return DP[a][b]
# If all types of characters are present.
# Try combining all pairs.
x = length(a - 1, b - 1, c + 1)
y = length(a - 1, b + 1, c - 1)
z = length(a + 1, b - 1, c - 1)
DP[a][b] = min([x, y, z])
return DP[a][b]
# Returns smallest possible length with
# given operation allowed.
def stringReduction(str):
n = len(str)
# Counting occurrences of three different
# characters 'a', 'b' and 'c' in str
count = [0] * 3
for i in range(n):
count[ord(str[i]) - ord('a')] += 1
return length(count[0], count[1], count[2])
# Driver code
if __name__ == '__main__':
DP = [[[-1 for i in range(110)]
for i in range(110)]
for i in range(110)]
str = "abcbbaacb"
print(stringReduction(str))
# This code is contributed by mohit kumar 29
|
linear
|
linear
|
# Python3 program to find smallest possible
# length of a string of only three characters
# Returns smallest possible length
# with given operation allowed.
def stringReduction(str):
n = len(str)
# Counint occurrences of three different
# characters 'a', 'b' and 'c' in str
count = [0] * 3
for i in range(n):
count[ord(str[i]) - ord('a')] += 1
# If all characters are same.
if (count[0] == n or count[1] == n or
count[2] == n):
return n
# If all characters are present even number
# of times or all are present odd number of
# times.
if ((count[0] % 2) == (count[1] % 2) and
(count[1] % 2) == (count[2] % 2)):
return 2
# Answer is 1 for all other cases.
return 1
# Driver code
if __name__ == "__main__":
str = "abcbbaacb"
print(stringReduction(str))
# This code is contributed by ita_c
|
constant
|
linear
|
# Python3 program to find if its possible to
# distribute balls without repetition
MAX_CHAR = 26
# function to find if its possible to
# distribute balls or not
def distributingBalls(k, n, string) :
# count array to count how many times
# each color has occurred
a = [0] * MAX_CHAR
for i in range(n) :
# increasing count of each color
# every time it appears
a[ord(string[i]) - ord('a')] += 1
for i in range(MAX_CHAR) :
# to check if any color appears
# more than K times if it does
# we will print NO
if (a[i] > k) :
return False
return True
# Driver code
if __name__ == "__main__" :
n, k = 6, 3
string = "aacaab"
if (distributingBalls(k, n, string)) :
print("YES")
else :
print("NO")
# This code is contributed by Ryuga
|
constant
|
linear
|
# Python 3 program to find the
# maximum consecutive repeating
# character in given string
# function to find out the maximum
# repeating character in given string
def maxRepeating(str):
l = len(str)
count = 0
# Find the maximum repeating
# character starting from str[i]
res = str[0]
for i in range(l):
cur_count = 1
for j in range(i + 1, l):
if (str[i] != str[j]):
break
cur_count += 1
# Update result if required
if cur_count > count :
count = cur_count
res = str[i]
return res
# Driver code
if __name__ == "__main__":
str = "aaaabbaaccde"
print(maxRepeating(str))
# This code is contributed
# by ChitraNayal
|
constant
|
quadratic
|
# Python 3 program to find the
# maximum consecutive repeating
# character in given string
# Returns the maximum repeating
# character in a given string
def maxRepeating(str):
n = len(str)
count = 0
res = str[0]
cur_count = 1
# Traverse string except
# last character
for i in range(n):
# If current character
# matches with next
if (i < n - 1 and
str[i] == str[i + 1]):
cur_count += 1
# If doesn't match, update result
# (if required) and reset count
else:
if cur_count > count:
count = cur_count
res = str[i]
cur_count = 1
return res
# Driver code
if __name__ == "__main__":
str = "aaaabbaaccde"
print(maxRepeating(str))
# This code is contributed
# by ChitraNayal
|
constant
|
linear
|
# Python3 program for a Queue based approach
# to find first non-repeating character
from queue import Queue
# function to find first non
# repeating character of sa Stream
def firstnonrepeating(Str):
global MAX_CHAR
q = Queue()
charCount = [0] * MAX_CHAR
# traverse whole Stream
for i in range(len(Str)):
# push each character in queue
q.put(Str[i])
# increment the frequency count
charCount[ord(Str[i]) -
ord('a')] += 1
# check for the non repeating
# character
while (not q.empty()):
if (charCount[ord(q.queue[0]) -
ord('a')] > 1):
q.get()
else:
print(q.queue[0], end = " ")
break
if (q.empty()):
print(-1, end = " ")
print()
# Driver Code
MAX_CHAR = 26
Str = "aabc"
firstnonrepeating(Str)
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python 3 program to find k'th
# non-repeating character in a string
MAX_CHAR = 256
# Returns index of k'th non-repeating
# character in given string str[]
def kthNonRepeating(str, k):
n = len(str)
# count[x] is going to store count of
# character 'x' in str. If x is not
# present, then it is going to store 0.
count = [0] * MAX_CHAR
# index[x] is going to store index of
# character 'x' in str. If x is not
# present or x is repeating, then it
# is going to store a value (for example,
# length of string) that cannot be a valid
# index in str[]
index = [0] * MAX_CHAR
# Initialize counts of all characters
# and indexes of non-repeating characters.
for i in range( MAX_CHAR):
count[i] = 0
index[i] = n # A value more than any
# index in str[]
# Traverse the input string
for i in range(n):
# Find current character and
# increment its count
x = str[i]
count[ord(x)] += 1
# If this is first occurrence, then
# set value in index as index of it.
if (count[ord(x)] == 1):
index[ord(x)] = i
# If character repeats, then remove
# it from index[]
if (count[ord(x)] == 2):
index[ord(x)] = n
# Sort index[] in increasing order. This step
# takes O(1) time as size of index is 256 only
index.sort()
# After sorting, if index[k-1] is value,
# then return it, else return -1.
return index[k - 1] if (index[k - 1] != n) else -1
# Driver code
if __name__ == "__main__":
str = "geeksforgeeks"
k = 3
res = kthNonRepeating(str, k)
if(res == -1):
print("There are less than k",
"non-repeating characters")
else:
print("k'th non-repeating character is",
str[res])
# This code is contributed
# by ChitraNayal
|
linear
|
nlogn
|
MAX_CHAR = 256
def kthNonRepeating(Input,k):
inputLength = len(Input)
# indexArr will store index of non-repeating characters,
# inputLength for characters not in input and
# inputLength+1 for repeated characters.
# initialize all values in indexArr as inputLength.
indexArr = [inputLength for i in range(MAX_CHAR)]
for i in range(inputLength):
c = Input[i]
if (indexArr[ord(c)] == inputLength):
indexArr[ord(c)] = i
else:
indexArr[ord(c)] = inputLength + 2
indexArr.sort()
if(indexArr[k - 1] != inputLength):
return indexArr[k - 1]
else:
return -1
Input = "geeksforgeeks"
k = 3
res = kthNonRepeating(Input, k)
if(res == -1):
print("There are less than k non-repeating characters")
else:
print("k'th non-repeating character is", Input[res])
# This code is contributed by rag2127
|
linear
|
nlogn
|
# Python3 program to find the first
# character that is repeated
def findRepeatFirstN2(s):
# this is O(N^2) method
p = -1
for i in range(len(s)):
for j in range (i + 1, len(s)):
if (s[i] == s[j]):
p = i
break
if (p != -1):
break
return p
# Driver code
if __name__ == "__main__":
str = "geeksforgeeks"
pos = findRepeatFirstN2(str)
if (pos == -1):
print ("Not found")
else:
print (str[pos])
# This code is contributed
# by ChitraNayal
|
constant
|
quadratic
|
# Python 3 program to find the first
# character that is repeated
# 256 is taken just to ensure nothing
# is left, actual max ASCII limit is 128
MAX_CHAR = 256
def findRepeatFirst(s):
# this is optimized method
p = -1
# initialized counts of occurrences
# of elements as zero
hash = [0 for i in range(MAX_CHAR)]
# initialized positions
pos = [0 for i in range(MAX_CHAR)]
for i in range(len(s)):
k = ord(s[i])
if (hash[k] == 0):
hash[k] += 1
pos[k] = i
elif(hash[k] == 1):
hash[k] += 1
for i in range(MAX_CHAR):
if (hash[i] == 2):
if (p == -1): # base case
p = pos[i]
elif(p > pos[i]):
p = pos[i]
return p
# Driver code
if __name__ == '__main__':
str = "geeksforgeeks"
pos = findRepeatFirst(str);
if (pos == -1):
print("Not found")
else:
print(str[pos])
# This code is contributed by
# Shashank_Sharma
|
constant
|
linear
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.