Solve in Python:
Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights w_{i} kilograms.

Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions:   Take the leftmost item with the left hand and spend w_{i} · l energy units (w_{i} is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Q_{l} energy units;  Take the rightmost item with the right hand and spend w_{j} · r energy units (w_{j} is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Q_{r} energy units;

Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.

-----Input-----

The first line contains five integers n, l, r, Q_{l}, Q_{r} (1 ≤ n ≤ 10^5; 1 ≤ l, r ≤ 100; 1 ≤ Q_{l}, Q_{r} ≤ 10^4).

The second line contains n integers w_1, w_2, ..., w_{n} (1 ≤ w_{i} ≤ 100).

-----Output-----

In the single line print a single number — the answer to the problem.

-----Examples-----
Input
3 4 4 19 1
42 3 99

Output
576

Input
4 7 2 3 9
1 2 3 4

Output
34

-----Note-----

Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units.

The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units.

n, l, r, ql, qr = list(map(int, input().split()))
w = list(map(int, input().split()))
prefix = [0]
suffix = [sum(w)]
for i in range(n):
  prefix.append(prefix[i] + w[i])
  suffix.append(suffix[i] - w[i])

m = 1e10
for i in range(n+1):
  res = l*prefix[i] + r*suffix[i]
  if (i > n - i):
    res += (2*i - n - 1) * ql
  if (i < n - i):
    res += (n - 2*i - 1) * qr
  m = min(m, res)
print(m)


Solve in Python:
Vasya has ordered a pizza delivery. The pizza can be considered a perfect circle. There were $n$ premade cuts in the pizza when it was delivered. Each cut is a straight segment connecting the center of the pizza with its boundary.
Let $O$ be the center of the pizza, $P_i$ be the endpoint of the $i$-th cut lying on the boundary, and $R$ be the point of the boundary straight to the right of $O$. Then the counterclockwise-measured angle $\angle ROP_i$ is equal to $a_i$ degrees, where $a_i$ is an integer between $0$ and $359$. Note that angles between $0$ and $180$ angles correspond to $P_i$ in the top half of the pizza, while angles between $180$ and $360$ angles correspond to the bottom half.
Vasya may cut his pizza a few more times, and the new cuts still have to be straight segments starting at the center. He wants to make the pizza separated into several equal slices, with each slice being a circular sector with no cuts inside of it. How many new cuts Vasya will have to make?

-----Input:-----
The first line of input contains $T$ , i.e number of test cases per file.
The first line of each test case contains a single integer $n-$  the numbers of premade cuts ($2 \leq n \leq 360$).
The second lines contains $n$ integers $a_1, \ldots, a_n-$ angles of the cuts $1, \ldots, n$ respectively ($0 \leq a_1 < \ldots, a_{n - 1} < 360$).

-----Output:-----
Print a single integer$-$ the smallest number of additional cuts Vasya has to make so that the pizza is divided into several equal slices.

-----Constraints-----
- $1  \leq T  \leq 36$
- $2 \leq n \leq 360$
- $0 \leq a_1 < \ldots, a_{n - 1} < 360$

-----Sample Input:-----
3
4
0 90 180 270
2
90 210
2
0 1

-----Sample Output:-----
0
1
358

-----EXPLANATION:-----
In the first sample the pizza is already cut into four equal slices.
In the second sample the pizza will be cut into three equal slices after making one extra cut at $330$ degrees.
In the third sample Vasya will have to cut his pizza into $360$ pieces of $1$ degree angle each.

# cook your dish here
t = int(input())

for x in range(t):
 cu = int(input())
 angle = list(map(int, input().split()))

 diff = []
 mi = float('infinity')
 for i in range(cu - 1):
  diff.append(angle[i + 1] - angle[i])
  if diff[i] < mi:
   mi = diff[i]

 diff.append(angle[0] - angle[cu - 1] + 360)
 if diff[cu - 1] < mi:
  mi = diff[cu - 1]
 div = 1
 while div < 360:
  smallest = mi / div
  count = 0
  flag = True
  for i in diff:
   dm = divmod(i, smallest)
   if dm[1] != 0:
    flag = False
    break
   count += dm[0]
  if flag:
   print(int(count - cu))
   break
  div += 1


Solve in Python:
Vasya has written some permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, so for all $1 \leq i \leq n$ it is true that $1 \leq p_i \leq n$ and all $p_1, p_2, \ldots, p_n$ are different. After that he wrote $n$ numbers $next_1, next_2, \ldots, next_n$. The number $next_i$ is equal to the minimal index $i < j \leq n$, such that $p_j > p_i$. If there is no such $j$ let's let's define as $next_i = n + 1$.

In the evening Vasya went home from school and due to rain, his notebook got wet. Now it is impossible to read some written numbers. Permutation and some values $next_i$ are completely lost! If for some $i$ the value $next_i$ is lost, let's say that $next_i = -1$.

You are given numbers $next_1, next_2, \ldots, next_n$ (maybe some of them are equal to $-1$). Help Vasya to find such permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, that he can write it to the notebook and all numbers $next_i$, which are not equal to $-1$, will be correct.

-----Input-----

The first line contains one integer $t$ — the number of test cases ($1 \leq t \leq 100\,000$).

Next $2 \cdot t$ lines contains the description of test cases,two lines for each. The first line contains one integer $n$ — the length of the permutation, written by Vasya ($1 \leq n \leq 500\,000$). The second line contains $n$ integers $next_1, next_2, \ldots, next_n$, separated by spaces ($next_i = -1$ or $i < next_i \leq n + 1$).

It is guaranteed, that the sum of $n$ in all test cases doesn't exceed $500\,000$.

In hacks you can only use one test case, so $T = 1$.

-----Output-----

Print $T$ lines, in $i$-th of them answer to the $i$-th test case.

If there is no such permutations $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, that Vasya could write, print the only number $-1$.

In the other case print $n$ different integers $p_1, p_2, \ldots, p_n$, separated by spaces ($1 \leq p_i \leq n$). All defined values of $next_i$ which are not equal to $-1$ should be computed correctly $p_1, p_2, \ldots, p_n$ using defenition...

import sys
input = sys.stdin.readline

T = int(input())
for _ in range(T):
    n = int(input())
    l = list(map(int, input().split()))

    stack = []
    out = [-1] * n
    curr = 0
    works = True
    for i in range(n):
        while stack and stack[-1][0] == i:
            _, j = stack.pop()
            curr += 1
            out[j] = curr

        nex = l[i] - 1
        if nex == -2:
            curr += 1
            out[i] = curr
        else:
            if stack and nex > stack[-1][0]:
                works = False
            else:
                stack.append((nex, i))

    while stack:
        _, j = stack.pop()
        curr += 1
        out[j] = curr

    if works:
        print(*out)
    else:
        print(-1)


Solve in Python:
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>]

where:  <protocol> can equal either "http" (without the quotes) or "ftp" (without the quotes),  <domain> is a non-empty string, consisting of lowercase English letters,  the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters.

If string <context> isn't present in the address, then the additional character "/" isn't written. Thus, the address has either two characters "/" (the ones that go before the domain), or three (an extra one in front of the context).

When the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters ":", "/", ".".

Help Vasya to restore the possible address of the recorded Internet resource.

-----Input-----

The first line contains a non-empty string that Vasya wrote out in his notebook. This line consists of lowercase English letters only.

It is guaranteed that the given string contains at most 50 letters. It is guaranteed that the given string can be obtained from some correct Internet resource address, described above.

-----Output-----

Print a single line — the address of the Internet resource that Vasya liked. If there are several addresses that meet the problem limitations, you are allowed to print any of them.

-----Examples-----
Input
httpsunrux

Output
http://sun.ru/x

Input
ftphttprururu

Output
ftp://http.ru/ruru

-----Note-----

In the second sample there are two more possible answers: "ftp://httpruru.ru" and "ftp://httpru.ru/ru".


Solve in Python:
Vasya learned about integer subtraction in school. He is still not very good at it, so he is only able to subtract any single digit number from any other number (which is not necessarily single digit).
For practice, Vasya chose a positive integer n$n$ and wrote it on the first line in his notepad. After that, on the second line he wrote the result of subtraction of the first digit of n$n$ from itself. For example, if n=968$n = 968$, then the second line would contain 968−9=959$968 - 9 = 959$, while with n=5$n = 5$ the second number would be 5−5=0$5 - 5 = 0$. If the second number was still positive, then Vasya would write the result of the same operation on the following line, and so on. For example, if n=91$n = 91$, then the sequence of numbers Vasya would write starts as follows: 91,82,74,67,61,55,50,…$91, 82, 74, 67, 61, 55, 50, \ldots$. One can see that any such sequence eventually terminates with the number 0$0$.
Since then, Vasya lost his notepad. However, he remembered the total number k$k$ of integers he wrote down (including the first number n$n$ and the final number 0$0$). What was the largest possible value of n$n$ Vasya could have started with?

-----Input:-----
The first line contains T$T$ , number of test cases per file.
The only line in each testcase contains a single integer k−$k-$ the total number of integers in Vasya's notepad (2≤k≤1012$2 \leq k \leq 10^{12}$).

-----Output:-----
Print a single integer−$-$ the largest possible value of the starting number n$n$. It is guaranteed that at least one such number n$n$ exists, and the largest possible value is finite.

-----Constraints-----
- 1≤T≤34$1 \leq  T \leq 34 $
- 2≤k≤1012$2 \leq k \leq 10^{12}$

-----Sample Input-----
3
2
3
100

-----Sample Output:-----
9
10
170

def getAns(num):
    if num<10:return 2
    last=int(str(num)[0]);rem=int(str(num)[1:]);steps=2;p=len(str(num))-1
    while True:
     steps+=rem//last+1;rem=rem%last
     if last>0:rem=rem+10**p-last
     last=last-1
     if last==0:
      p=p-1;last=9
      if(len(str(rem))==1):rem=0
      else:rem=int(str(rem)[1:])
     if rem==0:            break
    return steps
for awa in range(int(input())):
    k=int(input())
    if(k==1):print(0)
    elif(k==2):print(9)
    elif(k==3):print(10)
    else:
     low,high,ans = 0,10**18,0
     while(low<=high):
      mid=(low+high)//2;temp=getAns(mid)
      if int(temp)==k:ans=max(ans,mid);low=mid+1
      elif temp<k:low=mid+1
      else:high=mid-1
     print(ans)


Solve in Python:
Vasya likes the number $239$. Therefore, he considers a number pretty if its last digit is $2$, $3$ or $9$.
Vasya wants to watch the numbers between $L$ and $R$ (both inclusive), so he asked you to determine how many pretty numbers are in this range. Can you help him?

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains two space-separated integers $L$ and $R$.

-----Output-----
For each test case, print a single line containing one integer — the number of pretty numbers between $L$ and $R$.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le L \le R \le 10^5$

-----Subtasks-----
Subtask #1 (100 points): original constraints

-----Example Input-----
2
1 10
11 33

-----Example Output-----
3
8

-----Explanation-----
Example case 1: The pretty numbers between $1$ and $10$ are $2$, $3$ and $9$.
Example case 2: The pretty numbers between $11$ and $33$ are $12$, $13$, $19$, $22$, $23$, $29$, $32$ and $33$.

t= int(input())
while t:
 l,r=input().split()
 l=int(l)
 r=int(r)
 count=0
 for i in range(l,r+1):
  rem = i%10
  if rem ==2 or rem == 3 or rem == 9 :
   count=count+1
 print(count)
 t=t-1


Solve in Python:
Vasya wants to climb up a stair of certain amount of steps (Input parameter 1). There are 2 simple rules that he has to stick to.

1. Vasya can climb 1 or 2 steps at each move.
2. Vasya wants the number of moves to be a multiple of a certain integer. (Input parameter 2).

### Task:
What is the `MINIMAL` number of moves making him climb to the top of the stairs that satisfies his conditions?

### Input

1. Number of stairs:    `0 <  N  ≤ 10000` ;
2. Integer to be multiplied : `1 < M ≤ 10 `;

### Output

1. Return a single integer - the minimal number of moves being a multiple of M;
2. If there is no way he can climb satisfying condition return - 1 instead. (`Nothing` in Haskell)

### Examples

```python
numberOfSteps(10, 2) => 6  # Sequence of steps : {2, 2, 2, 2, 1, 1}

numberOfSteps(3, 5) => -1 # !Possible sequences of steps : {2, 1}, {1, 2}, {1, 1, 1}
```
``` haskell
numberOfSteps 10 2 == Just 6  -- Sequence of steps : {2, 2, 2, 2, 1, 1}
numberOfSteps  3 5 == Nothing -- Not possible, since the sequences of steps would be {2, 1}, {1, 2} or {1, 1, 1}
```

def numberOfSteps(steps, m):
    if m > steps:
        return -1
    c = 1
    while steps > 2*m*c:
        c += 1
    return m*c


Solve in Python:
Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n.

Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array a left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by k for each number).

The seller can obtain array b from array a if the following conditions hold: b_{i} > 0; 0 ≤ a_{i} - b_{i} ≤ k for all 1 ≤ i ≤ n.

Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 3·10^5; 1 ≤ k ≤ 10^6). The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^6) — array a.

-----Output-----

In the single line print a single number — the maximum possible beauty of the resulting array.

-----Examples-----
Input
6 1
3 6 10 12 13 16

Output
3

Input
5 3
8 21 52 15 77

Output
7

-----Note-----

In the first sample we can obtain the array:

3 6 9 12 12 15

In the second sample we can obtain the next array:

7 21 49 14 77

n,k=list(map(int,input().split()))
t=set(map(int,input().split()))
y=x=min(t)
t=list(t)
while True:
    for i in t:
        if i%x>k:x=i//(i//x+1)
    if y==x:break
    y=x
print(y)


Solve in Python:
Vasya's older brother, Petya, attends an algorithm course in his school. Today he learned about matchings in graphs. Formally, a set of edges in a graph is called a matching if no pair of distinct edges in the set shares a common endpoint.
Petya instantly came up with an inverse concept, an antimatching. In an antimatching, any pair of distinct edges should have a common endpoint.
Petya knows that finding a largest matching in a graph is a somewhat formidable task. He wonders if finding the largest antimatching is any easier. Help him find the number of edges in a largest antimatching in a given graph.

-----Input:-----
The first line contains T$T$, number of test cases per file.
The first line of each test case contains two integers n$n$ and m−$m-$ the number of vertices and edges of the graph respectively (1≤n≤104$1 \leq n \leq 10^4$, 0≤m≤104$0 \leq m \leq 10^4$).
The next m$m$ lines describe the edges. The i$i$-th of these lines contains two integers ui$u_i$ and vi−$v_i-$ the indices of endpoints of the i$i$-th edge (1≤ui,vi≤n$1 \leq u_i, v_i \leq n$, ui≠vi$u_i \neq v_i$).
It is guaranteed that the graph does not contain self-loops nor multiple edges. It is not guaranteed that the graph is connected.

-----Output:-----
Print a single number per test case −$-$ the maximum size of an antichain in the graph.

-----Constraints-----
- 1≤T≤10$1 \leq T \leq 10$
- 1≤n≤104$1 \leq n \leq 10^4$
- 0≤m≤104$0 \leq m \leq 10^4$
- 1≤ui,vi≤n$1 \leq u_i, v_i \leq n$
- ui≠vi$u_i \neq v_i$

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

-----Sample Output:-----
3
1
0

-----EXPLANATION:-----
In the first sample all three edges form an antimatching.
In the second sample at most one of the two edges can be included in an antimatching since they do not share common endpoints.
In the third sample there are no edges, hence the answer is 0$0$.

# cook your dish here
def detect_triangle(adj):
    for x in range(len(adj)):
     for y in adj[x]:
      if not set(adj[x]).isdisjoint(adj[y]):
       return True

for _ in range(int(input())):
    n,m=map(int,input().split())
    graph=[[] for i in range(n)]
    for i in range(m):
     u,v=map(int,input().split())
     graph[u-1].append(v-1)
     graph[v-1].append(u-1)
    h=[]
    for i in range(len(graph)):
     h.append(len(graph[i]))
    h1=max(h)
    if h1>=3:
     print(h1)
     continue
    if detect_triangle(graph):
     print(3)
     continue
    print(h1)


Solve in Python:
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.

For each photo it is known which orientation is intended for it — horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.

Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.

Help Vasya find the maximum number of photos he is able to watch during T seconds.

-----Input-----

The first line of the input contains 4 integers n, a, b, T (1 ≤ n ≤ 5·10^5, 1 ≤ a, b ≤ 1000, 1 ≤ T ≤ 10^9) — the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.

Second line of the input contains a string of length n containing symbols 'w' and 'h'.

If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.

If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.

-----Output-----

Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.

-----Examples-----
Input
4 2 3 10
wwhw

Output
2

Input
5 2 4 13
hhwhh

Output
4

Input
5 2 4 1000
hhwhh

Output
5

Input
3 1 100 10
whw

Output
0

-----Note-----

In the first sample test you can rotate the first photo (3 seconds), watch the first...

def main():
    n, a, b, t = list(map(int, input().split()))
    b += 1
    l = [b if char == "w" else 1 for char in input()]
    t -= sum(l) - a * (n + 2)
    hi, n2 = n, n * 2
    n3 = n2 + 1
    lo = res = 0
    l *= 2
    while lo <= n and hi < n2:
        t -= l[hi]
        hi += 1
        while (hi - lo + (hi if hi < n3 else n3)) * a > t or lo < hi - n:
            t += l[lo]
            lo += 1
            n3 -= 1
        if res < hi - lo:
            res = hi - lo
            if res == n:
                break
    print(res)

def __starting_point():
    main()

__starting_point()


Solve in Python:
Very simple, given a number, find its opposite.

Examples:
```
1: -1
14: -14
-34: 34
```

~~~if:sql
You will be given a table: `opposite`, with a column: `number`. Return a table with a column: `res`.
~~~

def opposite(number):
    return number * -1
    #Nobody saw this


Solve in Python:
Vietnamese and Bengali as well.
An $N$-bonacci sequence is an infinite sequence $F_1, F_2, \ldots$ such that for each integer $i > N$, $F_i$ is calculated as $f(F_{i-1}, F_{i-2}, \ldots, F_{i-N})$, where $f$ is some function. A XOR $N$-bonacci sequence is an $N$-bonacci sequence for which $f(F_{i-1}, F_{i-2}, \ldots, F_{i-N}) = F_{i-1} \oplus F_{i−2} \oplus \ldots \oplus F_{i−N}$, where $\oplus$ denotes the bitwise XOR operation.
Recently, Chef has found an interesting sequence $S_1, S_2, \ldots$, which is obtained from prefix XORs of a XOR $N$-bonacci sequence $F_1, F_2, \ldots$. Formally, for each positive integer $i$, $S_i = F_1 \oplus F_2 \oplus \ldots \oplus F_i$. You are given the first $N$ elements of the sequence $F$, which uniquely determine the entire sequence $S$.
You should answer $Q$ queries. In each query, you are given an index $k$ and you should calculate $S_k$. It is guaranteed that in each query, $S_k$ does not exceed $10^{50}$.

-----Input-----
- The first line of the input contains two space-separated integers $N$ and $Q$.
- The second line contains $N$ space-separated integers $F_1, F_2, \ldots, F_N$.
- The following $Q$ lines describe queries. Each of these lines contains a single integer $k$.

-----Output-----
For each query, print a single line containing one integer $S_k$.

-----Constraints-----
- $1 \le N, Q \le 10^5$
- $0 \le F_i \le 10^9$ for each $i$ such that $1 \le i \le N$
- $1 \le k \le 10^9$

-----Example Input-----
3 4
0 1 2
7
2
5
1000000000

-----Example Output-----
3
1
0
0

n,q=list(map(int,input().split()))
l=list(map(int,input().split()))
v=[0 for x in range(n)]
v[0]=l[0]
for j in range(1,n):
 v[j]=v[j-1]^l[j]
for i in range(q):
 k=int(input())
 if k<=n:
  print(v[k-1])
 else:
  ans=(k-n)%(n+1)-1
  if ans==0:
   print(0)
  elif ans<0:
   print(v[n-1])
  else:
   print(v[ans-1])


Solve in Python:
Vishal Wants to buy 2 gifts for his best friend whose name is Annabelle(her age is 20), So they both went for shopping in a store. But Annabelle gave, Vishal a condition that she will accept this gifts only when the total price of the gifts is the same as her age times 100.
The store contains, a list of items whose prices are also displayed, Now Vishal is asking for your help to buy gifts, as he wants to impress Annabelle this time.
Note: Vishal cannot buy the same item more than once.

-----Input:-----
- The first line of the input contains a single integer $T$. $T$ denoting the number of test cases. The description of $T$ test cases is as follows.
- The next line of the input contains a single integer $N$. $N$ denotes the total number of items in store.
- The next line of the input contains $N$ space-separated integers $A1, A2, A3...An$ where $ith$ number denotes the price of $ith$ element.

-----Output:-----
- For each test-case print "Accepted"(without quotes) if the gifts are accepted by Annabelle, else print "Rejected"(without quotes)

-----Constraints:-----
- $1 \leq T \leq 10^3$
- $1 \leq N \leq 10^5$
- $1 \leq A1, A2, A3...An \leq 10^7$

-----Sample Input:-----
1
5
10 2 1000 50 1000

-----Sample Output:-----
Accepted

-----Explanation:-----
- As the given list of items have 2 items whose price sum up to the age times 100 of Annabelle i.e. 1000+1000 = (20 *100)

def main():
 for _ in range(int(input())):
  n=int(input())
  a=list(map(int,input().split()))
  flag=False
  s=set(a)
  if(a.count(1000)>=2):
   flag=True
  for i in a:
   if(2000-i in s and i!=1000):
    flag=True
    break
  print("Accepted" if(flag) else "Rejected")
main()


Solve in Python:
Vision has finally made it to Wakanda to get his MindStone extracted. The MindStone was linked to his brain in a highly sophisticated manner and Shuri had to solve a complex problem to extract the stone. The MindStone had $n$ integers inscribed in it and Shuri needs to apply the prefix sum operation on the array $k$ times to extract the stone.
Formally, given $n$ integers $A[1], A[2] ..... A[n]$ and a number $k$, apply the operation
$A[i] = \sum_{j=1}^{i} A[j]$
on the array $k$ times.
Finally Shuri needs to apply $modulo$ $(10^9 + 7)$ operation to each element of the array. Can you help Shuri accomplish this task before Thanos gets to them?

-----Input:-----
- First line of the input consists of two space separated integers $n$ and $k$.
- Second line contains $n$ space separated integers $A[1] .. A[n]$.

-----Output:-----
In a single line print $n$ space separated integers, the values of the resultant array after applying all the operations.

-----Constraints-----
- $1 \leq n \leq 1000$
- $1 \leq k \leq 10^{12}$
- $1 \leq A[i] \leq 10^9$

-----Subtasks-----
- 20 Points: $1 \leq k \leq 1000$
- 30 Points: $1 \leq k \leq 1000000$
- 50 Points: Original Constraints

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

-----Sample Output:-----
$3$ $10$ $18$ $31$

-----EXPLANATION:-----
After applying the prefix sum operation once the array becomes -> $3$ $7$ $8$ $13$
After applying the prefix sum operation for the second time, the array becomes -> $3$ $10$ $18$ $31$
After applying $modulo$ $(10^9 +7)$ operation, array becomes -> $3$ $10$ $18$ $31$

# cook your dish here
# cook your dish here
list0=list(map(int,input().split()))
n=list0[0]
k=list0[1]
list1=list(map(int,input().split()))
M = 1000000007
for j in range(k):
    for i in range(n-1):
        list1[i+1]=((list1[i+1]%M)+(list1[i]%M))%M
for i in list1:
    print(i%M,end=" ")


Solve in Python:
Vivek was quite bored with the lockdown, so he came up with an interesting task. He successfully completed this task and now, he would like you to solve it.
You are given two strings $A$ and $B$, each with length $N$. Let's index the characters in each string from $0$ ― for each $i$ ($0 \le i < N$), the $i+1$-th characters of $A$ and $B$ are denoted by $A_i$ and $B_i$ respectively. You should convert $A$ to $B$ by performing operations of the following type:
- Choose a subset $S$ of the set $\{0, 1, \ldots, N-1\}$.
- Let $c$ be the alphabetically smallest character among $A_x$ for all $x \in S$.
- For each $x \in S$, replace $A_x$ by $c$.
You should find the smallest necessary number of operations or report that it is impossible to convert $A$ to $B$. If it is possible, you also need to find one way to convert $A$ to $B$ using this smallest number of operations. If there are multiple solutions, you may find any one.

-----Input-----
- The first line of the input contains a single 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$.
- The second line contains a single string $A$.
- The third line contains a single string $B$.

-----Output-----
For each test case:
- If it is impossible to convert $A$ to $B$, print a single line containing the integer $-1$.
- Otherwise, first, print a line containing a single integer $K$ ― the minimum number of operations.
- Then, print $K$ lines describing the operations. Each of these lines should contain a positive integer $Z$, followed by a space and $Z$ pairwise distinct space-separated integers from the set $\{0, 1, \ldots, N-1\}$ ― the elements of $S$.

-----Constraints-----
- $1 \le T \le 20$
- $1 \le N \le 10^3$
- $|A| = |B| = N$
- $A$ and $B$ contain only lowercase English letters

-----Subtasks-----
Subtask #1 (30 points): $B$ contains only characters 'a' and 'b'
Subtask #2 (70 points): original constraints

-----Example...

T=int(input())
for _ in range(T):
 N=int(input())
 A=input()
 B=input()
 dupdel=list(dict.fromkeys(B))
 def notpossible(A,B,dupdel):
  for i in range(len(dupdel)):
   if dupdel[i] not in A:
    return -1
  for i in range(len(A)):
   if A[i]<B[i]:
    return -1
 if notpossible(A,B,dupdel)==-1:
  print(-1)
  continue
 else:
  L=[]
  for i in range(len(A)):
   if A[i]!=B[i]:
    L.append(B[i])
  #print(L)
  P=list(dict.fromkeys(L))
  print(len(P))
  P.sort(reverse=True)
  for i in range(len(P)):
   Q=[]
   R=[]
   for j in range(len(A)):
    if B[j]==P[i]:
     Q.append(j)
     R.append(A[j])
   if P[i] not in R:
    for k in range(N):
     if A[k]==P[i]:
      Q.append(k)
      break
   print(len(Q),*Q)


Solve in Python:
Vlad enjoys listening to music. He lives in Sam's Town. A few days ago he had a birthday, so his parents gave him a gift: MP3-player! Vlad was the happiest man in the world! Now he can listen his favorite songs whenever he wants!
Vlad built up his own playlist. The playlist consists of N songs, each has a unique positive integer length. Vlad likes all the songs from his playlist, but there is a song, which he likes more than the others. It's named "Uncle Johny".
After creation of the playlist, Vlad decided to sort the songs in increasing order of their lengths. For example, if the lengths of the songs in playlist was {1, 3, 5, 2, 4} after sorting it becomes {1, 2, 3, 4, 5}. Before the sorting, "Uncle Johny" was on K-th position (1-indexing is assumed for the playlist) in the playlist.
Vlad needs your help! He gives you all the information of his playlist. Your task is to find the position of "Uncle Johny" in  the sorted playlist.

-----Input-----
The first line of the 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 one integer N denoting the number of songs in Vlad's playlist. The second line contains N space-separated integers A1, A2, ..., AN denoting the lenghts of Vlad's songs.
The third line contains the only integer K - the position of "Uncle Johny" in the initial playlist.

-----Output-----
For each test case, output a single line containing the position of "Uncle Johny" in the sorted playlist.

-----Constraints-----
1 ≤ T ≤ 1000

1 ≤ K ≤ N ≤ 100

1 ≤ Ai ≤ 109

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

Output:
3
4
1

-----Explanation-----
In the example test there are T=3 test cases.
Test case 1
In the first test case N equals to 4, K equals to 2, A equals to {1, 3, 4, 2}. The answer is 3, because {1, 3, 4, 2} -> {1, 2, 3, 4}. A2 now is on the 3-rd position.
Test case 2
In the second test case N equals to 5, K equals to 5, A equals to {1, 2, 3, 9, 4}. The answer is 4, because...

for _ in range(int(input())):
    num=int(input())
    lst=list(map(int,input().split()))
    n=int(input())
    a=lst[n-1]
    lst.sort()
    for i in range(num):
        if a==lst[i]:
            print(i+1)
            break# cook your dish here


Solve in Python:
Voritex a big data scientist collected huge amount of big data having structure of two rows and n columns.
Voritex is storing all the valid data for manipulations and pressing invalid command when data not satisfying the constraints.
Voritex likes brute force method and he calls it as BT, he decided to run newly created BT engine for getting good result.
At each instance when BT engine is outputting a newly created number Voritex calls it as BT number.
Voritex is daydreaming and thinking that his engine is extremely optimised and will get an interview call in which he will be explaining the structure of BT engine and which will be staring from 1 and simultaneously performing $i$-th xor operation with $i$ and previously(one step before) obtained BT number.
BT engine is outputting the $K$-th highest BT number in the first $N$ natural numbers.
Chef : (thinking) I also want to create BT engine……..

-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of T test cases follows.
- The line of each test case contains a two integers $N$ and $K$.

-----Output:-----
For each test case, print a single line containing integer $K$-th highest number else print -$1$ when invalid command pressed.

-----Constraints-----
- $1 \leq T \leq 100000$
- $1 \leq N \leq 100000$
- $1 \leq K \leq N$

-----Sample Input:-----
2
4 2
5 5

-----Sample Output:-----
2
0

-----EXPLANATION:-----
For first valid constraints generating output as 0 2 1 5
1^1 first BT number is 0
2^0 second BT number is 2
3^2 third BT number is 1
4^1 fourth BT number is 5
Hence the answer is 2.

import math
import os
import random
import re
import sys

r = 100000
prev = 1
s = set()
for i in range(1, r+1):
    now = i ^ prev
    s.add(now)
    prev = now
s = list(s)
t = int(input())
while t > 0:
    t -= 1
    n, k = list(map(int, input().split()))

    if n > 3:
        if n % 2 == 0:
            size = (n//2) + 2
        else:
            size = ((n-1)//2) + 2
    else:
        size = n
    if size - k >= 0:
        print(s[size-k])
    else:
        print(-1)


Solve in Python:
Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task.

Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices.

Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction.

 [Image] The picture illustrates the contraction of two vertices marked by red.

Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain.

-----Input-----

The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph.

Next m lines contain the descriptions of edges in the format a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}), which means that there is an edge between vertices a_{i} and b_{i}. It is guaranteed that there is at most one edge between each pair of vertexes.

-----Output-----

If it is...

n, m = list(map(int, input().split()))
g = [[] for _ in range(n)]
for i in range(m):
    p, q = list(map(int, input().split()))
    g[p - 1].append(q - 1)
    g[q - 1].append(p - 1)

comp = [-1] * n
def shortest(root):
    dist = [-1] * n
    q = [0] * n
    left, right = 0, 1
    q[left] = root
    dist[root] = 0
    good = True
    while left < right:
        x = q[left]
        left = left + 1
        for i in g[x]:
            if dist[i] is -1:
                dist[i] = 1 + dist[x]
                q[right] = i
                right = right + 1
            elif dist[i] == dist[x]:
                good = False
    far = 0
    for i in dist:
        if i > far: far = i
    return good, far, dist

arr = [0] * n
good = True
for i in range(n):
    _, opt, dist = shortest(i)
    if _ is False: good = False
    if comp[i] is -1:
        for j in range(n):
            if dist[j] is not -1:
                comp[j] = i
    if arr[comp[i]] < opt:
        arr[comp[i]] = opt

if good is False: print('-1')
else: print(sum(arr))


Solve in Python:
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $(x_1,y_1)$ to the point $(x_2,y_2)$.

He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly $1$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $1$ unit.  [Image]

For example, if the box is at the point $(1,2)$ and Wabbit is standing at the point $(2,2)$, he can pull the box right by $1$ unit, with the box ending up at the point $(2,2)$ and Wabbit ending at the point $(3,2)$.

Also, Wabbit can move $1$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $1$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.

Wabbit can start at any point. It takes $1$ second to travel $1$ unit right, left, up, or down, regardless of whether he pulls the box while moving.

Determine the minimum amount of time he needs to move the box from $(x_1,y_1)$ to $(x_2,y_2)$. Note that the point where Wabbit ends up at does not matter.

-----Input-----

Each test contains multiple test cases. The first line contains a single integer $t$ $(1 \leq t \leq 1000)$: the number of test cases. The description of the test cases follows.

Each of the next $t$ lines contains four space-separated integers $x_1, y_1, x_2, y_2$ $(1 \leq x_1, y_1, x_2, y_2 \leq 10^9)$, describing the next test case.

-----Output-----

For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from $(x_1,y_1)$ to $(x_2,y_2)$.

-----Example-----
Input
2
1 2 2 2
1 1 2 2

Output
1
4

-----Note-----

In the first test case, the starting and the ending points of the box are $(1,2)$ and $(2,2)$ respectively. This is the same as the picture in the statement. Wabbit needs only...

for __ in range(int(input())):
    a, b, c, d = list(map(int, input().split()))
    if a == c or b == d:
        print(abs(a - c) + abs(b - d))
    else:
        print(abs(a - c) + abs(b - d) + 2)


Solve in Python:
Walter White and Jesse Pinkman (a drug addict) both love to play with chemicals. One day they were playing with some chemicals to make an energy drink. Unknowingly they made a highly powerful drink. To test the drink on others also they called some of their friends and gave a drop of it to everyone. Now they all were feeling highly energetic and thought of an unique game to play with each other.
After pondering for a while, Jesse came up with an extraordinary idea of competing in a race around a circular globe with N checkpoints each of one unit. Walter and all their other friends agreed with it.They divided themselves in $2$ teams with $N$ teammates in each team.This race has two commencing points $A$ and $B$ strictly facing each other. Walter and his team commences from $A$ point and other team starts from $B$. Both the teams start running at the same time clockwise around the globe. Speed of every player is constant throughout the race. If a player has a speed $X$ then it means that he covers a distance of $X$ units in one second.The race ends when some member of one team overtakes all members of opposite team at any point of time. Now you have to tell if any team will win the race or not.They all are stubborn and can run forever just to win the race. Help them to know if it is possible in anyway that the race will come to an end.
For Clarity, you can visualize the path as a circular paths where $A$ and $B$ are opposite ends of diameter. It can be proven that the actual circumference of circle do not affect the answer.
It is also possible that someone don't run at all.Keep in mind that the fastest one wins the race so does the code.

-----Input:------
- The first line of the input contains a single 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$ number of teammates in both team.
- The second line contains $N$ space-separated integers $A_1, A_2 \ldots A_N$ denoting speed of A's Team
- The third line...

for i in range(int(input())):
    n=int(input())
    a=list(map(int, input().split()))
    b=list(map(int, input().split()))
    if max(a)!=max(b):
        print("YES")
    else:
        print("NO")


Solve in Python:
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (x_{i}, y_{i}).

They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |x_{i} - x_{j}| + |y_{i} - y_{j}|. Daniel, as an ordinary person, calculates the distance using the formula $\sqrt{(x_{i} - x_{j})^{2} +(y_{i} - y_{j})^{2}}$.

The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.

-----Input-----

The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.

Each of the following n lines contains two integers x_{i} and y_{i} (|x_{i}|, |y_{i}| ≤ 10^9).

Some positions may coincide.

-----Output-----

Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.

-----Examples-----
Input
3
1 1
7 5
1 5

Output
2

Input
6
0 0
0 1
0 2
-1 1
0 1
1 1

Output
11

-----Note-----

In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and $\sqrt{(1 - 7)^{2} +(1 - 5)^{2}} = 2 \cdot \sqrt{13}$ for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.

3
from collections import Counter
from functools import reduce

n = int(input())
x = Counter()
y = Counter()
points = Counter()
for i in range(n):
  point = list(map(int, input().split()))
  x[point[0]] += 1
  y[point[1]] += 1
  points[(point[0], point[1])] += 1

def getPairsNumber(n):
  return n * (n-1) // 2

def getCounterPairsNumber(counter):
  return reduce(lambda s, n: s + getPairsNumber(n), list(counter.values()), 0)

s = getCounterPairsNumber(x) + getCounterPairsNumber(y) - getCounterPairsNumber(points)
print(s)


Solve in Python:
Watson gives to Sherlock two strings S1 and S2 consisting of uppercase English alphabets. Next he wants Sherlock to build a flower in the following way:

He puts both strings perpendicular to each other in such a way that they overlap at the same character. For example, if he has two strings "ABCDEF" and "XXBCZQ", one possible way to make a flower is:

Length of petals in the above flower are 2, 2, 3 and 3.
A flower's ugliness is sum of absolute difference of adjacent petal lengths i.e. i.e. if adjacent petal lengths are L1, L2, L3, L4, then ugliness of flower is |L1 - L2| + |L2 - L3| + |L3 - L4| + |L4 - L1|.
Sherlock wants to find minimum value of ugliness if we consider all possible flower configurations. Note that a configuration is valid even if any of the petal length is 0.

-----Input-----
First line contains T, number of test cases. Each test case consists of string S1 in one line followed by string S2 in the next line. It is guaranteed that there exists at least one possible way to make a flower.

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

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ length(S1), length(S2) ≤ 105

-----Example-----
Input:
2
ABCDE
XXBCZQ
BBB
BBBBBB

Output:
2
6

-----Explanation-----

Test case 1:

If we keep the configuration shown in statement, the ugliness is 2, which is minimum possible.

Test case 2:

One of the best configurations is

B
B B B  B  B B
B

where petal lengths are 1, 3, 1, 2.


Solve in Python:
We all know Gru loves Agnes very much. One day Agnes asked Gru to answer some of her queries. She lined up $N$ minions in a straight line from $1$ to $N$.
You are given an array $A$ which contains the height of minions. Agnes will ask him several queries. In each query, Gru has to tell whether the bitwise AND of  $A[L \ldots R]$ is EVEN or ODD. Since Gru is busy planning the biggest heist on Earth, he asks for your help.

-----Input:-----
- First line of the input contains an integer $T$ denoting the number of test cases.
For each test case:-
- First line contains an integer $N$ denoting the number of elements.
- Second line contains $N$ spaced integer representing array elements.
- Third line contains $Q$ representing number of query.
- Next $Q$ lines contains two integer $L$ and $R$ as defined above.

-----Output:-----
For each query, output "EVEN" or "ODD" without quotes.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $1 \leq A_i \leq 10^5$
- $1 \leq Q \leq 10^5$

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

-----Sample Output:-----
ODD
EVEN
EVEN

-----Explanation-----
- For the first query, the bitwise AND of 1 and 3 is 1, which is Odd. Hence the first output is ODD.
- For the third query, the bitwise AND of 2 and 4 is 0, which is Even. Hence the third output is EVEN.

for _ in range(int(input())):
 n = int(input())
 a = list(map(int,input().split()))
 p = []; cnt = 0
 for i in range(n):
  if a[i]%2==0:
   cnt += 1
   p.append(cnt)
   cnt += 1
   continue
  p.append(cnt)
 for _ in range(int(input())):
  l,r = list(map(int,input().split()))
  if p[r-1]-p[l-1]>0:
   print('EVEN')
  else:
   print('ODD')


Solve in Python:
We all know about Roman Numerals, and if not, here's a nice [introduction kata](http://www.codewars.com/kata/5580d8dc8e4ee9ffcb000050). And if you were anything like me, you 'knew' that the numerals were not used for zeroes or fractions; but not so!

I learned something new today: the [Romans did use fractions](https://en.wikipedia.org/wiki/Roman_numerals#Special_values) and there was even a glyph used to indicate zero.

So in this kata, we will be implementing Roman numerals and fractions.

Although the Romans used base 10 for their counting of units, they used base 12 for their fractions. The system used dots to represent twelfths, and an `S` to represent a half like so:

* ^(1)/12 = `.`
* ^(2)/12 = `:`
* ^(3)/12 = `:.`
* ^(4)/12 = `::`
* ^(5)/12 = `:.:`
* ^(6)/12 = `S`
* ^(7)/12 = `S.`
* ^(8)/12 = `S:`
* ^(9)/12 = `S:.`
* ^(10)/12 = `S::`
* ^(11)/12 = `S:.:`
* ^(12)/12 = `I` (as usual)

Further, zero was represented by `N`

## Kata

Complete the method that takes two parameters: an integer component in the range 0 to 5000 inclusive, and an optional fractional component in the range 0 to 11 inclusive.

You must return a string with the encoded value. Any input values outside the ranges given above should return `"NaR"` (i.e. "Not a Roman" :-)

## Examples

```python
roman_fractions(-12)     #=> "NaR"
roman_fractions(0, -1)   #=> "NaR"
roman_fractions(0, 12)   #=> "NaR"
roman_fractions(0)       #=> "N"
roman_fractions(0, 3)    #=> ":."
roman_fractions(1)       #=> "I"
roman_fractions(1, 0)    #=> "I"
roman_fractions(1, 5)    #=> "I:.:"
roman_fractions(1, 9)    #=> "IS:."
roman_fractions(1632, 2) #=> "MDCXXXII:"
roman_fractions(5000)    #=> "MMMMM"
roman_fractions(5001)    #=> "NaR"
```

def roman_fractions(num, fraction=0):
    rom = ''
    FACT = { 1:'.', 2:':', 3:':.',4:'::',5:':.:',6:'S',7:'S.',8:'S:', 9:'S:.',10:'S::', 11:'S:.:' }
    ENCO = { 1:'I',  5:'V', 10:'X', 50:'L', 100:'C', 500:'D', 1000:'M' }
    EDGE = {
         0:lambda x, elem,  dict, number : dict.get(elem, '') * number,
         1:lambda e, i, D, l : e +D.get(i*(l+1),'M'*(l-1)) if l in [4,9] else D.get(i*l, 'M'*5) if l is 5 else D[i*5] + (e * (l%5))
           }
    if num < 0 or num>5000 or fraction and fraction not in FACT:
        return 'NaR'

    for element in list(ENCO.keys())[0::2][::-1]:
        left = num // element
        rom += EDGE.get(left>3, '')( ENCO[element] , element, ENCO, left )
        num %= element

    ret = rom + FACT.get(fraction,'')

    return  ret if ret else 'N'


Solve in Python:
We all know how great ABD aka AB-DE-VILLIERS is. However his team mates were jealous of him and posed a problem for him to solve.The problem description is as follows :

Given an array of integers,find the length of the largest subarray(contiguous) of the given array with the maximum possible GCD (Greatest Common Divisor).

For info on GCD ,see this link: https://en.wikipedia.org/wiki/Greatest_common_divisor

GCD of the subarray is defined as the GCD of all the elements of the subarray.
As ABD is not aware of competitive programming he asks your help. Help him!

-----Input-----
First line will contain integer N denoting the size of array.

Second line will contain N integers denoting array elements.

-----Output-----
The answer as specified in the problem statement .

-----Constraints-----
1 <= N <= 1000000

1 <= array[i] <=100000000000

-----Example-----
Input:
4
2 4 8 3

Output:
1

Explanation
GCD of all possible subarrays of the given array are : 2 , 2 , 2 , 1 , 4 , 4, 1 , 8 , 1 , 3

Largest GCD possible : 8

Length of the largest subarray with GCD as 8 is 1

Hence answer is 1 .

from fractions import gcd as G
n=eval(input())
flag=1
arr=list(map(int,input().split()))
a=max(arr)
best = 0
I_I = 0
while I_I<n:
 if arr[I_I]==a:
  k=I_I
  while k<n and arr[k]==a:
   k+=1
  best = max(best, k-I_I)
  I_I = k
 else: I_I+=1

print(best)


Solve in Python:
We all know how to handle exceptions in Python. Just use:

    try:
        num = float(input())
    except ValueError:
        print("That's not a number!")
    else:
        print(num)

Code such as this

    def factorial(x, n = 1):
        if x == 0:
          raise ValueError(n)
        factorial(x - 1, n * x)

relies on ridiculous exception misuse, but you can't change it because that would require a complete refactor. Code such as this

    try:
        return int(input("Input a number: ")
    except ValueError:
        return 4 # random number

relies on reasonable exception use - almost all of the Python documentation examples are written in this way.

What if you are using a faulty implementation of Embedded Python that doesn't implement the `try` statement? Where `sys.excepthook` is a hard-coded, unoverrideable value? Where even `__file__` is not defined? How do you use basic functions like `list.index`?

Your task is to write a function that can handle exceptions raised in a program or function _without_ using `try` or `except`. Somehow.

The first argument of your function `handle` will be a `lambda` requiring no parameters. You will call this function and handle any exceptions raised. The second argument will be a callable `success`:

    def success(func, val):
        pass

The third argument will be a callable `failure`:

    def failure(func, exc):
        pass

Subsequent arguments will be exceptions. If instances of these exceptions are raised, you must call the handler and no error message must be printed to `stderr`. If the exception raised is not provided as an argument, it should appear as though the exception was never caught.

Pass the return value of `func` to `success` unless it raises an exception. If it raises an exception that `isinstance` of an exception class passed to `handle`, call `failure` with an instance of the raised exception.

Don't worry about the little things like dealing with the extra arguments to exceptions or maintaining the call stack. Whoever writes code like...

def handle(func, success, failure, *exceptions):
    class manager:
        def __enter__(self):
            pass
        def __exit__(self, type, value, traceback):
            if isinstance(value, exceptions):
                failure(func, value)
                return True
            return not value
    with manager():
        success(func, func())


Solve in Python:
We all know that Share market is place where drastic change occurs within moments. So we have one Stockholder, Isabella, who wants to maximize her profit by selling her shares. She has $N$ shares of a Doofenshmirtz Corporation which is represented by $N$ different lines where each line contains two space separated integers $a_i$ , $b_i$ corresponding to initial and final values of the share prize. Isabella can sell any number of shares. But, she will sell those shares only if the following condition is satisfied -
- for any pair $(i,j)$ of shares that she choses to sell, $a_i \leq a_j$  and $b_i < b_j$ must be satisfied.
You need to tell Isabella the maximum number of Shares she can sell.

-----Input:-----
- First line will contain $T$, number of test cases.
- Each test case has the following format:
- First line of each test case contain single integer $N$, the number of shares of Isabella.
- Next $N$ lines of each test case contain two space separated integers $a_i$, $b_i$ (initial and final value of share prize respectively) for each $1 \leq i \leq N$.

-----Output:-----
For each test case output a single integer: the maximum number of shares that can be sold by Isabella.

-----Constraints-----
- $1 \leq T \leq 5$
- $1 \leq N \leq 10^5$
- $1 \leq a_i , b_i \leq 10^9 , for  each $1$ \leq $i$ \leq $N

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

-----Sample Output:-----
$3$

-----Explanation:-----
Here, Isabella decided to sell share 1, share 3 and share 4 as any two pair of
chosen share hold the given condition.

# Python program to find
# length of longest
# increasing subsequence
# in O(n Log n) time

# Binary search (note
# boundaries in the caller)
# A[] is ceilIndex
# in the caller
def CeilIndex(A, l, r, key):

	while (r - l > 1):

		m = l + (r - l)//2
		if (A[m] >= key):
			r = m
		else:
			l = m
	return r

def LongestIncreasingSubsequenceLength(A, size):

	# Add boundary case,
	# when array size is one

	tailTable = [0 for i in range(size + 1)]
	len = 0 # always points empty slot

	tailTable[0] = A[0]
	len = 1
	for i in range(1, size):

		if (A[i] < tailTable[0]):

			# new smallest value
			tailTable[0] = A[i]

		elif (A[i] > tailTable[len-1]):

			# A[i] wants to extend
			# largest subsequence
			tailTable[len] = A[i]
			len+= 1

		else:
			# A[i] wants to be current
			# end candidate of an existing
			# subsequence. It will replace
			# ceil value in tailTable
			tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i]

	return len

T=int(input())
while T:
    N=int(input())
    ls=[]
    for i in range(N):
        a,b=map(int,input().split())
        ls.append([a,b])
    ls.sort()
    temp=[ls[i][1] for i in range(N)]
    print(LongestIncreasingSubsequenceLength(temp,N))
    T-=1


Solve in Python:
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.

There are n citizens in Kekoland, each person has c_{i} coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people.

After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.

Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.

-----Input-----

The first line of the input contains two integers n and k (1 ≤ n ≤ 500 000, 0 ≤ k ≤ 10^9) — the number of citizens in Kekoland and the number of days left till Robin Hood's retirement.

The second line contains n integers, the i-th of them is c_{i} (1 ≤ c_{i} ≤ 10^9) — initial wealth of the i-th person.

-----Output-----

Print a single line containing the difference between richest and poorest peoples wealth.

-----Examples-----
Input
4 1
1 1 4 2

Output
2

Input
3 1
2 2 2

Output
0

-----Note-----

Lets look at how wealth changes through day in the first sample.  [1, 1, 4, 2]  [2, 1, 3, 2] or [1, 2, 3, 2]

So the answer is 3 - 1 = 2

In second sample wealth will remain the same for each person.

import sys

n, k = map(int, sys.stdin.readline().split())
nums = list(map(int, sys.stdin.readline().split()))
total = sum(nums)
avg = int(total / n)

def check1(nums, target, K):
    for x in nums:
        if K < 0:
            return False
        if x < target:
            K -= target - x
    return K >= 0

def check2(nums, target, K):
    for x in nums:
        if K < 0:
            return False
        if x > target:
            K -= x - target
    return K >= 0

l1, r1 = min(nums), avg + 1
while l1 + 1 < r1:
    mid = (l1 + r1) >> 1
    if check1(nums, mid, k):
        l1 = mid
    else:
        r1 = mid

if check2(nums, avg + (0 if total % n == 0 else 1), k):
    r2 = avg + (0 if total % n == 0 else 1)
else:
    l2, r2 = avg + (0 if total % n == 0 else 1), max(nums)
    while l2 + 1 < r2:
        mid = (l2 + r2) >> 1
        if check2(nums, mid, k):
            r2 = mid
        else:
            l2 = mid

print(r2 - l1)


Solve in Python:
We all love the future president (or Führer or duce or sōtō as he could find them more fitting) donald trump, but we might fear that some of his many fans like John Miller or John Barron are not making him justice, sounding too much like their (and our as well, of course!) hero and thus risking to compromise him.

For this reason we need to create a function to detect the original and unique rythm of our beloved leader, typically having a lot of extra vowels, all ready to fight the estabilishment.

The index is calculated based on how many vowels are repeated more than once in a row and dividing them by the total number of vowels a petty enemy of America would use.

For example:
```python
trump_detector("I will build a huge wall")==0 #definitely not our trump: 0 on the trump score
trump_detector("HUUUUUGEEEE WAAAAAALL")==4 #4 extra "U", 3 extra "E" and 5 extra "A" on 3 different vowel groups: 12/3 make for a trumpy trumping score of 4: not bad at all!
trump_detector("listen migrants: IIII KIIIDD YOOOUUU NOOOOOOTTT")==1.56 #14 extra vowels on 9 base ones
```
**Notes:** vowels are only the ones in the patriotic group of "aeiou": "y" should go back to Greece if she thinks she can have the same rights of true American vowels; there is always going to be at least a vowel, as silence is the option of coward Kenyan/terrorist presidents and their friends.

Round each result by two decimal digits: there is no place for small fry in Trump's America.

*Special thanks for [Izabela](https://www.codewars.com/users/ijelonek) for support and proof-reading.*

from re import findall, IGNORECASE

def trump_detector(trump_speech):

    final = [len(c[1]) for c in findall(r'([aeiou])(\1*)',trump_speech,IGNORECASE)]

    return round(sum(final)/len(final),2)


Solve in Python:
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions.

Function should take width and height of an image and return a ratio string (ex."16:9").
If any of width or height entry is 0 function should throw an exception (or return `Nothing`).

from fractions import gcd

def lcm(a, b):
    return a * b / gcd(a, b)

def calculate_ratio(w,h):
    if all(x > 0 for x in [w,h]):
        return "{}:{}".format(lcm(w,h)/h,lcm(w,h)/w)
    return 'You threw an error'


Solve in Python:
We are committed to the well being of all participants. Therefore, instead of the problem, we suggest you enjoy a piece of cake.

Uh oh. Somebody cut the cake. We told them to wait for you, but they did it anyway. There is still some left, though, if you hurry back. Of course, before you taste the cake, you thought about how the cake was cut.

It is known that the cake was originally a regular $n$-sided polygon, each vertex of which had a unique number from $1$ to $n$. The vertices were numbered in random order.

Each piece of the cake is a triangle. The cake was cut into $n - 2$ pieces as follows: each time one cut was made with a knife (from one vertex to another) such that exactly one triangular piece was separated from the current cake, and the rest continued to be a convex polygon. In other words, each time three consecutive vertices of the polygon were selected and the corresponding triangle was cut off.

A possible process of cutting the cake is presented in the picture below. [Image] Example of 6-sided cake slicing.

You are given a set of $n-2$ triangular pieces in random order. The vertices of each piece are given in random order — clockwise or counterclockwise. Each piece is defined by three numbers — the numbers of the corresponding $n$-sided cake vertices.

For example, for the situation in the picture above, you could be given a set of pieces: $[3, 6, 5], [5, 2, 4], [5, 4, 6], [6, 3, 1]$.

You are interested in two questions.  What was the enumeration of the $n$-sided cake vertices?  In what order were the pieces cut?

Formally, you have to find two permutations $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$) and $q_1, q_2, \dots, q_{n - 2}$ ($1 \le q_i \le n - 2$) such that if the cake vertices are numbered with the numbers $p_1, p_2, \dots, p_n$ in order clockwise or counterclockwise, then when cutting pieces of the cake in the order $q_1, q_2, \dots, q_{n - 2}$ always cuts off a triangular piece so that the remaining part forms one convex polygon.

For example, in the picture above the answer...

def get_edge(vertex1, vertex2):
    return (vertex1, vertex2) if vertex1 < vertex2 else (vertex2, vertex1)

def swap(arr, i, j):
    temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp

def __starting_point():
    T = int(input())
    for t in range(T):
        n = int(input())
        pieces = []
        for c in range(n-2):
            inp = input().rstrip().split(" ")
            pieces.append([int(inp[0]), int(inp[1]), int(inp[2])])

        # Preparing the graph
        G = {}
        piece_index = 0
        while piece_index < len(pieces):
            for vertex in pieces[piece_index]:
                if vertex not in G:
                    G[vertex] = {}
                G[vertex][piece_index] = True
            piece_index += 1

        # prepare list of vertices associated with only one piece
        # That piece can be safely removed
        next_vertices = []
        for vertex in G:
            if len(G[vertex]) == 1:
                next_vertices.append(vertex)

        q = []
        border_edges = {}
        non_border_edges = {}
        while len(next_vertices) > 0:
            v = next_vertices.pop()
            if len(G[v]) > 0:
                piece_index = list(G[v].keys()).pop()
                q.append(str(piece_index+1))
                piece = pieces[piece_index]
                G.pop(v)
                for vertex_index in range(3):
                    vertex = piece[vertex_index]
                    if vertex != v:
                        G[vertex].pop(piece_index)
                        if len(G[vertex]) == 1:
                            next_vertices.append(vertex)
                        edge = get_edge(v, vertex)
                        if edge not in non_border_edges:
                            border_edges[edge] = True
                    else:
                        swap(piece, 0, vertex_index)
                edge = get_edge(piece[1], piece[2])
                non_border_edges[edge] = True

        border_edges = list(border_edges.keys())
        vertices = {}
        for...


Solve in Python:
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".)
A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i:

If S[i] == 'D', then P[i] > P[i+1], and;
If S[i] == 'I', then P[i] < P[i+1].

How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.

Example 1:
Input: "DID"
Output: 5
Explanation:
The 5 valid permutations of (0, 1, 2, 3) are:
(1, 0, 3, 2)
(2, 0, 3, 1)
(2, 1, 3, 0)
(3, 0, 2, 1)
(3, 1, 2, 0)

Note:

1 <= S.length <= 200
S consists only of characters from the set {'D', 'I'}.

from functools import lru_cache

class Solution:
    def numPermsDISequence(self, S: str) -> int:
        # Dynamic Programming
        # Time  complexity: O(N^3)
        # Space complexity: O(N^2)
        MOD = 10**9 + 7
        N = len(S)

        @lru_cache(None)
        def dp(i, j):
            # How many ways to place P_i with relative rank j?
            if i == 0:
                return 1
            elif S[i - 1] == 'D':
                return sum(dp(i - 1, k) for k in range(j, i)) % MOD
            else:
                return sum(dp(i - 1, k) for k in range(j))

        return sum(dp(N, j) for j in range(N + 1)) % MOD


Solve in Python:
We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b", ...) are keys, and ("A", "B", ...) are locks.
We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions.  We cannot walk outside the grid, or walk into a wall.  If we walk over a key, we pick it up.  We can't walk over a lock unless we have the corresponding key.
For some 1 <= K <= 6, there is exactly one lowercase and one uppercase letter of the first K letters of the English alphabet in the grid.  This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.
Return the lowest number of moves to acquire all keys.  If it's impossible, return -1.

Example 1:
Input: ["@.a.#","###.#","b.A.B"]
Output: 8

Example 2:
Input: ["@..aA","..B#.","....b"]
Output: 6

Note:

1 <= grid.length <= 30
1 <= grid[0].length <= 30
grid[i][j] contains only '.', '#', '@', 'a'-'f' and 'A'-'F'
The number of keys is in [1, 6].  Each key has a different letter and opens exactly one lock.

class Solution:
    def shortestPathAllKeys(self, grid: List[str]) -> int:
        # bfs: x,y, ownkeys -> n*m* 2^6

        def have_keys(status, key_id):
            return status & (2**key_id)

        sx, sy = -1, -1
        key_number = 0
        key_idx = 'abcdef'
        lock_idx = 'ABCDEF'
        n, m = len(grid), len(grid[0])
        for i in range(n):
            for j in range(m):
                if grid[i][j] == '@':
                    sx, sy = i, j
                elif grid[i][j] in key_idx:
                    key_number = max(key_number, key_idx.find(grid[i][j]))
        #print(sx, sy)
        #print(key_number)
        # bfs: (x, y, ownkeys)
        final_ownkey = 2 ** (key_number+1) - 1
        head, queue = 0, [(sx, sy, 0)]
        moves = [(0,1), (0,-1), (1,0), (-1,0)]

        visited = {(sx, sy, 0): 0}

        while head < len(queue):
            x, y, status = queue[head]
            step = visited[queue[head]]
            #print(x, y, status)
            #print(step)
            for dx, dy in moves:
                tx, ty, new_status = x + dx, y + dy, status
                if n > tx >= 0 and m > ty >=0:
                    # wall?
                    if grid[tx][ty] == '#':
                        continue

                    # locked
                    if grid[tx][ty] in lock_idx and not have_keys(new_status, lock_idx.find(grid[tx][ty])):
                        continue

                    # first time pick up key
                    if grid[tx][ty] in key_idx and not have_keys(new_status, key_idx.find(grid[tx][ty])):
                        new_status += 2 ** key_idx.find(grid[tx][ty])

                    if new_status == final_ownkey:
                        return step + 1

                    if (tx, ty, new_status) not in visited:
                        queue.append((tx, ty, new_status))
                        visited[(tx, ty, new_status)] = step + 1
  ...


Solve in Python:
We are given a certain number ```n``` and we do the product partitions of it.
```[59, 3, 2, 2, 2]``` is a product partition of ```1416``` because:
```
59 * 3 * 2 * 2 * 2 = 1416
```
We form a score, ```sc``` for each partition in the following way:
- if ```d1, d2, ...., dk``` are the prime factors of ```n```, and ```f1, f2, ...., fk```, the corresponding frequencies for each factor, we calculate:

Suposse that we have that ```n = 1416```
The product partitions of this number with a corresponding special score are as follows:
```
Product Partition           Score(sc)
[59, 3, 2, 2, 2]             350    # equals to: (59^1 + 3^1 + 2^3) * 5
[177, 2, 2, 2]               740    # equals to: (177^1 + 2^3) * 4
[118, 3, 2, 2]               500
[59, 6, 2, 2]                276
[354, 2, 2]                 1074
[59, 4, 3, 2]                272
[236, 3, 2]                  723
[177, 4, 2]                  549
[118, 6, 2]                  378
[59, 12, 2]                  219
[708, 2]                    1420  <---- maximum value
[118, 4, 3]                  375
[59, 8, 3]                   210
[472, 3]                     950
[59, 6, 4]                   207
[354, 4]                     716
[236, 6]                     484
[177, 8]                     370
[118, 12]                    260
[59, 24]                     166  <---- minimum value
```
So we need a function that may give us the product partition with maximum or minimum score.

The function ```find_spec_prod_part()``` will receive two arguments:

- an integer ```n, n > 0```
- a command as a string, one of the following ones: ```'max' or 'min'```

The function should output a list with two elements: the found product partition (as a list sorted in descendin order) with its corresponding score.
```
find_spec_prod_part(n, com) ---> [prod_partition, score]
```
Let'see some cases:
```python
find_spec_prod_part(1416, 'max') == [[708, 2], 1420]

find_spec_prod_part(1416, 'min') == [[59, 24], 166]
```

The function should reject prime...

def partition(n):
    return [[int(n/x)] for x in range(1, 1+int(n/2)) if n % x == 0]

def prod(a):
    prod = 1
    for n in a:
        prod *= n
    return prod

def score(a):
    return sum(n**a.count(n) for n in reversed(sorted(set(a))))*len(a)

def find_spec_prod_part(n, com):
    there_are_new = True

    partitions = partition(n)

    while there_are_new:
        there_are_new = False
        new_partitions = []
        for p in partitions:
            product = prod(p)
            if product < n:
                for new in partition(n/product):
                    if new[0] <= p[-1] and prod(p+new) <= n:
                        there_are_new = True
                        new_partitions.append(p + new)
            else:
                new_partitions.append(p)

        partitions = new_partitions

    if len(partitions) <= 1:
        return ("It is a prime number")

    result = None
    result_score = None

    for p in partitions:
        if len(p) > 1:
            s = score(p)
            if (com == "max" and (not result_score or result_score < s)) or (com == "min" and (not result_score or result_score > s)):
                result = p
                result_score = s

    return [result, result_score]


Solve in Python:
We are given a linked list with head as the first node.  Let's number the nodes in the list: node_1, node_2, node_3, ... etc.
Each node may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice.  If such a j does not exist, the next larger value is 0.
Return an array of integers answer, where answer[i] = next_larger(node_{i+1}).
Note that in the example inputs (not outputs) below, arrays such as [2,1,5] represent the serialization of a linked list with a head node value of 2, second node value of 1, and third node value of 5.

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

Example 2:
Input: [2,7,4,3,5]
Output: [7,0,5,5,0]

Example 3:
Input: [1,7,5,1,9,2,5,1]
Output: [7,9,9,9,0,5,0,0]

Note:

1 <= node.val <= 10^9 for each node in the linked list.
The given list has length in the range [0, 10000].

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def nextLargerNodes(self, head: ListNode) -> List[int]:
        ans, stack = [], []
        while head:
            while stack and stack[-1][1] < head.val:
                ans[stack.pop()[0]] = head.val
            stack.append([len(ans), head.val])
            ans.append(0)
            head = head.next
        return ans


Solve in Python:
We are given a list of (axis-aligned) rectangles.  Each rectangle[i] = [x1, y1, x2, y2] , where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the ith rectangle.
Find the total area covered by all rectangles in the plane.  Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:
Input: [[0,0,2,2],[1,0,2,3],[1,0,3,1]]
Output: 6
Explanation: As illustrated in the picture.

Example 2:
Input: [[0,0,1000000000,1000000000]]
Output: 49
Explanation: The answer is 10^18 modulo (10^9 + 7), which is (10^9)^2 = (-7)^2 = 49.

Note:

1 <= rectangles.length <= 200
rectanges[i].length = 4
0 <= rectangles[i][j] <= 10^9
The total area covered by all rectangles will never exceed 2^63 - 1 and thus will fit in a 64-bit signed integer.

class Solution:
    def rectangleArea(self, rectangles: List[List[int]]) -> int:
        Xs = [x for x1, _, x2, _ in rectangles for x in [x1, x2]]
        Xs.sort()
        X_idx_lookup = {x: idx for idx, x in enumerate(Xs)}

        res = 0
        prev_y = 0
        X_span = 0

        Ys = [e for x1, y1, x2, y2 in rectangles for e in [[y1, x1, x2, 1], [y2, x1, x2, -1]]]
        Ys.sort()

        overlap_count = [0] * len(Xs)

        for y, xl, xr, inout in Ys:
            res += (y - prev_y) * X_span
            prev_y = y
            start_idx, end_idx = X_idx_lookup[xl], X_idx_lookup[xr]
            for i in range(start_idx, end_idx):
                overlap_count[i] += inout
            X_span = sum(x2 - x1 if c > 0 else 0 for x1, x2, c in zip(Xs, Xs[1:], overlap_count))
        return res % 1000000007

    def rectangleArea(self, rectangles: List[List[int]]) -> int:
        Xs = [x for x1, _, x2, _ in rectangles for x in [x1, x2]]
        Xs.sort()
        covered = [0] * len(Xs)
        res = 0

        keypoints = [e for x1, y1, x2, y2 in rectangles for e in [[y1, x1, x2, 1], [y2, x1, x2, -1]]]
        keypoints.sort()

        prev_y = 0
        width_span = 0
        for y, x1, x2, inout in keypoints:
            res += (y - prev_y) * width_span
            prev_y = y
            for i in range(len(covered) - 1):
                a, b = Xs[i], Xs[i + 1]
                if x1 <= a and b <= x2:
                    covered[i] += inout
            width_span = sum(Xs[i + 1] - Xs[i] if covered[i] > 0 else 0 for i in range(len(covered) - 1))
        return res % 1000000007


Solve in Python:
We are given a list schedule of employees, which represents the working time for each employee.

Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.

Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.

Example 1:

Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
Output: [[3,4]]
Explanation:
There are a total of three employees, and all common
free time intervals would be [-inf, 1], [3, 4], [10, inf].
We discard any intervals that contain inf as they aren't finite.

Example 2:

Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
Output: [[5,6],[7,9]]

(Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays.  For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined.)

Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.

Note:
schedule and schedule[i] are lists with lengths in range [1, 50].
0 .

class Solution:
     def intersectionSizeTwo(self, intervals):
         """
         :type intervals: List[List[int]]
         :rtype: int
         """
         intervals.sort(key=lambda x: x[1])
         if len(intervals) <= 1:
             return len(intervals[0])
         s = set()
         for e in intervals:
             if not s:
                 a = e[1] - 1
                 b = e[1]
                 s.add(a)
                 s.add(b)
                 continue
             if e[0] <= a :
                 continue

             if e[0] > a and  e[1] > b >= e[0] :
                 a = b
                 b = e[-1]
                 s.add(b)
                 continue
             a = e[1] - 1
             b = e[1]
             s.add(a)
             s.add(b)

         return len(s)


Solve in Python:
We are given a sequence of coplanar points and see all the possible triangles that may be generated which all combinations of three points.

We have the following list of points with the cartesian coordinates of each one:
```
Points [x, y]
   A   [1, 2]
   B   [3, 3]
   C   [4, 1]
   D   [1, 1]
   E   [4, -1]
```
With these points we may have the following triangles: ```ABC, ABD, ABE, ACD, ACE, ADE, BCD, BCE, BDE, CDE.``` There are three special ones: ```ABC, ACD and CDE```, that have an angle of 90°. All is shown in the picture below:

We need to count all the rectangle triangles that may be formed by a given list of points.

The case decribed above will be:
```python
count_rect_triang([[1, 2],[3, 3],[4, 1],[1, 1],[4, -1]]) == 3
```

Observe this case:
```python
count_rect_triang([[1, 2],[4, -1],[3, 3],[4, -1],[4, 1],[1, 1],[4, -1], [4, -1], [3, 3], [1, 2]]) == 3
```
If no rectangle triangles may be generated the function will output ```0```.

Enjoy it!

from itertools import combinations
def count_rect_triang(points):
    n=0
    points_set=set()
    for p in points:
        points_set.add(tuple(p))
    for (x1,y1),(x2,y2),(x3,y3) in combinations(points_set,3):
        l1,l2,l3=sorted([(x2-x1)**2+(y2-y1)**2,(x3-x2)**2+(y3-y2)**2,(x1-x3)**2+(y1-y3)**2])
        if l1+l2==l3:
            n+=1
    return n


Solve in Python:
We are given an array asteroids of integers representing asteroids in a row.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left).  Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions.  If two asteroids meet, the smaller one will explode.  If both are the same size, both will explode.  Two asteroids moving in the same direction will never meet.

Example 1:

Input:
asteroids = [5, 10, -5]
Output: [5, 10]
Explanation:
The 10 and -5 collide resulting in 10.  The 5 and 10 never collide.

Example 2:

Input:
asteroids = [8, -8]
Output: []
Explanation:
The 8 and -8 collide exploding each other.

Example 3:

Input:
asteroids = [10, 2, -5]
Output: [10]
Explanation:
The 2 and -5 collide resulting in -5.  The 10 and -5 collide resulting in 10.

Example 4:

Input:
asteroids = [-2, -1, 1, 2]
Output: [-2, -1, 1, 2]
Explanation:
The -2 and -1 are moving left, while the 1 and 2 are moving right.
Asteroids moving the same direction never meet, so no asteroids will meet each other.

Note:
The length of asteroids will be at most 10000.
Each asteroid will be a non-zero integer in the range [-1000, 1000]..

class Solution:
     def asteroidCollision(self, asteroids):
         """
         :type asteroids: List[int]
         :rtype: List[int]
         """

         ret = []

         for val in asteroids:

             append_flag = True

             while len(ret) > 0:

                 # both neg or pos
                 if val * ret[-1] > 0:
                     break

                 if val > 0:
                     break

                 # val fails, ignore it
                 if abs(val) < abs(ret[-1]):
                     append_flag = False
                     break

                 # [-5, 5]
                 if val + ret[-1] == 0:
                     ret.pop()
                     append_flag = False
                     break

                 ret.pop()

             if append_flag:
                 ret.append(val)

         return ret


Solve in Python:
We are given an array A of N lowercase letter strings, all of the same length.
Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.
For example, if we have an array A = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"], and the remaining columns of A are ["b","v"], ["e","y"], and ["f","z"].  (Formally, the c-th column is [A[0][c], A[1][c], ..., A[A.length-1][c]]).
Suppose we chose a set of deletion indices D such that after deletions, each remaining column in A is in non-decreasing sorted order.
Return the minimum possible value of D.length.

Example 1:
Input: A = ["cba","daf","ghi"]
Output: 1
Explanation:
After choosing D = {1}, each column ["c","d","g"] and ["a","f","i"] are in non-decreasing sorted order.
If we chose D = {}, then a column ["b","a","h"] would not be in non-decreasing sorted order.

Example 2:
Input: A = ["a","b"]
Output: 0
Explanation: D = {}

Example 3:
Input: A = ["zyx","wvu","tsr"]
Output: 3
Explanation: D = {0, 1, 2}

Constraints:

1 <= A.length <= 100
1 <= A[i].length <= 1000

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        for i in range(len(A)):
            self.convertCharsToIntArray(i,A)
        counts = 0
        for i in range(len(A[0])):
            checker = False
            for j in range(1,len(A)):
                if A[j-1][i] > A[j][i]:
                    checker = True
            if checker:
                counts += 1
        return counts

    def convertCharsToIntArray(self,i,A):
        chars = A[i]
        array = []
        for char in chars:
            array.append(ord(char))
        A[i] = array


Solve in Python:
We are given an array A of N lowercase letter strings, all of the same length.
Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.
For example, if we have an array A = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef","vyz"].
Suppose we chose a set of deletion indices D such that after deletions, the final array has its elements in lexicographic order (A[0] <= A[1] <= A[2] ... <= A[A.length - 1]).
Return the minimum possible value of D.length.

Example 1:
Input: ["ca","bb","ac"]
Output: 1
Explanation:
After deleting the first column, A = ["a", "b", "c"].
Now A is in lexicographic order (ie. A[0] <= A[1] <= A[2]).
We require at least 1 deletion since initially A was not in lexicographic order, so the answer is 1.

Example 2:
Input: ["xc","yb","za"]
Output: 0
Explanation:
A is already in lexicographic order, so we don't need to delete anything.
Note that the rows of A are not necessarily in lexicographic order:
ie. it is NOT necessarily true that (A[0][0] <= A[0][1] <= ...)

Example 3:
Input: ["zyx","wvu","tsr"]
Output: 3
Explanation:
We have to delete every column.

Note:

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

class Solution:
    def minDeletionSize(self, A):
        m, n = len(A), len(A[0])
        first = [-1] * m
        res = 0
        for j in range(n):
            for i in range(1, m):
                if first[i] == -1 and A[i][j] < A[i - 1][j]:
                    res += 1
                    break
            else:
                for i in range(1, m):
                    if A[i][j] > A[i - 1][j] and first[i] == -1:
                        first[i] = j
        return res


Solve in Python:
We are given an array A of N lowercase letter strings, all of the same length.
Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.
For example, if we have an array A = ["babca","bbazb"] and deletion indices {0, 1, 4}, then the final array after deletions is ["bc","az"].
Suppose we chose a set of deletion indices D such that after deletions, the final array has every element (row) in lexicographic order.
For clarity, A[0] is in lexicographic order (ie. A[0][0] <= A[0][1] <= ... <= A[0][A[0].length - 1]), A[1] is in lexicographic order (ie. A[1][0] <= A[1][1] <= ... <= A[1][A[1].length - 1]), and so on.
Return the minimum possible value of D.length.

Example 1:
Input: ["babca","bbazb"]
Output: 3
Explanation: After deleting columns 0, 1, and 4, the final array is A = ["bc", "az"].
Both these rows are individually in lexicographic order (ie. A[0][0] <= A[0][1] and A[1][0] <= A[1][1]).
Note that A[0] > A[1] - the array A isn't necessarily in lexicographic order.

Example 2:
Input: ["edcba"]
Output: 4
Explanation: If we delete less than 4 columns, the only row won't be lexicographically sorted.

Example 3:
Input: ["ghi","def","abc"]
Output: 0
Explanation: All rows are already lexicographically sorted.

Note:

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

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        size = len(A[0])
        best = [0] * size
        best[0] = 1
        for i in range(1, size):
            best[i] = 1
            for j in range(0, i):
                if best[j] >= best[i] and self.beats(A, i, j):
                    best[i] = best[j] + 1

        return size - max(best)

    def beats(self, A, a, b):
        # Returns True if idx a beats idx b
        for s in A:
            if s[b] > s[a]:
                return False

        return True


Solve in Python:
We are given an elevation map, heights[i] representing the height of the terrain at that index.  The width at each index is 1.  After V units of water fall at index K, how much water is at each index?

Water first drops at index K and rests on top of the highest terrain or water at that index.  Then, it flows according to the following rules:
If the droplet would eventually fall by moving left, then move left.
Otherwise, if the droplet would eventually fall by moving right, then move right.
Otherwise, rise at it's current position.
Here, "eventually fall" means that the droplet will eventually be at a lower level if it moves in that direction.
Also, "level" means the height of the terrain plus any water in that column.

We can assume there's infinitely high terrain on the two sides out of bounds of the array.  Also, there could not be partial water being spread out evenly on more than 1 grid block - each unit of water has to be in exactly one block.

Example 1:

Input: heights = [2,1,1,2,1,2,2], V = 4, K = 3
Output: [2,2,2,3,2,2,2]
Explanation:
#       #
#       #
##  # ###
#########
 0123456

Example 2:

Input: heights = [1,2,3,4], V = 2, K = 2
Output: [2,3,3,4]
Explanation:
The last droplet settles at index 1, since moving further left would not cause it to eventually fall to a lower height.

Example 3:

Input: heights = [3,1,3], V = 5, K = 1
Output: [4,4,4]

Note:
heights will have length in [1, 100] and contain integers in [0, 99].
V will be in range [0, 2000].
K will be in range [0, heights.length - 1].

class Solution:
     def reachNumber(self, target):
         """
         :type target: int
         :rtype: int
         """
         target=abs(target)

         n=math.ceil(((1+8*target)**0.5-1)/2)

         if target%2>0:
             if n%4==1 or n%4==2:
                 return n
             elif n%4==3:
                 return n+2
             else:
                 return n+1
         else:
             if n%4==3 or n%4==0:
                 return n
             elif n%4==1:
                 return n+2
             else:
                 return n+1


Solve in Python:
We are given a personal information string S, which may represent either an email address or a phone number.
We would like to mask this personal information according to the following rules:

1. Email address:
We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-Z.
An email address starts with a name, followed by the symbol '@', followed by a name, followed by the dot '.' and followed by a name.
All email addresses are guaranteed to be valid and in the format of "name1@name2.name3".
To mask an email, all names must be converted to lowercase and all letters between the first and last letter of the first name must be replaced by 5 asterisks '*'.

2. Phone number:
A phone number is a string consisting of only the digits 0-9 or the characters from the set {'+', '-', '(', ')', ' '}. You may assume a phone number contains 10 to 13 digits.
The last 10 digits make up the local number, while the digits before those make up the country code. Note that the country code is optional. We want to expose only the last 4 digits and mask all other digits.
The local number should be formatted and masked as "***-***-1111", where 1 represents the exposed digits.
To mask a phone number with country code like "+111 111 111 1111", we write it in the form "+***-***-***-1111".  The '+' sign and the first '-' sign before the local number should only exist if there is a country code.  For example, a 12 digit phone number mask should start with "+**-".
Note that extraneous characters like "(", ")", " ", as well as extra dashes or plus signs not part of the above formatting scheme should be removed.

Return the correct "mask" of the information provided.

Example 1:
Input: "LeetCode@LeetCode.com"
Output: "l*****e@leetcode.com"
Explanation: All names are converted to lowercase, and the letters between the
             first and last letter of the first name is replaced by 5 asterisks.
             Therefore, "leetcode" -> "l*****e".

Example 2:
Input: "AB@qq.com"
Output:...

class Solution:
    def maskPII(self, S: str) -> str:
        if '@' in S:
            name, domain = S.split('@')
            return name[0].lower() + '*****' + name[-1].lower() + '@' + domain.lower()
        else:
            number = ''
            for c in S:
                if c.isdigit():
                    number += c
            if len(number) == 10:
                return '***-***-' + number[-4:]
            else:
                return '+' + '*'*(len(number)-10) + '-***-***-' + number[-4:]


Solve in Python:
We are given hours, a list of the number of hours worked per day for a given employee.
A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.
A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.
Return the length of the longest well-performing interval.

Example 1:
Input: hours = [9,9,6,0,6,6,9]
Output: 3
Explanation: The longest well-performing interval is [9,9,6].

Constraints:

1 <= hours.length <= 10000
0 <= hours[i] <= 16

class Solution:
    def longestWPI(self, hours: List[int]) -> int:
        # Convert array to 0 and 1s
        bits = [1 if x > 8 else -1 for x in hours]
        # Problem becomes: find the longest interval bits[i:j] where sum(bits[i:j]) > 0
        # Get prefix sum of bits
        pref = [0] * (len(bits)+1)
        for i in range(1, len(bits)+1):
            pref[i] = pref[i-1] + bits[i-1]
        # Problem becomes: find the longest interval pref[i:j] where pref[j] > pref[i]
        # Sort index of pref by value. Problem becomes: find the largest sorted_pref[j]-sorted_pref[i] where j > i
        # Greedy to solve the new problem
        ans = 0
        min_val = len(bits) + 1
        for y in sorted(enumerate(pref), key=lambda x: (x[1], -x[0])):
            min_val = min(min_val, y[0])
            ans = max(ans, y[0] - min_val)
        return ans


Solve in Python:
We are given non-negative integers nums[i] which are written on a chalkboard.  Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first.  If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses.  (Also, we'll say the bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.)

Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.

Return True if and only if Alice wins the game, assuming both players play optimally.

Example:
Input: nums = [1, 1, 2]
Output: false
Explanation:
Alice has two choices: erase 1 or erase 2.
If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose.
If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.

Notes:

       1 <= N <= 1000.
       0 <= nums[i] <= 2^16.

class Solution:
     def validTicTacToe(self, board):
         """
         :type board: List[str]
         :rtype: bool
         """
         O, X = 0, 0
         for r in board:
             for c in r:
                 if c == 'O':
                     O += 1
                 elif c == 'X':
                     X += 1
         if O - X > 0:
             return False
         if X - O > 1:
             return False
         if X - O == 0:
             for r in board:
                 if r == 'XXX':
                     return False
             for c in range(2):
                 if board[0][c] == board[1][c] == board[2][c] == 'X':
                     return False
             if board[0][0] == board[1][1] == board[2][2] == 'X':
                 return False
             if board[2][0] == board[1][1] == board[0][2] == 'X':
                 return False
         else:
             for r in board:
                 if r == 'OOO':
                     return False
             for c in range(2):
                 if board[0][c] == board[1][c] == board[2][c] == 'O':
                     return False
             if board[0][0] == board[1][1] == board[2][2] == 'O':
                 return False
             if board[2][0] == board[1][1] == board[0][2] == 'O':
                 return False

         return True


Solve in Python:
We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)
Example 1:
Input: [1,null,0,0,1]
Output: [1,null,0,null,1]

Explanation:
Only the red nodes satisfy the property "every subtree not containing a 1".
The diagram on the right represents the answer.

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

Example 3:
Input: [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]

Note:

The binary tree will have at most 200 nodes.
The value of each node will only be 0 or 1.

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

        if not root:
            return None

        root.left =self.pruneTree(root.left)

        root.right= self.pruneTree(root.right)
        if not root.left and not root.right and root.val ==0:
            return None

        return root


Solve in Python:
We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree.
Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A)) recursively with the following Construct(A) routine:

If A is empty, return null.
Otherwise, let A[i] be the largest element of A.  Create a root node with value A[i].
The left child of root will be Construct([A[0], A[1], ..., A[i-1]])
The right child of root will be Construct([A[i+1], A[i+2], ..., A[A.length - 1]])
Return root.

Note that we were not given A directly, only a root node root = Construct(A).
Suppose B is a copy of A with the value val appended to it.  It is guaranteed that B has unique values.
Return Construct(B).

Example 1:

Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: A = [1,4,2,3], B = [1,4,2,3,5]

Example 2:

Input: root = [5,2,4,null,1], val = 3
Output: [5,2,4,null,1,null,3]
Explanation: A = [2,1,5,4], B = [2,1,5,4,3]

Example 3:

Input: root = [5,2,3,null,1], val = 4
Output: [5,2,4,null,1,3]
Explanation: A = [2,1,5,3], B = [2,1,5,3,4]

Constraints:

1 <= B.length <= 100

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