giulio98/xlcost-single-prompt huggingface dataset:
# group multiple occurrence of array elements ordered by first occurrence | a simple method to group all occurrences of individual elements ; initialize all elements as not visited ; traverse all elements ; check if this is first occurrence ; if yes , print it and all subsequent occurrences ; 
def groupElements(arr, n):
    visited = [False] * n
    for i in range(0, n):
        visited[i] = False
    for i in range(0, n):
        if (visited[i] == False):
            print(arr[i], end=" ")
            for j in range(i + 1, n):
                if (arr[i] == arr[j]):
                    print(arr[i], end=" ")
                    visited[j] = True


arr = [4, 6, 9, 2, 3, 4, 9, 6, 10, 4]
n = len(arr)
groupElements(arr, n)

# Expected output:
4 4 4 6 6 9 9 2 3 10
# group multiple occurrence of array elements ordered by first occurrence | a hashing based method to group all occurrences of individual elements ; creates an empty hashmap ; traverse the array elements , and store count for every element in hashmap ; increment count of elements in hashmap ; traverse array again ; check if this is first occurrence ; if yes , then print the element ' count ' times ; and remove the element from hashmap . ; 
def orderedGroup(arr):
    hM = {}
    for i in range(0, len(arr)):
        hM[arr[i]] = hM .get(arr[i], 0) + 1
    for i in range(0, len(arr)):
        count = hM .get(arr[i], None)
        if count is not None:
            for j in range(0, count):
                print(arr[i], end=" ")
            del hM[arr[i]]


if __name__ == "__main__":
    arr = [10, 5, 3, 10, 10, 4, 1, 3]
    orderedGroup(arr)

# Expected output:
10 10 10 5 3 3 4 1
# how to check if two given sets are disjoint ? | returns true if set1 [ ] and set2 [ ] are disjoint , else false ; take every element of set1 [ ] and search it in set2 ; if no element of set1 is present in set2 ; 
def areDisjoint(set1, set2, m, n):
    for i in range(0, m):
        for j in range(0, n):
            if (set1[i] == set2[j]):
                return False
    return True


set1 = [12, 34, 11, 9, 3]
set2 = [7, 2, 1, 5]
m = len(set1)
n = len(set2)
print("yes")if areDisjoint(set1, set2, m, n)else (" No")

# Expected output:
yes
# how to check if two given sets are disjoint ? | returns true if set1 [ ] and set2 [ ] are disjoint , else false ; sort the given two sets ; check for same elements using merge like process ; if set1 [ i ] == set2 [ j ] ; 
def areDisjoint(set1, set2, m, n):
    set1 .sort()
    set2 .sort()
    i = 0
    j = 0
    while (i < m and j < n):
        if (set1[i] < set2[j]):
            i += 1
        elif (set2[j] < set1[i]):
            j += 1
        else:
            return False
    return True


set1 = [12, 34, 11, 9, 3]
set2 = [7, 2, 1, 5]
m = len(set1)
n = len(set2)
print("Yes")if areDisjoint(set1, set2, m, n)else print("No")

# Expected output:
Yes
# how to check if two given sets are disjoint ? | this function prints all distinct elements ; creates an empty hashset ; traverse the first set and store its elements in hash ; traverse the second set and check if any element of it is already in hash or not . ; 
def areDisjoint(set1, set2, n1, n2):
    myset = set([])
    for i in range(n1):
        myset .add(set1[i])
    for i in range(n2):
        if (set2[i] in myset):
            return False
    return True


if __name__ == "__main__":
    set1 = [10, 5, 3, 4, 6]
    set2 = [8, 7, 9, 3]
    n1 = len(set1)
    n2 = len(set2)
    if (areDisjoint(set1, set2, n1, n2)):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# non | python3 program to find non - overlapping sum ; function for calculating non - overlapping sum of two array ; insert elements of both arrays ; calculate non - overlapped sum ; 

from collections import defaultdict


def findSum(A, B, n):
    Hash = defaultdict(lambda: 0)
    for i in range(0, n):
        Hash[A[i]] += 1
        Hash[B[i]] += 1
    Sum = 0
    for x in Hash:
        if Hash[x] == 1:
            Sum += x
    return Sum


if __name__ == "__main__":
    A = [5, 4, 9, 2, 3]
    B = [2, 8, 7, 6, 3]
    n = len(A)
    print(findSum(A, B, n))

# Expected output:
39
# find elements which are present in first array and not in second | function for finding elements which are there in a [ ] but not in b [ ] . ; 
def findMissing(a, b, n, m):
    for i in range(n):
        for j in range(m):
            if (a[i] == b[j]):
                break
        if (j == m - 1):
            print(a[i], end=" ")


if __name__ == "__main__":
    a = [1, 2, 6, 3, 4, 5]
    b = [2, 4, 3, 1, 0]
    n = len(a)
    m = len(b)
    findMissing(a, b, n, m)

# Expected output:
6 5
# find elements which are present in first array and not in second | function for finding elements which are there in a [ ] but not in b [ ] . ; store all elements of second array in a hash table ; print all elements of first array that are not present in hash table ; 
def findMissing(a, b, n, m):
    s = dict()
    for i in range(m):
        s[b[i]] = 1
    for i in range(n):
        if a[i]not in s .keys():
            print(a[i], end=" ")


a = [1, 2, 6, 3, 4, 5]
b = [2, 4, 3, 1, 0]
n = len(a)
m = len(b)
findMissing(a, b, n, m)

# Expected output:
6 5
# check if two arrays are equal or not | returns true if arr1 [ 0. . n - 1 ] and arr2 [ 0. . m - 1 ] contain same elements . ; if lengths of array are not equal means array are not equal ; sort both arrays ; linearly compare elements ; if all elements were same . ; 
def areEqual(arr1, arr2, n, m):
    if (n != m):
        return False
    arr1 .sort()
    arr2 .sort()
    for i in range(0, n - 1):
        if (arr1[i] != arr2[i]):
            return False
    return True


arr1 = [3, 5, 2, 5, 2]
arr2 = [2, 3, 5, 5, 2]
n = len(arr1)
m = len(arr2)
if (areEqual(arr1, arr2, n, m)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# pair with given sum and maximum shortest distance from end | function to find maximum shortest distance ; stores the shortest distance of every element in original array . ; shortest distance from ends ; if duplicates are found , b [ x ] is replaced with minimum of the previous and current position 's  shortest distance ; similar elements ignore them cause we need distinct elements ; 
def find_maximum(a, n, k):
    b = dict()
    for i in range(n):
        x = a[i]
        d = min(1 + i, n - i)
        if x not in b .keys():
            b[x] = d
        else:
            b[x] = min(d, b[x])
    ans = 10 ** 9
    for i in range(n):
        x = a[i]
        if (x != (k - x) and (k - x) in b .keys()):
            ans = min(max(b[x], b[k - x]), ans)
    return ans


a = [3, 5, 8, 6, 7]
K = 11
n = len(a)
print(find_maximum(a, n, K))

# Expected output:
2
# pair with given product | set 1 ( find if any pair exists ) | returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x ; consider all possible pairs and check for every pair . ; 
def isProduct(arr, n, x):
    for i in arr:
        for j in arr:
            if i * j == x:
                return True
    return False


arr = [10, 20, 9, 40]
x = 400
n = len(arr)
if (isProduct(arr, n, x)):
    print("Yes")
else:
    print("No")
x = 900
if (isProduct(arr, n, x)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
No
# pair with given product | set 1 ( find if any pair exists ) | returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x . ; create an empty set and insert first element into it ; traverse remaining elements ; 0 case must be handles explicitly as x % 0 is undefined behaviour in c ++ ; x / arr [ i ] exists in hash , then we found a pair ; insert arr [ i ] ; 
def isProduct(arr, n, x):
    if n < 2:
        return False
    s = set()
    for i in range(0, n):
        if arr[i] == 0:
            if x == 0:
                return True
            else:
                continue
        if x % arr[i] == 0:
            if x // arr[i] in s:
                return True
            s .add(arr[i])
    return False


if __name__ == "__main__":
    arr = [10, 20, 9, 40]
    x = 400
    n = len(arr)
    if isProduct(arr, n, x):
        print("Yes")
    else:
        print("No")
    x = 190
    if isProduct(arr, n, x):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
No
# find pair with greatest product in array | function to find greatest number ; 
def findGreatest(arr, n):
    result = -1
    for i in range(n):
        for j in range(n - 1):
            for k in range(j + 1, n):
                if (arr[j] * arr[k] == arr[i]):
                    result = max(result, arr[i])
    return result


if __name__ == "__main__":
    arr = [30, 10, 9, 3, 35]
    n = len(arr)
    print(findGreatest(arr, n))

# Expected output:
30
# find pair with greatest product in array | python3 program to find the largest product number ; function to find greatest number ; store occurrences of all elements in hash array ; sort the array and traverse all elements from end . ; for every element , check if there is another element which divides it . ; check if the result value exists in array or not if yes the return arr [ i ] ; to handle the case like arr [ i ] = 4 and arr [ j ] = 2 ; 

from math import sqrt


def findGreatest(arr, n):
    m = dict()
    for i in arr:
        m[i] = m .get(i, 0) + 1
    arr = sorted(arr)
    for i in range(n - 1, 0, -1):
        j = 0
        while (j < i and arr[j] <= sqrt(arr[i])):
            if (arr[i] % arr[j] == 0):
                result = arr[i] // arr[j]
                if (result != arr[j] and (
                        result in m .keys()) and m[result] > 0):
                    return arr[i]
                elif (result == arr[j] and (result in m .keys()) and m[result] > 1):
                    return arr[i]
            j += 1
    return -1


arr = [17, 2, 1, 15, 30]
n = len(arr)
print(findGreatest(arr, n))

# Expected output:
30
# remove minimum number of elements such that no common element exist in both array | to find no elements to remove so no common element exist ; to store count of array element ; count elements of a ; count elements of b ; traverse through all common element , and pick minimum occurrence from two arrays ; to return count of minimum elements ; 
def minRemove(a, b, n, m):
    countA = dict()
    countB = dict()
    for i in range(n):
        countA[a[i]] = countA .get(a[i], 0) + 1
    for i in range(n):
        countB[b[i]] = countB .get(b[i], 0) + 1
    res = 0
    for x in countA:
        if x in countB .keys():
            res += min(countA[x], countB[x])
    return res


a = [1, 2, 3, 4]
b = [2, 3, 4, 5, 8]
n = len(a)
m = len(b)
print(minRemove(a, b, n, m))

# Expected output:
3
# count items common to both the lists but with different prices | function to count items common to both the lists but with different prices ; for each item of ' list1' check if it is in ' list2' but with a different price ; required count of items ; 
def countItems(list1, list2):
    count = 0
    for i in list1:
        for j in list2:
            if i[0] == j[0] and i[1] != j[1]:
                count += 1
    return count


list1 = [("apple", 60), ("bread", 20), ("wheat", 50), ("oil", 30)]
list2 = [("milk", 20), ("bread", 15), ("wheat", 40), ("apple", 60)]
print("Count = ", countItems(list1, list2))

# Expected output:
Count =  2
# minimum index sum for common elements of two lists | function to print common strings with minimum index sum ; resultant list ; iterating over sum in ascending order ; iterating over one list and check index ( corresponding to 
def find(list1, list2):
    res = []
    max_possible_sum = len(list1) + len(list2) - 2
    for sum in range(max_possible_sum + 1):
        for i in range(sum + 1):
            if (i < len(list1) and (sum - i) < len(list2)
                    and list1[i] == list2[sum - i]):
                res .append(list1[i])
        if (len(res) > 0):
            break
    for i in range(len(res)):
        print(res[i], end=" ")


list1 = []
list1 .append("GeeksforGeeks")
list1 .append("Udemy")
list1 .append("Coursera")
list1 .append("edX")
list2 = []
list2 .append("Codecademy")
list2 .append("Khan Academy")
list2 .append("GeeksforGeeks")
find(list1, list2)

# Expected output:
GeeksforGeeks
# Minimum Index Sum for Common Elements of Two Lists | Hashing based Python3 program to find common elements with minimum index sum ; Function to print common strings with minimum index sum ; Mapping strings to their indices ; Resultant list ; If current sum is smaller than minsum ; If index sum is same then put this string in resultant list as well ; Print result ; Creating list1 ; Creating list2

import sys


def find(list1, list2):
    Map = {}
    for i in range(len(list1)):
        Map[list1[i]] = i
    res = []
    minsum = sys .maxsize
    for j in range(len(list2)):
        if list2[j] in Map:
            Sum = j + Map[list2[j]]
            if (Sum < minsum):
                minsum = Sum
                res .clear()
                res .append(list2[j])
            elif (Sum == minsum):
                res .append(list2[j])
    print(*res, sep=" ")


list1 = []
list1 .append("GeeksforGeeks")
list1 .append("Udemy")
list1 .append("Coursera")
list1 .append("edX")
list2 = []
list2 .append("Codecademy")
list2 .append("Khan Academy")
list2 .append("GeeksforGeeks")
find(list1, list2)

# Expected output:
GeeksforGeeks
# check whether a binary tree is a full binary tree or not | constructor of the node class for creating the node ; checks if the binary tree is full or not ; if empty tree ; if leaf node ; if both left and right subtress are not none and left and right subtress are full ; we reach here when none of the above if condiitions work ; 

class Node:
    def __init__(self, key):
        self .key = key
        self .left = None
        self .right = None


def isFullTree(root):
    if root is None:
        return True
    if root .left is None and root .right is None:
        return True
    if root .left is not None and root .right is not None:
        return (isFullTree(root .left) and isFullTree(root .right))
    return False


root = Node(10)
root .left = Node(20)
root .right = Node(30)
root .left .right = Node(40)
root .left .left = Node(50)
root .right .left = Node(60)
root .right .right = Node(70)
root .left .left .left = Node(80)
root .left .left .right = Node(90)
root .left .right .left = Node(80)
root .left .right .right = Node(90)
root .right .left .left = Node(80)
root .right .left .right = Node(90)
root .right .right .left = Node(80)
root .right .right .right = Node(90)
if isFullTree(root):
    print("The Binary tree is full")
else:
    print("Binary tree is not full")

# Expected output:
The Binary tree is full
# change the array into a permutation of numbers from 1 to n | python3 code to make a permutation of numbers from 1 to n using minimum changes . ; store counts of all elements . ; find next missing element to put in place of current element . ; replace with next missing and insert the missing element in hash . ; 
def makePermutation(a, n):
    count = dict()
    for i in range(n):
        if count .get(a[i]):
            count[a[i]] += 1
        else:
            count[a[i]] = 1
    next_missing = 1
    for i in range(n):
        if count[a[i]] != 1 or a[i] > n or a[i] < 1:
            count[a[i]] -= 1
            while count .get(next_missing):
                next_missing += 1
            a[i] = next_missing
            count[next_missing] = 1


A = [2, 2, 3, 3]
n = len(A)
makePermutation(A, n)
for i in range(n):
    print(A[i], end=" ")

# Expected output:
1 2 4 3
# count pairs with given sum | returns number of pairs in arr [ 0. . n - 1 ] with sum equal to sum ; initialize result ; consider all possible pairs and check their sums ; 
def getPairsCount(arr, n, sum):
    count = 0
    for i in range(0, n):
        for j in range(i + 1, n):
            if arr[i] + arr[j] == sum:
                count += 1
    return count


arr = [1, 5, 7, -1, 5]
n = len(arr)
sum = 6
print("Count of pairs is", getPairsCount(arr, n, sum))

# Expected output:
Count of pairs is 3
# analysis of algorithms | big | ''function to find whether a key exists in an array or not using linear search ; '' traverse the given array, a[] ; '' check if a[i] is equal to key ; ''
def linearSearch(a, n, key):
    for i in range(0, n):
        if (a[i] == key):
            return True
    return False


arr = 2, 3, 4, 10, 40
x = 10
n = len(arr)
if (linearSearch(arr, n, x)):
    print("Element is present in array")
else:
    print("Element is not present in array")

# Expected output:
Element is present in array
# count pairs with given sum | python 3 implementation of simple method to find count of pairs with given sum . ; returns number of pairs in arr [ 0. . n - 1 ] with sum equal to 'sum   ; store counts of all elements in map m ; initializing value to 0 , if key not found ; iterate through each element and increment the count ( notice that every pair is counted twice ) ; if ( arr [ i ] , arr [ i ] ) pair satisfies the condition , then we need to ensure that the count is decreased by one such that the ( arr [ i ] , arr [ i ] ) pair is not considered ; return the half of twice_count ; 

import sys


def getPairsCount(arr, n, sum):
    m = [0] * 1000
    for i in range(0, n):
        m[arr[i]] += 1
    twice_count = 0
    for i in range(0, n):
        twice_count += m[sum - arr[i]]
        if (sum - arr[i] == arr[i]):
            twice_count -= 1
    return int(twice_count / 2)


arr = [1, 5, 7, -1, 5]
n = len(arr)
sum = 6
print("Count of pairs is", getPairsCount(arr, n, sum))

# Expected output:
Count of pairs is 3
# count pairs from two sorted arrays whose sum is equal to a given value x | function to count all pairs from both the sorted arrays whose sum is equal to a given value ; generating pairs from both the arrays ; if sum of pair is equal to ' x ' increment count ; required count of pairs ; 
def countPairs(arr1, arr2, m, n, x):
    count = 0
    for i in range(m):
        for j in range(n):
            if arr1[i] + arr2[j] == x:
                count = count + 1
    return count


arr1 = [1, 3, 5, 7]
arr2 = [2, 3, 5, 8]
m = len(arr1)
n = len(arr2)
x = 10
print("Count = ", countPairs(arr1, arr2, m, n, x))

# Expected output:
Count =  2
# count pairs from two sorted arrays whose sum is equal to a given value x | function to search ' value ' in the given array ' arr [ ] ' it uses binary search technique as ' arr [ ] ' is sorted ; value found ; value not found ; function to count all pairs from both the sorted arrays whose sum is equal to a given value ; for each arr1 [ i ] ; check if the ' value ' is present in 'arr2[]   ; required count of pairs ; 
def isPresent(arr, low, high, value):
    while (low <= high):
        mid = (low + high) // 2
        if (arr[mid] == value):
            return True
        elif (arr[mid] > value):
            high = mid - 1
        else:
            low = mid + 1
    return False


def countPairs(arr1, arr2, m, n, x):
    count = 0
    for i in range(m):
        value = x - arr1[i]
        if (isPresent(arr2, 0, n - 1, value)):
            count += 1
    return count


if __name__ == "__main__":
    arr1 = [1, 3, 5, 7]
    arr2 = [2, 3, 5, 8]
    m = len(arr1)
    n = len(arr2)
    x = 10
    print("Count = ", countPairs(arr1, arr2, m, n, x))

# Expected output:
Count =  2
# count pairs from two sorted arrays whose sum is equal to a given value x | function to count all pairs from both the sorted arrays whose sum is equal to a given value ; insert all the elements of 1 st array in the hash table ( unordered_set ' us ' ) ; or each element of 'arr2[] ; find ( x - arr2 [ j ] ) in 'us   ; required count of pairs ; 
def countPairs(arr1, arr2, m, n, x):
    count = 0
    us = set()
    for i in range(m):
        us .add(arr1[i])
    for j in range(n):
        if x - arr2[j] in us:
            count += 1
    return count


arr1 = [1, 3, 5, 7]
arr2 = [2, 3, 5, 8]
m = len(arr1)
n = len(arr2)
x = 10
print("Count =", countPairs(arr1, arr2, m, n, x))

# Expected output:
Count = 2
# count pairs from two sorted arrays whose sum is equal to a given value x | function to count all pairs from both the sorted arrays whose sum is equal to a given value ; traverse ' arr1 [ ] ' from left to right traverse ' arr2 [ ] ' from right to left ; if this sum is equal to ' x ' , then increment ' l ' , decrement ' r ' and increment 'count   ; if this sum is less than x , then increment l ; else decrement 'r   ; required count of pairs ; 
def countPairs(arr1, arr2, m, n, x):
    count, l, r = 0, 0, n - 1
    while (l < m and r >= 0):
        if ((arr1[l] + arr2[r]) == x):
            l += 1
            r -= 1
            count += 1
        elif ((arr1[l] + arr2[r]) < x):
            l += 1
        else:
            r -= 1
    return count


if __name__ == '__main__':
    arr1 = [1, 3, 5, 7]
    arr2 = [2, 3, 5, 8]
    m = len(arr1)
    n = len(arr2)
    x = 10
    print("Count =", countPairs(arr1, arr2, m, n, x))

# Expected output:
Count = 2
# count quadruples from four sorted arrays whose sum is equal to a given value x | count pairs from the two sorted array whose sum is equal to the given ' value ' ; traverse ' arr1 [ ] ' from left to right traverse ' arr2 [ ] ' from right to left ; if the ' sum ' is equal to ' value ' , then increment ' l ' , decrement ' r ' and increment ' count ' ; if the ' sum ' is greater than ' value ' , then decrement r ; else increment l ; required count of pairs print ( count ) ; function to count all quadruples from four sorted arrays whose sum is equal to a 
def countPairs(arr1, arr2, n, value):
    count = 0
    l = 0
    r = n - 1
    while (l < n and r >= 0):
        sum = arr1[l] + arr2[r]
        if (sum == value):
            l += 1
            r -= 1
            count += 1
        elif (sum > value):
            r -= 1
        else:
            l += 1
    return count


def countQuadruples(arr1, arr2, arr3, arr4, n, x):
    count = 0
    for i in range(0, n):
        for j in range(0, n):
            p_sum = arr1[i] + arr2[j]
            count += int(countPairs(arr3, arr4, n, x - p_sum))
    return count


arr1 = [1, 4, 5, 6]
arr2 = [2, 3, 7, 8]
arr3 = [1, 4, 6, 10]
arr4 = [2, 4, 7, 8]
n = len(arr1)
x = 30
print("Count = ", countQuadruples(arr1, arr2, arr3, arr4, n, x))

# Expected output:
Count =  4
# count quadruples from four sorted arrays whose sum is equal to a given value x | function to count all quadruples from four sorted arrays whose sum is equal to a 
def countQuadruples(arr1, arr2, arr3, arr4, n, x):
    count = 0
    m = {}
    for i in range(n):
        for j in range(n):
            if (arr1[i] + arr2[j]) in m:
                m[arr1[i] + arr2[j]] += 1
            else:
                m[arr1[i] + arr2[j]] = 1
    for k in range(n):
        for l in range(n):
            p_sum = arr3[k] + arr4[l]
            if (x - p_sum) in m:
                count += m[x - p_sum]
    return count


arr1 = [1, 4, 5, 6]
arr2 = [2, 3, 7, 8]
arr3 = [1, 4, 6, 10]
arr4 = [2, 4, 7, 8]
n = len(arr1)
x = 30
print("Count =", countQuadruples(arr1, arr2, arr3, arr4, n, x))

# Expected output:
Count = 4
# number of subarrays having sum exactly equal to k | python3 program to find the number of subarrays with sum exactly equal to k . ; function to find number of subarrays with sum exactly equal to k . ; dictionary to store number of subarrays starting from index zero having particular value of sum . ; sum of elements so far . ; add current element to sum so far . ; if currsum is equal to desired sum , then a new subarray is found . so increase count of subarrays . ; currsum exceeds given sum by currsum - sum . find number of subarrays having this sum and exclude those subarrays from currsum by increasing count by same amount . ; add currsum value to count of different values of sum . ; 

from collections import defaultdict


def findSubarraySum(arr, n, Sum):
    prevSum = defaultdict(lambda: 0)
    res = 0
    currsum = 0
    for i in range(0, n):
        currsum += arr[i]
        if currsum == Sum:
            res += 1
        if (currsum - Sum) in prevSum:
            res += prevSum[currsum - Sum]
        prevSum[currsum] += 1
    return res


if __name__ == "__main__":
    arr = [10, 2, -2, -20, 10]
    Sum = -10
    n = len(arr)
    print(findSubarraySum(arr, n, Sum))

# Expected output:
3