Banana-Leopard/TASTY huggingface dataset:
# Python3 program to find difficulty
# of a sentence
 
# Utility function to check character
# is vowel or not
def isVowel(ch):
    return (ch == 'a' or ch == 'e' or
            ch == 'i' or ch == 'o' or
            ch == 'u')
 
# Function to calculate difficulty
def calcDiff(str):
    str = str.lower()
    count_vowels = 0
    count_conso = 0
    consec_conso = 0
    hard_words = 0
    easy_words = 0
 
    # Start traversing the string
    for i in range(0, len(str)):
         
        # Check if current character is
        # vowel or consonant
        if(str[i]!= " " and isVowel(str[i])):
             
            # Increment if vowel
            count_vowels += 1
            consec_conso = 0
             
        # Increment counter for consonant
        # also maintain a separate counter for
        # counting consecutive consonants
        elif(str[i] != " "):
            count_conso += 1
            consec_conso += 1
 
        # If we get 4 consecutive consonants
        # then it is a hard word
        if(consec_conso == 4):
            hrad_words += 1
 
            # Move to the next word
            while(i < len(str) and str[i] != " "):
                i += 1
                 
            # Reset all counts
            count_conso = 0
            count_vowels = 0
            consec_conso = 0
        elif(i < len(str) and (str[i] == ' ' or
                          i == len(str) - 1)):
                               
            # Increment hard_words, if no. of
            # consonants are higher than no. of
            # vowels, otherwise increment count_vowels
            if(count_conso > count_vowels):
                hard_words += 1
            else:
                easy_words += 1
 
            # Reset all counts
            count_conso = 0
            count_vowels = 0
            consec_conso = 0
             
    # Return difficulty of sentence    
    return (5 * hard_words + 3 * easy_words)
     
# Driver Code
if __name__=="__main__":
    str = "I am a geek"
    str2 = "We are geeks"
    print(calcDiff(str))
    print(calcDiff(str2))
 
# This code is contributed
# by Sairahul Jella

Time complexity: linear
Space complexity: constant
# Python 3 program to count the uppercase,
# lowercase, special characters
# and numeric values
 
# Function to count uppercase, lowercase,
# special characters and numbers
def Count(str):
    upper, lower, number, special = 0, 0, 0, 0
    for i in range(len(str)):
        if str[i].isupper():
            upper += 1
        else if str[i].islower():
            lower += 1
        else if str[i].isdigit():
            number += 1
        else:
            special += 1
    print('Upper case letters:', upper)
    print('Lower case letters:', lower)
    print('Number:', number)
    print('Special characters:', special)
 
# Driver Code
str = "#GeeKs01fOr@gEEks07"
Count(str)
 
# This code is contributed
# by Sushma Reddy

Time complexity: linear
Space complexity: constant
# Python3 program to find the smallest window
# containing all characters of a pattern.
no_of_chars = 256
 
# Function to find smallest window
# containing all characters of 'pat'
def findSubString(string, pat):
 
    len1 = len(string)
    len2 = len(pat)
 
    # Check if string's length is
    # less than pattern's
    # length. If yes then no such
    # window can exist
    if len1 < len2:
 
        print("No such window exists")
        return ""
 
    hash_pat = [0] * no_of_chars
    hash_str = [0] * no_of_chars
 
    # Store occurrence ofs characters of pattern
    for i in range(0, len2):
        hash_pat[ord(pat[i])] += 1
 
    start, start_index, min_len = 0, -1, float('inf')
 
    # Start traversing the string
    count = 0  # count of characters
    for j in range(0, len1):
 
        # count occurrence of characters of string
        hash_str[ord(string[j])] += 1
 
        # If string's char matches with
        # pattern's char then increment count
        if (hash_str[ord(string[j])] <=
                hash_pat[ord(string[j])]):
            count += 1
 
        # if all the characters are matched
        if count == len2:
 
            # Try to minimize the window
            while (hash_str[ord(string[start])] >
                   hash_pat[ord(string[start])] or
                   hash_pat[ord(string[start])] == 0):
 
                if (hash_str[ord(string[start])] >
                        hash_pat[ord(string[start])]):
                    hash_str[ord(string[start])] -= 1
                start += 1
 
            # update window size
            len_window = j - start + 1
            if min_len > len_window:
 
                min_len = len_window
                start_index = start
 
    # If no window found
    if start_index == -1:
        print("No such window exists")
        return ""
 
    # Return substring starting from
    # start_index and length min_len
    return string[start_index: start_index + min_len]
 
 
# Driver code
if __name__ == "__main__":
 
    string = "this is a test string"
    pat = "tist"
 
    print(findSubString(string, pat))
 
# This code is contributed by Rituraj Jain

Time complexity: linear
Space complexity: constant
''' Python solution '''
 
 
def smallestWindow(s, p):
    n = len(s)
    if n < len(p):
        return -1
    mp = [0]*256
 
    # Starting index of ans
    start = 0
 
    # Answer
    # Length of ans
    ans = n + 1
    cnt = 0
 
    # creating map
    for i in p:
        mp[ord(i)] += 1
        if mp[ord(i)] == 1:
            cnt += 1
 
     # References of Window
    j = 0
    i = 0
 
    # Traversing the window
    while(j < n):
 
      # Calculating
        mp[ord(s[j])] -= 1
        if mp[ord(s[j])] == 0:
            cnt -= 1
 
            # Condition matching
            while cnt == 0:
                if ans > j - i + 1:
 
                  # calculating answer.
                    ans = j - i + 1
                    start = i
 
                 # Sliding I
                # Calculation for removing I
                mp[ord(s[i])] += 1
                if mp[ord(s[i])] > 0:
                    cnt += 1
                i += 1
        j += 1
    if ans > n:
        return "-1"
    return s[start:start+ans]
 
 
# Driver code
if __name__ == "__main__":
    s = "this is a test string"
    p = "tist"
    result = smallestWindow(s, p)
    print(result)
 
    # This code is contributed by cyclades.

Time complexity: linear
Space complexity: constant
# Python3 program to count number of substrings
# with counts of distinct characters as k.
 
MAX_CHAR = 26
 
# Returns true if all values
# in freq[] are either 0 or k.
def check(freq, k):
    for i in range(0, MAX_CHAR):
        if(freq[i] and freq[i] != k):
            return False
    return True
 
# Returns count of substrings where
# frequency of every present character is k
def substrings(s, k):
    res = 0 # Initialize result
 
    # Pick a starting point
    for i in range(0, len(s)):
 
        # Initialize all frequencies as 0
        # for this starting point
        freq = [0] * MAX_CHAR
 
        # One by one pick ending points
        for j in range(i, len(s)):
             
            # Increment frequency of current char
            index = ord(s[j]) - ord('a')
            freq[index] += 1
 
            # If frequency becomes more than
            # k, we can't have more substrings
            # starting with i
            if(freq[index] > k):
                break
             
            # If frequency becomes k, then check
            # other frequencies as well
            elif(freq[index] == k and
                 check(freq, k) == True):
                res += 1
             
    return res
 
# Driver Code
if __name__ == "__main__":
    s = "aabbcc"
    k = 2
    print(substrings(s, k))
 
    s = "aabbc";
    k = 2;
    print(substrings(s, k))
 
# This code is contributed
# by Sairahul Jella

Time complexity: quadratic
Space complexity: constant
from collections import defaultdict
 
 
def have_same_frequency(freq: defaultdict, k: int):
    return all([freq[i] == k or freq[i] == 0 for i in freq])
 
 
def count_substrings(s: str, k: int) -> int:
    count = 0
    distinct = len(set([i for i in s]))
    for length in range(1, distinct + 1):
        window_length = length * k
        freq = defaultdict(int)
        window_start = 0
        window_end = window_start + window_length - 1
        for i in range(window_start, min(window_end + 1, len(s))):
            freq[s[i]] += 1
        while window_end < len(s):
            if have_same_frequency(freq, k):
                count += 1
            freq[s[window_start]] -= 1
            window_start += 1
            window_end += 1
            if window_end < len(s):
                freq[s[window_end]] += 1
    return count
 
 
if __name__ == '__main__':
    s = "aabbcc"
    k = 2
    print(count_substrings(s, k))
    s = "aabbc"
    k = 2
    print(count_substrings(s, k))

Time complexity: quadratic
Space complexity: linear
# Python 3 program to construct a n
# length string with k distinct characters
# such that no two same characters are adjacent.
 
# Function to find a string of length
# n with k distinct characters.
def findString(n, k):
 
    # Initialize result with first k
    # Latin letters
    res = ""
    for i in range(k):
        res = res + chr(ord('a') + i)
 
    # Fill remaining n-k letters by
    # repeating k letters again and again.
    count = 0
    for i in range(n - k) :
        res = res + chr(ord('a') + count)
        count += 1
        if (count == k):
            count = 0;
     
    return res
 
# Driver code
if __name__ == "__main__":
     
    n = 5
    k = 2
    print(findString(n, k))
 
# This code is contributed by ita_c

Time complexity: linear
Space complexity: linear
# Python3 program to count number
# of substrings of a string
 
def countNonEmptySubstr(str):
    n = len(str);
    return int(n * (n + 1) / 2);
 
# driver code
s = "abcde";
print (countNonEmptySubstr(s));
 
# This code is contributed by
# Manish Shaw (manishshaw1)

Time complexity: constant
Space complexity: constant
# Python3 program to count distinct strings with
# even odd swapping allowed.
MAX_CHAR = 26
 
# Returns encoding of string that can be used
# for hashing. The idea is to return same encoding
# for strings which can become same after swapping
# a even positioned character with other even characters
# OR swapping an odd character with other odd characters.
def encodeString(string):
 
    # hashEven stores the count of even indexed character
    # for each string hashOdd stores the count of odd
    # indexed characters for each string
    hashEven = [0] * MAX_CHAR
    hashOdd = [0] * MAX_CHAR
 
    # creating hash for each string
    for i in range(len(string)):
        c = string[i]
        if i & 1: # If index of current character is odd
            hashOdd[ord(c) - ord('a')] += 1
        else:
            hashEven[ord(c) - ord('a')] += 1
 
    # For every character from 'a' to 'z', we store its
    # count at even position followed by a separator,
    # followed by count at odd position.
    encoding = ""
    for i in range(MAX_CHAR):
        encoding += str(hashEven[i])
        encoding += str('-')
        encoding += str(hashOdd[i])
        encoding += str('-')
 
    return encoding
 
# This function basically uses a hashing based set to
# store strings which are distinct according
# to criteria given in question.
def countDistinct(input, n):
    countDist = 0 # Initialize result
 
    # Create an empty set and store all distinct
    # strings in it.
    s = set()
    for i in range(n):
 
        # If this encoding appears first time, increment
        # count of distinct encodings.
        if encodeString(input[i]) not in s:
            s.add(encodeString(input[i]))
            countDist += 1
 
    return countDist
 
# Driver Code
if __name__ == "__main__":
    input = ["abcd", "acbd", "adcb",
             "cdba", "bcda", "badc"]
    n = len(input)
    print(countDistinct(input, n))
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: constant
# Python 3 program to find K'th character 
# in decrypted string
  
# Function to find K'th character 
# in Encoded String
def encodedChar(str, k):
      
    # expand string variable is used 
    # to store final string after 
    # decompressing string str
    expand = ""
  
    # Current substring
    freq = 0 # Count of current substring
    i = 0
    while(i < len(str)):
        temp = "" # Current substring
        freq = 0 # count frequency of current substring
  
        # read characters until you find 
        # a number or end of string
        while (i < len(str) and
               ord(str[i]) >= ord('a') and 
               ord(str[i]) <= ord('z')):
                     
            # push character in temp
            temp += str[i]
            i += 1
  
        # read number for how many times string temp
        # will be repeated in decompressed string
        while (i < len(str) and 
               ord(str[i]) >= ord('1') and
               ord(str[i]) <= ord('9')):
                     
            # generating frequency of temp
            freq = freq * 10 + ord(str[i]) - ord('0')
            i += 1
  
        # now append string temp into expand
        # equal to its frequency
        for j in range(1, freq + 1, 1):
            expand += temp
  
    # this condition is to handle the case
    # when string str is ended with alphabets
    # not with numeric value
    if (freq == 0):
        expand += temp
  
    return expand[k - 1]
  
# Driver Code
if __name__ == '__main__':
    str = "ab4c12ed3"
    k = 21
    print(encodedChar(str, k))
  
# This code is contributed by
# Shashank_Sharma

Time complexity: linear
Space complexity: constant
# Python program to find number of
# characters at same position as
# in English alphabets
 
# Function to count the number of
# characters at same position as
# in English alphabets
def findCount(str):
    result = 0
 
    # Traverse the input string
    for i in range(len(str)):
 
        # Check that index of characters of string is
        # same as of English alphabets by using ASCII
        # values and the fact that all lower case
        # alphabetic characters come together in same
        # order in ASCII table. And same is true for
        # upper case.
        if ((i == ord(str[i]) - ord('a')) or
            (i == ord(str[i]) - ord('A'))):
            result += 1
    return result
 
# Driver Code
str = 'AbgdeF'
print(findCount(str))
 
# This code is contributed
# by SamyuktaSHegde

Time complexity: linear
Space complexity: constant
# Python 3 program to count words  whose ith letter
# is either (i-1)th, ith, or (i+1)th letter
# of given word.
   
# Return the count of words.
def countWords( str,  l):
  
    count = 1;
   
    # If word contain single letter, return 1.
    if (l == 1):
        return count
   
    # Checking for first letter.
    if (str[0] == str[1]):
        count *= 1
    else:
        count *= 2
   
    # Traversing the string and multiplying
    # for combinations.
    for j in range(1,l-1):
        # If all three letters are same.
        if (str[j] == str[j-1] and str[j] == str[j+1]):
            count *= 1
   
        # If two letter are distinct.
        else if (str[j] == str[j-1] or
                 str[j] == str[j+1] or
                 str[j-1] == str[j+1]):
            count *= 2
   
        # If all three letter are distinct.
        else:
            count *= 3
   
    # Checking for last letter.
    if (str[l - 1] == str[l - 2]):
        count *= 1
    else:
        count *= 2
   
    return count
   
# Driven Program
if __name__ == "__main__":
      
    str = "abc"
    l = len(str)
   
    print(countWords(str, l))

Time complexity: linear
Space complexity: constant
# Python3 program to find Smallest and
# Largest Word in a String
 
# defining the method to find the longest
# word and the shortest word
def minMaxLengthWords(inp):
    length = len(inp)
    si = ei = 0
    min_length = length
    min_start_index = max_length = max_start_index = 0
     
    # loop to find the length and stating index
    # of both longest and shortest words
    while ei <= length:
        if (ei < length) and (inp[ei] != " "):
            ei += 1
        else:
            curr_length = ei - si
             
            # condition checking for the shortest word
            if curr_length < min_length:
                min_length = curr_length
                min_start_index = si
                 
            # condition for the longest word
            if curr_length > max_length:
                max_length = curr_length
                max_start_index = si
            ei += 1
            si = ei
             
    # extracting the shortest word using
    # it's starting index and length    
    minWord = inp[min_start_index :
                  min_start_index + min_length]
     
    # extracting the longest word using
    # it's starting index and length    
    maxWord = inp[max_start_index : max_length]
     
    # printing the final result
    print("Minimum length word: ", minWord)
    print ("Maximum length word: ", maxWord)
     
# Driver Code
 
# Using this string to test our code
a = "GeeksforGeeks A Computer Science portal for Geeks"
minMaxLengthWords(a)
 
# This code is contributed by Animesh_Gupta

Time complexity: linear
Space complexity: linear
# Python program to count all substrings with same
# first and last characters.
 
# Returns true if first and last characters
# of s are same.
def checkEquality(s):
    return (ord(s[0]) == ord(s[len(s) - 1]));
 
def countSubstringWithEqualEnds(s):
    result = 0;
    n = len(s);
 
    # Starting point of substring
    for i in range(n):
 
    # Length of substring
        for j in range(1,n-i+1):
 
        # Check if current substring has same
        # starting and ending characters.
            if (checkEquality(s[i:i+j])):
                result+=1;
 
    return result;
 
# Driver code
s = "abcab";
print(countSubstringWithEqualEnds(s));
 
# This code contributed by PrinciRaj1992

Time complexity: quadratic
Space complexity: linear
# Space efficient Python3 program to count all
# substrings with same first and last characters.
def countSubstringWithEqualEnds(s):
 
    result = 0;
    n = len(s);
 
    # Iterating through all substrings in
    # way so that we can find first and
    # last character easily
    for i in range(n):
        for j in range(i, n):
            if (s[i] == s[j]):
                result = result + 1
 
    return result
 
# Driver Code
s = "abcab";
print(countSubstringWithEqualEnds(s))
 
# This code is contributed
# by Akanksha Rai

Time complexity: quadratic
Space complexity: constant
# Most efficient Python program to count all
# substrings with same first and last characters.
 
MAX_CHAR = 26; # assuming lower case only
 
def countSubstringWithEqualEnds(s):
    result = 0;
    n = len(s);
 
    # Calculating frequency of each character
    # in the string.
    count = [0]*MAX_CHAR;
    for i in range(n):
        count[ord(s[i])-ord('a')]+=1;
 
    # Computing result using counts
    for i in range(MAX_CHAR):
        result += (count[i]*(count[i]+1)/2);
 
    return result;
 
# Driver code
s = "abcab";
print(countSubstringWithEqualEnds(s));
 
 
# This code is contributed by 29AjayKumar

Time complexity: linear
Space complexity: constant
# Python 3 program to count substrings with same
# first and last characters
 
# Function to count substrings with same first and
# last characters
def countSubstrs(str, i, j, n):
 
    # base cases
    if (n == 1):
        return 1
    if (n <= 0):
        return 0
 
    res = (countSubstrs(str, i + 1, j, n - 1)
        + countSubstrs(str, i, j - 1, n - 1)
        - countSubstrs(str, i + 1, j - 1, n - 2))    
 
    if (str[i] == str[j]):
        res += 1
 
    return res
 
# driver code
str = "abcab"
n = len(str)
print(countSubstrs(str, 0, n - 1, n))
 
# This code is contributed by Smitha

Time complexity: np
Space complexity: linear
# code
def countSubstr(s):
    if len(s) == 0:
        return 0
    charMap, numSubstr = countSubstrHelper(s, 0, len(s)-1)
    return numSubstr
 
 
def countSubstrHelper(string, start, end):
    if start >= end:  # our base case for the recursion. When we have one character
        return {string[start]: 1}, 1
    mid = (start + end)//2
    mapLeft, numSubstrLeft = countSubstrHelper(
        string, start, mid)  # solve the left half
    mapRight, numSubstrRight = countSubstrHelper(
        string, mid+1, end)  # solve the right half
    # add number of substrings from left and right
    numSubstrSelf = numSubstrLeft + numSubstrRight
 
    # multiply the characters from left set with matching characters from right set
    # then add to total number of substrings
    for char in mapLeft:
        if char in mapRight:
            numSubstrSelf += mapLeft[char] * mapRight[char]
 
    # Add all the key,value pairs from right map to left map
    for char in mapRight:
        if char in mapLeft:
            mapLeft[char] += mapRight[char]
        else:
            mapLeft[char] = mapRight[char]
    # Return the map of character and the sum of substring from left, right and self
    return mapLeft, numSubstrSelf
 
 
print(countSubstr("abcab"))
 
# Contributed by Xavier Jean Baptiste

Time complexity: nlogn
Space complexity: linear
# Python 3 program to count number of
# possible strings with n characters.
 
# Function to calculate number of strings
def possibleStrings(n, r, b, g):
     
    # Store factorial of numbers up to n
    # for further computation
    fact = [0 for i in range(n + 1)]
    fact[0] = 1
    for i in range(1, n + 1, 1):
        fact[i] = fact[i - 1] * i
 
    # Find the remaining values to be added
    left = n - (r + g + b)
    sum = 0
 
    # Make all possible combinations of
    # R, B and G for the remaining value
    for i in range(0, left + 1, 1):
        for j in range(0, left - i + 1, 1):
            k = left - (i + j)
 
            # Compute permutation of each
            # combination one by one and add them.
            sum = (sum + fact[n] / (fact[i + r] *
                         fact[j + b] * fact[k + g]))
     
    # Return total no. of
    # strings/permutation
    return sum
 
# Driver code
if __name__ == '__main__':
    n = 4
    r = 2
    b = 0
    g = 1
    print(int(possibleStrings(n, r, b, g)))
     
# This code is contributed by
# Sanjit_Prasad

Time complexity: quadratic
Space complexity: linear
# Python 3 program to count number of strings
# of n characters with
 
# n is total number of characters.
# bCount and cCount are counts of 'b'
# and 'c' respectively.
def countStrUtil(dp, n, bCount=1,cCount=2):
 
    # Base cases
    if (bCount < 0 or cCount < 0):
        return 0
    if (n == 0):
        return 1
    if (bCount == 0 and cCount == 0):
        return 1
 
    # if we had saw this combination previously
    if (dp[n][bCount][cCount] != -1):
        return dp[n][bCount][cCount]
 
    # Three cases, we choose, a or b or c
    # In all three cases n decreases by 1.
    res = countStrUtil(dp, n-1, bCount, cCount)
    res += countStrUtil(dp, n-1, bCount-1, cCount)
    res += countStrUtil(dp, n-1, bCount, cCount-1)
 
    dp[n][bCount][cCount] = res
    return dp[n][bCount][cCount]
 
# A wrapper over countStrUtil()
def countStr(n):
 
    dp = [ [ [-1 for x in range(2+1)] for y in range(1+1)]for z in range(n+1)]
    return countStrUtil(dp, n)
 
# Driver code
if __name__ == "__main__":
     
    n = 3 # Total number of characters
    print(countStr(n))
     
# This code is contributed by chitranayal   

Time complexity: linear
Space complexity: linear
# A O(1) Python3 program to find
# number of strings that can be
# made under given constraints.
 
def countStr(n):
    return (1 + (n * 2) +
                (n * ((n * n) - 1) // 2))
 
# Driver code
if __name__ == "__main__":
    n = 3
    print(countStr(n))
 
# This code is contributed
# by ChitraNayal

Time complexity: constant
Space complexity: constant