code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
# Python program to implement Manacher's Algorithm def findLongestPalindromicString(text): N = len(text) if N == 0: return N = 2*N+1 # Position count L = [0] * N L[0] = 0 L[1] = 1 C = 1 # centerPosition R = 2 # centerRightPosition i = 0 # currentRightPosition...
linear
linear
# Python 3 program to print the # string in 'plus' pattern max = 100 # Function to make a cross # in the matrix def carveCross(str): n = len(str) if (n % 2 == 0) : ''' As, it is not possible to make the cross exactly in the middle of the matrix with an even length string.''...
constant
quadratic
# Python3 program to implement # wildcard pattern matching # algorithm # Function that matches input # txt with given wildcard pattern def stringmatch(txt, pat, n, m): # empty pattern can only # match with empty sting # Base case if (m == 0): return (n == 0) # step 1 # ...
constant
linear
# Python3 program to replace c1 with c2 # and c2 with c1 def replace(s, c1, c2): l = len(s) # loop to traverse in the string for i in range(l): # check for c1 and replace if (s[i] == c1): s = s[0:i] + c2 + s[i + 1:] # check for c2 and replace ...
constant
linear
# Python program for implementation of # Aho-Corasick algorithm for string matching # defaultdict is used only for storing the final output # We will return a dictionary where key is the matched word # and value is the list of indexes of matched word from collections import defaultdict # For simplicity, Arrays and ...
linear
linear
# Python program to calculate number of times # the pattern occurred in given string # Returns count of occurrences of "1(0+)1" def countPattern(s): length = len(s) oneSeen = False count = 0 # Initialize result for i in range(length): # Check if encountered '1' forms a valid ...
constant
linear
# Python3 program to find if a string follows # order defined by a given pattern CHAR_SIZE = 256 # Returns true if characters of str follow # order defined by a given ptr. def checkPattern(Str, pat): # Initialize all orders as -1 label = [-1] * CHAR_SIZE # Assign an order to pattern characters # a...
constant
linear
# Python code for finding count # of string in a given 2D # character array. # utility function to search # complete string from any # given index of 2d array def internalSearch(ii, needle, row, col, hay, row_max, col_max): found = 0 if (row >= 0 and row <= row_max and col >=...
quadratic
quadratic
# Python3 program to check if we can # break a into four distinct strings. # Return if the given string can be # split or not. def check(s): # We can always break a of size 10 or # more into four distinct strings. if (len(s) >= 10): return True # Brute Force for i in range(1, len(s)): ...
linear
np
# Python 3 program to split an alphanumeric # string using STL def splitString(str): alpha = "" num = "" special = "" for i in range(len(str)): if (str[i].isdigit()): num = num+ str[i] elif((str[i] >= 'A' and str[i] <= 'Z') or (str[i] >= 'a' and str[i] <= 'z'))...
linear
linear
# Python3 program to split a numeric # string in an Increasing # sequence if possible # Function accepts a string and # checks if string can be split. def split(Str) : Len = len(Str) # if there is only 1 number # in the string then # it is not possible to split it if (Len == 1) : print(...
linear
quadratic
# Python3 Program to find number of way # to split string such that each partition # starts with distinct character with # maximum number of partitions. # Returns the number of we can split # the string def countWays(s): count = [0] * 26; # Finding the frequency of each # character. for x in s: ...
constant
linear
# Python3 program to check if a can be splitted # into two strings such that one is divisible by 'a' # and other is divisible by 'b'. # Finds if it is possible to partition str # into two parts such that first part is # divisible by a and second part is divisible # by b. def findDivision(str, a, b): lenn = len(st...
linear
linear
# Python program to check if a string can be splitted # into two strings such that one is divisible by 'a' # and other is divisible by 'b'. # Finds if it is possible to partition str # into two parts such that first part is # divisible by a and second part is divisible # by b. def findDivision(S, a, b): for i i...
constant
linear
# Python3 code to implement the approach # This code kind of uses sliding window technique. First # checking if string[0] and string[0..n-1] is divisible if # yes then return else run a loop from 1 to n-1 and check if # taking this (0-i)index number and (i+1 to n-1)index number # on our two declared variables if they...
constant
linear
# Python3 program to count ways to divide # a string in two parts a and b such that # b/pow(10, p) == a def calculate( N ): length = len(N) l = int((length) / 2) count = 0 for i in range(l + 1): print(i) # substring representing int a s = N[0: 0 + i] ...
linear
quadratic
# Python program to print n equal parts of string # Function to print n equal parts of string def divideString(string, n): str_size = len(string) # Check if string can be divided in n equal parts if str_size % n != 0: print ("Invalid Input: String size is not divisible by n") return ...
constant
linear
# Python code for the same approach def divide(Str,n): if (len(Str) % n != 0): print("Invalid Input: String size",end="") print(" is not divisible by n") return parts = len(Str) // n start = 0 while (start < len(Str)): print(Str[start: start + parts]) start ...
linear
linear
# Python program to find minimum breaks needed # to break a string in dictionary words. import sys class TrieNode: def __init__(self): self.endOfTree = False self.children = [None for i in range(26)] root = TrieNode() minWordBreak = sys.maxsize # If not present, inserts...
linear
quadratic
class Solution(object): def wordBreak(self, s, wordDict): """ Author : @amitrajitbose :type s: str :type wordDict: List[str] :rtype: bool """ """CREATING THE TRIE CLASS""" class TrieNode(object): def __init__(self): self...
quadratic
quadratic
# A recursive program to print all possible # partitions of a given string into dictionary # words # A utility function to check whether a word # is present in dictionary or not. An array of # strings is used for dictionary. Using array # of strings for dictionary is definitely not # a good idea. We have used for s...
quadratic
np
# Python3 program to # mark balanced and # unbalanced parenthesis. def identifyParenthesis(a): st = [] # run the loop upto # end of the string for i in range (len(a)): # if a[i] is opening # bracket then push # into stack if (a[i] == '('): st.append(a[i]) ...
linear
linear
# Python 3 code to calculate the minimum cost # to make the given parentheses balanced def costToBalance(s): if (len(s) == 0): print(0) # To store absolute count of # balanced and unbalanced parenthesis ans = 0 # o(open bracket) stores count of '(' and # c(close bracket) stores count...
linear
linear
# Python 3 code to check balanced # parentheses with O(1) space. # Function1 to match closing bracket def matchClosing(X, start, end, open, close): c = 1 i = start + 1 while (i <= end): if (X[i] == open): c += 1 elif (X[i] == close): c -= 1 ...
constant
cubic
# Python3 program to check for # balanced brackets. # function to check if # brackets are balanced def areBracketsBalanced(expr): stack = [] # Traversing the Expression for char in expr: if char in ["(", "{", "["]: # Push the element in the stack stack.append(char) ...
linear
linear
# Python3 program to find length of # the longest balanced subsequence def maxLength(s, n): dp = [[0 for i in range(n)] for i in range(n)] # Considering all balanced # substrings of length 2 for i in range(n - 1): if (s[i] == '(' and s[i + 1] == ')'): ...
quadratic
quadratic
# Python3 program to find length of # the longest balanced subsequence def maxLength(s, n): # As it's subsequence - assuming first # open brace would map to a first close # brace which occurs after the open brace # to make subsequence balanced and second # open brace would map to sec...
constant
linear
# Python3 program to determine whether # given expression is balanced/ parenthesis # expression or not. # Function to check if two brackets are # matching or not. def isMatching(a, b): if ((a == '{' and b == '}') or (a == '[' and b == ']') or (a == '(' and b == ')') or a == 'X'): ...
linear
np
# Python3 program to evaluate value # of an expression. import math as mt def evaluateBoolExpr(s): n = len(s) # Traverse all operands by jumping # a character after every iteration. for i in range(0, n - 2, 2): # If operator next to current # operand is AND.''' if (s[...
linear
linear
# Python code to implement the approach def maxDepth(s): count = 0 st = [] for i in range(len(s)): if (s[i] == '('): st.append(i) # pushing the bracket in the stack elif (s[i] == ')'): if (count < len(st)): count = len(st) # keeping...
constant
linear
# A Python program to find the maximum depth of nested # parenthesis in a given expression # function takes a string and returns the # maximum depth nested parenthesis def maxDepth(S): current_max = 0 max = 0 n = len(S) # Traverse the input string for i in range(n): if S[i] == '(': ...
constant
linear
# Python3 Program to find all combinations of Non- # overlapping substrings formed from given # string # find all combinations of non-overlapping # substrings formed by input string str # index – index of the next character to # be processed # out - output string so far def findCombinations(string, index, ou...
quadratic
quadratic
# Method to find an equal index def findIndex(str): l = len(str) open = [0] * (l + 1) close = [0] * (l + 1) index = -1 open[0] = 0 close[l] = 0 if (str[0]=='('): open[1] = 1 if (str[l - 1] == ')'): close[l - 1] = 1 # Store the number of # opening brack...
linear
linear
# Method to find an equal index def findIndex(str): cnt_close = 0 l = len(str) for i in range(1, l): if(str[i] == ')'): cnt_close = cnt_close + 1 for i in range(1, l): if(cnt_close == i): return i # If no opening brackets return l # Driver Code str =...
constant
linear
# Python3 program to check if two expressions # evaluate to same. MAX_CHAR = 26; # Return local sign of the operand. For example, # in the expr a-b-(c), local signs of the operands # are +a, -b, +c def adjSign(s, i): if (i == 0): return True; if (s[i - 1] == '-'): return False; return True; # Evaluate...
linear
linear
# Python3 Program to check whether valid # expression is redundant or not # Function to check redundant brackets # in a balanced expression def checkRedundancy(Str): # create a stack of characters st = [] # Iterate through the given expression for ch in Str: # if current character is...
linear
linear
# Python3 program to find sum of given # array of string type in integer form # Function to find the sum of given array def calculateSum(arr, n): # if string is empty if (n == 0): return 0 s = arr[0] # stoi function to convert # string into integer value = int(s) sum = value ...
constant
linear
# Python3 implementation to print the bracket number # function to print the bracket number def printBracketNumber(exp, n): # used to print the bracket number # for the left bracket left_bnum = 1 # used to obtain the bracket number # for the right bracket right_bnum = list() # traver...
linear
linear
# Python program to find index of closing # bracket for a given opening bracket. from collections import deque def getIndex(s, i): # If input is invalid. if s[i] != '[': return -1 # Create a deque to use it as a stack. d = deque() # Traverse through all elements # starting fr...
linear
linear
# Python3 program to construct string from binary tree # A binary tree node has data, pointer to left # child and a pointer to right child class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to construct string from binary tree def treeToS...
linear
linear
# Python3 program to conStruct a # binary tree from the given String # Helper class that allocates a new node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # This function is here just to test def preOrder(node): if (node == None): re...
linear
quadratic
class newNode: def __init__(self, data): self.data = data self.left = self.right = None def preOrder(node): if (node == None): return print(node.data, end=" ") preOrder(node.left) preOrder(node.right) def treeFromStringHelper(si, ei, arr, root): if si[0] >= ei: ...
linear
quadratic
# Simple Python3 program to convert # all substrings from decimal to given base. import math def substringConversions(s, k, b): l = len(s); for i in range(l): if((i + k) < l + 1): # Saving substring in sub sub = s[i : i + k]; ...
linear
quadratic
# Simple Python3 program to convert all # substrings from decimal to given base. import math as mt def substringConversions(str1, k, b): for i in range(0, len(str1) - k + 1): # Saving substring in sub sub = str1[i:k + i] # Evaluating decimal for current # substrin...
linear
linear
# Python3 program to demonstrate above steps # of binary fractional to decimal conversion # Function to convert binary fractional # to decimal def binaryToDecimal(binary, length) : # Fetch the radix point point = binary.find('.') # Update point if not found if (point == -1) : point = ...
linear
linear
# Python3 program to convert fractional # decimal to binary number # Function to convert decimal to binary # upto k-precision after decimal point def decimalToBinary(num, k_prec) : binary = "" # Fetch the integral part of # decimal number Integral = int(num) # Fetch the fractional part #...
linear
linear
# Python3 implementation to convert # a sentence into its equivalent # mobile numeric keypad sequence # Function which computes the # sequence def printSequence(arr, input): # length of input string n = len(input) output = "" for i in range(n): # checking for space if(input[i...
linear
linear
# Python Program for above implementation # Function to check is it possible to convert # first string into another string or not. def isItPossible(str1, str2, m, n): # To Check Length of Both String is Equal or Not if (m != n): return False # To Check Frequency of A's and B's are # equal ...
linear
quadratic
# Python 3 Program to convert str1 to # str2 in exactly k operations # Returns true if it is possible to convert # str1 to str2 using k operations. def isConvertible(str1, str2, k): # Case A (i) if ((len(str1) + len(str2)) < k): return True # finding common length of both string common...
constant
linear
# Python3 program to convert # decimal number to roman numerals ls=[1000,900,500,400,100,90,50,40,10,9,5,4,1] dict={1:"I",4:"IV",5:"V",9:"IX",10:"X",40:"XL",50:"L",90:"XC",100:"C",400:"CD",500:"D",900:"CM",1000:"M"} ls2=[] # Function to convert decimal to Roman Numerals def func(no,res): for i in range(0,len(ls...
constant
linear
# Python3 program for above approach # Function to calculate roman equivalent def intToRoman(num): # Storing roman values of digits from 0-9 # when placed at different places m = ["", "M", "MM", "MMM"] c = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM "] x = ["", "X", "...
constant
linear
# Python 3 program to convert Decimal # number to Roman numbers. import math def integerToRoman(A): romansDict = \ { 1: "I", 5: "V", 10: "X", 50: "L", 100: "C", 500: "D", 1000: "M", 5000: "G", 10000...
constant
linear
# Python program to convert Roman Numerals # to Numbers # This function returns value of each Roman symbol def value(r): if (r == 'I'): return 1 if (r == 'V'): return 5 if (r == 'X'): return 10 if (r == 'L'): return 50 if (r == 'C'): return 100 if (r...
constant
linear
# Program to convert Roman # Numerals to Numbers roman = {} roman['I'] = 1 roman['V'] = 5 roman['X'] = 10 roman['L'] = 50 roman['C'] = 100 roman['D'] = 500 roman['M'] = 1000 # This function returns value # of a Roman symbol def romanToInt(s): sum = 0 n = len(s) i = 0 while i < n : # If prese...
constant
constant
def romanToInt(s): translations = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } number = 0 s = s.replace("IV", "IIII").replace("IX", "VIIII") s = s.replace("XL", "XXXX").repl...
constant
constant
# Python3 program to check if a string can # be converted to another string by # performing operations # function to check if a string can be # converted to another string by # performing following operations def check(s1,s2): # calculates length n = len(s1) m = len(s2) dp=([[False for i in ra...
quadratic
quadratic
# Python code to # transform string # def to change # character's case def change_case(s) : a = list(s) l = len(s) for i in range(0, l) : # If character is # lowercase change # to uppercase if(a[i] >= 'a' and a[i] <= 'z') : a[i] = s[...
linear
linear
# Python implementation of above approach # A utility function to reverse string str[low..high] def Reverse(string: list, low: int, high: int): while low < high: string[low], string[high] = string[high], string[low] low += 1 high -= 1 # Cycle leader algorithm to move all even # positione...
constant
quadratic
# Python3 program to count the distinct # transformation of one string to other. def countTransformation(a, b): n = len(a) m = len(b) # If b = "" i.e., an empty string. There # is only one way to transform (remove all # characters) if m == 0: return 1 dp = [[0] * (n) for _ in r...
quadratic
quadratic
# Class to define a node # structure of the tree class Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function to convert ternary # expression to a Binary tree # It returns the root node # of the tree def convert_expression(expression, i): if i ...
linear
linear
# Python Program to convert prefix to Infix def prefixToInfix(prefix): stack = [] # read prefix in reverse order i = len(prefix) - 1 while i >= 0: if not isOperator(prefix[i]): # symbol is operand stack.append(prefix[i]) i -= 1 else...
linear
linear
# Write Python3 code here # -*- coding: utf-8 -*- # Example Input s = "*-A/BC-/AKL" # Stack for storing operands stack = [] operators = set(['+', '-', '*', '/', '^']) # Reversing the order s = s[::-1] # iterating through individual tokens for i in s: # if token is operator if i in operators: ...
linear
linear
# Python3 Program to convert postfix to prefix # function to check if # character is operator or not def isOperator(x): if x == "+": return True if x == "-": return True if x == "/": return True if x == "*": return True return False # Convert postfix...
linear
linear
# Python3 program to find infix for # a given postfix. def isOperand(x): return ((x >= 'a' and x <= 'z') or (x >= 'A' and x <= 'Z')) # Get Infix for a given postfix # expression def getInfix(exp) : s = [] for i in exp: # Push operands if (isOperand(i)) : ...
linear
linear
# Python 3 program for space optimized # solution of Word Wrap problem. import sys # Function to find space optimized # solution of Word Wrap problem. def solveWordWrap(arr, n, k): dp = [0] * n # Array in which ans[i] store index # of last word in line starting with # word arr[i]. ans = [0] * ...
linear
quadratic
# Python 3 program to print shortest possible # path to type all characters of given string # using a remote # Function to print shortest possible path # to type all characters of given string # using a remote def printPath(str): i = 0 # start from character 'A' present # at position (0, 0) curX...
constant
quadratic
# Python program to check whether second string # can be formed from first string def canMakeStr2(s1, s2): # Create a count array and count # frequencies characters in s1 count = {s1[i] : 0 for i in range(len(s1))} for i in range(len(s1)): count[s1[i]] += 1 # Now traverse throu...
constant
linear
# python code to find the reverse # alphabetical order from a given # position # Function which take the given string and the # position from which the reversing shall be # done and returns the modified string def compute(st, n): # Creating a string having reversed # alphabetical order reverseAlphab...
constant
linear
# A Python program to find last # index of character x in given # string. # Returns last index of x if it # is present. Else returns -1. def findLastIndex(str, x): index = -1 for i in range(0, len(str)): if str[i] == x: index = i return index # Driver program # String in which char...
constant
linear
# Simple Python3 program to find last # index of character x in given string. # Returns last index of x if it is # present. Else returns -1. def findLastIndex(str, x): # Traverse from right for i in range(len(str) - 1, -1,-1): if (str[i] == x): return i return -1 # Driver code st...
constant
linear
# python program to find position # of a number in a series of # numbers with 4 and 7 as the # only digits. def findpos(n): i = 0 j = len(n) pos = 0 while (i<j): # check all digit position # if number is left then # pos*2+1 if(n[i] == '4'): pos = pos...
constant
linear
# Python3 program to find winner in an election. from collections import defaultdict ''' We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. ''' def findWinner(votes): # Insert all vo...
linear
linear
# Python 3 program to check if a query # string is present is given set. MAX_CHAR = 256 def isPresent(s, q): # Count occurrences of all characters # in s. freq = [0] * MAX_CHAR for i in range(0 , len(s)): freq[ord(s[i])] += 1 # Check if number of occurrences of # every character i...
constant
linear
# Python program to find # the arrangement of # queue at time = t # prints the arrangement # at time = t def solve(n, t, p) : s = list(p) # Checking the entire # queue for every # moment from time = 1 # to time = t. for i in range(0, t) : for j in range(0, n - 1) : ...
constant
quadratic
# Python3 code to check whether the # given EMEI number is valid or not # Function for finding and returning # sum of digits of a number def sumDig( n ): a = 0 while n > 0: a = a + n % 10 n = int(n / 10) return a # Returns True if n is valid EMEI def isValidEMEI(n): # Converting ...
linear
nlogn
# Python3 program to decode a median # string to the original string # function to calculate the median # back string def decodeMedianString(s): # length of string l = len(s) # initialize a blank string s1 = "" # Flag to check if length is # even or odd if(l % 2 == 0): is...
constant
linear
# Python program to decode a string recursively # encoded as count followed substring # Returns decoded string for 'str' def decode(Str): integerstack = [] stringstack = [] temp = "" result = "" i = 0 # Traversing the string while i < len(Str): count = 0 # If number, conv...
linear
linear
def decodeString(s): st = [] for i in range(len(s)): # When ']' is encountered, we need to start decoding if s[i] == ']': temp = "" while len(st) > 0 and st[-1] != '[': # st.top() + temp makes sure that the # string ...
linear
linear
# Python 3 program to make a number magical # function to calculate the minimal changes def calculate( s): # maximum digits that can be changed ans = 6 # nested loops to generate all 6 # digit numbers for i in range(10): for j in range(10): for k in range(10): ...
constant
np
# Python code to check if a # given ISBN is valid or not. def isValidISBN(isbn): # check for length if len(isbn) != 10: return False # Computing weighted sum # of first 9 digits _sum = 0 for i in range(9): if 0 <= int(isbn[i]) <= 9: _sum += int(isbn[i]) * (1...
constant
constant
class CreditCard: # Main Method @staticmethod def main(args): number = 5196081888500645 print(str(number) + " is " + ("valid" if CreditCard.isValid(number) else "invalid")) # Return true if the card number is valid @staticmethod def isValid(number): ...
constant
linear
# Python3 program to implement the approach # Python3 has no built-in swap function. def swap(str, i, j): ch = list(str) temp = ch[i] ch[i] = ch[j] ch[j] = temp return "".join(ch) # Since STRINGS are immutable in JavaScript, first we have # to convert it to a character array in order to sort. de...
linear
cubic
# Python program to find # if a given corner string # is present at corners. def isCornerPresent(str, corner) : n = len(str) cl = len(corner) # If length of corner # string is more, it # cannot be present # at corners. if (n < cl) : return False # Return true if corner ...
constant
linear