Solve in Python:
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.

Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"

Constraints:

1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.

class Solution:
    def removeDuplicates(self, s: str, k: int) -> str:

        ret = list(s)

        while True:
            s = ret
            ret = []
            ac = 1
            for c in s:
                if not ret or ret[-1] != c:
                    ac = 1
                    ret.append(c)
                else:
                    if ac + 1 == k:
                        while ac:
                            ret.pop()
                            ac -= 1
                    else:
                        ret.append(c)
                        ac += 1
                # print(ret, ac)
            if len(ret) == len(s):
                break

        return ''.join(ret)


Solve in Python:
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.

Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.

Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].

Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.

Constraints:

1 <= s.length <= 16

s contains only lower case English letters.

class Solution:
    def maxUniqueSplit(self, s: str) -> int:
        # dp = [[\"\"] for _ in range(len(s))]
        # dp[0] = [s[0]]
        # for i in range(1, len(s)):
        #     maxnum_ = 1
        #     for j in range(i):
        #         if s[j+1:i] not in dp[j]:
        #             maxnum = len(dp[j]) + 1
        #             if maxnum > maxnum_:
        #                 maxnum_ = maxnum
        #                 dp[i] = dp[j].copy()
        #                 dp[i].append(s[j+1:i])
        # print(dp)
        # return len(dp[len(s)-1])
#         return len(self.maxUniqueSplit_(s, len(s)-1)[-1])

#     @lru_cache
#     def maxUniqueSplit_(self, s, i):
#         if i == 0:
#             return [[s[i]]]
#         else:
#             max_ = 0
#             toreturn = []
#             for j in range(i):
#                 maxUniqueSplit_j = self.maxUniqueSplit_(s, j)
#                 for uniquesplit_j in maxUniqueSplit_j:
#                     if s[j+1:i+1] not in uniquesplit_j:
#                         if len(uniquesplit_j) + 1 > max_:
#                             toreturn = [uniquesplit_j + [s[j+1:i+1]]]
#                             max_ = len(uniquesplit_j) + 1
#                         elif len(uniquesplit_j) + 1 == max_:
#                             toreturn.append(uniquesplit_j + [s[j+1:i+1]])
#                     if j == i - 1 and len(toreturn) == 0:
#                         toreturn = [uniquesplit_j]
#             print(toreturn, i)
#             return toreturn
        if len(s) == 1:
            return 1
        def splitter(str):
            for i in range(1, len(str)):
                start = str[0:i]
                end = str[i:]
                yield (start, end)
                for split in splitter(end):
                    result = [start]
                    result.extend(split)
                    yield result

        maxnum = 0
        for split in splitter(s):
            if len(set(split)) == len(split):
                maxnum = max(len(split), maxnum)
      ...


Solve in Python:
Given a string s containing only lower case English letters and the '?' character, convert all the '?' characters into lower case letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters.
It is guaranteed that there are no consecutive repeating characters in the given string except for '?'.
Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints.

Example 1:
Input: s = "?zs"
Output: "azs"
Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs".
Example 2:
Input: s = "ubv?w"
Output: "ubvaw"
Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww".

Example 3:
Input: s = "j?qg??b"
Output: "jaqgacb"

Example 4:
Input: s = "??yw?ipkj?"
Output: "acywaipkja"

Constraints:

1 <= s.length <= 100
s contains only lower case English letters and '?'.

class Solution:
    def modifyString(self, s: str) -> str:
        r = ''

        if s[0] == '?':
            r += 'b' if (len(s) > 1 and s[1] == 'a') else 'a'
        else:
            r += s[0]

        for i in range(1, len(s) - 1):
            if s[i] == '?':
                if r[i - 1] != 'a' and s[i + 1] != 'a':
                    r += 'a'
                elif r[i - 1] != 'b' and s[i + 1] != 'b':
                    r += 'b'
                else:
                    r += 'c'
            else:
                r += s[i]

        if len(s) > 1:
            if s[len(s) - 1] == '?':
                r += 'b' if r[len(s) - 2] == 'a' else 'a'
            else:
                r += s[len(s) - 1]

        return r


Solve in Python:
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.

Example 1:

Input: text = "nlaebolko"
Output: 1

Example 2:

Input: text = "loonbalxballpoon"
Output: 2

Example 3:
Input: text = "leetcode"
Output: 0

Constraints:

1 <= text.length <= 10^4
text consists of lower case English letters only.

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        count_balloon = 0

        count_b = 0
        count_a = 0
        count_l = 0
        count_o = 0
        count_n = 0

        for char in text:
            if(char == 'b'):
                count_b += 1
            elif(char == 'a'):
                count_a += 1
            elif(char == 'l'):
                count_l += 1
            elif(char == 'o'):
                count_o += 1
            elif(char == 'n'):
                count_n += 1

        count_balloon =  min(count_b, count_a, count_l // 2, count_o // 2, count_n)
        return count_balloon


Solve in Python:
Given a time in AM/PM format as a string, convert it to military (24-hour) time as a string.

Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock

Sample Input: 07:05:45PM
Sample Output: 19:05:45

Try not to use built in DateTime libraries.

For more information on military time, check the wiki https://en.wikipedia.org/wiki/24-hour_clock#Military_time


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

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

find the triangle's row knowing its index (the rows are 1-indexed), e.g.:

```
odd_row(1)  ==  [1]
odd_row(2)  ==  [3, 5]
odd_row(3)  ==  [7, 9, 11]
```

**Note**: your code should be optimized to handle big inputs.

___

The idea for this kata was taken from this kata: [Sum of odd numbers](https://www.codewars.com/kata/sum-of-odd-numbers)

def odd_row(n):
    return list(range(n**2 - n + 1, n**2 + n, 2))


Solve in Python:
Given a triplet of integers (X , Y , Z), such that X ≤ Y and Y ≥ Z, we define f(X , Y , Z) to be (X + Y) * (Y + Z). If either X > Y or Y < Z, or both, then f(X , Y , Z) is defined to be 0.
You are provided three arrays  A , B and C   of any length (their lengths may or may not be equal).
Your task is to find the sum of f(X , Y , Z) over all triplets (X, Y , Z) where   X, Y and Z  belong to  A, B and C respectively.
Output your sum for each test case modulo 1000000007.

-----Input-----
- The first line contains a single integer, T, which is the number of test cases. The description of each testcase follows:
- The first line of each testcase contains 3 integers: p, q and r. These denote the lengths of A,B and C respectively.
- The second line contains p integers, which are the elements of A
- The third line contains q integers, which are the elements of B
- The fourth line contains r integers, which are the elements of C

-----Output-----
Output the required sum modulo  1000000007  for each test case in a new line.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ p, q, r ≤ 100000
- 1 ≤ every array element ≤ 1000000000

-----Subtasks  -----
- Subtask #1 (30 points): 1 ≤ p,q,r  ≤ 100
- Subtask #2 (70 points): 1 ≤ p,q,r  ≤ 100000

-----Example : -----
Input:
1
3 1 3
1 2 3
5
4 5 6

Output:
399

-----Explanation: -----
As there is only one choice for Y which equals to 5, to get a non-zero function value,we can choose any element for X from the set { 1 , 2 , 3 } and for Z from the set { 4  , 5 }
So triplets which give non-zero function values are:
{ 1 , 5  , 4 } :  ( 1 + 5 ) * ( 5 + 4 )  = 54
{ 1 , 5  , 5 } :  ( 1 + 5 ) * ( 5 + 5 )  = 60
{ 2 , 5  , 4 } :  ( 2 + 5 ) * ( 5 + 4 )  = 63
{ 2 , 5  , 5 } :  ( 2 + 5 ) * ( 5 + 5 )  = 70
{ 3 , 5  , 4 } :  ( 3 + 5 ) * ( 5 + 4 )  = 72
{ 3 , 5  , 5 } :  ( 3 + 5 ) * ( 5 + 5 )  = 80
Final answer : 54 + 60 + 63 + 70 + 72 + 80  = 399

testcases = int(input())
while testcases > 0:
    array_length = list(map(int,input().split()))
    array1 = list(map(int,input().split()))
    array2 = list(map(int, input().split()))
    array3 = list(map(int, input().split()))
    sum = 0
    for i in range(array_length[0]):
        for j in range(array_length[1]):
            for k in range(array_length[2]):
                if array1[i] <= array2[j] and array2[j] >= array3[k] :
                    sum = (sum + (((array1[i] + array2[j])%1000000007 )*((array2[j]+array3[k]) % 1000000007))) % 1000000007
    testcases -= 1
    print(sum%1000000007)


Solve in Python:
Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".

Example 1:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"

Constraints:

The given address is a valid IPv4 address.

class Solution:
    def defangIPaddr(self, address: str) -> str:
        new_string =''
        for s in address:
            if s =='.':
                new_string+='[.]'
            else:
                new_string+=s
        return new_string


Solve in Python:
Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:

Given an integer array cuts where cuts[i] denotes a position you should perform a cut at.
You should perform the cuts in order, you can change the order of the cuts as you wish.
The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.
Return the minimum total cost of the cuts.

Example 1:

Input: n = 7, cuts = [1,3,4,5]
Output: 16
Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:

The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.
Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).
Example 2:
Input: n = 9, cuts = [5,6,1,4,2]
Output: 22
Explanation: If you try the given cuts ordering the cost will be 25.
There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.

Constraints:

2 <= n <= 10^6
1 <= cuts.length <= min(n - 1, 100)
1 <= cuts[i] <= n - 1
All the integers in cuts array are distinct.

class Solution:
    def minCost(self, n: int, cuts: List[int]) -> int:
        return self.dp(0, n, cuts, dict())

    def dp(self, i, j, cuts, memo):
        if (i, j) not in memo:
            minV = float('inf')
            for k in cuts:
                if k > i and k < j: # Valid cutting point
                    l, r = self.dp(i, k, cuts, memo), self.dp(k, j, cuts, memo)
                    minV = min(minV, l+r)
            if minV != float('inf'):
                memo[(i, j)] = minV+j-i
            else:
                memo[(i, j)] = 0
        return memo[(i, j)]


Solve in Python:
Given a word, you need to judge whether the usage of capitals in it is right or not.

We define the usage of capitals in a word to be right when one of the following cases holds:

All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital if it has more than one letter, like "Google".

Otherwise, we define that this word doesn't use capitals in a right way.

Example 1:

Input: "USA"
Output: True

Example 2:

Input: "FlaG"
Output: False

Note:
The input will be a non-empty word consisting of uppercase and lowercase latin letters.

class Solution:
     def detectCapitalUse(self, word):
         """
         :type word: str
         :rtype: bool
         """
         if len(word) == 0:
             return True
         elif word.isupper() or word.islower():
             return True
         elif len(word) > 1:
             return word.istitle()
         else:
             return False


Solve in Python:
Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.
Return the reformatted string or return an empty string if it is impossible to reformat the string.

Example 1:
Input: s = "a0b1c2"
Output: "0a1b2c"
Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.

Example 2:
Input: s = "leetcode"
Output: ""
Explanation: "leetcode" has only characters so we cannot separate them by digits.

Example 3:
Input: s = "1229857369"
Output: ""
Explanation: "1229857369" has only digits so we cannot separate them by characters.

Example 4:
Input: s = "covid2019"
Output: "c2o0v1i9d"

Example 5:
Input: s = "ab123"
Output: "1a2b3"

Constraints:

1 <= s.length <= 500
s consists of only lowercase English letters and/or digits.

class Solution:
    def reformat(self, s: str) -> str:
        chars = []
        nums = []
        for i in s:
            try:
                nums.append(int(i))
            except ValueError:
                chars.append(i)
        if abs(len(nums)-len(chars)) > 1:
            return ''

        out = [0]*len(s)
        if len(nums) >= len(chars):
            out[::2], out[1::2] = nums, chars
        else:
            out[::2], out[1::2] = chars,nums

        return ''.join([str(i) for i in out])


Solve in Python:
Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:

You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.

Example:
X..X
...X
...X

In the above board there are 2 battleships.

Invalid Example:
...X
XXXX
...X

This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

Follow up:Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?

class Solution:
     def countBattleships(self, board):
         """
         :type board: List[List[str]]
         :rtype: int
         """
         num=0

         record=[(-1,-1)]

         colnum=0
         for i in board:
             rownum=0
             cont=0
             for j in i:

                 if j=="X":
                       if (cont==1):
                             rownum+=1
                             continue
                       else:
                              ind=0
                              for k in record:
                                   a,b=k
                                   if (a==colnum)&(b==rownum):
                                     ind=1
                                     record.append((a+1,b))
                                     record.remove((a,b))
                                     break

                              if (ind==0):
                                     num=num+1
                                     record.append((colnum+1,rownum))
                                     cont=1
                 if j!="X":
                     cont=0
                 rownum+=1

             colnum+=1

         return num


Solve in Python:
Given an Array and an Example-Array to sort to, write a function that sorts the Array following the Example-Array.

Assume Example Array catalogs all elements possibly seen in the input Array. However, the input Array does not necessarily have to have all elements seen in the Example.

Example:

Arr:
[1,3,4,4,4,4,5]

Example Arr:
[4,1,2,3,5]

Result:
[4,4,4,4,1,3,5]

def example_sort(arr, example_arr):
    d = {x: i for i, x in enumerate(example_arr)}
    return sorted(arr, key=d.__getitem__)


Solve in Python:
Given an Array of length  $N$  containing elements $Ai$ ( i = 1 to n ) . You have to handle $Q$ queries on this array . Each Query is of two types k=(1 or 2).
Type 1:- $k$ $l$ $r$ in which you have to tell whether the product of numbers in range l to r results in a perfect square or not. if product of numbers in range $l$ to$r$ is a perfect square then simply output YES else output NO.
Type 2:- $k$ $i$ $val$ Multiply the value present at index $i$ with $val$.
Note#1: 1 based indexing in each query.
Note#2: Values of prime factors of all numbers $val$ and $Ai$ is between 2 to 100 only.

-----Input:-----
- First line will contain $N$, denoting the size of the array. Then the next line follow.
- N integers  $Ai - An$.
- Third line will contain $Q$, denoting the number of queries. Then the next $Q$ lines follow -description of each query.
- Each query consists of either type 1 or type 2 and each query gives you three elements either
-{$k$ $l$ $r$} or {$k$ $i$ $val$}

-----Output:-----
For each  Query of Type 1 Output either "YES" or "NO" Without Quotes.

-----Constraints-----
- $1 \leq N \leq 20000$
- $1 \leq Q \leq 20000$
- $2 \leq Ai \leq 1000000$
- $1 \leq i ,l,r \leq N$
- $1 \leq val \leq 1000000$
- $1 \leq l \leq r$

-----Subtasks-----
Subtask 1 :-40 points
- Values of prime factors of all numbers $val$ and $Ai$ is between 2 to 40 only.
Subtask 2 :- 60 points
- Original Constraints

-----Sample Input:-----
4
2 2 3 4
4
1 1 2
1 3 4
2 3 3
1 1 4

-----Sample Output:-----
YES
NO
YES

-----EXPLANATION:-----
-Query 1 :- product of numbers in range 1 to 2=2 * 2=4 (perfect square so YES)
-Query 2:- product of numbers in range 3 to 4 = 3 * 4 = 12 (not perfect square so NO)
-Query 3:- multiply number at index3 with 3 so number at index 3= 3*3 = 9 .
-Query 4:- product of numbers in range 1 to 4 = 2 * 2 * 9 * 4 = 144 (perfect square so YES)

def update(index, value, bi_tree):
 while index < len(bi_tree):
  bi_tree[index] += value
  index += index & -index

def get_sum(index, bi_tree):
 ans = 0
 while index > 0:
  ans += bi_tree[index]
  index -= index & -index

 return ans

def get_range_sum(left, right, bi_tree):
 ans = get_sum(right, bi_tree) - get_sum(left - 1, bi_tree)
 return ans

def solve(x):
 s = set()
 res = 1
 i = 2
 while (i * i <= x):
  count = 0
  while (x % i == 0):
   x = x // i
   count += 1
  if (count % 2):
   s.add(i)
  i += 1
 if (x > 0):
  s.add(x)
 return s

n = int(input())
l = [0] + [int(i) for i in input().split()]
bit = [[0 for i in range(n + 1)] for i in range(101)]

for i in range(1, n + 1):
 s = solve(l[i])
 for j in s:
  update(i, 1, bit[j])

q = int(input())
for i in range(q):
 k, a, b = [int(i) for i in input().split()]
 if (k == 1):
  f = 1
  for i in range(2, 100):
   res = get_range_sum(a, b, bit[i])
   if (res % 2):
    f = 0
    break
  if (f):
   print("YES")
  else:
   print("NO")
 else:
  s = solve(b)
  for j in s:
   update(a, 1, bit[j])


Solve in Python:
Given an D-dimension array, where each axis is of length N, your goal is to find the sum of every index in the array starting from 0.

For Example if D=1 and N=10 then the answer would be 45 ([0,1,2,3,4,5,6,7,8,9])
If D=2 and N = 3 the answer is 18 which would be the sum of every number in the following:
```python
[
[(0,0), (0,1), (0,2)],
[(1,0), (1,1), (1,2)],
[(2,0), (2,1), (2,2)]
]
```

A naive solution could be to loop over every index in every dimension and add to a global sum. This won't work as the number of dimension is expected to be quite large.

Hint: A formulaic approach would be best
Hint 2: Gauss could solve the one dimensional case in his earliest of years, This is just a generalization.

~~~if:javascript
Note for JS version: Because the results will exceed the maximum safe integer easily, for such values you're only required to have a precision of at least `1 in 1e-9` to the actual answer.
~~~

def super_sum(D, N):
    #Number of possible combinations of D length from set [0...N]
    num = pow(N,D)
    #2x average value of a combination; 2x because dividing results in float and loss of precision
    dblAvg = D*(N-1)
    #Multiply number of possible combinations by the avergae value; now use true division to ensure result is an integer
    return num*dblAvg//2


Solve in Python:
Given an Integer N, write a program to reverse it.

-----Input-----

The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N.

-----Output-----
For each test case, display the reverse of the given number N, in a new line.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 1000000

-----Example-----
Input
4
12345
31203
2123
2300
Output
54321
30213
3212
32

# cook your dish here
t=int(input())
while t>0:
    n=int(input())
    tmp=int(n)
    r=0
    while tmp>0:
        d=int(tmp%10)
        r=int(r*10+d)
        tmp=int(tmp/10)
    print(r)
    t-=1


Solve in Python:
Given an N x N grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized and return the distance.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
If no land or water exists in the grid, return -1.

Example 1:

Input: [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation:
The cell (1, 1) is as far as possible from all the land with distance 2.

Example 2:

Input: [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation:
The cell (2, 2) is as far as possible from all the land with distance 4.

Note:

1 <= grid.length == grid[0].length <= 100
grid[i][j] is 0 or 1

class Solution:
    def maxDistance(self, grid: List[List[int]]) -> int:

        from collections import deque

        queue = deque()
        for i, row in enumerate(grid):
            for j, cell in enumerate(row):
                if cell == 1:
                    queue.append((i, j, None, None))

        dist = {}
        while queue:

            i, j, previ, prevj = queue.popleft()
            if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]):
                continue
            if (i, j) not in dist:
                dist[(i, j)] = 1 + dist.get((previ, prevj), -1)
                # if previ is None and prevj is None:
                #     dist[(i, j)] = 0
                # else:
                #     dist[(i, j)] = 1 + dist[(previ, prevj)]
                for di, dj in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                    newi, newj = i +di, j + dj
                    queue.append((newi, newj, i, j))

        ans = max(list(dist.values()), default=-1)
        return ans if ans != 0 else -1


Solve in Python:
Given an `array` of digital numbers, return a new array of length `number` containing the last even numbers from the original array (in the same order). The original array will be not empty and will contain at least "number" even numbers.

For example:
```
([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) => [4, 6, 8]
([-22, 5, 3, 11, 26, -6, -7, -8, -9, -8, 26], 2) => [-8, 26]
([6, -25, 3, 7, 5, 5, 7, -3, 23], 1) => [6]

```

def even_numbers(array, requiredResultLength):
    return [number for number in array if not number % 2][-requiredResultLength:]


Solve in Python:
Given an `x` and `y` find the smallest and greatest numbers **above** and **below** a given `n` that are divisible by both `x` and `y`.

### Examples
```python
greatest(2, 3, 20) => 18   # 18 is the greatest number under 20 that is divisible by both 2 and 3
smallest(2, 3, 20) => 24   # 24 is the smallest number above 20 that is divisible by both 2 and 3

greatest(5, 15, 100) => 90
smallest(5, 15, 100) => 105

greatest(123, 456, 789) => 0   # there are no numbers under 789 that are divisible by both 123 and 456
smallest(123, 456, 789) => 18696
```

**Notes:**

1. you should never return `n` even if it is divisible by `x` and `y` always the number above or below it
2. `greatest` should return 0 if there are no numbers under `n` that are divisible by both `x` and `y`
3. and all arguments will be valid (integers greater than 0).

### Note for Haskell users

>Please take a look at [bkaes comment](http://www.codewars.com/kata/when-greatest-is-less-than-smallest/discuss#56418f0fbf1f44834d000050) and give us your opinion

import math
def greatest(x, y, n):
    lcm = x*y//math.gcd(x, y)
    return lcm*(n//lcm) if lcm < n else 0

def smallest(x, y, n):
    lcm = x*y//math.gcd(x, y)
    n2 = int(n//lcm)+1
    return lcm*n2


Solve in Python:
Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

Corner Cases:

       Did you consider the case where path = "/../"?
       In this case, you should return "/".
       Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
       In this case, you should ignore redundant slashes and return "/home/foo".

class Solution:
     def simplifyPath(self, path):
         """
         :type path: str
         :rtype: str
         """

         places = [tmp for tmp in path.split("/") if tmp!="." and tmp!=""]
         stack = []
         for name in places:

             if name == "." or name == "":
                 continue
             elif name == "..":
                 if len(stack) > 0:
                     stack.pop()
             else:
                 stack.append(name)

         return "/" + "/".join(stack)


Solve in Python:
Given an alphanumeric string made up of digits and lower case Latin characters only, find the sum of all the digit characters in the string.

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. Then T test cases follow.
- Each test case is described with a single line containing a string S, the alphanumeric string.

-----Output-----
- For each test case, output a single line containing the sum of all the digit characters in that string.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ |S| ≤ 1000, where |S| is the length of the string S.

-----Example-----
Input:
1
ab1231da

Output:
7

-----Explanation-----
The digits in this string are 1, 2, 3 and 1. Hence, the sum of all of them is 7.

t=int(input().strip())
for _ in range(t):
 p = input().strip()
 count=0
 for i in p:
  if not('a'<=i<='z'):
   count+=int(i)
 print(count)


Solve in Python:
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom
note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:
You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

class Solution:
     def canConstruct(self, ransomNote, magazine):
         """
         :type ransomNote: str
         :type magazine: str
         :rtype: bool
         """
         return all(ransomNote.count(i)<=magazine.count(i) for i in set(ransomNote))


Solve in Python:
Given an array $A$ of length $N$.
We have to find the $maximum$ sum of elements of the subarray between $two$ nearest occurrences of $same$ elements (excluding both).
If both the elements are $even$ then the total number of $even$ elements in that subarray should be $even$ then and then only we consider that subarray and if both the elements are $odd$ then the total number of $odd$ element in that subarray should be $odd$ then and then only we consider that subarray.
If the condition never matches print $0$.

-----Input:-----
- First line contains $T$, number of test cases. Then the test cases follow.
- Each testcase consists of two lines:
The first line has $N$ : number of elements in the array and second-line has $N$ space separated integers: elements of the array.

-----Output:-----
- For each test case, output in a single line $maximum$ sum.

-----Constraints-----
- $1 \leq T \leq 10$
- $3 \leq N \leq 2*10^5$
- $1 \leq A[i] \leq 10^8$
$NOTE $: Use of Fast Input Output is recommended.

-----Sample Input:-----
1
10
1 2 3 2 1 5 1 2 8 2

-----Sample Output:-----
7

-----EXPLANATION:-----
The maximum sum is 7, between 1 at  1st position and 1 at 5th position i.e sum of 2,3,2

t=int(input())
while t!=0:
    t-=1
    n=int(input())
    li=list(map(int,input().split()))
    odd=[0]*n
    eve=[0]*n
    su=[0]*n
    ans=0
    x=0
    o=0
    e=0
    dic={}
    for i in range(n):
        x+=li[i]
        su[i]=x
        if li[i] not in dic:
            dic[li[i]]=[]
            dic[li[i]].append(i)
        else:
            dic[li[i]].append(i)
        if li[i]%2==0:
            e+=1
        else:
            o+=1
        eve[i]=e
        odd[i]=o
    for j in dic:
        if len(dic[j])==1:
            continue
        else:
            for o in range(0,len(dic[j])-1):
                fir=dic[j][o]
                sec=dic[j][o+1]
                if j%2==0:
                    if (eve[sec-1]-eve[fir])%2==0:
                        jk=su[sec-1]-su[fir]

                        if jk>ans:
                            ans=jk
                else:
                    if (odd[sec-1]-odd[fir])%2!=0 and (odd[sec-1]!=0 or odd[fir]!=0):
                        jk=su[sec-1]-su[fir]

                        if jk>ans:
                            ans=jk
    print(ans)


Solve in Python:
Given an array $A$ of size $N$ , count number of pairs of index $i,j$ such that $A_i$ is even, $A_j$ is odd and $i < j$

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases.
- The first line of each test case contains integer $N$.
- The second line of each test case contains $N$ space separated integers $A_i$.

-----Output-----
For each test case, print a single line containing an integer denoting number of pairs.

-----Constraints-----
- $1 \le T \le 100$
- $2 \le N \le 10^5$
- $1 \le A_i \le 10^9$
- Sum of $N$ over all test cases doesn't exceed $10^6 $

-----Subtasks-----
Subtask #1 (30 points):
- $2 \le N \le 100$
Subtask #2 (70 points): original constraints

-----Example Input-----
2
4
1 2 1 3
5
5 4 1 2 3

-----Example Output-----
2
3

-----Explanation-----
Example case 1:$(A_2,A_3)$ and $(A_2,A_4)$ .
Example case 2:$(A_2,A_3)$ , $(A_2,A_5)$ and $(A_4,A_5)$  .

t=int(input())
for i in range(t):
 n=int(input())
 ans=0
 a=list(map(int,input().split()))
 for j in range(len(a)-1):
  for k in range(j+1,len(a)):
   if j<k and a[j]%2==0 and a[k]%2!=0:
    ans+=1
 print(ans)


Solve in Python:
Given an array $A_1, A_2, ..., A_N$, count the number of subarrays of array $A$ which are non-decreasing.

A subarray $A[i, j]$, where $1 ≤ i ≤ j ≤ N$ is a sequence of integers $A_i, A_i+1, ..., A_j$.
A subarray $A[i, j]$ is non-decreasing if $A_i ≤ A_i+1 ≤ A_i+2 ≤ ... ≤ A_j$. You have to count the total number of such subarrays.

-----Input-----
-
The first line of input contains an integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
-
The first line of each test case contains a single integer $N$ denoting the size of array.
-
The second line contains $N$ space-separated integers $A_1$, $A_2$, …, $A_N$ denoting the elements of the array.

-----Output-----
For each test case, output in a single line the required answer.

-----Constraints-----
- $1 ≤ T ≤ 5$
- $1 ≤ N ≤ 10^5$
- $1 ≤ A_i ≤ 10^9$

-----Subtasks-----
- Subtask 1 (20 points) : $1 ≤ N ≤ 100$
- Subtask 2 (30 points) : $1 ≤ N ≤ 1000$
- Subtask 3 (50 points) : Original constraints

-----Sample Input:-----
2
4
1 4 2 3
1
5

-----Sample Output:-----
6
1

-----Explanation-----
Example case 1.

All valid subarrays are $A[1, 1], A[1, 2], A[2, 2], A[3, 3], A[3, 4], A[4, 4]$.

Note that singleton subarrays are identically non-decreasing.
Example case 2.

Only single subarray $A[1, 1]$ is non-decreasing.

import math
for _ in range(int(input())):
 n=int(input())
 a=list(map(int,input().split()))
 c=1
 m=[]
 for i in range(n-1):
  if a[i]<=a[i+1]:
   c+=1
  else:
   m.append(c)
   c=1
 if c!=0:
  m.append(c)
 z=n
 for i in m:
  z+=i*(i-1)//2
 print(z)


Solve in Python:
Given an array (a list in Python) of integers and an integer `n`, find all occurrences of `n` in the given array and return another array containing all the index positions of `n` in the given array.

If `n` is not in the given array, return an empty array `[]`.

Assume that `n` and all values in the given array will always be integers.

Example:
```python
find_all([6, 9, 3, 4, 3, 82, 11], 3)
> [2, 4]
```

def find_all(array, n):
    l = []
    for i,v in enumerate(array):
        if v == n:
            l.append(i)
    return l


Solve in Python:
Given an array (arr) as an argument complete the function `countSmileys` that should return the total number of smiling faces.

Rules for a smiling face:
- Each smiley face must contain a valid pair of eyes. Eyes can be marked as `:` or `;`
- A smiley face can have a nose but it does not have to. Valid characters for a nose are `-` or `~`
- Every smiling face must have a smiling mouth that should be marked with either `)` or `D`

No additional characters are allowed except for those mentioned.

**Valid smiley face examples:** `:) :D ;-D :~)`
**Invalid smiley faces:**  `;( :> :} :]`

## Example

```
countSmileys([':)', ';(', ';}', ':-D']);       // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']);     // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
```

## Note

In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same.

from re import findall
def count_smileys(arr):
    return len(list(findall(r"[:;][-~]?[)D]", " ".join(arr))))


Solve in Python:
Given an array (ints) of n integers, find three integers in arr such that the sum is closest to a given number (num), target.

Return the sum of the three integers.
You may assume that each input would have exactly one solution.

Example:

Note: your solution should not modify the input array.

from itertools import combinations

def closest_sum(ints, num):
    return min(map(sum, combinations(ints, 3)), key=lambda x: abs(x - num))


Solve in Python:
Given an array (or list or vector) of arrays (or, guess what, lists or vectors) of integers, your goal is to return the sum of a specific set of numbers, starting with elements whose position is equal to the main array length and going down by one at each step.

Say for example the parent array (etc, etc) has 3 sub-arrays inside: you should consider the third  element of the first sub-array, the second of the second array and the first element in the third one: `[[3, 2, 1, 0], [4, 6, 5, 3, 2], [9, 8, 7, 4]]` would have you considering `1` for `[3, 2, 1, 0]`, `6` for `[4, 6, 5, 3, 2]` and `9` for `[9, 8, 7, 4]`, which sums up to `16`.

One small note is that not always each sub-array will have enough elements, in which case you should then use a default value (if provided) or `0` (if not provided), as shown in the test cases.

def elements_sum(arr, d=0):
    count = len(arr)
    result = 0
    for i in arr:
        if len(i) >= count:
            result += i[count-1]
        else:
            result += d
        count -= 1
    return result


Solve in Python:
Given an array (or list) of scores, return the array of _ranks_ for each value in the array.  The largest value has rank 1, the second largest value has rank 2, and so on. Ties should be handled by assigning the same rank to all tied values. For example:

    ranks([9,3,6,10]) = [2,4,3,1]

and

    ranks([3,3,3,3,3,5,1]) = [2,2,2,2,2,1,7]

because there is one 1st place value, a five-way tie for 2nd place, and one in 7th place.

def ranks(a):
    rankarr = [None] + sorted(a)[::-1]
    return [rankarr.index(x) for x in a]


Solve in Python:
Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j].  The width of such a ramp is j - i.
Find the maximum width of a ramp in A.  If one doesn't exist, return 0.

Example 1:
Input: [6,0,8,2,1,5]
Output: 4
Explanation:
The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5.

Example 2:
Input: [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation:
The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.

Note:

2 <= A.length <= 50000
0 <= A[i] <= 50000

class Solution:
    def maxWidthRamp(self, A: List[int]) -> int:
        n = len(A)
        minLeft, maxRight = [A[0]] * n, [A[-1]] * n
        for i in range(1, n):
            minLeft[i] = min(minLeft[i - 1], A[i])
            maxRight[n - i - 1] = max(maxRight[n - i], A[n - i - 1])
        i = j = n - 1
        res = 0
        while i >= 0 and j >= 0:
            if minLeft[i] <= maxRight[j]:
                res = max(res, j - i)
                i -= 1
            else:
                j -= 1
        return res


Solve in Python:
Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].
After this process, we have some array B.
Return the smallest possible difference between the maximum value of B and the minimum value of B.

Example 1:
Input: A = [1], K = 0
Output: 0
Explanation: B = [1]

Example 2:
Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]

Example 3:
Input: A = [1,3,6], K = 3
Output: 0
Explanation: B = [3,3,3] or B = [4,4,4]

Note:

1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000

class Solution:
    def smallestRangeI(self, A: List[int], K: int) -> int:
        return max(0, max(A)-min(A)-2*K)


Solve in Python:
Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once).
After this process, we have some array B.
Return the smallest possible difference between the maximum value of B and the minimum value of B.

Example 1:
Input: A = [1], K = 0
Output: 0
Explanation: B = [1]

Example 2:
Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]

Example 3:
Input: A = [1,3,6], K = 3
Output: 3
Explanation: B = [4,6,3]

Note:

1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000

class Solution:
    def smallestRangeII(self, A: List[int], K: int) -> int:

        A.sort()

        min_diff=A[-1]-A[0]

        for i in range(len(A)-1):
            #vs=[A[0]+K,A[i]+K,A[i+1]-K,A[-1]-K]

            v_min=min(A[0]+K,A[i+1]-K)
            v_max=max(A[i]+K,A[-1]-K)

            min_diff=min(min_diff,max(v_min,v_max)-min(v_min,v_max))

        return min_diff


Solve in Python:
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).

Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.

Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].

Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].

Constraints:

2 <= A.length <= 1000
0 <= A[i] <= 500

class Solution:
    def longestArithSeqLength(self, A: List[int]) -> int:
        dp = {}
        for i in range(len(A)):
            for j in range(i+1,len(A)):
                diff = A[j]-A[i]
                dp[j,diff] = dp.get((i,diff),1)+1
        return max(dp.values())


Solve in Python:
Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.

Example 1:
Input: A = [4,5,0,-2,-3,1], K = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by K = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]

Note:

1 <= A.length <= 30000
-10000 <= A[i] <= 10000
2 <= K <= 10000

class Solution:
    def subarraysDivByK(self, A: List[int], K: int) -> int:
        mod_count = Counter({0:1})

        ans = 0
        for s in [*accumulate(A)]:
            m = s % K
            if m in mod_count:
                ans += mod_count[m]
            mod_count[m] += 1
        return ans


Solve in Python:
Given an array A of integers, return true if and only if it is a valid mountain array.
Recall that A is a mountain array if and only if:

A.length >= 3
There exists some i with 0 < i < A.length - 1 such that:

A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[A.length - 1]

Example 1:
Input: [2,1]
Output: false

Example 2:
Input: [3,5,5]
Output: false

Example 3:
Input: [0,3,2,1]
Output: true

Note:

0 <= A.length <= 10000
0 <= A[i] <= 10000

class Solution:
    def validMountainArray(self, A: List[int]) -> bool:
        if len(A) <= 2:
            return False
        i = 0
        N = len(A)
        while i < N and i+1<N and A[i] < A[i+1]:
            i+=1
        if i ==0 or i ==N-1:
            return False
        while i<N and i+1<N and A[i] > A[i+1]:
            i+=1
        if i==N-1:
            return True
        return False


Solve in Python:
Given an array A of length N, your task is to find the element which repeats in A maximum number of times as well as the corresponding count. In case of ties, choose the smaller element first.

-----Input-----
First line of input contains an integer T, denoting the number of test cases. Then follows description of T cases. Each case begins with a single integer N, the length of A. Then follow N space separated integers in next line.  Assume that 1 <= T <= 100, 1 <= N <= 100 and for all i in [1..N] : 1 <= A[i] <= 10000

-----Output-----
For each test case, output two space separated integers V & C. V is the value which occurs maximum number of times and C is its count.

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

Output:
2 2
1 3

Description:
In first case 2 occurs twice whereas all other elements occur only once.
In second case, both 1 and 2 occur 3 times but 1 is smaller than 2.

def solve():
	N = int(input())
	V = [0] * 10001
	I = list(map(int,input().split()))
	for i in I:
		V[i] += 1
	Ans = 0
	for i in range(len(V)):
		if V[i] > V[Ans]:
			Ans = i
	print(Ans , V[Ans])

def main():
	t = int(input())
	for i in range(t):
		solve()

main()


Solve in Python:
Given an array A of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengths L and M.  (For clarification, the L-length subarray could occur before or after the M-length subarray.)
Formally, return the largest V for which V = (A[i] + A[i+1] + ... + A[i+L-1]) + (A[j] + A[j+1] + ... + A[j+M-1]) and either:

0 <= i < i + L - 1 < j < j + M - 1 < A.length, or
0 <= j < j + M - 1 < i < i + L - 1 < A.length.

Example 1:
Input: A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
Output: 20
Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.

Example 2:
Input: A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2
Output: 29
Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.

Example 3:
Input: A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3
Output: 31
Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [3,8] with length 3.

Note:

L >= 1
M >= 1
L + M <= A.length <= 1000
0 <= A[i] <= 1000

from functools import reduce

class Solution:

    def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:

        lsum = []

        csum = reduce(lambda a,b:a+b, A[:L])
        lsum.append(csum)

        for i in range(L, len(A)):
            csum += A[i] - A[i-L]
            lsum.append(csum)

        msum = []
        csum = reduce(lambda a,b:a+b, A[:M])

        msum.append(csum)

        for i in range(M, len(A)):
            csum += A[i] - A[i-M]
            msum.append(csum)

        maxSum = 0
        for i in range(len(A)-L+1):
            ls = i
            le = i + L - 1

            for j in range(len(A) - M+1):
                ms = j
                me = j + M - 1

                if (le < ms) or (me < ls):
                    maxSum = max(maxSum, lsum[ls] + msum[ms])

        return maxSum


Solve in Python:
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful.  Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].

Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.

Example 2:
Input: [2,2,2]
Output: 1

Note:

1 <= A.length <= 12
0 <= A[i] <= 1e9

import numpy as np
class Solution:
    graph = {}
    count = {}
    def numSquarefulPerms(self, A: List[int]) -> int:
        self.graph = {}
        self.count = {}
        for i in A:
            if i in self.count:
                self.count[i] += 1
            else:
                self.count[i] = 1
            self.graph[i] = []

        for i in self.count:
            for j in self.count:
                r = int(np.sqrt(i + j))
                if r * r == i + j:
                    self.graph[i].append(j)
        ans = 0
        L = len(A)
        for i in self.graph:
            ans += self.dfs(i, L-1)
        return ans

    def dfs(self, i, L):
        self.count[i] -= 1
        ans = 1
        if L != 0:
            ans = 0
            for j in self.graph[i]:
                if self.count[j] != 0:
                    ans += self.dfs(j, L - 1)
        self.count[i] += 1
        return ans


Solve in Python:
Given an array A of positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller than A, that can be made with one swap (A swap exchanges the positions of two numbers A[i] and A[j]).  If it cannot be done, then return the same array.

Example 1:
Input: [3,2,1]
Output: [3,1,2]
Explanation: Swapping 2 and 1.

Example 2:
Input: [1,1,5]
Output: [1,1,5]
Explanation: This is already the smallest permutation.

Example 3:
Input: [1,9,4,6,7]
Output: [1,7,4,6,9]
Explanation: Swapping 9 and 7.

Example 4:
Input: [3,1,1,3]
Output: [1,3,1,3]
Explanation: Swapping 1 and 3.

Note:

1 <= A.length <= 10000
1 <= A[i] <= 10000

class Solution:
    def prevPermOpt1(self, A: List[int]) -> List[int]:
        prev_vals = [(float('inf'), None)]

        for i in range(len(A) - 1, -1, -1):
            num = A[i]

            if num > prev_vals[-1][0]:
                max_prev = 0
                ind = None
                while num > prev_vals[-1][0]:
                    prev_n, prev_ind = prev_vals.pop()
                    if prev_n > max_prev:
                        max_prev = prev_n
                        ind = prev_ind

                A[i], A[ind] = max_prev, num
                return A

            prev_vals.append((num, i))

        return A


Solve in Python:
Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them.
The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : the sum of the values of the sightseeing spots, minus the distance between them.
Return the maximum score of a pair of sightseeing spots.

Example 1:
Input: [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11

Note:

2 <= A.length <= 50000
1 <= A[i] <= 1000

class Solution:
    def maxScoreSightseeingPair(self, A: List[int]) -> int:
        n = len(A)
        res = max_i = -n
        for j in range(1,n):
            max_i = max(max_i, A[j-1] + j-1)
            res = max(res, max_i + A[j] - j)
        return res


Solve in Python:
Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.
(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)
Return the number of good subarrays of A.

Example 1:
Input: A = [1,2,1,2,3], K = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Example 2:
Input: A = [1,2,1,3,4], K = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

Note:

1 <= A.length <= 20000
1 <= A[i] <= A.length
1 <= K <= A.length

class Solution:

    def _identify_limit(self, A, current_limit, K,  char_count_after_limit):
        char_count_after_limit = {k: v for k, v in char_count_after_limit.items()}
        unique_chars = {i for i in char_count_after_limit if char_count_after_limit[i] > 0}
        # print(unique_chars)
        while len(unique_chars) == K :
            # print(\"WHILE\", char_count_after_limit)
            temp_char = A[current_limit]
            char_count_after_limit[temp_char] = char_count_after_limit[temp_char] - 1
            if char_count_after_limit[temp_char] == 0:
                unique_chars.remove(temp_char)
            current_limit += 1

        char_count_after_limit[A[current_limit - 1]] = char_count_after_limit[A[current_limit - 1]] + 1
        return  current_limit - 1, char_count_after_limit

    def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
        # char_info = {item : [] for item in set(A)}
        # unique_char_count = {}
        # unique_char = set()
        # start_idx = 0
        # end_idx = 0
        # num_substr = 0
        # current_subarray = []
        # current_valid_count = 0
        # # In any valid subarray what is the index upto which left index could be moved without making subarray bad
        # # Whenever end_idx is moved to right keeping subarray good compute limit_idx again
        # limit_idx = 0
        # while end_idx < len(A) + 1 :
        #     if len(unique_char) == K :
        #         # temp_unique_char = {i for i in unique_char}
        #         # temp_char_count = {k:v for k, v in unique_char_count.items()}
        #         # temp_start_idx = start_idx
        #         # while len(temp_unique_char) == K:
        #         #     temp_char = A[temp_start_idx]
        #         #     temp_char_count[temp_char] = temp_char_count[temp_char] - 1
        #         #     if temp_char_count[temp_char] == 0:
        #         #         temp_unique_char.remove(temp_char)
        #         #     temp_start_idx += 1
        # ...


Solve in Python:
Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.
If it is impossible to form any triangle of non-zero area, return 0.

Example 1:
Input: [2,1,2]
Output: 5

Example 2:
Input: [1,2,1]
Output: 0

Example 3:
Input: [3,2,3,4]
Output: 10

Example 4:
Input: [3,6,2,3]
Output: 8

Note:

3 <= A.length <= 10000
1 <= A[i] <= 10^6

class Solution:
    def largestPerimeter(self, A: List[int]) -> int:
      res = 0
      A.sort()
      for i in range(len(A)):
        for j in range(i+1, len(A)):
          source = A[i]
          target = A[j]
          lower = abs(target - source)
          upper = source + target
          if (upper*2 < res):
            continue
          for t in range(j+1, len(A)):
            if lower < A[t] < upper:
              res = max(source + target + A[t], res)
              break
          if res != 0:
            break
      return res


Solve in Python:
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.

Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.

Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"

Note:

1 <= A.length <= 12
1 <= A[i].length <= 20

# we can memorize the path while doing dp
# let dp[used][i] = (string length, actual string) represents the bitmask used ends with ith element.

class Solution:
    def shortestSuperstring(self, A: List[str]) -> str:
        n = len(A)
        common = {}
        for i, s1 in enumerate(A):
            for j in range(i):
                s2 = A[j]
                longest1, longest2 = 0, 0
                for k in range(min(len(s1), len(s2)) + 1):
                    if s1.endswith(s2[:k]):
                        longest1 = k
                    if s2.endswith(s1[: k]):
                        longest2 = k
                common[(i, j)] = longest1
                common[(j, i)] = longest2

        end = 1 << n
        dp = [[(float('inf'), '')
               for i in range(n)] for m in range(end)]
        le, res = float('inf'), ''
        for used in range(end):
            for i, s in enumerate(A):
                if (used >> i) & 1 != 1:
                    continue
                mask = 1 << i
                if used ^ mask == 0:
                    dp[used][i] = (len(A[i]), A[i])
                else:
                    for j, last in enumerate(A):
                        if i == j or (used >> j) & 1 != 1:
                            continue
                        l, pref = dp[used ^ mask][j]
                        cand = pref + A[i][common[(j, i)] :]
                        if len(cand) < dp[used][i][0]:
                            dp[used][i] = (len(cand), cand)
                if used == end - 1 and dp[used][i][0] < le:
                    le, res = dp[used][i]
        return res

# class Solution:

#     def addCost(self, from_word, to_word):
#         n = min(len(from_word), len(to_word))
#         cost = len(to_word)
#         for i in range(n):
#             if from_word[-i-1] == to_word[i]:
#                 cost -= 1
#         return cost

#     def shortestSuperstring(self, A: List[str]) -> str:
#         # initalize 2D adjacency matrix
#         n = len(A)
#        ...


Solve in Python:
Given an array A, partition it into two (contiguous) subarrays left and right so that:

Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.

Return the length of left after such a partitioning.  It is guaranteed that such a partitioning exists.

Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]

Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]

Note:

2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.

class Solution:
    def partitionDisjoint(self, A: List[int]) -> int:
        l = [A[0]]
        r = [A[-1]]

        for i, v in enumerate(A):
            if i == 0:
                continue

            l.append(max(l[i-1], A[i]))
            r.append(min(r[i-1], A[len(A) - i - 1]))

        r.reverse()
        for i in range(1, len(l)):
            if l[i-1] <= r[i]:
                return i


Solve in Python:
Given an array A, we may rotate it by a non-negative integer K so that the array becomes A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1].  Afterward, any entries that are less than or equal to their index are worth 1 point.

For example, if we have [2, 4, 1, 3, 0], and we rotate by K = 2, it becomes [1, 3, 0, 2, 4].  This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].

Over all possible rotations, return the rotation index K that corresponds to the highest score we could receive.  If there are multiple answers, return the smallest such index K.

Example 1:
Input: [2, 3, 1, 4, 0]
Output: 3
Explanation:
Scores for each K are listed below:
K = 0,  A = [2,3,1,4,0],    score 2
K = 1,  A = [3,1,4,0,2],    score 3
K = 2,  A = [1,4,0,2,3],    score 3
K = 3,  A = [4,0,2,3,1],    score 4
K = 4,  A = [0,2,3,1,4],    score 3

So we should choose K = 3, which has the highest score.

Example 2:
Input: [1, 3, 0, 2, 4]
Output: 0
Explanation:  A will always have 3 points no matter how it shifts.
So we will choose the smallest K, which is 0.

Note:

       A will have length at most 20000.
       A[i] will be in the range [0, A.length].

 class Solution:
     def movesToChessboard(self, board):
         N = len(board)
         R = [sum([board[i][j]<<j for j in range(N)]) for i in range(N) ]
         C = [sum([board[i][j]<<i for i in range(N)]) for j in range(N) ]
         def calcMove(R, N):
             def sumOne(n) :
                 k = 0
                 while n:
                     n = n&(n-1)
                     k+=1
                 return k
             d = {}
             for i in range(N):
                 if not R[i] in d:
                     d[R[i]] = []
                 d[R[i]].append(i)
             akey =[]
             for k in d:
                 akey.append(k)

             if len(akey)==2 and akey[0]^akey[1] == (1<<N) -1 and abs(sumOne(akey[0])-sumOne(akey[1]))<=1:
                 a0, a1 = d[akey[0]], d[akey[1]]
                 if abs(len(a0)-len(a1))>1:
                     return -1
                 if len(a0) >= len(a1):
                     res = sum( [i%2  for i in a0])
                 else:
                     res = sum( [i%2  for i in a1])
                 return res if N%2 else min(res, max(N//2-res, 0))
             return -1
         r, c = calcMove(R, N), calcMove(C, N)
         return -1 if r == -1 or c == -1 else r + c


Solve in Python:
Given an array A1,A2...AN, you have to print the size of the largest contiguous subarray such that
GCD of all integers in that subarray is 1.

Formally,
For a subarray Ai,Ai+1...Aj where 1 ≤ i < j ≤ N to be valid: GCD(Ai,Ai+1...Aj) should be 1. You have to print the size of the largest valid subarray.
If no valid subarray exists, output -1.
Note:A single element is not considered as a subarray according to the definition of this problem.

-----Input-----
First line contains T, the number of testcases. Each testcase consists of N in one line followed by N integers in the next line.

-----Output-----
For each testcase, print the required answer in one line.

-----Constraints-----
- 1 ≤ T ≤ 10
- 2 ≤ N ≤ 105
- 1 ≤ Ai ≤ 105

-----Example-----
Input:
2
2
7 2
3
2 2 4

Output:
2
-1

-----Explanation-----
Example case 1.GCD(2,7)=1. So the subarray [A1,A2] is valid.
Example case 2.No subarray satisfies.
Note: Use scanf/print instead of cin/cout. Large input files.

# cook your dish here
from math import gcd
t = int(input())
for _ in range(t):
 n = int(input())
 ar = list(map(int, input().split()))
 d = ar[0]
 for i in range(1, n):
  d = gcd(d, ar[i])
 if d > 1:
  print(-1)
 else:
  print(n)


Solve in Python:
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.

Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.

Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.

Note:

1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1

class Solution:
    def longestOnes(self, A: List[int], K: int) -> int:
        res = 0
        start, end = 0, 0
        cnt = 0
        while end < len(A) and start < len(A):
            if A[end] == 1:
                res = max(res, end - start + 1)
                end += 1
            elif A[end] == 0 and cnt < K:
                res = max(res, end - start + 1)
                cnt += 1
                end += 1
            else:
                if A[start] == 0 and K > 0:
                    cnt -= 1
                start += 1
                if start > end:
                    end = start
        return res


Solve in Python:
Given an array `A` and an integer `x`, map each element in the array to `F(A[i],x)` then return the xor sum of the resulting array.

where F(n,x) is defined as follows:

F(n, x) = ^(x)Cx **+** ^(x+1)Cx **+** ^(x+2)Cx **+** ... **+** ^(n)Cx

and ^(n)Cx represents [Combination](https://en.m.wikipedia.org/wiki/Combination) in mathematics

### Example

```python
a = [7, 4, 11, 6, 5]
x = 3

# after mapping, `a` becomes [F(7,3), F(4,3), F(11,3), F(6,3), F(5,3)]

return F(7,3) ^ F(4,3) ^ F(11,3) ^ F(6,3) ^ F(5,3)
#=> 384
```
##### e.g
F(7, 3) = ^(3)C3 + ^(4)C3 + ^(5)C3  + ^(6)C3 + ^(7)C3

## Constraints

**1 <= x <= 10**

**x <= A[i] <= 10^(4)**

**5 <= |A| <= 10^(3)**

from scipy.special import comb as f
from functools import reduce

def transform(arr, n):
    arr = (f(x+1, n+1, exact=True) for x in arr)
    return reduce(lambda x,y: x^y, arr)


Solve in Python:
Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
More formally check if there exists two indices i and j such that :

i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]

Example 1:
Input: arr = [10,2,5,3]
Output: true
Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.

Example 2:
Input: arr = [7,1,14,11]
Output: true
Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.

Example 3:
Input: arr = [3,1,7,11]
Output: false
Explanation: In this case does not exist N and M, such that N = 2 * M.

Constraints:

2 <= arr.length <= 500
-10^3 <= arr[i] <= 10^3

class Solution:
    def checkIfExist(self, arr: List[int]) -> bool:
        seen = set()
        for e in arr:
            if 2*e in seen or (e % 2 == 0 and e//2 in seen):
                return True
            seen.add(e)
        return False


Solve in Python:
Given an array arr of positive integers, consider all binary trees such that:

Each node has either 0 or 2 children;
The values of arr correspond to the values of each leaf in an in-order traversal of the tree.  (Recall that a node is a leaf if and only if it has 0 children.)
The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively.

Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node.  It is guaranteed this sum fits into a 32-bit integer.

Example 1:
Input: arr = [6,2,4]
Output: 32
Explanation:
There are two possible trees.  The first has non-leaf node sum 36, and the second has non-leaf node sum 32.

    24            24
   /  \          /  \
  12   4        6    8
 /  \               / \
6    2             2   4

Constraints:

2 <= arr.length <= 40
1 <= arr[i] <= 15
It is guaranteed that the answer fits into a 32-bit signed integer (ie. it is less than 2^31).

class Solution:
    def mctFromLeafValues(self, arr: List[int]) -> int:
        if not arr: return 0

        res = []

        while len(arr) > 1:
            temp_res = []
            temp_res = [arr[i]*arr[i+1] for i in range(len(arr)-1)]
            idx = temp_res.index(min(temp_res))

            res.append(temp_res[idx])
            arr.pop(idx if arr[idx] < arr[idx+1] else idx+1)

            # left = arr[0] * arr[1]
            # right = arr[-1] * arr[-2]
            # if left < right:
            #     res.append(left)
            #     arr.pop(1 if arr[1] < arr[0] else 0)
            # elif right < left:
            #     res.append(right)
            #     arr.pop(-2 if arr[-2] < arr[-1] else -1)
            # else:
            #     res.append(left)
            #     if max(arr[0], arr[1]) > max(arr[-1], arr[-2]):
            #         arr.pop(-2 if arr[-2] < arr[-1] else -1)
            #     else:
            #         arr.pop(1 if arr[1] < arr[0] else 0)

        return sum(res)


Solve in Python:
Given an array arr.  You can choose a set of integers and remove all the occurrences of these integers in the array.
Return the minimum size of the set so that at least half of the integers of the array are removed.

Example 1:
Input: arr = [3,3,3,3,5,5,5,2,2,7]
Output: 2
Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
Possible sets of size 2 are {3,5},{3,2},{5,2}.
Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has size greater than half of the size of the old array.

Example 2:
Input: arr = [7,7,7,7,7,7]
Output: 1
Explanation: The only possible set you can choose is {7}. This will make the new array empty.

Example 3:
Input: arr = [1,9]
Output: 1

Example 4:
Input: arr = [1000,1000,3,7]
Output: 1

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

Constraints:

1 <= arr.length <= 10^5
arr.length is even.
1 <= arr[i] <= 10^5

class Solution:
    def minSetSize(self, arr: List[int]) -> int:

#         total_count = len(arr)
#         values = set(arr)
#         values = list(values)
#         possible_combinations = []

#         for i in values:
#             possible_combinations.append([i,arr.count(i)])

#         result = [seq for i in range(len([item[1] for item in possible_combinations]), 0, -1) for seq in itertools.combinations([item[1] for item in possible_combinations], i) if sum(seq) >= total_count//2]

#         return min(len(i) for i in result)

        total_count = 0
        arr_mc = collections.Counter(arr).most_common()

        print(arr_mc)

        for i in range(len(arr_mc)):
            total_count += arr_mc[i][1]
            if total_count >= len(arr)/2:
                return i + 1


Solve in Python:
Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.
Find the kth positive integer that is missing from this array.

Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.

Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.

Constraints:

1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length

class Solution:
    def findKthPositive(self, arr: List[int], k: int) -> int:
        m=max(arr)
        a=[]
        for i in range(1,m+k+1):
            if i not in arr:
                a.append(i)
        a=sorted(a)
        return a[k-1]


Solve in Python:
Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero.
At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are given an integer m and you need to find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1s such that it cannot be extended in either direction.
Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.

Example 1:
Input: arr = [3,5,1,2,4], m = 1
Output: 4
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "00101", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "11101", groups: ["111", "1"]
Step 5: "11111", groups: ["11111"]
The latest step at which there exists a group of size 1 is step 4.
Example 2:
Input: arr = [3,1,5,4,2], m = 2
Output: -1
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "10100", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "10111", groups: ["1", "111"]
Step 5: "11111", groups: ["11111"]
No group of size 2 exists during any step.

Example 3:
Input: arr = [1], m = 1
Output: 1

Example 4:
Input: arr = [2,1], m = 2
Output: 2

Constraints:

n == arr.length
1 <= n <= 10^5
1 <= arr[i] <= n
All integers in arr are distinct.
1 <= m <= arr.length

#https://leetcode.com/problems/find-latest-group-of-size-m/discuss/836441/Very-Easy

class Solution:
    def findLatestStep(self, arr: List[int], m: int) -> int:
        n = len(arr)
        if n==m:
            return n

        memo = collections.defaultdict(lambda : 0)
        res = -1
        for idx, i in enumerate(arr):
            left = memo[i-1]
            right = memo[i+1]
            if left==m or right==m:
                res = idx
            memo[i-left] = left+right+1
            memo[i+right] = left+right+1
        # if m in memo.values():
        #     res = n
        return res


Solve in Python:
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

class Solution:
     def missingNumber(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         nums.append(nums[0])
         for i in range(len(nums)):
           v = nums[i]
           while v != nums[v]:
             nums[v], v = v, nums[v]
         for i, num in enumerate(nums):
           if i != num:
             return i
         return None


Solve in Python:
Given an array containing only integers, add all the elements and return the binary equivalent of that sum.

If the array contains any non-integer element (e.g. an object, a float, a string and so on), return false.

**Note:** The sum of an empty array is zero.

```python
arr2bin([1,2]) == '11'
arr2bin([1,2,'a']) == False
```

def arr2bin(arr):
    return all(isinstance(n, int) and not isinstance(n, bool) for n in arr) and bin(sum(n for n in arr))[2:]


Solve in Python:
Given an array containing only zeros and ones, find the index of the zero that, if converted to one, will make the longest sequence of ones.

For instance, given the array:

```
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1]
```

replacing the zero at index 10 (counting from 0) forms a sequence of 9 ones:

```
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1]
                  '------------^------------'
```

Your task is to complete the function that determines where to replace a zero with a one to make the maximum length subsequence.

**Notes:**
- If there are multiple results, return the last one:

 `[1, 1, 0, 1, 1, 0, 1, 1] ==> 5`

- The array will always contain only zeros and ones.

Can you do this in one pass?

def replace_zero(arr):
    # (len, index)
    best_len, best_idx = 0, 0
    curr_len, curr_idx = 0, None

    for i, e in enumerate(arr):
        if e == 1:
            curr_len += 1
        else:
            if curr_len >= best_len:
                best_len, best_idx = curr_len, curr_idx

            if curr_idx is None:
                curr_len += 1
            elif i - curr_idx < 2:
                curr_len = 1
            else:
                curr_len = i - curr_idx
            curr_idx = i

    if curr_len >= best_len:
        best_len, best_idx = curr_len, curr_idx

    return best_idx


Solve in Python:
Given an array nums and an integer target.
Return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.

Example 1:
Input: nums = [1,1,1,1,1], target = 2
Output: 2
Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).

Example 2:
Input: nums = [-1,3,5,1,4,2,-9], target = 6
Output: 2
Explanation: There are 3 subarrays with sum equal to 6.
([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.
Example 3:
Input: nums = [-2,6,6,3,5,4,1,2,8], target = 10
Output: 3

Example 4:
Input: nums = [0,0,0], target = 0
Output: 3

Constraints:

1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
0 <= target <= 10^6

class Solution:
    def maxNonOverlapping(self, nums: List[int], target: int) -> int:
        ans, m, j, cur = 0, {0:-1}, -1, 0
        for i, x in enumerate(nums):
            cur += x
            k = cur - target
            if k in m and m[k] >= j:
                ans += 1; j = i
            m[cur] = i
        return ans


Solve in Python:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Example 1:

Input: [1,3,4,2,2]
Output: 2

Example 2:

Input: [3,1,3,4,2]
Output: 3

Note:

       You must not modify the array (assume the array is read only).
       You must use only constant, O(1) extra space.
       Your runtime complexity should be less than O(n2).
       There is only one duplicate number in the array, but it could be repeated more than once.

class Solution:
     def findDuplicate(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         if len(nums) == 0:
             return None
         slow = fast = nums[0]
         while True:
             slow = nums[slow]
             fast = nums[nums[fast]]
             if slow == fast:
                 break
         fast = nums[0]
         while slow != fast:
             slow = nums[slow]
             fast = nums[fast]
         return slow


Solve in Python:
Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.

Example 1:

Input: nums = [1,0,0,0,1,0,0,1], k = 2
Output: true
Explanation: Each of the 1s are at least 2 places away from each other.

Example 2:

Input: nums = [1,0,0,1,0,1], k = 2
Output: false
Explanation: The second 1 and third 1 are only one apart from each other.
Example 3:
Input: nums = [1,1,1,1,1], k = 0
Output: true

Example 4:
Input: nums = [0,1,0,1], k = 1
Output: true

Constraints:

1 <= nums.length <= 10^5
0 <= k <= nums.length
nums[i] is 0 or 1

class Solution:
    def kLengthApart(self, nums: List[int], k: int) -> bool:
        if k == 0:
            return True

        idx = [n for n, x in enumerate(nums) if x == 1]

        for i in range(1, len(idx)):
            print((idx[i], idx[i-1]))
            if idx[i] - idx[i-1] <= k:
                return False

        return True


Solve in Python:
Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.
An array A is a zigzag array if either:

Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...
OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ...

Return the minimum number of moves to transform the given array nums into a zigzag array.

Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation: We can decrease 2 to 0 or 3 to 1.

Example 2:
Input: nums = [9,6,1,6,2]
Output: 4

Constraints:

1 <= nums.length <= 1000
1 <= nums[i] <= 1000

class Solution:
    def movesToMakeZigzag(self, nums: List[int]) -> int:
        if len(nums) <= 2:
            return 0
        n = len(nums)
        if n%2 == 0:
            step1 = max(0,nums[-1]-nums[-2]+1)
            for i in range(1,n-1,2):
                step1 += max(0, nums[i] - min(nums[i-1], nums[i+1])+1)
            step2 = max(0, nums[0]-nums[1] +1)
            for i in range(2,n,2):
                step2 += max(0, nums[i] - min(nums[i-1], nums[i+1])+1)
        else:
            step1 = max(0,nums[-1]-nums[-2]+1) + max(0, nums[0]-nums[1] +1)
            for i in range(2,n-1,2):
                step1 += max(0, nums[i] - min(nums[i-1], nums[i+1])+1)
            step2 = 0
            for i in range(1,n,2):
                step2 += max(0, nums[i] - min(nums[i-1], nums[i+1])+1)
        return min(step1, step2)


Solve in Python:
Given an array nums of integers, return how many of them contain an even number of digits.

Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.

Example 2:
Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.

Constraints:

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

class Solution:

    def findNumbers(self, nums: List[int]) -> int:
        def has_even_digits(number: int):
            if number < 10:
                return False
            elif number < 100:
                return True
            elif number < 1000:
                return False
            elif number < 10000:
                return True
            elif number < 100000:
                return False
            return True

        return sum([1 for num in nums if has_even_digits(num)])


Solve in Python:
Given an array nums of integers, you can perform operations on the array.

In each operation, you pick any nums[i] and delete it to earn nums[i] points.  After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.

You start with 0 points.  Return the maximum number of points you can earn by applying such operations.

Example 1:

Input: nums = [3, 4, 2]
Output: 6
Explanation:
Delete 4 to earn 4 points, consequently 3 is also deleted.
Then, delete 2 to earn 2 points. 6 total points are earned.

Example 2:

Input: nums = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation:
Delete 3 to earn 3 points, deleting both 2's and the 4.
Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
9 total points are earned.

Note:
The length of nums is at most 20000.
Each element nums[i] is an integer in the range [1, 10000].

class Solution:
     def deleteAndEarn(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         nums.sort()
         nums.append(-1) #end symbol
         prev_max, cur_max = 0, 0
         prev = -1
         j, i = 0, 0
         while i < len(nums):
             if nums[i] == nums[j]:
                 i += 1
                 continue
             dif = i - j
             temp = dif*nums[j]
             if nums[j] == prev + 1:
                 prev_max, cur_max = cur_max, max(temp + prev_max, cur_max)
             else:
                 prev_max, cur_max = cur_max, temp + cur_max
             prev = nums[j]
             j = i
             i += 1
         return cur_max


Solve in Python:
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

class Solution:
     def threeSumClosest(self, nums, target):
         """
         :type nums: List[int]
         :type target: int
         :rtype: int
         """
         if len(nums) < 3:
             return sum(nums)
         elif len(nums) == 3:
             return sum(nums)
         nums = sorted(nums)
         res = nums[0]+nums[1]+nums[2]
         for i in range(len(nums) - 2):
             if i!= 0 and nums[i] == nums[i-1]:
                 continue
             j = i+1
             k = len(nums) - 1
             while j < k:
                 s = nums[i] + nums[j] + nums[k]
                 if s == target:
                     return target
                 if s < target:
                     j += 1
                 else:
                     k -= 1
                 if abs(s-target) < abs(res-target):
                     res = s
         return res


Solve in Python:
Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

class Solution:
     def productExceptSelf(self, nums):
         """
         :type nums: List[int]
         :rtype: List[int]
         """
         p = 1
         result = []
         for i in range(0, len(nums)):
             result.append(p)
             p = p * nums[i]

         p = 1

         for i in range(len(nums)-1, -1, -1):
             result[i] = result[i] * p
             p = p * nums[i]

         return result


Solve in Python:
Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.
Return True if the array is good otherwise return False.

Example 1:
Input: nums = [12,5,7,23]
Output: true
Explanation: Pick numbers 5 and 7.
5*3 + 7*(-2) = 1

Example 2:
Input: nums = [29,6,10]
Output: true
Explanation: Pick numbers 29, 6 and 10.
29*1 + 6*(-3) + 10*(-1) = 1

Example 3:
Input: nums = [3,6]
Output: false

Constraints:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9

class Solution:
    def isGoodArray(self, nums: List[int]) -> bool:
#         primeSet = set()
#         def isPrime(x):
#             if x < 2 or x in primeSet:
#                 return False
#             i = 2
#             limit = int(x**0.5)
#             while i < limit +1:
#                 if x%i == 0:
#                     return False
#                 limit = x//i
#                 i += 1
#             primeSet.add(x)
#             return True

#         numsLen = len(nums)
#         primeCounter = 0
#         for i in range(numsLen):
#             if nums[i] == 1:
#                 return True
#             if isPrime(nums[i]):
#                 primeCounter += 1
#                 if primeCounter == 2:
#                     return True
#             else:
#                 for j in range(i):
#                     if isPrime(abs(nums[j] - nums[i])):
#                         primeCounter += 1
#                         if primeCounter == 2:
#                             return True
#         return False
        g=nums[0]
        for i in nums:
            g=gcd(i,g)
        return g==1


Solve in Python:
Given an array nums, you are allowed to choose one element of nums and change it by any value in one move.
Return the minimum difference between the largest and smallest value of nums after perfoming at most 3 moves.

Example 1:
Input: nums = [5,3,2,4]
Output: 0
Explanation: Change the array [5,3,2,4] to [2,2,2,2].
The difference between the maximum and minimum is 2-2 = 0.
Example 2:
Input: nums = [1,5,0,10,14]
Output: 1
Explanation: Change the array [1,5,0,10,14] to [1,1,0,1,1].
The difference between the maximum and minimum is 1-0 = 1.

Example 3:
Input: nums = [6,6,0,1,1,4,6]
Output: 2

Example 4:
Input: nums = [1,5,6,14,15]
Output: 1

Constraints:

1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9

class Solution:
    def minDifference(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 5:
            return 0
        nums.sort()
        return min(nums[-1] - nums[3], nums[-2]-nums[2], nums[-3]-nums[1], nums[-4]-nums[0])


Solve in Python:
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).

Example 1:
Input: nums = [2,2,1,1,5,3,3,5]
Output: 7
Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.

Example 2:
Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]
Output: 13

Example 3:
Input: nums = [1,1,1,2,2,2]
Output: 5

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

Constraints:

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

class Solution:
    def maxEqualFreq(self, nums: List[int]) -> int:
        freq_count, count, res, maxf = defaultdict(int), defaultdict(int), 0, 0

        for i, a in enumerate(nums):
            count[a] += 1
            freq_count[count[a]-1] -= 1
            freq_count[count[a]] += 1
            maxf = max(maxf, count[a])
            if maxf==1 or maxf*freq_count[maxf]+1==i+1 or (maxf-1)*freq_count[maxf-1]+maxf==i+1:
                res = i+1

        return res


Solve in Python:
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).

Note:

n is a positive integer, which is in the range of [1, 10000].
All the integers in the array will be in the range of [-10000, 10000].

class Solution:
     def arrayPairSum(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         nums.sort()
         return sum(nums[::2])


Solve in Python:
Given an array of 4 integers
```[a,b,c,d]``` representing two points ```(a, b)``` and ```(c, d)```, return a string representation of the slope of the line joining these two points.

For an undefined slope (division by 0), return  ```undefined```  . Note that the "undefined" is case-sensitive.
```
   a:x1
   b:y1
   c:x2
   d:y2
```

Assume that ```[a,b,c,d]``` and the answer are all integers
(no floating numbers!).
Slope:

def find_slope(points):
    a,b,c,d = points
    if a == c:
        return "undefined"
    else:
        return str((d-b)//(c-a))


Solve in Python:
Given an array of arguments, representing system call arguments keys and values, join it into a single, space-delimited string. You don't need to care about the application name -- your task is only about parameters.

Each element of the given array can be:
* a single string,
* a single string array,
* an array of two strings

In the last case (array of two strings) the first string should have a `"--"` prefix if it is more than one character long; or a `"-"` prefix otherwise; e.g.:
  * `["foo", "bar"]` becomes `"--foo bar"`
  * `["f", "bar"]` becomes `"-f bar"`

You may assume that all strings are non-empty and have no spaces.

## Examples

```python
["foo", "bar"]                    #  "foo bar"
[["foo", "bar"]]                  #  "--foo bar"
[["f", "bar"]]                    #  "-f bar"
[["foo", "bar"], "baz"]           #  "--foo bar baz"
[["foo"], ["bar", "baz"], "qux"]  #  "foo --bar baz qux"
```

def args_to_string(args):
    r=[]
    for a in args:
        if type(a)==list:
            if len(a)==1:
                r+=a[0],
            else:
                s='-'
                if len(a[0])>1:s+='-'
                r+=s+' '.join(a),
        else:r+=a,
    return' '.join(r)


Solve in Python:
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.

According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."

Example:

Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had
             received 3, 0, 6, 1, 5 citations respectively.
             Since the researcher has 3 papers with at least 3 citations each and the remaining
             two with no more than 3 citations each, her h-index is 3.

Note: If there are several possible values for h, the maximum one is taken as the h-index.

class Solution:
     def hIndex(self, citations):
         """
         :type citations: List[int]
         :rtype: int
         """

         if len(citations) == 0:
             return 0
         else:
             citations.sort()
             i = 0
             while i < len(citations) :
                 if citations[-i-1] >= (i+1):
                     i += 1
                 else:
                     break
             return i


Solve in Python:
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.

According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."

Example:

Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
             received 0, 1, 3, 5, 6 citations respectively.
             Since the researcher has 3 papers with at least 3 citations each and the remaining
             two with no more than 3 citations each, her h-index is 3.

Note:

If there are several possible values for h, the maximum one is taken as the h-index.

Follow up:

       This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
       Could you solve it in logarithmic time complexity?

class Solution:
     def hIndex(self, citations):
         """
         :type citations: List[int]
         :rtype: int
         """

         # my solution......beat 95 %

         l = len(citations)
         if l == 0:                return 0
         if l == 1:
             if citations[0] == 0: return 0
             else:                 return 1
         if min(citations) >= l:   return l

         citations = citations[::-1]
         count = 0
         thres = 0
         i = 0
         while i < len(citations):
             if thres >= count:
                 thres = citations[i]
                 count += 1
                 i += 1
             else:
                 return count-1
         return count-1


Solve in Python:
Given an array of digits, you can write numbers using each digits[i] as many times as we want.  For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.
Return the number of positive integers that can be generated that are less than or equal to a given integer n.

Example 1:
Input: digits = ["1","3","5","7"], n = 100
Output: 20
Explanation:
The 20 numbers that can be written are:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.

Example 2:
Input: digits = ["1","4","9"], n = 1000000000
Output: 29523
Explanation:
We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
In total, this is 29523 integers that can be written using the digits array.

Example 3:
Input: digits = ["7"], n = 8
Output: 1

Constraints:

1 <= digits.length <= 9
digits[i].length == 1
digits[i] is a digit from '1' to '9'.
All the values in digits are unique.
1 <= n <= 109

class Solution:
    def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:

        count = 0
        length = 1
        n_str = str(n)
        while length < len(n_str):
            count+= len(digits)**length
            length+=1

        digits_sorted = sorted(digits)

        ## now length should equal to len(n), we compare the number with same length
        current_digit = 0
        while current_digit < length:
            for digit in digits_sorted:
                next_round = False
                if digit < n_str[current_digit]:
                    count+=len(digits)**(length-current_digit-1)
                elif digit > n_str[current_digit]:
                    return count
                else:
                    if current_digit == length-1:
                        return count+1
                    else:
                        current_digit+=1
                        next_round = True
                        break
            if not next_round:
                return count

        return count


Solve in Python:
Given an array of integers (x), and a target (t), you must find out if any two consecutive numbers in the array sum to t. If so, remove the second number.

Example:

x = [1, 2, 3, 4, 5]
t = 3

1+2 = t, so remove 2. No other pairs = t, so rest of array remains:

[1, 3, 4, 5]

Work through the array from left to right.

Return the resulting array.

def trouble(x, t):
    while(1):
        for i in range(len(x) - 1):
            if x[i] + x[i+1] == t:
                x.pop(i+1)
                break
        else:
            break
    return x


Solve in Python:
Given an array of integers A, a move consists of choosing any A[i], and incrementing it by 1.
Return the least number of moves to make every value in A unique.

Example 1:
Input: [1,2,2]
Output: 1
Explanation:  After 1 move, the array could be [1, 2, 3].

Example 2:
Input: [3,2,1,2,1,7]
Output: 6
Explanation:  After 6 moves, the array could be [3, 4, 1, 2, 5, 7].
It can be shown with 5 or less moves that it is impossible for the array to have all unique values.

Note:

0 <= A.length <= 40000
0 <= A[i] < 40000

class Solution:
    def minIncrementForUnique(self, A: List[int]) -> int:
        if not A:
            return 0

        n = len(A)
        A.sort()

        tail_num = A[0]
        result = 0
        for i in range(1, n):
            if A[i] > tail_num:
                tail_num = A[i]
            else:
                tail_num += 1

            # result = result + (tail_num - A[i])
            result += tail_num - A[i]

        return result


Solve in Python:
Given an array of integers A, consider all non-empty subsequences of A.
For any sequence S, let the width of S be the difference between the maximum and minimum element of S.
Return the sum of the widths of all subsequences of A.
As the answer may be very large, return the answer modulo 10^9 + 7.

Example 1:
Input: [2,1,3]
Output: 6
Explanation:
Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.

Note:

1 <= A.length <= 20000
1 <= A[i] <= 20000

class Solution:
    def sumSubseqWidths(self, A: List[int]) -> int:
        B = sorted(A)
        res = 0
        mod = 10**9 + 7
        for i in range(len(B)):
            res += B[i] * ((1 << i) - (1 << (len(B) - i - 1)))
        return res % mod


class Solution:
    def countTriplets(self, A: List[int]) -> int:
        combo = collections.Counter(x&y for x in A for y in A)
        return sum(combo[k] for z in A for k in combo if z&k == 0)


Solve in Python:
Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A.
Since the answer may be large, return the answer modulo 10^9 + 7.

Example 1:
Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.  Sum is 17.

Note:

1 <= A.length <= 30000
1 <= A[i] <= 30000

class Solution:
    def sumSubarrayMins(self, A: List[int]) -> int:
        mod = 10 ** 9 + 7
        stack = []
        ans = dot = 0
        for idx, val in enumerate(A):
            count = 1
            while stack and stack[-1][0] >= val:
                x,c = stack.pop()
                count += c
                dot -= x*c

            stack.append((val,count))
            dot += val * count
            ans += dot
        return ans % mod


Solve in Python:
Given an array of integers A with even length, return true if and only if it is possible to reorder it such that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2.

Example 1:
Input: A = [3,1,3,6]
Output: false

Example 2:
Input: A = [2,1,2,6]
Output: false

Example 3:
Input: A = [4,-2,2,-4]
Output: true
Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].

Example 4:
Input: A = [1,2,4,16,8,4]
Output: false

Constraints:

0 <= A.length <= 3 * 104
A.length is even.
-105 <= A[i] <= 105

class Solution:
    def canReorderDoubled(self, A: List[int]) -> bool:
        count = collections.Counter(A)
        for a in sorted(count, key = lambda x: abs(x)):
            if count[a] > count[2 * a]:
                return False
            count[2 * a] -= count[a]
        return True