Solve in Python:
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

The largest rectangle is shown in the shaded area, which has area = 10 unit.

Example:

Input: [2,1,5,6,2,3]
Output: 10

class Solution:
     def largestRectangleArea(self, heights):
         """
         :type heights: List[int]
         :rtype: int
         """

         # # sol1: mono_inc stack
         # stack = [(-1, 0)]
         # res = 0
         # for i, h in enumerate(heights + [0]):
         #     while stack[-1][1] > h:
         #         H = stack.pop()[1]
         #         W = i - stack[-1][0] - 1
         #         res = max(res, H*W)
         #     stack.append((i, h))
         # return res

         # sol2: left/right(include self) higher neighbors
         if not heights:
             return 0
         N = len(heights)
         left, right = [1]*N, [1]*N
         for i in range(1, N):
             j = i - 1
             while j >= 0 and heights[j] >= heights[i]:
                 left[i] += left[j]
                 j -= left[j]
         for i in range(N - 1, -1, -1): # 注意降序要写完整 -1, -1
             j = i + 1
             while j <= N - 1 and heights[j] >= heights[i]:
                 right[i] += right[j]
                 j += right[j]
         return max((l+r-1)*h for l,r,h in zip(left,right,heights))


Solve in Python:
Given n number of people in a room, calculate the probability that any two people in that room have the same birthday (assume 365 days every year = ignore leap year). Answers should be two decimals unless whole (0 or 1) eg 0.05

from math import factorial as f
def calculate_probability(n):
    a = 1
    for x in range(n):
        a *= (365-x)/365
    return round(1-a, 2)


Solve in Python:
Given n orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:
Input: n = 1
Output: 1
Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.

Example 2:
Input: n = 2
Output: 6
Explanation: All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.

Example 3:
Input: n = 3
Output: 90

Constraints:

1 <= n <= 500

class Solution:
    def countOrders(self, n: int) -> int:
        DP = [0]*(n+1)
        DP[1] = 1
        for i in range(2, n+1):
            newpos = ((i*2-1)+1)*(i*2-1)//2
            DP[i] = newpos*DP[i-1]

        return DP[-1]%(10**9+7)


Solve in Python:
Given n words w[1..n], which originate from the same stem (e.g. grace, graceful, disgraceful, gracefully), we are interested in the original stem. To simplify the problem, we define the stem as the longest consecutive substring that occurs in all the n words. If there are ties, we will choose the smallest one in the alphabetical (lexicographic) order.

-----Input-----
The first line contains an integer T denoting the total number of test cases.
In each test cases, the first line contains an integer n denoting the number of words. In the second line, n words w[1..n] consisting of lower case characters are given as a single space-spearated list.

-----Output-----
For each test case, output the stem in a new line.

-----Constraints-----
- 1 <= T <= 10
- 1 <= n <= 10
- 1 <= |w[i]| <= 20

-----Example-----
Input:
1
4
grace graceful disgraceful gracefully
Output:
grace

-----Explanation-----
The stem is grace.

t = eval(input())
while t != 0:
 md = {}
 t -= 1
 n = eval(input())
 wrds = input().split()
 c = 0
 for w in wrds:
  c += 1
  for i in range(len(w)):
   for j in range(i,len(w)):
    sub = w[i:j+1]
    if sub not in md:
     md[sub] = 1
    elif sub in md and md[sub] == c-1:
     md[sub] = c
 res = ""
 for k in list(md.keys()):
  if md[k] == n:
   if len(k) > len(res):
    res = k
   elif len(k) == len(res) and k < res:
    res = k
 print(res)


Solve in Python:
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

class Solution:
     hash = {}
     def numTrees(self, n):
         """
         :type n: int
         :rtype: int
         """
         # return base case
         if n == 0:
             return 1
         if n == 1 or n == 2:
             return n

         # try fetching from hash
         try:
             return self.hash[n]
         except KeyError:
             pass

         # holds the sum
         resSum = 0

         # iterate i from 1 to n-1
         # should add up (0,4), (1,3), (2,2), (3,1), (4,0)
         for i in range(n):
             #print(i,n - (i+1))
             tempSum = self.numTrees(i) * self.numTrees(n - (i+1))
             #print(tempSum)
             resSum += tempSum

         # append to hash
         self.hash[n]=resSum
         return resSum


Solve in Python:
Given positive integers N, K and M, solve the following problem for every integer x between 1 and N (inclusive):
 - Find the number, modulo M, of non-empty multisets containing between 0 and K (inclusive) instances of each of the integers 1, 2, 3 \cdots, N such that the average of the elements is x.

-----Constraints-----
 - 1 \leq N, K \leq 100
 - 10^8 \leq M \leq 10^9 + 9
 - M is prime.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N K M

-----Output-----
Use the following format:
c_1
c_2
:
c_N

Here, c_x should be the number, modulo M, of multisets such that the average of the elements is x.

-----Sample Input-----
3 1 998244353

-----Sample Output-----
1
3
1

Consider non-empty multisets containing between 0 and 1 instance(s) of each of the integers between 1 and 3. Among them, there are:
 - one multiset such that the average of the elements is k = 1: \{1\};
 - three multisets such that the average of the elements is k = 2: \{2\}, \{1, 3\}, \{1, 2, 3\};
 - one multiset such that the average of the elements is k = 3: \{3\}.

import numpy as np
from numba import njit
@njit
def main(n,k,mod):
    l=k*(n*(n+1))//2
    dp=np.zeros((n+1,l+1),dtype=np.int32)
    # dp[i][j]:iまでの数字を使い、合計がjになるものの個数
    # O(N^3*k)<=O(10^8)で計算可能らしい
    dp[0,0]=1
    ary=np.ones((1,l+2),dtype=np.int32)
    ary[0,0]=0
    for i in range(1,n+1):
        nary=np.zeros((i+1,2+l//i),dtype=np.int32)
        for j in range(l+1):
            a=j//i
            b=max(0,j//i-k)
            dp[i,j]=ary[j%i,a+1]-ary[j%i,b]
            dp[i,j]%=mod
            nary[j%(i+1),j//(i+1)+1]=dp[i,j]
            nary[j%(i+1),j//(i+1)+1]+=nary[j%(i+1),j//(i+1)]
            nary[j%(i+1),j//(i+1)+1]%=mod
        ary=nary
    ret=[]
    for i in range(1,n+1):
        # 左区間=[1,i-1]
        # 右区間=[1,n-i]
        ans=0
        num=dp[i-1,0]
        num*=dp[n-i,0]
        ans+=num*k
        ans%=mod
        for j in range(1,l+1):
            num=dp[i-1,j]
            num*=dp[n-i,j]
            num%=mod
            ans+=(num*(k+1))%mod
            ans%=mod
        ret.append(ans)
    #for x in ret:
    #    print(x)
    return ret

n,k,mod=map(int,input().split())
print(*main(n,k,mod),sep='\n')


Solve in Python:
Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

# Definition for a binary tree node.
 # class TreeNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.left = None
 #         self.right = None

 class Solution:
     def buildTree(self, preorder, inorder):
         """
         :type preorder: List[int]
         :type inorder: List[int]
         :rtype: TreeNode
         """
         INDICES = {}
         for idx, val in enumerate(inorder):
             INDICES[val] = idx

         seen = {}
         ptr = 0
         def build(left, right):
             nonlocal ptr
             print(left, right)
             if left > right or right < left or ptr >= len(preorder):
                 return
             val = preorder[ptr]
             print(val, left, right)

             node = TreeNode(preorder[ptr])
             ptr += 1
             node.left = build(left, INDICES[val]-1) #if (INDICES[val] != 0 and INDICES[val] != len(inorder) - 1) else None
             node.right = build(INDICES[val]+1, right) #if (INDICES[val] != 0 and INDICES[val] != len(inorder) - 1) else None

             return node

         return build(0, len(inorder))


Solve in Python:
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

class Solution:
     def isInterleave(self, s1, s2, s3):
         """
         :type s1: str
         :type s2: str
         :type s3: str
         :rtype: bool
         """
         if len(s3) != len(s1) + len(s2): return False
         if '' in [s1, s2]: return s3 == s1+s2

         dp = [[False]*(len(s2)+1) for _ in range(len(s1)+1)]
         for i in range(len(s1)+1):
             for j in range(len(s2)+1):
                 if i == 0 and j == 0:
                     dp[i][j] = True
                 else:
                     dp[i][j] = False
                     if j > 0: dp[i][j] |= dp[i][j-1] and s2[j-1] == s3[i+j-1]
                     if i > 0: dp[i][j] |= dp[i-1][j] and s1[i-1] == s3[i+j-1]
         return dp[-1][-1]


Solve in Python:
Given some points (cartesian coordinates), return true if all of them lie on a line.  Treat both an empty set and a single point as a line.

```python
on_line(((1,2), (7,4), (22,9)) == True
on_line(((1,2), (-3,-14), (22,9))) == False
```

from fractions import Fraction

def on_line(ps):
    ps = list(set(ps))
    if ps and all(isinstance(x, int) for x in ps):
        return True
    return len({
        (x1 if x1 == x2 else Fraction(y2-y1, x2-x1))
        for (x1,y1), (x2,y2) in zip(ps, ps[1:])
    }) <= 1


Solve in Python:
Given some positive integers, I wish to print the integers such that all take up the same width by adding a minimum number of leading zeroes. No leading zeroes shall be added to the largest integer.

For example, given `1, 23, 2, 17, 102`, I wish to print out these numbers as follows:

```python
001
023
002
017
102
```

Write a function `print_nums(n1, n2, n3, ...)` that takes a variable number of arguments and returns the string to be printed out.

def print_nums(*args):
    return '\n'.join(['0'*(len(str(max(args)))-len(str(x)))+str(x) for x in args])


Solve in Python:
Given that
```
f0 = '0'
f1 = '01'
f2 = '010' = f1 + f0
f3 = '01001' = f2 + f1
```

You will be given a number and your task is to return the `nth` fibonacci string. For example:

```
solve(2) = '010'
solve(3) = '01001'
```

More examples in test cases. Good luck!

If you like sequence Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)

def solve(n):
    a,b = '01'
    for _ in range(n): a,b = a+b,a
    return a


Solve in Python:
Given the array arr of positive integers and the array queries where queries[i] = [Li, Ri], for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor ... xor arr[Ri] ). Return an array containing the result for the given queries.

Example 1:
Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
Output: [2,7,14,8]
Explanation:
The binary representation of the elements in the array are:
1 = 0001
3 = 0011
4 = 0100
8 = 1000
The XOR values for queries are:
[0,1] = 1 xor 3 = 2
[1,2] = 3 xor 4 = 7
[0,3] = 1 xor 3 xor 4 xor 8 = 14
[3,3] = 8

Example 2:
Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output: [8,0,4,4]

Constraints:

1 <= arr.length <= 3 * 10^4
1 <= arr[i] <= 10^9
1 <= queries.length <= 3 * 10^4
queries[i].length == 2
0 <= queries[i][0] <= queries[i][1] < arr.length

class Solution:
    def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
        xor_arr = [0]*len(arr)
        xor_arr[0] = arr[0]
        for i in range(1,len(arr)):
            xor_arr[i] = xor_arr[i-1] ^ arr[i]

        res = [0]*len(queries)
        for i, (s,e) in enumerate(queries):
            if s == e:
                res[i] = arr[s]
            elif s == 0:
                res[i] = xor_arr[e]
            else:
                res[i] = xor_arr[e] ^ xor_arr[s-1]

        return res


Solve in Python:
Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).
Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.

Example 1:
Input: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]
Output: [0,1,4]
Explanation:
Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0.
Person with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"].
Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].

Example 2:
Input: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]
Output: [0,1]
Explanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1].

Example 3:
Input: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]
Output: [0,1,2,3]

Constraints:

1 <= favoriteCompanies.length <= 100
1 <= favoriteCompanies[i].length <= 500
1 <= favoriteCompanies[i][j].length <= 20
All strings in favoriteCompanies[i] are distinct.
All lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].
All strings consist of lowercase English letters only.

class Solution:
    def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
        length = len(favoriteCompanies)
        for i in range(length):
            favoriteCompanies[i] = set(favoriteCompanies[i])
        res = []
        for i in range(length):
            pattern = favoriteCompanies[i]
            for flist in favoriteCompanies:
                if pattern < flist: break
            else:
                res.append(i)
        return res


Solve in Python:
Given the array nums consisting of n positive integers. You computed the sum of all non-empty continous subarrays from the array and then sort them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.
Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 10^9 + 7.

Example 1:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 5
Output: 13
Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.

Example 2:
Input: nums = [1,2,3,4], n = 4, left = 3, right = 4
Output: 6
Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.

Example 3:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 10
Output: 50

Constraints:

1 <= nums.length <= 10^3
nums.length == n
1 <= nums[i] <= 100
1 <= left <= right <= n * (n + 1) / 2

class Solution:
    def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
        s = [0]
        for x in nums:
            s.append(s[-1] + x)
        n = len(nums)
        q = [(x, i, i) for i, x in enumerate(nums)]
        heapq.heapify(q)
        i = 1
        ans = 0
        while i <= right:
            x, j, k = heapq.heappop(q)
            if i >= left:
                ans += x
            if k > 0:
                k -= 1
                y = s[j + 1] - s[k]
                heapq.heappush(q,(y, j, k))
            i += 1
        return ans % (10 ** 9 + 7)


Solve in Python:
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).

Example 1:
Input: nums = [3,4,5,2]
Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.

Example 2:
Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3:
Input: nums = [3,7]
Output: 12

Constraints:

2 <= nums.length <= 500
1 <= nums[i] <= 10^3

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        products = []
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                products.append((nums[i]-1)*(nums[j]-1))
        return max(products)


Solve in Python:
Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:

In the beginning, you have the permutation P=[1,2,3,...,m].
For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].

Return an array containing the result for the given queries.

Example 1:
Input: queries = [3,1,2,1], m = 5
Output: [2,1,2,1]
Explanation: The queries are processed as follow:
For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5].
For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5].
For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5].
For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5].
Therefore, the array containing the result is [2,1,2,1].

Example 2:
Input: queries = [4,1,2,2], m = 4
Output: [3,1,2,0]

Example 3:
Input: queries = [7,5,5,8,3], m = 8
Output: [6,5,0,7,5]

Constraints:

1 <= m <= 10^3
1 <= queries.length <= m
1 <= queries[i] <= m

class Solution:
    def processQueries(self, queries: List[int], m: int) -> List[int]:
        p = []
        res = []
        for i in range(1, m + 1):
            p.append(i)
        for n in queries:
            pos = 0
            while p[pos] != n and pos < m:
                pos += 1
            res.append(pos)
            del p[pos]
            p.insert(0, n)
        return res


Solve in Python:
Given the coordinates of four points in 2D space, return whether the four points could construct a square.

The coordinate (x,y) of a point is represented by an integer array with two integers.

Example:

Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True

 Note:

All the input integers are in the range [-10000, 10000].
A valid square has four equal sides with positive length and four equal angles (90-degree angles).
Input points have no order.

class Solution:
     def validSquare(self, A, B, C, D):
         """
         A B   A D   A C
         C D   B C   D B

         A C   A B   A D
         B D   D C   C B

         - figure out which orientation this is
         - B-A == D-C and C-A == D-B
         - D-A == C-B and B-A == C-D
         - C-A == B-D and D-A == B-C

         - if one of those is true, just need to check angles
         - check length of two perpendicular sides is same
             - enough to check -y, x?

         4     A(2,4)
         3
         2 C(0,2)  B(4,2)
         1
         0     D(2,0)
           0 1 2 3 4

         [1,0]
         [-1,0]
         [0,-1]
         [0,1]

         1       D

         0  B         A

        -1       C

           -1    0    1

         :type p1: List[int]
         :type p2: List[int]
         :type p3: List[int]
         :type p4: List[int]
         :rtype: bool
         """
         def sub(p2, p1):
             return [p2[0]-p1[0], p2[1]-p1[1]]

 #         def add(p1, p2):
 #             return [p1[0]+p2[0], p1[1]+p2[1]]

         if sub(A, B) == [0, 0]:
             return False

         if sub(B, A) == sub(D, C) and sub(C, A) == sub(D, B):
             print((1))
             diff1 = sub(B, A)
             diff2 = sub(A, C)
             print((diff1, diff2))
             if diff1 == [-diff2[1], diff2[0]] or diff1 == [diff2[1], -diff2[0]]:
                 return True

         elif sub(D, A) == sub(C, B) and sub(B, A) == sub(C, D):
             print((2))
             diff1 = sub(D, A)
             diff2 = sub(A, B)
             print((diff1, diff2))
             if diff1 == [-diff2[1], diff2[0]] or diff1 == [diff2[1], -diff2[0]]:
                 return True

         elif sub(C, A) == sub(B, D) and sub(D, A) == sub(B, C):
             print((3))
             diff1 = sub(C, A)
             diff2 =...


Solve in Python:
Given the current exchange rate between the USD and the EUR is 1.1363636 write a function that will accept the Curency type to be returned and a list of the amounts that need to be converted.

Don't forget this is a currency so the result will need to be rounded to the second decimal.

'USD' Return format should be `'$100,000.00'`

'EUR' Return format for this kata should be `'100,000.00€'`

`to_currency` is a string with values `'USD','EUR'` , `values_list` is a list of floats

`solution(to_currency,values)`

#EXAMPLES:

```
solution('USD',[1394.0, 250.85, 721.3, 911.25, 1170.67])
= ['$1,584.09', '$285.06', '$819.66', '$1,035.51', '$1,330.31']

solution('EUR',[109.45, 640.31, 1310.99, 669.51, 415.54])
= ['96.32€', '563.47€', '1,153.67€', '589.17€', '365.68€']

```

def solution(to_cur,value):
    return ['${:,.2f}'.format(x*1.1363636) if to_cur == 'USD' else '{:,.2f}€'.format(x/1.1363636) for x in value]


Solve in Python:
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.
After doing so, return the head of the final linked list.  You may return any such answer.

(Note that in the examples below, all sequences are serializations of ListNode objects.)
Example 1:
Input: head = [1,2,-3,3,1]
Output: [3,1]
Note: The answer [1,2,1] would also be accepted.

Example 2:
Input: head = [1,2,3,-3,4]
Output: [1,2,4]

Example 3:
Input: head = [1,2,3,-3,-2]
Output: [1]

Constraints:

The given linked list will contain between 1 and 1000 nodes.
Each node in the linked list has -1000 <= node.val <= 1000.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeZeroSumSublists(self, head: ListNode) -> ListNode:

        array = []
        modified = False
        node = head
        #print(\"Head: \", head)
        while node:
            #print(\"node: \", node.val, modified, matched)
            next_node = node.__next__
            matched = False
            if node.val == 0:
                matched = True
                modified = True
                if len(array) > 0:
                    array[-1].next = next_node
                else:
                    head = next_node

            else:
                tsum = 0
                #print(\"For: \", node.val)
                for i in range(len(array) -1, -1, -1):
                    tsum += array[i].val
                    if tsum + node.val == 0:
                        matched = True
                        modified = True
                        #print(i)
                        if i != 0:
                            j = 0
                            popi = len(array) - i
                            while j != popi:
                                array.pop()
                                j += 1
                            array[i-1].next = next_node
                            #print(array[i-1].val, next_node.val, head)
                        else:
                            # all elements removed
                            head = next_node
                            array = []
                    # elif tsum + node.val > 0:
                    #     break

            if not matched:
                array.append(node)
            node = next_node
        #print(\"op head: \", head)
        if modified:
            return self.removeZeroSumSublists(head)
        else:
            return head


Solve in Python:
Given the list of numbers, you are to sort them in non decreasing order.

-----Input-----
t – the number of numbers in list, then t lines follow [t <= 10^6].

Each line contains one integer: N [0 <= N <= 10^6]

-----Output-----
Output given numbers in non decreasing order.

-----Example-----
Input:
5
5
3
6
7
1

Output:
1
3
5
6
7

# cook your dish here
x=int(input())
lst=[]
for i in range(0,x):
     y=int(input())
     lst.append(y)
lst.sort()
for i in range(0,x):
     print(lst[i])


Solve in Python:
Given the moleculer mass of two molecules ( __M1__ and __M2__ ), their masses present ( __m1__ and __m2__ ) in a vessel of volume ( __V__ ) at a specific temperature ( __T__ ). Find the total pressure exerted by the molecules ( __Ptotal__ ) .

input
====

Six values :

- __m1__
- __m2__
- __M1__
- __M2__
- __V__
- __T__

output
====

One value :

- __Ptotal__

notes
====

Units for each of the following are given as under :

- _m1_ = gram
- _m2_ = gram
- _M1_ = _gram.mole^(-1)_
- _M2_ = _gram.mole^(-1)_
- _V_             = _dm^(3)_
- _T_             = Celsius
- __Ptotal__ = atmpspheric pressure (_atm_)

Remember : Temperature is given in Celsius while SI unit is Kelvin (_K_)

0 Celsius = 273.15Kelvin

The gas constant (_R_) has value of _0.082dm^(3).atm.K^(-1).mol^(-1)_


Solve in Python:
Given the number n, return a string which shows the minimum number of moves to complete the tower of Hanoi consisting of n layers.
Tower of Hanoi : https://en.wikipedia.org/wiki/Tower_of_Hanoi

Example - 2 layered Tower of Hanoi

Input: n=2

Start
[[2, 1], [], []]

Goal
[[], [], [2, 1]]

Expected Output : '[[2, 1], [], []]\n[[2], [1], []]\n[[], [1], [2]]\n[[], [], [2, 1]]'

def hanoiArray(n):

  def move(n, source, target, auxiliary):
      if n > 0:
          # Move n - 1 disks from source to auxiliary, so they are out of the way
          move(n - 1, source, auxiliary, target)

          # Move the nth disk from source to target
          target.append(source.pop())

          # Store new state
          res.append([A[:], B[:], C[:]])

          # Move the n - 1 disks that we left on auxiliary onto target
          move(n - 1, auxiliary, target, source)

  A = list(range(n, 0, -1))
  B = []
  C = []

  res = [[A[:], B[:], C[:]]]

  # Initiate call from source A to target C with auxiliary B
  move(n, A, C, B)
  return '\n'.join(map(str, res))


Solve in Python:
Given the number pledged for a year, current value and name of the month, return string that gives information about the challenge status:

- ahead of schedule
- behind schedule
- on track
- challenge is completed

Examples:

`(12, 1, "February")` - should return `"You are on track."`

`(12, 1, "March")` - should return `"You are 1 behind schedule."`

`(12, 5, "March")` - should return `"You are 3 ahead of schedule."`

`(12, 12, "September")` - should return `"Challenge is completed."`

Details:
- you do not need to do any prechecks (input will always be a natural number and correct name of the month)
- months should be as even as possible (i.e. for 100 items: January, February, March and April - 9, other months 8)
- count only the item for completed months (i.e. for March check the values from January and February) and it means that for January you should always return `"You are on track."`.

def check_challenge(p,c,m):
    if p==c:return'Challenge is completed.'
    n='Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split().index(m[:3])
    s=p//12*n+min(p%12,n)-c
    return"You are "+("%s schedule"%('%d ahead of'%(-s),'%d behind'%s)[0<s]+'.!'[s<0],"on track.")[n==0 or s==0]


Solve in Python:
Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on.
Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root.
(As a reminder, any shorter prefix of a string is lexicographically smaller: for example, "ab" is lexicographically smaller than "aba".  A leaf of a node is a node that has no children.)

Example 1:

Input: [0,1,2,3,4,3,4]
Output: "dba"

Example 2:

Input: [25,1,3,1,3,0,2]
Output: "adz"

Example 3:

Input: [2,2,1,null,1,0,null,0]
Output: "abc"

Note:

The number of nodes in the given tree will be between 1 and 8500.
Each node in the tree will have a value between 0 and 25.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
import string
class Solution:
    def smallestFromLeaf(self, root: TreeNode) -> str:
        def pathToLeaf(root, letters):
            nonlocal smallest
            if root:
                letters+=chr(root.val + ord('a'))
                if root.right == None and root.left == None:
                    reversed_letters = letters[::-1]
                    if smallest > reversed_letters:
                        smallest =  reversed_letters
                else:
                    pathToLeaf(root.left, letters)
                    pathToLeaf(root.right,  letters)

        smallest = \"~\"
        pathToLeaf(root, \"\")
        return smallest


Solve in Python:
Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.
(A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.)

Example 1:

Input: [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
Explanation:
We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.

Note:

The number of nodes in the tree is between 2 and 5000.
Each node will have value between 0 and 100000.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxAncestorDiff(self, root: TreeNode) -> int:

        def traverse(root,anc,diff):

            if root:
                for an in anc:
                    if abs(root.val-an)>diff:
                        diff=abs(root.val-an)

                diff=traverse(root.left,anc+[root.val],diff)
                diff=traverse(root.right,anc+[root.val],diff)

            return diff

        return traverse(root,[],0)


Solve in Python:
Given the root of a binary tree, the depth of each node is the shortest distance to the root.
Return the smallest subtree such that it contains all the deepest nodes in the original tree.
A node is called the deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is tree consisting of that node, plus the set of all descendants of that node.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation: We return the node with value 2, colored in yellow in the diagram.
The nodes coloured in blue are the deepest nodes of the tree.
Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.

Example 2:
Input: root = [1]
Output: [1]
Explanation: The root is the deepest node in the tree.

Example 3:
Input: root = [0,1,3,null,2]
Output: [2]
Explanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.

Constraints:

The number of nodes in the tree will be in the range [1, 500].
The values of the nodes in the tree are unique.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:

        def getDepth(root):
            if not root:
                return 0
            left=getDepth(root.left)
            right=getDepth(root.right)
            return 1+max(left,right)

        def getSubtrees(root):
            if root:

                leftDepth=getDepth(root.left)
                rightDepth=getDepth(root.right)
                if leftDepth==rightDepth:
                    return root
                elif leftDepth>rightDepth:
                    return getSubtrees(root.left)
                else:
                    return getSubtrees(root.right)

        return getSubtrees(root)


Solve in Python:
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
Return the smallest level X such that the sum of all the values of nodes at level X is maximal.

Example 1:

Input: root = [1,7,0,7,-8,null,null]
Output: 2
Explanation:
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.

Example 2:
Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output: 2

Constraints:

The number of nodes in the tree is in the range [1, 104].
-105 <= Node.val <= 105

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxLevelSum(self, root: TreeNode) -> int:
        self.max_sum = {}

        def sum_tree(node: TreeNode,level):

            if not node:
                return
            sum_tree(node.left,level+1)
            sum_tree(node.right,level+1)
            if level in self.max_sum:
                self.max_sum[level] +=  node.val
            else:
                self.max_sum[level] =  node.val

        sum_tree(root,1)
        output, max_val = float('inf'), -float('inf')
        for key, val in list(self.max_sum.items()):
            if val > max_val:
                output, max_val = key, val
            elif val == max_val:
                output = min(key, output)
        return output


Solve in Python:
Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.

The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.

Example 1:

Input:
A binary tree as following:
       4
     /   \
    2     6
   / \   /
  3   1 5

v = 1

d = 2

Output:
       4
      / \
     1   1
    /     \
   2       6
  / \     /
 3   1   5

Example 2:

Input:
A binary tree as following:
      4
     /
    2
   / \
  3   1

v = 1

d = 3

Output:
      4
     /
    2
   / \
  1   1
 /     \
3       1

Note:

The given d is in range [1, maximum depth of the given tree + 1].
The given binary tree has at least one tree node.

class Solution:
     def addOneRow(self, root, v, d):
         """
         :type root: TreeNode
         :type v: int
         :type d: int
         :rtype: TreeNode
         """
         q, depth = [root], 1
         while depth != d: parent, q, depth = q, [kid for node in q for kid in (node.left, node.right) if kid], depth+1
         if d != 1:
             for node in parent: node.left, node.right, node.left.left, node.right.right = TreeNode(v), TreeNode(v), node.left, node.right
             return root
         else:
             first, first.left = TreeNode(v), root
             return first


Solve in Python:
Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

Examples 1
Input:

  5
 /  \
2   -3

return [2, -3, 4], since all the values happen only once, return all of them in any order.

Examples 2
Input:

  5
 /  \
2   -5

return [2], since 2 happens twice, however -5 only occur once.

Note:
You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

from collections import defaultdict
 # Definition for a binary tree node.
 # class TreeNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.left = None
 #         self.right = None

 class Solution:
     """
     :type root: TreeNode
     :rtype: map{sum:int : frequency:int}
     """
     def __init__(self):
         self._iter = 0
     def getAllSums(self, root):
         if not root:
             return defaultdict(int), 0
         all_sums, left_sum = self.getAllSums(root.left)
         all_right_sums, right_sum = self.getAllSums(root.right)
         # mege both maps
         for key,val in all_right_sums.items():
             all_sums[key] += val
         cur_sum = right_sum + root.val + left_sum
         all_sums[cur_sum] += 1
         return all_sums, cur_sum

     def findFrequentTreeSum(self, root):
         """
         :type root: TreeNode
         :rtype: List[int]
         """
         all_sums,_ = self.getAllSums(root)
         result = []
         max_occurence = 0
         for key,val in all_sums.items():
             max_occurence = max(max_occurence,val)
         for key,val in all_sums.items():
             if val == max_occurence:
                 result.append(key)
         return result


Solve in Python:
Given the root of a binary tree, consider all root to leaf paths: paths from the root to any leaf.  (A leaf is a node with no children.)
A node is insufficient if every such root to leaf path intersecting this node has sum strictly less than limit.
Delete all insufficient nodes simultaneously, and return the root of the resulting binary tree.

Example 1:

Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1

Output: [1,2,3,4,null,null,7,8,9,null,14]

Example 2:

Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22

Output: [5,4,8,11,null,17,4,7,null,null,null,5]

Example 3:

Input: root = [1,2,-3,-5,null,4,null], limit = -1

Output: [1,null,-3,4]

Note:

The given tree will have between 1 and 5000 nodes.
-10^5 <= node.val <= 10^5
-10^9 <= limit <= 10^9

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
        def helper(root, currsum, limit):
            if not root:
                return True
            currsum += root.val
            if root.left is None and root.right is None:
                return currsum < limit

            deleteme = [True, True]

            if root.left:
                should_del = helper(root.left, currsum, limit)
                if should_del:
                    del root.left
                    root.left = None
                deleteme[0] = should_del

            if root.right:
                should_del = helper(root.right, currsum, limit)
                if should_del:
                    del root.right
                    root.right = None
                deleteme[1] = should_del

            return all(deleteme)

        deleteroot = helper(root, 0, limit)
        if deleteroot:
            del root
            return None
        return root


Solve in Python:
Given the root of a binary tree, each node in the tree has a distinct value.
After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).
Return the roots of the trees in the remaining forest.  You may return the result in any order.

Example 1:

Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]

Constraints:

The number of nodes in the given tree is at most 1000.
Each node has a distinct value between 1 and 1000.
to_delete.length <= 1000
to_delete contains distinct values between 1 and 1000.

class Solution:
    def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
        final_list = []
        def rec(node):
            if node == None:
                return None
            node.left = rec(node.left)
            node.right = rec(node.right)
            if node.val in to_delete:
                if node.left!= None:
                    final_list.append(node.left)
                if node.right!= None:
                    final_list.append(node.right)
                return None
            return node
        rec(root)
        if root.val not in to_delete:
            final_list.append(root)
        return(final_list)


Solve in Python:
Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions.

Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function.

A log is a string has this format : function_id:start_or_end:timestamp. For example, "0:start:0" means function 0 starts from the very beginning of time 0. "0:end:0" means function 0 ends to the very end of time 0.

Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id.

Example 1:

Input:
n = 2
logs =
["0:start:0",
 "1:start:2",
 "1:end:5",
 "0:end:6"]
Output:[3, 4]
Explanation:
Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1.
Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5.
Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time.
So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time.

Note:

Input logs will be sorted by timestamp, NOT log id.
Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0.
Two functions won't start or end at the same time.
Functions could be called recursively, and will always end.
1

class Solution:
     def exclusiveTime(self, n, logs):
         """
         :type n: int
         :type logs: List[str]
         :rtype: List[int]
         """
         result = [0 for _ in range(n)]
         stack = []
         for log in logs:
             func, op, time = log.split(":")
             func = int(func)
             time = int(time)
             if op == "start":
                 if stack:
                     func_last, time_last = stack[-1]
                     result[func_last] += time - time_last
                 stack.append([func, time])
             else:
                 func_last, time_last = stack.pop()
                 result[func_last] += time - time_last + 1
                 if stack:
                     stack[-1][1] = time + 1
         return result


Solve in Python:
Given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple “croak” are mixed. Return the minimum number of different frogs to finish all the croak in the given string.
A valid "croak" means a frog is printing 5 letters ‘c’, ’r’, ’o’, ’a’, ’k’ sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of valid "croak" return -1.

Example 1:
Input: croakOfFrogs = "croakcroak"
Output: 1
Explanation: One frog yelling "croak" twice.

Example 2:
Input: croakOfFrogs = "crcoakroak"
Output: 2
Explanation: The minimum number of frogs is two.
The first frog could yell "crcoakroak".
The second frog could yell later "crcoakroak".

Example 3:
Input: croakOfFrogs = "croakcrook"
Output: -1
Explanation: The given string is an invalid combination of "croak" from different frogs.

Example 4:
Input: croakOfFrogs = "croakcroa"
Output: -1

Constraints:

1 <= croakOfFrogs.length <= 10^5
All characters in the string are: 'c', 'r', 'o', 'a' or 'k'.

class Solution:
    def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
        croaks = {'c':[], 'r':[], 'o':[], 'a':[]}
        nfrogs = 0
        icroak = 0
        curfrogs = 0
        for sound in croakOfFrogs:
            if sound == 'c':
                icroak += 1
                croaks['c'].append(icroak)
                curfrogs += 1
                nfrogs = max(curfrogs, nfrogs)
            elif sound == 'r':
                if croaks['c']:
                    croaks['r'].append(croaks['c'].pop())
                else:
                    return -1
            elif sound == 'o':
                if croaks['r']:
                    croaks['o'].append(croaks['r'].pop())
                else:
                    return -1
            elif sound == 'a':
                if croaks['o']:
                    croaks['a'].append(croaks['o'].pop())
                else:
                    return -1
            elif sound == 'k':
                if croaks['a']:
                    croaks['a'].pop()
                    curfrogs -= 1
                else:
                    return -1
            else:
                return -1

        for sound in croaks:
            if croaks[sound] != []:
                return -1

        return nfrogs


Solve in Python:
Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.

Example 1:
Input: s = "eleetminicoworoep"
Output: 13
Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.

Example 2:
Input: s = "leetcodeisgreat"
Output: 5
Explanation: The longest substring is "leetc" which contains two e's.

Example 3:
Input: s = "bcbcbc"
Output: 6
Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.

Constraints:

1 <= s.length <= 5 x 10^5
s contains only lowercase English letters.

class Solution:
    def findTheLongestSubstring(self, s: str) -> int:
        def countVowels(ct):
            if not ct['a'] % 2 and not ct['e'] % 2 and not ct['i'] % 2 and not ct['o'] % 2 and not ct['u'] % 2:
                return True
            return False

        #Reducer
            #Slider
            #0 - len(s)
            #0 - len(s) -1 -> 1 - len(s)
        for i in range(len(s)):
            ctr = collections.Counter(s[:len(s) - i])
            for j in range(i+1):
                #window = s[j:(len(s)+j) - i]
                if j != 0:
                    ctr[s[j - 1]] -= 1
                    ctr[s[len(s)+j - i - 1]] += 1
                if countVowels(ctr):
                    return sum(ctr.values())
        return 0


Solve in Python:
Given the strings s1 and s2 of size n, and the string evil. Return the number of good strings.
A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 10^9 + 7.

Example 1:
Input: n = 2, s1 = "aa", s2 = "da", evil = "b"
Output: 51
Explanation: There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da".

Example 2:
Input: n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"
Output: 0
Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string.

Example 3:
Input: n = 2, s1 = "gx", s2 = "gz", evil = "x"
Output: 2

Constraints:

s1.length == n
s2.length == n
s1 <= s2
1 <= n <= 500
1 <= evil.length <= 50
All strings consist of lowercase English letters.

from functools import lru_cache

def failure(pat):
    i, target, n = 1, 0, len(pat)
    res = [0]
    while i < n:
        if pat[i] == pat[target]:
            target += 1
            res.append(target)
            i += 1
        elif target:
            target = res[target-1]
        else:
            res.append(0)
            i += 1
    return res

def srange(a, b):
    yield from (chr(i) for i in range(ord(a), ord(b)+1))

class Solution:
    def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:
        f = failure(evil)
        @lru_cache(None)
        def dfs(idx, max_matched=0, lb=True, rb=True):

            if max_matched == len(evil): return 0
            if idx == n: return 1

            l = s1[idx] if lb else 'a'
            r = s2[idx] if rb else 'z'

            candidates = [*srange(l, r)]

            res = 0
            for i, c in enumerate(candidates):
                next_matched = max_matched
                while next_matched and evil[next_matched] != c:
                    next_matched = f[next_matched-1]
                res += dfs(idx+1, next_matched + (evil[next_matched] == c),
                          (lb and i == 0), (rb and i == (len(candidates) - 1)))
            return res

        return dfs(0) % (10**9 + 7)


Solve in Python:
Given the sum and gcd of two numbers, return those two numbers in ascending order. If the numbers do not exist, return `-1`, (or `NULL` in C, `tuple (-1,-1)` in C#, `pair (-1,-1)` in C++,`None` in Rust, `array {-1,-1} ` in Java and Golang).

```
For example:
Given sum = 12 and gcd = 4...

solve(12,4) = [4,8]. The two numbers 4 and 8 sum to 12 and have a gcd of 4.

solve(12,5) = -1. No two numbers exist that sum to 12 and have gcd of 5.

solve(10,2) = [2,8]. Note that [4,6] is also a possibility but we pick the one with the lower first element: 2 < 4, so we take [2,8].
```

More examples in test cases.

Good luck!

def solve(s,g):
    return (g, s-g) if s % g == 0 else -1


Solve in Python:
Given the triangle of consecutive odd numbers:

```
             1
          3     5
       7     9    11
   13    15    17    19
21    23    25    27    29
...
```

Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:

```python
row_sum_odd_numbers(1); # 1
row_sum_odd_numbers(2); # 3 + 5 = 8
```

```if:nasm
row_sum_odd_numbers:
```

def row_sum_odd_numbers(n):
    count = 0
    kokosik = 1
    result = 0
    for huesosina in range(0, n):
        kokosik += count
        count += 2
    result += kokosik
    for guccigang in range(0, n - 1):
        kokosik += 2
        result += kokosik
    return result


Solve in Python:
Given the values at the leaf nodes of a complete binary tree. The total number of nodes in the binary tree, is also given. Sum of the values at both the children of a node is equal to the value of the node itself. You can add any value or subtract any value from a node. Print the minimum change(difference made) in the sum of values of all the nodes in the tree, such that all the leaf nodes have the same value.

Note: If a value transfers from one node to another, then that is not a change, but if an extra is needed to be added or subtracted to the entire total value of the nodes, then that is a change.

Input Description:

Input will contain an integer N, the number of nodes in the tree on a newline, followed by N space separated integers representing the values at the leaf nodes of the tree.

Output Description:

Print the required value on a newline.

Constraints:

1<=N<=20000
1<=Value at each node in the leaves<=1000

Example 1:
Input:

1

50
Output:

0

Explanation: Since there is only one node, it is a leaf node itself and no change needs to be made.

Example 2:
Input:

3

200 800
Output:

0

Explanation: There are two leaf nodes, and they can be made to 500 500, since no change in the total was made so difference made is 0.

Example 3:
Input:

30

29 33 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Output:

6

Output: A total change of 6 needs to be changed to the entire value of the nodes, to get the leaf nodes equal.


Solve in Python:
Given three arrays of integers, return the sum of elements that are common in all three arrays.

For example:

```
common([1,2,3],[5,3,2],[7,3,2]) = 5 because 2 & 3 are common in all 3 arrays
common([1,2,2,3],[5,3,2,2],[7,3,2,2]) = 7 because 2,2 & 3 are common in the 3 arrays
```

More examples in the test cases.

Good luck!

from collections import Counter
def common(a,b,c):
    return sum((Counter(a) & Counter(b) & Counter(c)).elements())


Solve in Python:
Given time in 24-hour format, convert it to words.

```
For example:
13:00 = one o'clock
13:09 = nine minutes past one
13:15 = quarter past one
13:29 = twenty nine minutes past one
13:30 = half past one
13:31 = twenty nine minutes to two
13:45 = quarter to two
00:48 = twelve minutes to one
00:08 = eight minutes past midnight
12:00 = twelve o'clock
00:00 = midnight

Note: If minutes == 0, use 'o'clock'. If minutes <= 30, use 'past', and for minutes > 30, use 'to'.

```

More examples in test cases. Good luck!

def solve(time):
    harr = ["midnight", "one", "two", "three", "four", "five", "six", "seven",
            "eight", "nine", "ten", "eleven", "twelve", "one", "two", "three", "four",
            "five", "six", "seven", "eight", "nine", "ten", "eleven", "midnight"]

    marr = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
         "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
         "eighteen", "nineteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five",
        "twenty six", "twenty seven", "twenty eight", "twenty nine"]

    hour, minute = list(map(int,time.split(":")))
    if minute == 0:
        if hour == 0:
            return "midnight"
        return harr[hour] + " o'clock"
    if minute == 15:
        return "quarter past " + harr[hour]
    if minute == 45:
        return "quarter to " + harr[1 + hour]
    if minute == 30:
        return "half past " + harr[hour]
    if minute == 1:
        return "one minute past " + harr[hour]
    if minute == 59:
        return "one minute to " + harr[1 + hour]
    if int(int(minute) < 30):
        return marr[minute] + " minutes past " + harr[hour]
    return marr[60 - minute] + " minutes to " + harr[1 + hour]


Solve in Python:
Given two arrays `a` and `b` write a function `comp(a, b)` (`compSame(a, b)` in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in `b` are the elements in `a` squared, regardless of the order.

## Examples
## Valid arrays
```
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
```
`comp(a, b)` returns true because in `b` 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on. It gets obvious if we write `b`'s elements in terms of squares:
```
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]
```
### Invalid arrays
If we change the first number to something else, `comp` may not return true anymore:
```
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [132, 14641, 20736, 361, 25921, 361, 20736, 361]
```
`comp(a,b)` returns false because in `b` 132 is not the square of any number of `a`.
```
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361]
```
`comp(a,b)` returns false because in `b` 36100 is not the square of any number of `a`.

## Remarks
- `a` or `b` might be `[]` (all languages except R, Shell).
- `a` or `b` might be `nil` or `null` or `None` or `nothing` (except in Haskell, Elixir, C++, Rust, R, Shell, PureScript).

If `a` or `b` are `nil` (or `null` or `None`), the problem doesn't make sense so return false.

#### Note for C
The two arrays have the same size `(> 0)` given as parameter in function `comp`.

def comp(array1, array2):
    return None not in (array1, array2) and sum([i*i for i in array1]) == sum(array2)


Solve in Python:
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).

Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.

Constraints:

1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000

import numpy as np
class Solution:
    def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:

        # DP(a=index of last, b=index of last) = max of:
        #   DP(a-1, b)
        #   DP(a-1, i) + nums1[a] * max_or_min(nums2[i+1:b+1])
        #   same for b

        INF = int(1e9)
        n, m = len(nums1), len(nums2)

        DP = np.ones((n, m), dtype=int) * -INF
        DP[0, 0] = nums1[0] * nums2[0]

        for a in range(n):
            for b in range(m):

                el = nums1[a] * nums2[b]
                curr = el

                if a > 0:
                    curr = max(curr, DP[a - 1, b])
                if b > 0:
                    curr = max(curr, DP[a, b - 1])
                if a > 0 and b > 0:
                    prev = DP[a - 1, b - 1]
                    curr = max(curr, prev, prev + el)

                DP[a, b] = curr

        return DP[-1, -1]


Solve in Python:
Given two arrays of integers `m` and `n`, test if they contain *at least* one identical element. Return `true` if they do; `false` if not.

Your code must handle any value within the range of a 32-bit integer, and must be capable of handling either array being empty (which is a `false` result, as there are no duplicated elements).

def duplicate_elements(m, n):
    return True if [x for x in m if x in n] else False


Solve in Python:
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.

Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13

Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20

Constraints:

2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6

class Solution:
    def maxAbsValExpr(self, A: List[int], B: List[int]) -> int:
        n = len(A)

        max1 = max2 = max3 = max4 = -10**6 - 1
        min1 = min2 = min3 = min4 = 10**6 + 1
        for i in range(n):
            temp = A[i] - B[i] - i
            min1 = min(min1,temp)
            max1 = max(max1,temp)

            temp = A[i] + B[i] - i
            min2 = min(min2,temp)
            max2 = max(max2,temp)

            temp = A[i] + B[i] + i
            min3 = min(min3,temp)
            max3 = max(max3,temp)

            temp = A[i] - B[i] +i
            min4 = min(min4,temp)
            max4 = max(max4,temp)

        ans = max(max4 - min4, max3 - min3, max2 - min2, max1 - min1)

        return ans


Solve in Python:
Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:

Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.
Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length.

Example 1:
Input: nums1 = [7,4], nums2 = [5,2,8,9]
Output: 1
Explanation: Type 1: (1,1,2), nums1[1]^2 = nums2[1] * nums2[2]. (4^2 = 2 * 8).

Example 2:
Input: nums1 = [1,1], nums2 = [1,1,1]
Output: 9
Explanation: All Triplets are valid, because 1^2 = 1 * 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2).  nums1[i]^2 = nums2[j] * nums2[k].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]^2 = nums1[j] * nums1[k].

Example 3:
Input: nums1 = [7,7,8,3], nums2 = [1,2,9,7]
Output: 2
Explanation: There are 2 valid triplets.
Type 1: (3,0,2).  nums1[3]^2 = nums2[0] * nums2[2].
Type 2: (3,0,1).  nums2[3]^2 = nums1[0] * nums1[1].

Example 4:
Input: nums1 = [4,7,9,11,23], nums2 = [3,5,1024,12,18]
Output: 0
Explanation: There are no valid triplets.

Constraints:

1 <= nums1.length, nums2.length <= 1000
1 <= nums1[i], nums2[i] <= 10^5

def func(xs, ys):
    sqs = [x**2 for x in xs]
    seen = collections.defaultdict(int)
    res = 0
    for y in ys:
        for x in sqs:
            if x % y == 0:
                res += seen[x//y]
        seen[y] += 1

    return res

class Solution:
    def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
        return func(nums1, nums2) + func(nums2, nums1)


Solve in Python:
Given two arrays of strings, return the number of times each string of the second array appears in the first array.

#### Example

```python
array1 = ['abc', 'abc', 'xyz', 'cde', 'uvw']
array2 = ['abc', 'cde', 'uap']
```

How many times do the elements in `array2` appear in `array1`?

* `'abc'` appears twice in the first array (2)
* `'cde'` appears only once (1)
* `'uap'` does not appear in the first array (0)

Therefore, `solve(array1, array2) = [2, 1, 0]`

Good luck!

If you like this Kata, please try:

[Word values](https://www.codewars.com/kata/598d91785d4ce3ec4f000018)

[Non-even substrings](https://www.codewars.com/kata/59da47fa27ee00a8b90000b4)

from collections import Counter

def solve(arr_1, arr_2):
    cnt = Counter(arr_1)
    return [cnt[a] for a in arr_2]


Solve in Python:
Given two arrays, the purpose of this Kata is to check if these two arrays are the same. "The same" in this Kata means the two arrays contains arrays of 2 numbers which are same and not necessarily sorted the same way. i.e. [[2,5], [3,6]] is same as [[5,2], [3,6]] or [[6,3], [5,2]] or [[6,3], [2,5]] etc

[[2,5], [3,6]] is NOT the same as [[2,3], [5,6]]
Two empty arrays [] are the same
[[2,5], [5,2]] is the same as [[2,5], [2,5]] but NOT the same as [[2,5]]
[[2,5], [3,5], [6,2]] is the same as [[2,6], [5,3], [2,5]] or [[3,5], [6,2], [5,2]], etc
An array can be empty or contain a minimun of one array of 2 integers and up to 100 array of 2 integers

Note:
1. [[]] is not applicable because if the array of array are to contain anything, there have to be two numbers.
2. 100 randomly generated tests that can contains either "same" or "not same" arrays.

def same(arr_a, arr_b):
    arr_a = sorted(list(map(sorted, arr_a)))
    arr_b = sorted(list(map(sorted, arr_b)))
    return arr_a == arr_b


Solve in Python:
Given two binary trees original and cloned and given a reference to a node target in the original tree.
The cloned tree is a copy of the original tree.
Return a reference to the same node in the cloned tree.
Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.
Follow up: Solve the problem if repeated values on the tree are allowed.

Example 1:

Input: tree = [7,4,3,null,null,6,19], target = 3
Output: 3
Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.

Example 2:

Input: tree = [7], target =  7
Output: 7

Example 3:

Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
Output: 4

Example 4:

Input: tree = [1,2,3,4,5,6,7,8,9,10], target = 5
Output: 5

Example 5:

Input: tree = [1,2,null,3], target = 2
Output: 2

Constraints:

The number of nodes in the tree is in the range [1, 10^4].
The values of the nodes of the tree are unique.
target node is a node from the original tree and is not null.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
        if not original or not cloned:
            return None
        stack = []
        stack.append((original, cloned))
        while stack:
            orig, clone = stack.pop()
            if orig == target:
                return clone
            if orig.right:
                stack.append((orig.right, clone.right))
            if orig.left:
                stack.append((orig.left, clone.left))


Solve in Python:
Given two different positions on a chess board, find the least number of moves it would take a knight to get from one to the other.
The positions will be passed as two arguments in algebraic notation.
For example, `knight("a3", "b5")` should return 1.

The knight is not allowed to move off the board.
The board is 8x8.

For information on knight moves, see https://en.wikipedia.org/wiki/Knight_%28chess%29

For information on algebraic notation, see
https://en.wikipedia.org/wiki/Algebraic_notation_%28chess%29

(Warning: many of the tests were generated randomly. If any do not work, the test cases will return the input, output, and expected output; please post them.)

from copy import copy
move_map = ((-2, -1), (-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1))

def algebraic_to_eucledian(pos):
    return (int(pos[1]) - 1, 'abcdefgh'.index(pos[0]))

def knight(p1, p2):
    p1, p2 = algebraic_to_eucledian(p1), algebraic_to_eucledian(p2)
    num_moves = -1
    visited = []
    moves = [p1]
    while moves:
        next_moves = []
        num_moves += 1
        for move in moves:
            if move == p2:
                return num_moves
            visited.append(move)
            next_moves.extend([(move[0]+x, move[1]+y) for x, y in move_map if 0 <= move[0]+x < 8 and 0 <= move[1]+y < 8 and (move[0]+x, move[1]+y) not in visited])
        moves = copy(next_moves)


Solve in Python:
Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character.
Return the minimum number of steps to make t an anagram of s.
An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

Example 1:
Input: s = "bab", t = "aba"
Output: 1
Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.

Example 2:
Input: s = "leetcode", t = "practice"
Output: 5
Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.

Example 3:
Input: s = "anagram", t = "mangaar"
Output: 0
Explanation: "anagram" and "mangaar" are anagrams.

Example 4:
Input: s = "xxyyzz", t = "xxyyzz"
Output: 0

Example 5:
Input: s = "friend", t = "family"
Output: 4

Constraints:

1 <= s.length <= 50000
s.length == t.length
s and t contain lower-case English letters only.

class Solution:
    def minSteps(self, s: str, t: str) -> int:
        count=0
        for curr in s:
            # print(\"Curr=\",curr,\"and t=\",t)
            if curr in t:
                t=t.replace(curr,'',1)
                # print(\"Now t=\",t)
            else:
                count+=1
        return count


Solve in Python:
Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.

Example 1:

Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output: 3
Explanation:
The repeated subarray with maximum length is [3, 2, 1].

Note:

1
0

class Solution:
     def findLength(self, A, B):
         def check(length):
             seen = {A[i:i+length]
                     for i in range(len(A) - length + 1)}
             return any(B[j:j+length] in seen
                        for j in range(len(B) - length + 1))

         A = ''.join(map(chr, A))
         B = ''.join(map(chr, B))
         lo, hi = 0, min(len(A), len(B)) + 1
         while lo < hi:
             mi = int((lo + hi) / 2)
             if check(mi):
                 lo = mi + 1
             else:
                 hi = mi
         return lo - 1


Solve in Python:
Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.
The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.

Example 1:
Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2
Explanation:
For arr1[0]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1[1]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1[2]=8 we have:
|8-10|=2 <= d=2
|8-9|=1 <= d=2
|8-1|=7 > d=2
|8-8|=0 <= d=2

Example 2:
Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
Output: 2

Example 3:
Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
Output: 1

Constraints:

1 <= arr1.length, arr2.length <= 500
-10^3 <= arr1[i], arr2[j] <= 10^3
0 <= d <= 100

class Solution:
    def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:

        count=0
        for i in arr1:
            a = True
            for j in arr2:
                a=a & (abs(i-j)>d)
            if a==True:
                count+=1
        return count


Solve in Python:
Given two integer arrays of equal length target and arr.
In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps.
Return True if you can make arr equal to target, or False otherwise.

Example 1:
Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true
Explanation: You can follow the next steps to convert arr to target:
1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]
2- Reverse sub-array [4,2], arr becomes [1,2,4,3]
3- Reverse sub-array [4,3], arr becomes [1,2,3,4]
There are multiple ways to convert arr to target, this is not the only way to do so.

Example 2:
Input: target = [7], arr = [7]
Output: true
Explanation: arr is equal to target without any reverses.

Example 3:
Input: target = [1,12], arr = [12,1]
Output: true

Example 4:
Input: target = [3,7,9], arr = [3,7,11]
Output: false
Explanation: arr doesn't have value 9 and it can never be converted to target.

Example 5:
Input: target = [1,1,1,1,1], arr = [1,1,1,1,1]
Output: true

Constraints:

target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000

class Solution:
    def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
        if collections.Counter(target) != collections.Counter(arr):
            return False
        return True

        def reverse(left,right):
            while left<right:
                arr[left],arr[right] = arr[right],arr[left]
                left += 1
                right -=1

        for i in range(len(target)):
            if target[i] == arr[i]:
                continue
            j = arr.find(target[i])
            reverse(i,j)


Solve in Python:
Given two integer arrays startTime and endTime and given an integer queryTime.
The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].
Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.

Example 1:
Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
Output: 1
Explanation: We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.

Example 2:
Input: startTime = [4], endTime = [4], queryTime = 4
Output: 1
Explanation: The only student was doing their homework at the queryTime.

Example 3:
Input: startTime = [4], endTime = [4], queryTime = 5
Output: 0

Example 4:
Input: startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7
Output: 0

Example 5:
Input: startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5
Output: 5

Constraints:

startTime.length == endTime.length
1 <= startTime.length <= 100
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000

class Solution:
    def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
        return sum([1 if startTime[i] <= queryTime and endTime[i] >= queryTime else 0 for i in range(len(startTime))])


Solve in Python:
Given two integer arrays where the second array is a shuffled duplicate of the first array with one element missing, find the missing element.

Please note, there may be duplicates in the arrays, so checking if a numerical value exists in one and not the other is not a valid solution.

```
find_missing([1, 2, 2, 3], [1, 2, 3]) => 2
```
```
find_missing([6, 1, 3, 6, 8, 2], [3, 6, 6, 1, 2]) => 8
```

The first array will always have at least one element.

from functools import reduce
def find_missing(arr1, arr2):
    from itertools import chain
    from functools import reduce
    from operator import xor
    return reduce(xor, chain(arr1, arr2))


Solve in Python:
Given two integers A and B, return any string S such that:

S has length A + B and contains exactly A 'a' letters, and exactly B 'b' letters;
The substring 'aaa' does not occur in S;
The substring 'bbb' does not occur in S.

Example 1:
Input: A = 1, B = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all correct answers.

Example 2:
Input: A = 4, B = 1
Output: "aabaa"

Note:

0 <= A <= 100
0 <= B <= 100
It is guaranteed such an S exists for the given A and B.

class Solution:
    def strWithout3a3b(self, A: int, B: int) -> str:
        count = [A, B]
        char = ['aab', 'bba']
        for i in range(2):
            j = i ^ 1
            if count[i] >= count[j]:
                if count[i] >= count[j] * 2:
                    return char[i] * count[j] + char[i][:1] * (count[i] - count[j]*2)
                return char[i] * (count[i] - count[j]) + char[i][1:] * (count[j]*2 - count[i])


Solve in Python:
Given two integers `a` and `b`, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return `a` or `b`.

**Note:** `a` and `b` are not ordered!

## Examples

```python
get_sum(1, 0) == 1   // 1 + 0 = 1
get_sum(1, 2) == 3   // 1 + 2 = 3
get_sum(0, 1) == 1   // 0 + 1 = 1
get_sum(1, 1) == 1   // 1 Since both are same
get_sum(-1, 0) == -1 // -1 + 0 = -1
get_sum(-1, 2) == 2  // -1 + 0 + 1 + 2 = 2
```
```C
get_sum(1, 0) == 1   // 1 + 0 = 1
get_sum(1, 2) == 3   // 1 + 2 = 3
get_sum(0, 1) == 1   // 0 + 1 = 1
get_sum(1, 1) == 1   // 1 Since both are same
get_sum(-1, 0) == -1 // -1 + 0 = -1
get_sum(-1, 2) == 2  // -1 + 0 + 1 + 2 = 2
```

def get_sum(a,b):
    sum = 0
    if a==b:
        return a
    if b<a:
        a, b = b, a
    for i in range(a,b+1):
        sum += i
    return sum


Solve in Python:
Given two integers `a` and `x`, return the minimum non-negative number to **add to** / **subtract from** `a` to make it a multiple of `x`.

```python
minimum(10, 6)  #= 2

10+2 = 12 which is a multiple of 6
```

## Note
- 0 is always a multiple of `x`

## Constraints

**1 <= a <= 10^(6)**

**1 <= x <= 10^(5)**

def minimum(a, x):
    r = a % x
    return r and min(r, x - r)


Solve in Python:
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3

Example 2:

Input: dividend = 7, divisor = -3
Output: -2

Note:

       Both dividend and divisor will be 32-bit signed integers.
       The divisor will never be 0.
       Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

class Solution:
     def divide(self, dividend, divisor):
         """
         :type dividend: int
         :type divisor: int
         :rtype: int
         """
         MIN_INT = -2**31
         MAX_INT = -MIN_INT - 1
         if divisor == 0 or (dividend == MIN_INT and divisor==-1):
             return MAX_INT
         sign = 1
         if dividend < 0:
             sign = -sign
             dividend = -dividend
         if divisor < 0:
             sign = -sign
             divisor = -divisor
         ans = bits = 0
         while (divisor<<(bits+1)) <= dividend:
             bits += 1
         while bits >= 0:
             if dividend >= (divisor<<bits):
                 dividend -= (divisor<<bits)
                 ans += (1<<bits)
             bits -= 1
         return ans if sign==1 else -ans


Solve in Python:
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"

class Solution:
     def fractionToDecimal(self, numerator, denominator):
         """
         :type numerator: int
         :type denominator: int
         :rtype: str
         """
         if numerator*denominator < 0:
             add_negative = True
         else:
             add_negative = False
         numerator, denominator = abs(numerator), abs(denominator)

         integer_part = int(numerator//denominator)
         new_numerator = numerator-integer_part*denominator
         dict_residuals = {}
         digit_location = 0
         digit_array = []
         residual = new_numerator
         if residual == 0:
             if add_negative:
                 return "-"+str(integer_part)
             else:
                 return str(integer_part)
         is_repeating = True
         dict_residuals[residual] = 0
         while True:
             new_digit, residual = self.single_digit(residual, denominator)
             digit_location += 1
             if residual == 0:
                 dict_residuals[residual] = digit_location
                 digit_array.append(str(new_digit))
                 is_repeating = False
                 break
             elif residual in dict_residuals.keys():
                 digit_array.append(str(new_digit))
                 is_repeating = True
                 break
             else:
                 dict_residuals[residual] = digit_location
                 digit_array.append(str(new_digit))

         if not is_repeating:
             result = str(integer_part)+"."+"".join(digit_array)
         else:
             loc = dict_residuals[residual]
             result = str(integer_part)+"."+"".join(digit_array[0:loc])+"("+"".join(digit_array[loc:])+")"
         if add_negative:
             return "-"+result
         else:
             return result

     def single_digit(self, value, denominator):
         return int((10*value)//denominator), (10*value)%denominator


Solve in Python:
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.  The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval.  For example, the intersection of [1, 3] and [2, 4] is [2, 3].)

Example 1:

Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]

Note:

0 <= A.length < 1000
0 <= B.length < 1000
0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9

class Solution:
    def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:

        self.k1 = None
        self.k2 = None
        self.res2 = []
        def intersections_append2(k: (int, int), v: int):
            k1 = self.k1
            k2 = self.k2
            if k1 is not None and k2 is not None and k[0] == k1 and k[1] == k2:
                if self.res2:
                    self.res2[-1].append(v)
                    if len(self.res2[-1]) > 2:
                        self.res2[-1] = sorted(set(self.res2[-1]))
                else:
                    self.res2.append([v])
            else:
                self.k1 = k[0]
                self.k2 = k[1]
                self.res2.append([v])

        def get_next_items(lft_idx, rgt_idx):
            lft_idx_outer = int(lft_idx / 2)
            lft_idx_inner = lft_idx % 2
            rgt_idx_outer = int(rgt_idx / 2)
            rgt_idx_inner = rgt_idx % 2
            lft = A[lft_idx_outer][lft_idx_inner] if lft_idx_outer < len(A) else None
            rgt = B[rgt_idx_outer][rgt_idx_inner] if rgt_idx_outer < len(B) else None
            lft_full = A[lft_idx_outer] if lft_idx_outer < len(A) else A[lft_idx_outer-1]
            rgt_full = B[rgt_idx_outer] if rgt_idx_outer < len(B) else B[rgt_idx_outer-1]
            return (lft, rgt, lft_full, rgt_full, min(lft_idx_outer, len(A)-1), min(rgt_idx_outer, len(B)-1))

        u = (0, 0)

        if u[0] >= len(A) or u[0] >= len(B):
            return []

        i_a, i_b, next_a2, next_b2, counter_a, counter_b = get_next_items(u[0], u[1])

        redo_step = True

        while not (i_a is None and i_b is None):
            if (i_a is not None and i_b is None) :
                i, u = i_a, (u[0] + 1, u[1])
            elif (i_a is None and i_b is not None):
                i, u = i_b, (u[0], u[1] + 1)
            elif (i_a < i_b):
                i, u = i_a, (u[0] + 1, u[1])
            elif (i_a > i_b):
                i, u = i_b,...


Solve in Python:
Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).

Example 1:
Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].

Constraints:

0 <= low <= high <= 10^9

class Solution:
    def countOdds(self, low: int, high: int) -> int:
        return ((high + 1)>>1) - (low>>1)


Solve in Python:
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

class Solution:
     def addStrings(self, num1, num2):
         """
         :type num1: str
         :type num2: str
         :rtype: str
         """
         if len(num1) < len(num2):
             num1, num2 = num2, num1
         addon = 0
         res = ""
         l = len(num2)
         for i in range(l):
             s =  ord(num2[l - i - 1]) + ord(num1[len(num1) - i - 1]) - 2 * ord("0") + addon
             addon = s // 10
             res = chr(s % 10 + ord("0")) + res
         for i in range(l, len(num1)):
             s = ord(num1[len(num1) - i - 1]) - ord("0") + addon
             addon = s // 10
             res = chr(s % 10 + ord("0")) + res
         if addon > 0:
             res = "1" + res
         return res


Solve in Python:
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

       The length of both num1 and num2 is < 110.
       Both num1 and num2 contain only digits 0-9.
       Both num1 and num2 do not contain any leading zero, except the number 0 itself.
       You must not use any built-in BigInteger library or convert the inputs to integer directly.

class Solution:
     def multiply(self,num1, num2):
         a=['0','1','2','3','4','5','6','7','8','9']
         z=0
         x=0
         for i,element in enumerate(num1):
             for j in range(10):
                 if element==a[j]:
                     z+=j*(10**(len(num1)-i-1))

         for c,b in enumerate(num2):
             for k in range(10):
                 if b==a[k]:
                     x+=k*(10**(len(num2)-c-1))
         mul=z*x
         return(''.join('%d'%mul))


Solve in Python:
Given two numbers (m and n) :

- convert all numbers from m to n to binary
- sum them as if they were in base 10
- convert the result to binary
- return as string

Eg: with the numbers 1 and 4

   1 // 1 to binary is 1
+ 10 // 2 to binary is 10
+ 11 // 3 to binary is 11
+100 // 4 to binary is 100
----
 122 // 122 in Base 10 to Binary is 1111010

So BinaryPyramid ( 1 , 4 ) should return "1111010"

range should be ascending in order

def binary_pyramid(m,n):
    return bin(sum(eval(bin(i)[2:]) for i in range(m, n+1)))[2:]


Solve in Python:
Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them.

```a``` and ```b``` will both be positive integers, and ```a``` will always be the first number in the operation, and ```b``` always the second.

The four operators are "add", "subtract", "divide", "multiply".

A few examples:

``` javascript
ArithmeticFunction.arithmetic(5, 2, "add")      => returns 7
ArithmeticFunction.arithmetic(5, 2, "subtract") => returns 3
ArithmeticFunction.arithmetic(5, 2, "multiply") => returns 10
ArithmeticFunction.arithmetic(5, 2, "divide")   => returns 2
```

Try to do it without using if statements!

def arithmetic(a, b, operator):
    op = {
        'add': '+',
        'subtract': '-',
        'multiply': '*',
        'divide': '/'
    }
    return eval("{} {} {}".format(a, op[operator], b))


Solve in Python:
Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand.

Example 1:

Input: hour = 12, minutes = 30
Output: 165

Example 2:

Input: hour = 3, minutes = 30
Output: 75

Example 3:

Input: hour = 3, minutes = 15
Output: 7.5

Example 4:
Input: hour = 4, minutes = 50
Output: 155

Example 5:
Input: hour = 12, minutes = 0
Output: 0

Constraints:

1 <= hour <= 12
0 <= minutes <= 59
Answers within 10^-5 of the actual value will be accepted as correct.

class Solution:
    def angleClock(self, hour: int, minutes: int) -> float:
        angle_per_min = 360/(60)
        angle_per_5_min = 5*angle_per_min

        h = hour%12 + minutes/60
        hr_angle = h*angle_per_5_min
        min_angle = minutes*angle_per_min

        # print(f'h={h}, minutes={minutes}, hr_angle={hr_angle}, min_angle={min_angle}')
        r = abs(hr_angle-min_angle)
        return min(360-r, r)


Solve in Python:
Given two numbers: 'left' and 'right' (1 <= 'left' <= 'right' <= 200000000000000)
return sum of all '1' occurencies in binary representations of numbers between 'left' and 'right' (including both)

```
Example:
countOnes 4 7 should return 8, because:
4(dec) = 100(bin), which adds 1 to the result.
5(dec) = 101(bin), which adds 2 to the result.
6(dec) = 110(bin), which adds 2 to the result.
7(dec) = 111(bin), which adds 3 to the result.
So finally result equals 8.
```
WARNING: Segment may contain billion elements, to pass this kata, your solution cannot iterate through all numbers in the segment!

def countOnesFromZero(num):
    l = sorted([i for i, v in enumerate(bin(num)[2:][::-1]) if v == '1'], reverse=True)
    l.append(0)
    return sum(i * 2**v + v * 2**(v-1) for i, v in enumerate(l))

def countOnes(left, right):
    # Your code here!
    return countOnesFromZero(right) - countOnesFromZero(left) + bin(left).count('1')


Solve in Python:
Given two positive integers n and k.
A factor of an integer n is defined as an integer i where n % i == 0.
Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.

Example 1:
Input: n = 12, k = 3
Output: 3
Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.

Example 2:
Input: n = 7, k = 2
Output: 7
Explanation: Factors list is [1, 7], the 2nd factor is 7.

Example 3:
Input: n = 4, k = 4
Output: -1
Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.

Example 4:
Input: n = 1, k = 1
Output: 1
Explanation: Factors list is [1], the 1st factor is 1.

Example 5:
Input: n = 1000, k = 3
Output: 4
Explanation: Factors list is [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500, 1000].

Constraints:

1 <= k <= n <= 1000

class Solution:
    def kthFactor(self, n, k):

        solution_space = list([x for x in list(range(1,n+1)) if n % x == 0])
        if len(solution_space) < k:
            return -1
        else:
            return list([x for x in list(range(1,n+1)) if n % x == 0])[k-1]


Solve in Python:
Given two positive integers n and k, the binary string  Sn is formed as follows:

S1 = "0"
Si = Si-1 + "1" + reverse(invert(Si-1)) for i > 1

Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).
For example, the first 4 strings in the above sequence are:

S1 = "0"
S2 = "011"
S3 = "0111001"
S4 = "011100110110001"

Return the kth bit in Sn. It is guaranteed that k is valid for the given n.

Example 1:
Input: n = 3, k = 1
Output: "0"
Explanation: S3 is "0111001". The first bit is "0".

Example 2:
Input: n = 4, k = 11
Output: "1"
Explanation: S4 is "011100110110001". The 11th bit is "1".

Example 3:
Input: n = 1, k = 1
Output: "0"

Example 4:
Input: n = 2, k = 3
Output: "1"

Constraints:

1 <= n <= 20
1 <= k <= 2n - 1

class Solution:
    def findKthBit(self, n: int, k: int) -> str:
        def reverse_invert(array: List[str]) -> List[str]:
            res = []
            for ind in range(len(array)-1, -1, -1):
                res.append('1' if array[ind] == '0' else '0')
            return res

        bits = ['0']
        for curr in range(2, n+1):
            bits += ['1'] + reverse_invert(bits)
        return bits[k-1]


Solve in Python:
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.

Constraints:

0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.

class Solution:
    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
        pushed.reverse()
        popped.reverse()

        stack = []
        while pushed:
            value = pushed.pop()
            stack.append(value)
            while stack and popped and stack[-1] == popped[-1]:
                popped.pop()
                stack.pop()

        if not pushed and not popped:
            return True
        return False


Solve in Python:
Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad".

Example 1:
Input: A = "ab", B = "ba"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.

Example 2:
Input: A = "ab", B = "ab"
Output: false
Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.

Example 3:
Input: A = "aa", B = "aa"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.

Example 4:
Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true

Example 5:
Input: A = "", B = "aa"
Output: false

Constraints:

0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist of lowercase letters.

class Solution:
    def buddyStrings(self, A: str, B: str) -> bool:
        count_A = {}
        doubled = False
        for i,a in enumerate(A):
            if a not in count_A:
                count_A[a] = set()
            else:
                doubled = True
            count_A[a].add(i)
        off = 0
        for i,b in enumerate(B):
            if b not in count_A:
                return False
            else:
                if i in count_A[b]:
                    count_A[b].remove(i)
                    if not count_A[b]:
                        del count_A[b]
                else:
                    off += 1
                    if off > 2:
                        return False
        return doubled or off == 2


Solve in Python:
Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.

For example, with A = "abcd" and B = "cdabcdab".

Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").

Note:
The length of A and B will be between 1 and 10000.

class Solution:
     def repeatedStringMatch(self, A, B):

         times = 1
         tmp = A
         if (not set(B).issubset(set(A))):
             return -1
         maxTime = math.ceil(len(B) / len(A))
         while True:
             if B in A:
                 break
             elif (times <= maxTime):
                 A += tmp
                 times += 1
             else:
                 return -1
         return times


Solve in Python:
Given two strings S and T, each of which represents a non-negative rational number, return True if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
In general a rational number can be represented using up to three parts: an integer part, a non-repeating part, and a repeating part. The number will be represented in one of the following three ways:

<IntegerPart> (e.g. 0, 12, 123)
<IntegerPart><.><NonRepeatingPart>  (e.g. 0.5, 1., 2.12, 2.0001)
<IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> (e.g. 0.1(6), 0.9(9), 0.00(1212))

The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets.  For example:
1 / 6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)
Both 0.1(6) or 0.1666(6) or 0.166(66) are correct representations of 1 / 6.

Example 1:
Input: S = "0.(52)", T = "0.5(25)"
Output: true
Explanation:
Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number.

Example 2:
Input: S = "0.1666(6)", T = "0.166(66)"
Output: true

Example 3:
Input: S = "0.9(9)", T = "1."
Output: true
Explanation:
"0.9(9)" represents 0.999999999... repeated forever, which equals 1.  [See this link for an explanation.]
"1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".

Note:

Each part consists only of digits.
The <IntegerPart> will not begin with 2 or more zeros.  (There is no other restriction on the digits of each part.)
1 <= <IntegerPart>.length <= 4
0 <= <NonRepeatingPart>.length <= 4
1 <= <RepeatingPart>.length <= 4

import math
class Solution:
    def isRationalEqual(self, S: str, T: str) -> bool:
        if len(S) == 0 or len(T) == 0:
            return False
        def process(s):
            if s[-1] == '.':
                s = s[:-1]
            stack, repeat_9 = [], False
            for i, x in enumerate(s):
                if x != ')':
                    stack.append(x)
                else:
                    tmp = ''
                    while stack[-1] != '(':
                        tmp += stack.pop()
                    if len(tmp) == tmp.count('9'):
                        repeat_9 = True
                    stack.pop()
                    return ''.join(stack) + tmp[::-1] * (24 // len(tmp)), repeat_9
            return ''.join(stack), repeat_9

        x, y = process(S), process(T)
        if x[0].count('.') == 0 or y[0].count('.') == 0:
            return float(x[0]) == float(y[0])
        l = max(len(x[0]), len(y[0]))
        if x[0][:17] == y[0][:17]:
            return True
        if x[1] or y[1]:
            m = min(len(x[0].split('.')[1]), len(y[0].split('.')[1]))
            if round(float(x[0]), m) == round(float(y[0]), m):
                return True

        return False