giulio98/xlcost-single-prompt huggingface dataset:
# longest subsequence of the form 0 * 1 * 0 * in a binary string | returns length of the longest subsequence of the form 0 * 1 * 0 * ; precomputing values in three arrays pre_count_0 [ i ] is going to store count of 0 s in prefix str [ 0. . i - 1 ] pre_count_1 [ i ] is going to store count of 1 s in prefix str [ 0. . i - 1 ] post_count_0 [ i ] is going to store count of 0 s in suffix str [ i - 1. . n - 1 ] ; string is made up of all 0 s or all 1 s ; compute result using precomputed values ; 
def longestSubseq(s):
    n = len(s)
    pre_count_0 = [0 for i in range(n + 2)]
    pre_count_1 = [0 for i in range(n + 1)]
    post_count_0 = [0 for i in range(n + 2)]
    pre_count_0[0] = 0
    post_count_0[n + 1] = 0
    pre_count_1[0] = 0
    for j in range(1, n + 1):
        pre_count_0[j] = pre_count_0[j - 1]
        pre_count_1[j] = pre_count_1[j - 1]
        post_count_0[n - j + 1] = post_count_0[n - j + 2]
        if (s[j - 1] == '0'):
            pre_count_0[j] += 1
        else:
            pre_count_1[j] += 1
        if (s[n - j] == '0'):
            post_count_0[n - j + 1] += 1
    if (pre_count_0[n] == n or pre_count_0[n] == 0):
        return n
    ans = 0
    for i in range(1, n + 1):
        for j in range(i, n + 1, 1):
            ans = max(pre_count_0[i - 1] + pre_count_1[j] -
                      pre_count_1[i - 1] + post_count_0[j + 1], ans)
    return ans


if __name__ == '__main__':
    s = "000011100000"
    print(longestSubseq(s))

# Expected output:
12
# distinct permutations of the string | set 2 | returns true if str [ curr ] does not matches with any of the characters after str [ start ] ; prints all distinct permutations in str [ 0. . n - 1 ] ; proceed further for str [ i ] only if it doesn 't match with any of  the characters after str[index] ; 
def shouldSwap(string, start, curr):
    for i in range(start, curr):
        if string[i] == string[curr]:
            return 0
    return 1


def findPermutations(string, index, n):
    if index >= n:
        print(''.join(string))
        return
    for i in range(index, n):
        check = shouldSwap(string, index, i)
        if check:
            string[index], string[i] = string[i], string[index]
            findPermutations(string, index + 1, n)
            string[index], string[i] = string[i], string[index]


if __name__ == "__main__":
    string = list("ABCA")
    n = len(string)
    findPermutations(string, 0, n)

# Expected output:
ABCA
ABAC
ACBA
ACAB
AACB
AABC
BACA
BAAC
BCAA
CBAA
CABA
CAAB
# generate permutations with only adjacent swaps allowed | python3 program to generate permutations with only one swap allowed . ; don 't swap the current position ; swap with the next character and revert the changes . as explained above , swapping with previous is is not needed as it anyways happens for next character . ; 
def findPermutations(string, index, n):
    if index >= n or (index + 1) >= n:
        print(''.join(string))
        return
    findPermutations(string, index + 1, n)
    string[index], string[index + 1] = string[index + 1], string[index]
    findPermutations(string, index + 2, n)
    string[index], string[index + 1] = string[index + 1], string[index]


if __name__ == "__main__":
    string = list("12345")
    n = len(string)
    findPermutations(string, 0, n)

# Expected output:
12345
12354
12435
13245
13254
21345
21354
21435
# decode a median string to the original string | function to calculate the median back string ; length of string ; initialize a blank string ; flag to check if length is even or odd ; traverse from first to last ; if len is even then add first character to beginning of new string and second character to end ; if current length is odd and is greater than 1 ; add first character to end and second character to beginning ; if length is 1 , add character to end ; 
def decodeMedianString(s):
    l = len(s)
    s1 = ""
    if (l % 2 == 0):
        isEven = True
    else:
        isEven = False
    for i in range(0, l, 2):
        if (isEven):
            s1 = s[i] + s1
            s1 += s[i + 1]
        else:
            if (l - i > 1):
                s1 += s[i]
                s1 = s[i + 1] + s1
            else:
                s1 += s[i]
    return s1


if __name__ == '__main__':
    s = "eekgs"
    print(decodeMedianString(s))

# Expected output:
geeks
# maximum number of characters between any two same character in a string | simple python3 program to find maximum number of characters between two occurrences of same character ; 
def maximumChars(str):
    n = len(str)
    res = -1
    for i in range(0, n - 1):
        for j in range(i + 1, n):
            if (str[i] == str[j]):
                res = max(res, abs(j - i - 1))
    return res


if __name__ == '__main__':
    str = "abba"
    print(maximumChars(str))

# Expected output:
2
# maximum number of characters between any two same character in a string | efficient python3 program to find maximum number of characters between two occurrences of same character ; initialize all indexes as - 1. ; if this is first occurrence ; else find distance from previous occurrence and update result ( if required ) . ; 

MAX_CHAR = 256


def maximumChars(str1):
    n = len(str1)
    res = -1
    firstInd = [-1 for i in range(MAX_CHAR)]
    for i in range(n):
        first_ind = firstInd[ord(str1[i])]
        if (first_ind == -1):
            firstInd[ord(str1[i])] = i
        else:
            res = max(res, abs(i - first_ind - 1))
    return res


str1 = "abba"
print(maximumChars(str1))

# Expected output:
2
# check if an encoding represents a unique binary string | python 3 program to check if given encoding represents a single string . ; return true if sum becomes k ; 
def isUnique(a, n, k):
    sum = 0
    for i in range(0, n, 1):
        sum += a[i]
    sum += n - 1
    return (sum == k)


if __name__ == '__main__':
    a = [3, 3, 3]
    n = len(a)
    k = 12
    if (isUnique(a, n, k)):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# lexicographically next string | python 3 program to find lexicographically next string ; if string is empty . ; find first character from right which is not z . ; if all characters are ' z ' , append an ' a ' at the end . ; if there are some non - z characters ; 
def nextWord(s):
    if (s == " "):
        return "a"
    i = len(s) - 1
    while (s[i] == 'z' and i >= 0):
        i -= 1
    if (i == -1):
        s = s + 'a'
    else:
        s = s .replace(s[i], chr(ord(s[i]) + 1), 1)
    return s


if __name__ == '__main__':
    str = "samez"
    print(nextWord(str))

# Expected output:
samfz
# length of the longest substring with equal 1 s and 0 s | function to check if a contains equal number of one and zeros or not ; function to find the length of the longest balanced substring ; 
def isValid(p):
    n = len(p)
    c1 = 0
    c0 = 0
    for i in range(n):
        if (p[i] == '0'):
            c0 += 1
        if (p[i] == '1'):
            c1 += 1
    if (c0 == c1):
        return True
    else:
        return False


def longestSub(s):
    max_len = 0
    n = len(s)
    for i in range(n):
        for j in range(i, n):
            if (isValid(s[i:j - i + 1]) and max_len < j - i + 1):
                max_len = j - i + 1
    return max_len


if __name__ == '__main__':
    s = "101001000"
    print(longestSub(s))

# Expected output:
6
# common characters in n strings | python3 program to find all the common characters in n strings ; primary array for common characters we assume all characters are seen before . ; for each strings ; secondary array for common characters initially marked false ; for every character of ith strings ; if character is present in all strings before , mark it . ; copy whole secondary array into primary ; displaying common characters ; 

MAX_CHAR = 26


def commonCharacters(strings, n):
    prim = [True] * MAX_CHAR
    for i in range(n):
        sec = [False] * MAX_CHAR
        for j in range(len(strings[i])):
            if (prim[ord(strings[i][j]) - ord('a')]):
                sec[ord(strings[i][j]) - ord('a')] = True
        for i in range(MAX_CHAR):
            prim[i] = sec[i]
    for i in range(26):
        if (prim[i]):
            print("%c " % (i + ord('a')), end="")


strings = ["geeksforgeeks", "gemkstones", "acknowledges", "aguelikes"]
n = len(strings)
commonCharacters(strings, n)

# Expected output:
e g k s
# number of positions where a letter can be inserted such that a string becomes palindrome | function to check if the string is palindrome ; to know the length of string ; if the given string is a palindrome ( case - i ) ; sub - case - iii ) ; if ( n % 2 == 0 ) : if the length is even ; count = 2 * count + 1 sub - case - i ; count = 2 * count + 2 sub - case - ii ; insertion point ; case - i ; case - ii ; 
def isPalindrome(s, i, j):
    p = j
    for k in range(i, p + 1):
        if (s[k] != s[p]):
            return False
        p -= 1
    return True


def countWays(s):
    n = len(s)
    count = 0
    if (isPalindrome(s, 0, n - 1)):
        for i in range(n // 2, n):
            if (s[i] == s[i + 1]):
                count += 1
            else:
                break
            count += 1
    else:
        for i in range(n // 2):
            if (s[i] != s[n - 1 - i]):
                j = n - 1 - i
                if (isPalindrome(s, i, n - 2 - i)):
                    for k in range(i - 1, -1, -1):
                        if (s[k] != s[j]):
                            break
                        count += 1
                    count += 1
                if (isPalindrome(s, i + 1, n - 1 - i)):
                    for k in range(n - i, n):
                        if (s[k] != s[i]):
                            break
                        count += 1
                    count += 1
                break
    return count


if __name__ == "__main__":
    s = "abca"
    print(countWays(s))

# Expected output:
2
# count of substrings of a binary string containing k ones | method returns total number of substring having k ones ; initialize index having zero sum as 1 ; loop over binary characters of string ; update countofone variable with value of ith character ; if value reaches more than k , then update result ; add frequency of indices , having sum ( current sum - k ) , to the result ; update frequency of one 's count ; 
def countOfSubstringWithKOnes(s, K):
    N = len(s)
    res = 0
    countOfOne = 0
    freq = [0 for i in range(N + 1)]
    freq[0] = 1
    for i in range(0, N, 1):
        countOfOne += ord(s[i]) - ord('0')
        if (countOfOne >= K):
            res += freq[countOfOne - K]
        freq[countOfOne] += 1
    return res


if __name__ == '__main__':
    s = "10010"
    K = 1
    print(countOfSubstringWithKOnes(s, K))

# Expected output:
9
# generate two output strings depending upon occurrence of character in input string . | python3 program to print two strings made of character occurring once and multiple times ; function to print two strings generated from single string one with characters occurring onces other with character occurring multiple of times ; initialize hashtable with zero entry ; perform hashing for input string ; generate string ( str1 ) consisting char occurring once and string ( str2 ) consisting char occurring multiple times ; print both strings ; 

MAX_CHAR = 256


def printDuo(string):
    countChar = [0 for i in range(MAX_CHAR)]
    n = len(string)
    for i in range(n):
        countChar[ord(string[i]) - ord('a')] += 1
    str1 = ""
    str2 = ""
    for i in range(MAX_CHAR):
        if (countChar[i] > 1):
            str2 = str2 + chr(i + ord('a'))
        elif (countChar[i] == 1):
            str1 = str1 + chr(i + ord('a'))
    print("String with characters occurring once:", "", str1)
    print("String with characters occurring", "multiple times:", "", str2)


string = "lovetocode"
printDuo(string)

# Expected output:
String with characters occurring once:  cdltv
String with characters occurring multiple times:  eo
# print n | function to generate n digit numbers ; if number generated ; append 1 at the current number and reduce the remaining places by one ; if more ones than zeros , append 0 to the current number and reduce the remaining places by one ; 
def printRec(number, extraOnes, remainingPlaces):
    if (0 == remainingPlaces):
        print(number, end=" ")
        return
    printRec(number + "1", extraOnes + 1, remainingPlaces - 1)
    if (0 < extraOnes):
        printRec(number + "0", extraOnes - 1, remainingPlaces - 1)


def printNums(n):
    str = ""
    printRec(str, 0, n)


if __name__ == '__main__':
    n = 4
    printNums(n)

# Expected output:
1111 1110 1101 1100 1011 1010
# longest common substring in an array of strings | function to find the stem ( longestcommon substring ) from the string array ; determine size of the array ; take first word from array as reference ; generating all possible substrings of our reference string arr [ 0 ] i . e s ; check if the generated stem is common to all words ; if current substring is present in all strings and its length is greater than current result ; 
def findstem(arr):
    n = len(arr)
    s = arr[0]
    l = len(s)
    res = ""
    for i in range(l):
        for j in range(i + 1, l + 1):
            stem = s[i:j]
            k = 1
            for k in range(1, n):
                if stem not in arr[k]:
                    break
            if (k + 1 == n and len(res) < len(stem)):
                res = stem
    return res


if __name__ == "__main__":
    arr = ["grace", "graceful", "disgraceful", "gracefully"]
    stems = findstem(arr)
    print(stems)

# Expected output:
grace
# make a string from another by deletion and rearrangement of characters | python 3 program to find if it is possible to make a string from characters present in other string . ; returns true if it is possible to make s1 from characters present in s2 . ; count occurrences of all characters present in s2 . . ; for every character , present in s1 , reduce its count if count is more than 0. ; 

MAX_CHAR = 256


def isPossible(s1, s2):
    count = [0] * MAX_CHAR
    for i in range(len(s2)):
        count[ord(s2[i])] += 1
    for i in range(len(s1)):
        if (count[ord(s1[i])] == 0):
            return False
        count[ord(s1[i])] -= 1
    return True


if __name__ == "__main__":
    s1 = "GeeksforGeeks"
    s2 = "rteksfoGrdsskGeggehes"
    if (isPossible(s1, s2)):
        print("Possible")
    else:
        print("Not Possible")

# Expected output:
Possible
# next higher number using atmost one swap operation | function to find the next higher number using atmost one swap operation ; to store the index of the largest digit encountered so far from the right ; to store the index of rightmost digit which has a digit greater to it on its right side ; finding the ' index ' of rightmost digit which has a digit greater to it on its right side ; required digit found , store its ' index ' and break ; if no such digit is found which has a larger digit on its right side ; to store the index of the smallest digit greater than the digit at ' index ' and right to it ; finding the index of the smallest digit greater than the digit at ' index ' and right to it ; swapping the digits ; required number ; 
def nextHighUsingAtMostOneSwap(st):
    num = list(st)
    l = len(num)
    posRMax = l - 1
    index = -1
    i = l - 2
    while i >= 0:
        if (num[i] >= num[posRMax]):
            posRMax = i
        else:
            index = i
            break
        i = i - 1
    if (index == -1):
        return "Not Possible"
    greatSmallDgt = -1
    i = l - 1
    while i > index:
        if (num[i] > num[index]):
            if (greatSmallDgt == -1):
                greatSmallDgt = i
            elif (num[i] <= num[greatSmallDgt]):
                greatSmallDgt = i
        i = i - 1
    temp = num[index]
    num[index] = num[greatSmallDgt]
    num[greatSmallDgt] = temp
    return ''.join(num)


num = "218765"
print("Original number: ", num)
print("Next higher number: ", nextHighUsingAtMostOneSwap(num))

# Expected output:
Original number:  218765
Next higher number:  258761
# longest substring of vowels | python3 program to find the longest substring of vowels . ; increment current count if s [ i ] is vowel ; check previous value is greater then or not ; 
def isVowel(c):
    return (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u')


def longestVowel(s):
    count, res = 0, 0
    for i in range(len(s)):
        if (isVowel(s[i])):
            count += 1
        else:
            res = max(res, count)
            count = 0
    return max(res, count)


if __name__ == "__main__":
    s = "theeare"
    print(longestVowel(s))

# Expected output:
3
# number of substrings with count of each character as k | python3 program to count number of substrings with counts of distinct characters as k . ; returns true if all values in freq [ ] are either 0 or k . ; returns count of substrings where frequency of every present character is k ; pick a starting point ; initialize all frequencies as 0 for this starting point ; one by one pick ending points ; increment frequency of current char ; if frequency becomes more than k , we can 't have more substrings  starting with i ; if frequency becomes k , then check other frequencies as well ; 

MAX_CHAR = 26


def check(freq, k):
    for i in range(0, MAX_CHAR):
        if (freq[i] and freq[i] != k):
            return False
    return True


def substrings(s, k):
    res = 0
    for i in range(0, len(s)):
        freq = [0] * MAX_CHAR
        for j in range(i, len(s)):
            index = ord(s[j]) - ord('a')
            freq[index] += 1
            if (freq[index] > k):
                break
            elif (freq[index] == k and check(freq, k)):
                res += 1
    return res


if __name__ == "__main__":
    s = "aabbcc"
    k = 2
    print(substrings(s, k))
    s = "aabbc"
    k = 2
    print(substrings(s, k))

# Expected output:
6
3
# Number of substrings with count of each character as k |

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))

# Expected output:
6
3
# frequency of a string in an array of strings | python3 program to count number of times a string appears in an array of strings ; to store number of times a string is present . it is 0 is string is not present ; function to insert a string into the trie ; calculation ascii value ; if the given node is not already present in the trie than create the new node ; returns count of occurrences of s in trie ; inserting in trie ; searching the strings in trie ; 

MAX_CHAR = 26


class Trie:
    def __init__(self):
        self .cnt = 0
        self .node = [None for i in range(MAX_CHAR)]


def insert(root, s):
    temp = root
    n = len(s)
    for i in range(n):
        index = ord(s[i]) - ord('a')
        if (not root .node[index]):
            root .node[index] = Trie()
        root = root .node[index]
    root .cnt += 1
    return temp


def search(root, s):
    n = len(s)
    for i in range(n):
        index = ord(s[i]) - ord('a')
        if (not root .node[index]):
            return 0
        root = root .node[index]
    return root .cnt


def answerQueries(arr, n, q, m):
    root = Trie()
    for i in range(n):
        root = insert(root, arr[i])
    for i in range(m):
        print(search(root, q[i]))


if __name__ == '__main__':
    arr = ["aba", "baba", "aba", "xzxb"]
    n = len(arr)
    q = ["aba", "xzxb", "ab"]
    m = len(q)
    answerQueries(arr, n, q, m)

# Expected output:
2
1
0
# longest subsequence where every character appears at | python3 program to find longest subsequence where every character appears at - least k times ; count frequencies of all characters ; traverse given string again and print all those characters whose frequency is more than or equal to k . ; 

MAX_CHARS = 26


def longestSubseqWithK(str, k):
    n = len(str)
    freq = [0] * MAX_CHARS
    for i in range(n):
        freq[ord(str[i]) - ord('a')] += 1
    for i in range(n):
        if (freq[ord(str[i]) - ord('a')] >= k):
            print(str[i], end="")


if __name__ == "__main__":
    str = "geeksforgeeks"
    k = 2
    longestSubseqWithK(str, k)

# Expected output:
geeksgeeks
# recursive solution to count substrings with same first and last characters | function to count substrings with same first and last characters ; base cases ; 
def countSubstrs(str, i, j, n):
    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


str = "abcab"
n = len(str)
print(countSubstrs(str, 0, n - 1, n))

# Expected output:
7
# minimum number of manipulations required to make two strings anagram without deletion of character | counts the no of manipulations required ; store the count of character ; iterate though the first string and update count ; iterate through the second string update char_count . if character is not found in char_count then increase count ; 
def countManipulations(s1, s2):
    count = 0
    char_count = [0] * 26
    for i in range(26):
        char_count[i] = 0
    for i in range(len(s1)):
        char_count[ord(s1[i]) - ord('a')] += 1
    for i in range(len(s2)):
        char_count[ord(s2[i]) - ord('a')] -= 1
    for i in range(26):
        if char_count[i] != 0:
            count += abs(char_count[i])
    return count


if __name__ == "__main__":
    s1 = "ddcf"
    s2 = "cedk"
    print(countManipulations(s1, s2))

# Expected output:
4
# least number of manipulations needed to ensure two strings have identical characters | python3 program to count least number of manipulations to have two strings set of same characters ; return the count of manipulations required ; count the number of different characters in both strings ; check the difference in characters by comparing count arrays ; 

MAX_CHAR = 26


def leastCount(s1, s2, n):
    count1 = [0] * MAX_CHAR
    count2 = [0] * MAX_CHAR
    for i in range(n):
        count1[ord(s1[i]) - ord('a')] += 1
        count2[ord(s2[i]) - ord('a')] += 1
    res = 0
    for i in range(MAX_CHAR):
        if (count1[i] != 0):
            res += abs(count1[i] - count2[i])
    return res


if __name__ == "__main__":
    s1 = "abc"
    s2 = "cdd"
    l = len(s1)
    res = leastCount(s1, s2, l)
    print(res)

# Expected output:
2