Solve in Python:
You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.
Implement the BrowserHistory class:

BrowserHistory(string homepage) Initializes the object with the homepage of the browser.
void visit(string url) Visits url from the current page. It clears up all the forward history.
string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.
string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.

Example:
Input:
["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
Output:
[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]

Explanation:
BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
browserHistory.visit("google.com");       // You are in "leetcode.com". Visit "google.com"
browserHistory.visit("facebook.com");     // You are in "google.com". Visit "facebook.com"
browserHistory.visit("youtube.com");      // You are in "facebook.com". Visit "youtube.com"
browserHistory.back(1);                   // You are in "youtube.com", move back to "facebook.com" return "facebook.com"
browserHistory.back(1);                   // You are in "facebook.com", move back to "google.com" return "google.com"
browserHistory.forward(1);                // You are in "google.com", move forward to "facebook.com" return "facebook.com"
browserHistory.visit("linkedin.com");     // You are in "facebook.com". Visit "linkedin.com"
browserHistory.forward(2);                // You are in...

class BrowserHistory:

    def __init__(self, homepage: str):
        self.curr = homepage
        self.backw = []
        self.forw = []

    def visit(self, url: str) -> None:
        self.backw.append(self.curr)
        self.forw = []
        self.curr = url

    def back(self, steps: int) -> str:
        for _ in range(steps):
            if not self.backw: break
            self.forw.append(self.curr)
            self.curr = self.backw.pop()
        return self.curr

    def forward(self, steps: int) -> str:
        for _ in range(steps):
            if not self.forw: break
            self.backw.append(self.curr)
            self.curr = self.forw.pop()
        return self.curr

# Your BrowserHistory object will be instantiated and called as such:
# obj = BrowserHistory(homepage)
# obj.visit(url)
# param_2 = obj.back(steps)
# param_3 = obj.forward(steps)


Solve in Python:
You have a collection of lovely poems. Unfortuantely they aren't formatted very well. They're all on one line, like this:

```
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated.
```
What you want is to present each sentence on a new line, so that it looks like this:
```
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
```
Write a function, `format_poem()` that takes a string like the one line example as an argument and returns a new string that is formatted across multiple lines with each new sentence starting on a new line when you print it out.

Try to solve this challenge with the [str.split()](https://docs.python.org/3/library/stdtypes.html#str.split) and the [str.join()](https://docs.python.org/3/library/stdtypes.html#str.join) string methods.

Every sentence will end with a period, and every new sentence will have one space before the previous period. Be careful about trailing whitespace in your solution.

from re import sub

# Try to solve this challenge with the str.split() and the str.join() string methods.
# -> No
def format_poem(poem):
    return sub(r"(?<=\.)\s", "\n", poem)


Solve in Python:
You have a fence consisting of $n$ vertical boards. The width of each board is $1$. The height of the $i$-th board is $a_i$. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from $2$ to $n$, the condition $a_{i-1} \neq a_i$ holds.

Unfortunately, it is possible that now your fence is not great. But you can change it! You can increase the length of the $i$-th board by $1$, but you have to pay $b_i$ rubles for it. The length of each board can be increased any number of times (possibly, zero).

Calculate the minimum number of rubles you have to spend to make the fence great again!

You have to answer $q$ independent queries.

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 3 \cdot 10^5$) — the number of queries.

The first line of each query contains one integers $n$ ($1 \le n \le 3 \cdot 10^5$) — the number of boards in the fence.

The following $n$ lines of each query contain the descriptions of the boards. The $i$-th line contains two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le 10^9$) — the length of the $i$-th board and the price for increasing it by $1$, respectively.

It is guaranteed that sum of all $n$ over all queries not exceed $3 \cdot 10^5$.

It is guaranteed that answer to each query will not exceed $10^{18}$.

-----Output-----

For each query print one integer — the minimum number of rubles you have to spend to make the fence great.

-----Example-----
Input
3
3
2 4
2 1
3 5
3
2 3
2 10
2 6
4
1 7
3 3
2 6
1000000000 2

Output
2
9
0

-----Note-----

In the first query you have to increase the length of second board by $2$. So your total costs if $2 \cdot b_2 = 2$.

In the second query you have to increase the length of first board by $1$ and the length of third board by $1$. So your total costs if $1 \cdot b_1 + 1 \cdot b_3 = 9$.

In the third query the fence is great initially, so you don't need to spend rubles.


Solve in Python:
You have a grid with `$m$` rows and `$n$` columns. Return the number of unique ways that start from the top-left corner and go to the bottom-right corner. You are only allowed to move right and down.

For example, in the below grid of `$2$` rows and `$3$` columns, there are `$10$` unique paths:

```
o----o----o----o
|    |    |    |
o----o----o----o
|    |    |    |
o----o----o----o
```

**Note:** there are random tests for grids up to 1000 x 1000 in most languages, so a naive solution will not work.

---
*Hint: use mathematical permutation and combination*

import sys

sys.setrecursionlimit(1200)

cache = {}

def number_of_routes(m, n):
    if m == 0 or n == 0: return 1
    if m > n: return number_of_routes(n, m)
    result = cache.get((m,n))
    if result is None:
        cache[m,n] = result = number_of_routes(m-1, n) + number_of_routes(m, n-1)
    return result


Solve in Python:
You have a large electronic screen which can display up to $998244353$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $7$ segments which can be turned on and off to compose different digits. The following picture describes how you can display all $10$ decimal digits:

[Image]

As you can see, different digits may require different number of segments to be turned on. For example, if you want to display $1$, you have to turn on $2$ segments of the screen, and if you want to display $8$, all $7$ segments of some place to display a digit should be turned on.

You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than $n$ segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than $n$ segments.

Your program should be able to process $t$ different test cases.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases in the input.

Then the test cases follow, each of them is represented by a separate line containing one integer $n$ ($2 \le n \le 10^5$) — the maximum number of segments that can be turned on in the corresponding testcase.

It is guaranteed that the sum of $n$ over all test cases in the input does not exceed $10^5$.

-----Output-----

For each test case, print the greatest integer that can be displayed by turning on no more than $n$ segments of the screen. Note that the answer may not fit in the standard $32$-bit or $64$-bit integral data type.

-----Example-----
Input
2
3
4

Output
7
11

t = int(input())
for i in range(t):
    n = int(input())
    arr = ''
    if (n % 2 == 1):
        arr = '7'
        for j in range((n - 3) // 2):
            arr += '1'
    else:
        for j in range(n // 2):
            arr += '1'
    print(arr)


Solve in Python:
You have a laser with P amount of energy in it. You are playing a game where you have to use the laser to destroy some crystals, each with some health of their own. Initially, you have 0 points.
Each crystal has an associated health. The health of the ith crystal is given by health[i]. You can perform one of the two actions:
-
At the cost of health[i] energy, you can destroy the ith crystal and gain 1 point. You can only perform this action if your laser has atleast health[i] energy in it.
-
At the cost of 1 point, you can destroy the ith crystal and refuel the laser's energy by an amount equal to health[i]. This action can only be performed if you have atleast one point.
Note: Each crystal can only be destroyed once.
Determine the maximum number of points you can obtain by destroying any number of crystals and performing either action as you wish.

-----Input:-----
- First line will contain n, number of crystals.
- Second line will contain space separated integers, health of each crystal.
- Third line will contain an integer P, initial energy of the laser.

-----Output:-----
Print the largest number of points we can have after destroying any number of crystals.

-----Constraints-----
- health.length <= 1000
- 0 <= health[i] < 10000
- 0 <= P < 10000

-----Subtasks-----
- 40 points : 1 <= health.length <= 100
- 60 points : health.length > 100

-----Sample Input 1:-----
1
200
100

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

-----Explanation:-----
The laser initially has only 100 energy. Since the only crystal requires 200 energy to destroy, we cannot perform any action here, and the game ends. The number of points is zero.

-----Sample Input 2:-----
2
100 200
150

-----Sample Output 2:-----
1

-----Explanation:-----
The laser has 150 energy. We can consume 100 energy and destroy the first crystal and gain 1 point. The remaining energy is 50, which is not enough to destroy the other crystal. We end the game here as we have the maximum possible points attainable.

n=int(input())
n-=1
l=list(map(int,input().split()))
x=int(input())
c=0
m=0
z=0
i=0
l.sort()
while(i<n):
    if l[i]<x:
        c+=1
        x=x-l[i]
        i+=1
    elif c>=1:
        c-=1
        x=x+l[n]
        n-=1
    if m<c:
        m=c
print(m)


Solve in Python:
You have a list of words and a pattern, and you want to know which words in words matches the pattern.
A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.
(Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.)
Return a list of the words in words that match the given pattern.
You may return the answer in any order.

Example 1:
Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
Output: ["mee","aqq"]
Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}.
"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation,
since a and b map to the same letter.

Note:

1 <= words.length <= 50
1 <= pattern.length = words[i].length <= 20

class Solution:
    def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
        def match(list1 , pattern):
            for i in range(len(pattern)):
                if list1[i] != pattern[i]:
                    return False
            return True

        def number_arr(list1):
            dict = {}
            arr = []
            last_given_value = 0
            for i in list1:
                if i not in dict:
                    last_given_value +=1
                    dict[i] = last_given_value
                    arr.append(dict[i])
                else:
                    arr.append(dict[i])
            return arr

        pat = number_arr(pattern)
        ans = []
        for word in words:
            word_list = number_arr(word)
            if match(pat , word_list):
                ans.append(word)
        return ans


Solve in Python:
You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array or stay in the same place  (The pointer should not be placed outside the array at any time).
Given two integers steps and arrLen, return the number of ways such that your pointer still at index 0 after exactly steps steps.
Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:
Input: steps = 3, arrLen = 2
Output: 4
Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay

Example 2:
Input: steps = 2, arrLen = 4
Output: 2
Explanation: There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay

Example 3:
Input: steps = 4, arrLen = 2
Output: 8

Constraints:

1 <= steps <= 500
1 <= arrLen <= 10^6

MODULO = 10**9 + 7

class DP:
    def __init__(self, arrLen: int):
        self._len = arrLen
        self._cache = {}

    def get(self, index, steps):
        if (index, steps) in self._cache:
            return self._cache[(index, steps)]
        result = self._get_uncached(index, steps)
        # print(f\"index={index} steps={steps}  =>  ways={result}\")
        self._cache[(index, steps)] = result
        return result

    def _get_uncached(self, index, steps):
        if index < 0 or index >= self._len:
            return 0
        if steps == 0 and index == 0:
            return 1
        elif steps == 0:
            return 0
        return (self.get(index - 1, steps - 1) + self.get(index, steps - 1) + self.get(index + 1, steps - 1)) % MODULO

class Solution:
    def numWays(self, steps: int, arrLen: int) -> int:
        dp = DP(arrLen)
        return dp.get(0, steps)


Solve in Python:
You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar.

In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.

For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 3^2 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 2^2 = 4).

For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece.

-----Input-----

The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process.

Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.

-----Output-----

For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.

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

Output
5
5
4
0

-----Note-----

In the first query of the sample one needs to perform two breaks:  to split 2 × 2 bar into two pieces of 2 × 1 (cost is 2^2 = 4),  to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 1^2 = 1).

In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.

t = int(input())

dp = [[[0 for i in range(51)] for j in range(31)] for k in range(31)]

def cost(n, m, k):
    if (dp[n][m][k] or k == 0 or n * m == k): return dp[n][m][k]
    c = 10**9
    for i in range(1, n // 2 + 1):
        for j in range(k + 1):
            c = min(c, cost(n - i, m, k - j) + cost(i, m, j) + m * m)
    for i in range(1, m // 2 + 1):
        for j in range(k + 1):
            c = min(c, cost(n, m - i, k - j) + cost(n, i, j) + n * n)
    dp[n][m][k] = c
    return c

for _ in range(t):
    n, m, k = list(map(int, input().split()))
    print(cost(n, m, k))

# mem = [[[0 for i in range(51)] for j in range(31)] for k in range(31)]

# def f(n, m, k):
#     if mem[n][m][k]:
#         return mem[n][m][k]
#     if (n*m == k) or (k == 0):
#         return 0
#     cost = 10**9
#     for x in range(1, n//2 + 1):
#         for z in range(k+1):
#             cost = min(cost, m*m + f(n-x, m, k-z) + f(x, m, z))
#     for y in range(1, m//2 + 1):
#         for z in range(k+1):
#             cost = min(cost, n*n + f(n, m-y, k-z) + f(n, y, z))
#     mem[n][m][k] = cost
#     return cost

# t = int(input())
# for i in range(t):
#     n, m, k = map(int, input().split())
#     print(f(n, m, k))


Solve in Python:
You have a sequence $a$ with length $N$ created by removing some elements (possibly zero) from a permutation of numbers $(1, 2, \dots, N)$. When an element is removed, the length of the sequence doesn't change, but there is an empty spot left where the removed element was. You also have an integer $K$.
Let's call a permutation $p_1, p_2, \dots, p_N$ good if:
- it is possible replace empty spots in $a$ by numbers in such a way that we obtain the permutation $p$
- the number of positions $i$ ($1 < i \le N$) such that $p_i > p_{i-1}$ is equal to $K$
Your task is to find the number of good permutations.

-----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 two space-separated integers $N$ and $K$.
- The second line contains $N$ space-separated integers $a_1, a_2, \dots, a_N$. Each element of this sequence is either $0$ (indicating an empty spot previously occupied by a removed element) or an integer between $1$ and $N$ inclusive.

-----Output-----
For each test case, print a single line containing one integer — the number of good permutations.

-----Constraints-----
- $1 \le T \le 300$
- $0 \le K < N \le 8$
- each integer between $1$ and $N$ inclusive appears in $a$ at most once

-----Example Input-----
1
3 1
2 0 0

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

-----Explanation-----
Example case 1: The two possible good permutations are $(2,3,1)$ and $(2,1,3)$.

import itertools
t=int(input())
for _ in range(t):
 n,k=map(int,input().split())
 a=list(map(int,input().split()))
 p=[i for i in range(1,n+1)]
 good=0
 for i in a:
  if(i != 0 ):
   p.remove(i)

 x=list(itertools.permutations(p))
 for i in x:
  j=0
  b=[l for l in a]
  for z in range(n):
   if(b[z]==0):
    b[z]=i[j]
    j+=1
  loc_cnt=0
  for z in range(1,n):
   if(b[z]>b[z-1]):
    loc_cnt+=1
  if(loc_cnt==k):
   good+=1

 print(good)


Solve in Python:
You have a set of four (4) balls labeled with different numbers: ball_1 (1), ball_2 (2), ball_3 (3) and ball(4) and we have 3 equal boxes for distribute them. The possible combinations of the balls, without having empty boxes, are:

```
 (1)            (2)        (3)(4)
______        ______       _______

```

```
 (1)           (2)(4)        (3)
______         ______      ______

```

```
(1)(4)           (2)         (3)
______          ______      ______

```

```
  (1)           (2)(3)       (4)
_______         _______     ______

```

```
(1)(3)            (2)        (4)
_______         _______     ______
```

```
(1)(2)            (3)        (4)
_______         _______     ______
```
We have a total of **6** combinations.

Think how many combinations you will have with two boxes instead of three. You will obtain **7** combinations.

Obviously, the four balls in only box will give only one possible combination (the four balls in the unique box). Another particular case is the four balls in four boxes having again one possible combination(Each box having one ball).

What will be the reasonable result for a set of n elements with no boxes?

Think to create a function that may calculate the amount of these combinations of a set of ```n``` elements in ```k``` boxes.

You do no not have to check the inputs type that will be always valid integers.

The code should detect the cases when ```k > n```, returning "It cannot be possible!".

Features of the random tests:
```
1 <= k <= n <= 800
```
Ruby version will be published soon.

def combs_non_empty_boxes(n,k):
    if n<k:
        return "It cannot be possible!"
    else:
        row = [1]+[0 for x in range(k)]
        for i in range(1, n+1):
            new = [0]
            for j in range(1, k+1):
                 stirling = j * row[j] + row[j-1]
                 new.append(stirling)
            row = new
        return row[k]


Solve in Python:
You have a string $s$ consisting of $n$ characters. Each character is either 0 or 1.

You can perform operations on the string. Each operation consists of two steps:  select an integer $i$ from $1$ to the length of the string $s$, then delete the character $s_i$ (the string length gets reduced by $1$, the indices of characters to the right of the deleted one also get reduced by $1$);  if the string $s$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix).

Note that both steps are mandatory in each operation, and their order cannot be changed.

For example, if you have a string $s =$ 111010, the first operation can be one of the following:  select $i = 1$: we'll get 111010 $\rightarrow$ 11010 $\rightarrow$ 010;  select $i = 2$: we'll get 111010 $\rightarrow$ 11010 $\rightarrow$ 010;  select $i = 3$: we'll get 111010 $\rightarrow$ 11010 $\rightarrow$ 010;  select $i = 4$: we'll get 111010 $\rightarrow$ 11110 $\rightarrow$ 0;  select $i = 5$: we'll get 111010 $\rightarrow$ 11100 $\rightarrow$ 00;  select $i = 6$: we'll get 111010 $\rightarrow$ 11101 $\rightarrow$ 01.

You finish performing operations when the string $s$ becomes empty. What is the maximum number of operations you can perform?

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases.

The first line of each test case contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the string $s$.

The second line contains string $s$ of $n$ characters. Each character is either 0 or 1.

It's guaranteed that the total sum of $n$ over test cases doesn't exceed $2 \cdot 10^5$.

-----Output-----

For each test case, print a single integer — the maximum number of operations you can perform.

-----Example-----
Input
5
6
111010
1
0
1
1
2
11
6
101010

Output
3
1
1
1
3

-----Note-----

In the first test case, you can, for example, select $i = 2$ and...

for _ in range (int(input())):
    n=int(input())
    s=input()
    a=[]
    curr=1
    g=0
    for i in range (1,n):
        if s[i]==s[i-1]:
            curr+=1
        else:
            a.append(curr)
            if curr>1:
                g+=1
            curr=1
    if curr>0:
        if curr>1:
            g+=1
        a.append(curr)
    #print(a)
    j=0
    i=0
    res=0
    while i<len(a):
        if a[i]>1:
            res+=1
            i+=1
        else:
            j=max(i+1,j)
            ch=0
            while j<len(a):
                if a[j]>1:
                    a[j]-=1
                    ch=1
                    break
                j+=1
            if ch==1:
                i+=1
                res+=1
            else:
                i+=2
                res+=1
    print(res)


Solve in Python:
You have a string $s$ — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:  'W' — move one cell up;  'S' — move one cell down;  'A' — move one cell left;  'D' — move one cell right.

Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid:  you can place the robot in the cell $(3, 2)$;  the robot performs the command 'D' and moves to $(3, 3)$;  the robot performs the command 'S' and moves to $(4, 3)$;  the robot performs the command 'A' and moves to $(4, 2)$;  the robot performs the command 'W' and moves to $(3, 2)$;  the robot performs the command 'W' and moves to $(2, 2)$;  the robot performs the command 'A' and moves to $(2, 1)$;  the robot performs the command 'W' and moves to $(1, 1)$.  [Image]

You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.

What is the minimum area of $Grid(s)$ you can achieve?

-----Input-----

The first line contains one integer $T$ ($1 \le T \le 1000$) — the number of queries.

Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) — the sequence of commands.

It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.

-----Output-----

Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.

-----Example-----
Input
3
DSAWWAW
D
WA

Output
8
2
4

-----Note-----

In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.

In second and third queries you can not decrease the area of $Grid(s)$.

t = int(input())
for c in range(t):
    s = input()
    up_max = down_max = right_max = left_max = 0
    first_up = last_up = first_down = last_down = first_left = last_left = first_right = last_right = 0
    current_x = current_y = 0
    horizontal_count = vertical_count = 0
    for i in range(len(s)):
        if s[i] == 'W':
            current_y += 1
            vertical_count += 1
            if current_y > up_max:
                up_max = current_y
                first_up = last_up = i + 1
            elif current_y == up_max:
                last_up = i + 1
        elif s[i] == 'S':
            current_y -= 1
            vertical_count += 1
            if current_y < down_max:
                down_max = current_y
                first_down = last_down = i + 1
            elif current_y == down_max:
                last_down = i + 1
        elif s[i] == 'D':
            current_x += 1
            horizontal_count += 1
            if current_x > right_max:
                right_max = current_x
                first_right = last_right = i + 1
            elif current_x == right_max:
                last_right = i + 1
        else:
            current_x -= 1
            horizontal_count += 1
            if current_x < left_max:
                left_max = current_x
                first_left = last_left = i + 1
            elif current_x == left_max:
                last_left = i + 1

    h = up_max - down_max + 1
    w = right_max - left_max + 1
    ans = h * w
    if vertical_count > 1 and last_up < first_down:
        ans = min(ans, (h - 1) * w)
    if vertical_count > 1 and last_down < first_up:
        ans = min(ans, (h - 1) * w)
    if horizontal_count > 1 and last_right < first_left:
        ans = min(ans, h * (w - 1))
    if horizontal_count > 1 and last_left < first_right:
        ans = min(ans, h * (w - 1))

    print(ans)


Solve in Python:
You have a string S consisting of N uppercase English letters. You are allowed to perform at most one operation of following kind: Choose any position in the string, remove the character at that position and insert it back to any other place in the string.

Find the  lexicographically smallest  string you can achieve.

-----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 the single integer N denoting length of string S.
The second line contains the string S.

-----Output-----
For each test case, output a single line containing the answer to the corresponding test case.

-----Constraints-----
- 1 ≤ T ≤ 50
- 1 ≤ N ≤ 50
- S will consist of uppercase English letters.

-----Example-----
Input:
2
4
DCBA
7
XYZZYZZ

Output:
ADCB
XYYZZZZ

-----Explanation-----
Example case 1. The optimal solution here is to choose the last character and put it in the beginning of the string. So the answer will be ADCB
Example case 2. The optimal solution here is to choose the 5-th character (1-based index) and put it between the 2-nd and the 3-rd characters. So the answer will be XYYZZZZ

t = int(input())
for T in range(t):
 n = int(input())
 s = input()
 ans = s
 val, val1 = '', ''
 for i in range(n):
  ##print(val, end = " ")
  val = s[:i] + s[i + 1:]
  for j in range(n):
   val1 = val[:j] + s[i] + val[j:]
   ##print(val1)
   ans = min(ans, val1)
 print(ans)


Solve in Python:
You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

Given n, find the total number of full staircase rows that can be formed.

n is a non-negative integer and fits within the range of a 32-bit signed integer.

Example 1:

n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.

Example 2:

n = 8

The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤

Because the 4th row is incomplete, we return 3.

class Solution:
     def arrangeCoins(self, n):
         """
         :type n: int
         :rtype: int
         """
         return int(((8*n+1)**0.5-1)/2)


Solve in Python:
You have a tree consisting of n vertices. You want to color each vertex of the tree in one of the k colors such that for any pair of vertices having same color, all the vertices belonging to the path joining them should also have same color. In other words, for any two vertices u, v with same color, all the vertices in the path joining them should also have color same as that of the u (or same as v, as u and v have same color).

Find out possible number of ways in which you can color the tree satisfying the above property. As the answer could be large, print your answer modulo 109 + 7.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
For each test case, first line contains two space separated integers n, k denoting number of vertices in the tree and total number of colors, respectively
Each of the next n - 1 lines contain two space separated integers ui, vi, denoting that there is an edge between vertices ui and vi in the tree.

-----Output-----
For each test case, output a single line corresponding to number of ways of coloring the tree.

-----Constraints-----
- 1 ≤ T ≤ 50
- 1 ≤ n, k ≤ 50
- 1 ≤ ui, vi ≤ n
- ui ≠ vi

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

Output:
6
1
39

-----Explanation-----
In the first example, You can color the vertices in the following 6 ways - {1, 1, 1}, {2, 2, 2}, {1, 2, 2}, {1, 1, 2}, {2, 1, 1}, {2, 2, 1}. Note that you can't color the tree in {1, 2, 1} as the vertices in the path connecting vertex 1 and 3, (i.e. 1, 2, 3) don't have same color. You can see that the color of 2nd vertex is not same as that of 1st and 3rd.
In the second example, Only possible coloring you can do is to color all the vertices with color 1.

A = [0] * 100001
M = 1000000007

def nCk(n, k):
 if k ==0 or k ==n:
  return 1
 r = (A[n-k]*A[k])%M
 x = (A[n]*pow(r, M-2, M))%M
 return x

for _ in range(int(input())):
 n, k = list(map(int, input().split()))
 for i in range(n-1):
  u,v = input().split()
 summ = 0
 A[0] = 1
 for i in range(1, len(A)):
  A[i] = (i*A[i-1])%M
 for i in range(min(n, k)):
  b = nCk(k,i+1)
  c = (nCk(n-1,i)*b)%M
  c *= A[i+1]
  summ += (c%M)
  summ %= M
 print(summ)


Solve in Python:
You have a two-dimensional list in the following format:

```python
data = [[2, 5], [3, 4], [8, 7]]
```

Each sub-list contains two items, and each item in the sub-lists is an integer.

Write a function `process_data()` that processes each sub-list like so:

 * `[2, 5]` --> `2 - 5` --> `-3`
 * `[3, 4]` --> `3 - 4` --> `-1`
 * `[8, 7]` --> `8 - 7` --> `1`

and then returns the product of all the processed sub-lists: `-3 * -1 * 1` --> `3`.

For input, you can trust that neither the main list nor the sublists will be empty.

process_data = lambda d, reduce=__import__("functools").reduce: reduce(int.__mul__, (x - y for x, y in d))


Solve in Python:
You have a very large square wall and a circular dartboard placed on the wall. You have been challenged to throw darts into the board blindfolded. Darts thrown at the wall are represented as an array of points on a 2D plane.
Return the maximum number of points that are within or lie on any circular dartboard of radius r.

Example 1:

Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 2
Output: 4
Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.

Example 2:

Input: points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5
Output: 5
Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).

Example 3:
Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 1
Output: 1

Example 4:
Input: points = [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]], r = 2
Output: 4

Constraints:

1 <= points.length <= 100
points[i].length == 2
-10^4 <= points[i][0], points[i][1] <= 10^4
1 <= r <= 5000

class Solution:
    def numPoints(self, points: List[List[int]], r: int) -> int:
        ans = 1
        for (x1, y1), (x2, y2) in itertools.combinations(points, 2):
            q = math.sqrt((x1-x2)**2+(y1-y2)**2)
            if q > 2*r + 0.00001:
                continue
            # only need to calculate a circle on one side
            # consider 1-D case
            x0 = (x1+x2)/2 + math.sqrt(r**2-(q/2)**2)*(y1-y2)/q
            y0 = (y1+y2)/2 + math.sqrt(r**2-(q/2)**2)*(x2-x1)/q
            #print(x0, x1)
            ans = max(ans, sum(1 for x, y in points if (x-x0)**2+(y-y0)**2 <= r**2 + 0.00001))
        return ans


Solve in Python:
You have an array $a$ of length $n$. For every positive integer $x$ you are going to perform the following operation during the $x$-th second:

  Select some distinct indices $i_{1}, i_{2}, \ldots, i_{k}$ which are between $1$ and $n$ inclusive, and add $2^{x-1}$ to each corresponding position of $a$. Formally, $a_{i_{j}} := a_{i_{j}} + 2^{x-1}$ for $j = 1, 2, \ldots, k$. Note that you are allowed to not select any indices at all.

You have to make $a$ nondecreasing as fast as possible. Find the smallest number $T$ such that you can make the array nondecreasing after at most $T$ seconds.

Array $a$ is nondecreasing if and only if $a_{1} \le a_{2} \le \ldots \le a_{n}$.

You have to answer $t$ independent test cases.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 10^{4}$) — the number of test cases.

The first line of each test case contains single integer $n$ ($1 \le n \le 10^{5}$) — the length of array $a$. It is guaranteed that the sum of values of $n$ over all test cases in the input does not exceed $10^{5}$.

The second line of each test case contains $n$ integers $a_{1}, a_{2}, \ldots, a_{n}$ ($-10^{9} \le a_{i} \le 10^{9}$).

-----Output-----

For each test case, print the minimum number of seconds in which you can make $a$ nondecreasing.

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

Output
2
0
3

-----Note-----

In the first test case, if you select indices $3, 4$ at the $1$-st second and $4$ at the $2$-nd second, then $a$ will become $[1, 7, 7, 8]$. There are some other possible ways to make $a$ nondecreasing in $2$ seconds, but you can't do it faster.

In the second test case, $a$ is already nondecreasing, so answer is $0$.

In the third test case, if you do nothing at first $2$ seconds and select index $2$ at the $3$-rd second, $a$ will become $[0, 0]$.

for _ in range(int(input())):
    n = int(input())
    l1 = list(map(int, input().split()))
    answer = 0
    max_so_far = l1[0]
    for i in range(1, n):
        if l1[i] >= max_so_far:
            max_so_far = l1[i]
        else:
            answer = max(answer, (max_so_far - l1[i]).bit_length())

    print(answer)


Solve in Python:
You have an array A of size N containing only positive numbers. You have to output the maximum possible value of A[i]%A[j] where 1<=i,j<=N.

-----Input-----
The first line of each test case contains a single integer N denoting the size of the array. The next N lines contains integers A1, A2, ..., AN denoting the numbers

-----Output-----
Output a single integer answering what is asked in the problem.

-----Subtask 1 (20 points)-----
- 1 ≤ N ≤ 5000
- 1 ≤ A[i] ≤ 2*(10^9)

-----Subtask 2 (80 points)-----
- 1 ≤ N ≤ 1000000
- 1 ≤ A[i] ≤ 2*(10^9)

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

Output:
1

-----Explanation-----
There will be four values, A[0]%A[0] = 0, A[0]%A[1]=1, A[1]%A[0]=0, A[1]%A[1]=0, and hence the output will be the maximum among them all, that is 1.

size = int(input())
array = []

for x in range(size):
 array.append(int(input()))

diff = 0

if size < 1600 :
 for i in range(size):
  for j in range(i + 1, size):
   if array[i]%array[j] > diff :
    diff = array[i]%array[j]
else :
 m1 = max(array)
 array.pop(array.index(m1))
 m2 = max(array)
 diff = m2%m1

print(diff)


Solve in Python:
You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n).
In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.
Given an integer n, the length of the array. Return the minimum number of operations needed to make all the elements of arr equal.

Example 1:
Input: n = 3
Output: 2
Explanation: arr = [1, 3, 5]
First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]
In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].

Example 2:
Input: n = 6
Output: 9

Constraints:

1 <= n <= 10^4

class Solution:
    def minOperations(self, n: int) -> int:
        if n%2==0:
            return int(n/2)*int(n/2)
        else:
            return int(n/2)*(int(n/2)+1)


Solve in Python:
You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.

Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.

*Example*
```python
sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
```

def sort_array(numbers):
    evens = []
    odds = []
    for a in numbers:
        if a % 2:
            odds.append(a)
            evens.append(None)
        else:
            evens.append(a)
    odds = iter(sorted(odds))
    return [next(odds) if b is None else b for b in evens]


Solve in Python:
You have an award-winning garden and everyday the plants need exactly 40mm of water. You created a great piece of JavaScript to calculate the amount of water your plants will need when you have taken into consideration the amount of rain water that is forecast for the day. Your jealous neighbour hacked your computer and filled your code with bugs.

Your task is to debug the code before your plants die!

def rain_amount(rain_amount):
    if rain_amount < 40:
         return f'You need to give your plant {40 - rain_amount}mm of water'
    else:
         return 'Your plant has had more than enough water for today!'


Solve in Python:
You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity.
Implement the DinnerPlates class:

DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks.
void push(int val) Pushes the given positive integer val into the leftmost stack with size less than capacity.
int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all stacks are empty.
int popAtStack(int index) Returns the value at the top of the stack with the given index and removes it from that stack, and returns -1 if the stack with that given index is empty.

Example:
Input:
["DinnerPlates","push","push","push","push","push","popAtStack","push","push","popAtStack","popAtStack","pop","pop","pop","pop","pop"]
[[2],[1],[2],[3],[4],[5],[0],[20],[21],[0],[2],[],[],[],[],[]]
Output:
[null,null,null,null,null,null,2,null,null,20,21,5,4,3,1,-1]

Explanation:
DinnerPlates D = DinnerPlates(2);  // Initialize with capacity = 2
D.push(1);
D.push(2);
D.push(3);
D.push(4);
D.push(5);         // The stacks are now:  2  4
                                           1  3  5
                                           ﹈ ﹈ ﹈
D.popAtStack(0);   // Returns 2.  The stacks are now:     4
                                                       1  3  5
                                                       ﹈ ﹈ ﹈
D.push(20);        // The stacks are now: 20  4
                                           1  3  5
                                           ﹈ ﹈ ﹈
D.push(21);        // The stacks are now: 20  4 21
                                           1  3  5
                                           ﹈ ﹈ ﹈
D.popAtStack(0);   // Returns 20.  The stacks are now:     4 21
                                                        1  3  5
                                                        ﹈ ﹈ ﹈
D.popAtStack(2);   // Returns 21.  The stacks are now:     4
                                             ...

class DinnerPlates:

    def __init__(self, capacity: int):
        self.max = capacity
        self.top = 0
        self.stack = collections.defaultdict(list)
        self.stack[self.top] = [0, []]
        self.h = [];
        heapq.heappush(self.h, 0)

    def push(self, val: int) -> None:

        ptr = heapq.heappop(self.h)
        self.stack[ptr][1].append(val)
        self.stack[ptr][0] += 1
        if self.stack[ptr][0]<self.max: heapq.heappush(self.h, ptr)
        elif ptr==self.top:
            self.top += 1
            self.stack[self.top] = [0, []]
            heapq.heappush(self.h, self.top)

    def popAtStack(self, index: int) -> int:

        if not index in self.stack or not self.stack[index][0]: return -1
        if self.stack[index][0]==self.max:
            heapq.heappush(self.h, index)
        self.stack[index][0] -= 1
        return self.stack[index][1].pop()

    def pop(self) -> int:
        while self.top  and not self.stack[self.top][0]:
            self.top -= 1
        return self.popAtStack(self.top)

# Your DinnerPlates object will be instantiated and called as such:
# obj = DinnerPlates(capacity)
# obj.push(val)
# param_2 = obj.pop()
# param_3 = obj.popAtStack(index)


Solve in Python:
You have an initial power P, an initial score of 0 points, and a bag of tokens.
Each token can be used at most once, has a value token[i], and has potentially two ways to use it.

If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point.
If we have at least 1 point, we may play the token face down, gaining token[i] power, and losing 1 point.

Return the largest number of points we can have after playing any number of tokens.

Example 1:
Input: tokens = [100], P = 50
Output: 0

Example 2:
Input: tokens = [100,200], P = 150
Output: 1

Example 3:
Input: tokens = [100,200,300,400], P = 200
Output: 2

Note:

tokens.length <= 1000
0 <= tokens[i] < 10000
0 <= P < 10000

class Solution:
    def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
        if not len(tokens) :
            return 0
        tokens.sort()
        res = 0
        deque = collections.deque(tokens)

        while( len( deque ) > 1 and ( P >= deque[0] or res ) ):
            while( deque and P > deque[0] ):
                res += 1
                P -= deque.popleft()
            if( len( deque ) > 1 and res ):
                P += deque.pop()
                res -= 1

        if ( deque and P >= deque[0] ):
            res += 1
        return res


Solve in Python:
You have been appointed as the designer for your school's computer network.
In total, there are N computers in the class, and M computer-to-computer connections need to be made. Also, there are three mandatory conditions the design should fulfill.
The first requirement is that any computer in the network should be able to communicate with any other computer through the connections, possibly, through some other computers.
Network attacks are possible, so the second requirement is that even if any one computer from the network gets disabled so that the rest of the computers are unable to communicate with it, the rest of the computers can still communicate with each other. In other words, the first requirement still holds for any subset of (N-1) computers.
The third requirement is that there shouldn't be any irrelevant connections in the network. We will call a connection irrelevant if and only if after its' removal, the above two requirements are still held.
Given N, M, please build a network with N computers and M connections, or state that it is impossible.

-----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 and only line of each test case contains a pair of space-separated integers N and M denoting the number of computers and the number of connections.

-----Output-----
Output T blocks.
If it is impossible to construct a network with the given parameters for the corresponding test case, output just -1 -1. Otherwise, output M lines, each of which contains a space-separated pairs of integers denoting the IDs of the computers that should be connected. Note that multiple connections between any pair of computers and connections connecting a computer to itself are implicitly not allowed due to the third requirement.

-----Constraints-----

- 1 ≤ T ≤ 1000
- 1 ≤ M ≤ N * (N - 1) / 2
- 1 ≤ Sum of all N ≤ 1000
- Subtask 1 (21 point): 1 ≤ N ≤ 4
- Subtask 2 (79 points): 1 ≤ N ≤ 100

-----Example-----
Input:2
10 1
5...

# EXNETWRK.py

t = int(input())
for _ in range(t):
 n,m = list(map(int, input().split()))
 if n == m :
  for i in range(1,n+1):
   print(i,i%n+1)
 else:
  print(-1,-1)


Solve in Python:
You have been presented with a cipher, your goal is to re-create the cipher with little information. Use the examples provided to see if you can find a solution to how this cipher is made. You will be given no hints, only the handful of phrases that have already been deciphered for you.

Your only hint: Spaces are left alone, they are not altered in any way. Anytime there is a space, it should remain untouched and in place.

I hope you enjoy, but this one should be genuinely infuriating.

def shift(s=1):
    yield 0
    while 1:
        yield s ; s+=1
        yield s
        yield s-2

def cipher(s):
    return ''.join( c if c==' ' else chr( (x+ord(c)-97)%26 + 97 )
                    for c,x in zip(s,shift()) )


Solve in Python:
You have been recently hired as a developer in CodeChef. Your first mission is to implement a feature that will determine the number of submissions that were judged late in a contest.
There are $N$ submissions, numbered $1$ through $N$. For each valid $i$, the $i$-th submission was submitted at time $S_i$ and judged at time $J_i$ (in minutes). Submitting and judging both take zero time. Please determine how many submissions received their verdicts after a delay of more than $5$ minutes.

-----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 the input contains a single integer $N$.
- $N$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $S_i$ and $J_i$.

-----Output-----
For each test case, print a single line containing one integer — the number of submissions for which the judging was delayed by more than 5 minutes.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 100$
- $1 \le S_i \le J_i \le 300$ for each valid $i$

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

-----Example Input-----
1
5
1 3
4 4
4 10
1 11
2 7

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

-----Explanation-----
Example case 1: The delays of the respective submissions are $2$ minutes, $0$ minutes, $6$ minutes, $10$ minutes and $5$ minutes. Only submissions $3$ and $4$ are delayed by more than $5$ minutes, hence the answer is $2$.

t=int(input())
for i in range(t):
 n=int(input())
 count=0
 for i in range(n):
  a,b=map(int,input().split())
  if(b-a>5):
   count=count+1
 print(count)


Solve in Python:
You have been recruited by an unknown organization for your cipher encrypting/decrypting skills.
Being new to the organization they decide to test your skills.
Your first test is to write an algorithm that encrypts the given string in the following steps.

1. The first step of the encryption is a standard ROT13 cipher.
This is a special case of the caesar cipher where the letter is encrypted with its key that is thirteen letters down the alphabet,
i.e. `A => N, B => O, C => P, etc..`

1. Part two of the encryption is to take the ROT13 output and replace each letter with its exact opposite. `A => Z, B => Y, C => X`.
The return value of this should be the encrypted message.

Do not worry about capitalization or punctuation. All encrypted messages should be lower case and punctuation free.
As an example, the string `"welcome to our organization"` should return `"qibkyai ty ysv yvgmzenmteyz"`.

Good luck, and congratulations on the new position.

encrypter=lambda s: "".join(["mlkjihgfedcbazyxwvutsrqpon"["abcdefghijklmnopqrstuvwxyz".index(a)] if a in "abcdefghijklmnopqrstuvwxyz" else a for a in s])


Solve in Python:
You have been speeding on a motorway and a police car had to stop you. The policeman is a funny guy that likes to play games. Before issuing penalty charge notice he gives you a choice to change your penalty.

Your penalty charge is a combination of numbers like: speed of your car, speed limit in the area, speed of the police car chasing you, the number of police cars involved, etc.  So, your task is to combine the given numbers and make the penalty charge to be as small as possible.

For example, if  you are given numbers  ```[45, 30, 50, 1]``` your best choice is ```1304550```

Examples:
```Python
['45', '30', '50', '1'] => '1304550'

['100', '10', '1'] => '100101'

['32', '3'] => '323'
```

def penalty(a_list):
    return ''.join(sorted(a_list,key=lambda x:x*10))


Solve in Python:
You have been tasked with converting a number from base i (sqrt of -1) to base 10.

Recall how bases are defined:

    abcdef = a * 10^5 + b * 10^4 + c * 10^3 + d * 10^2 + e * 10^1 + f * 10^0

Base i follows then like this:

    ... i^4 + i^3 + i^2 + i^1 + i^0

The only numbers in any place will be 1 or 0
Examples:
  101 in base i would be:

      1 * i^2 + 0 * i^1 + 1*i^0 = -1 + 0 + 1 = 0

  10010 in base i would be:

      1*i^4 + 0 * i^3 + 0 * i^2 + 1 * i^1 + 0 * i^0 = 1 + -i = 1-i

You must take some number, n, in base i and convert it into a number in base 10, in the format of a 2x1 vector.

    [a,b] = a+b*i

The number will always be some combination of 0 and 1

In Python you will be given an integer.
In Javascript and C++ you will be given a string

from itertools import cycle

def convert(n):
    c, i, val = cycle([1,1,-1,-1]), cycle([0,1]), [0, 0]
    for l in str(n)[::-1]: val[next(i)] += next(c) * (l == '1')
    return val


Solve in Python:
You have d dice, and each die has f faces numbered 1, 2, ..., f.
Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.

Example 1:
Input: d = 1, f = 6, target = 3
Output: 1
Explanation:
You throw one die with 6 faces.  There is only one way to get a sum of 3.

Example 2:
Input: d = 2, f = 6, target = 7
Output: 6
Explanation:
You throw two dice, each with 6 faces.  There are 6 ways to get a sum of 7:
1+6, 2+5, 3+4, 4+3, 5+2, 6+1.

Example 3:
Input: d = 2, f = 5, target = 10
Output: 1
Explanation:
You throw two dice, each with 5 faces.  There is only one way to get a sum of 10: 5+5.

Example 4:
Input: d = 1, f = 2, target = 3
Output: 0
Explanation:
You throw one die with 2 faces.  There is no way to get a sum of 3.

Example 5:
Input: d = 30, f = 30, target = 500
Output: 222616187
Explanation:
The answer must be returned modulo 10^9 + 7.

Constraints:

1 <= d, f <= 30
1 <= target <= 1000

class Solution:
    def numRollsToTarget(self, d, f, target):

        if d == 0:
            return 0

        dp = [[0 for _ in range(target+1)] for _ in range(d+1)]

        for i in range(1, target+1):
            dp[0][i] = 0
        for j in range(1, d+1):
            dp[j][0] = 0

        dp[0][0] = 1

        for i in range(1, d+1):
            for j in range(1, target+1):
                for k in range(1, f+1):
                    if j-k >= 0:
                        dp[i][j] += dp[i-1][j-k]

        return dp[d][target] % ((10 ** 9) + 7)

#         def recursive(d, f, target):

#             if target == 0 and d == 0:
#                 return 1

#             if target < 0 or d == 0:
#                 return 0

#             if dp[d][target] != -1:
#                 return dp[d][target]
#             temp = 0
#             for i in range(1, f+1):
#                 temp += recursive(d - 1, f, target - i)

#             dp[d][target] =  temp
#             return dp[d][target]

#         return (recursive(d, f, target) % ((10 ** 9) + 7))


Solve in Python:
You have found $M$ different types of jewels in a mine and each type of jewel is present in an infinite number.
There are $N$ different boxes located at position $(1 ,2 ,3 ,...N)$.
Each box can collect jewels up to a certain number ( box at position $i$ have $i$ different partitions and each partition can collect at most one jewel of any type).
Boxes at odd positions are already fully filled with jewels while boxes at even positions are completely empty.
Print the total number of different arrangements possible so that all boxes can be fully filled.
As the answer can be very large you can print it by doing modulo with 1000000007(10^9+7).

-----Input:-----
- First line will contain $T$, number of testcases.
- Each testcase contains of a single line of input, two integers $N ,  M$.

-----Output:-----
For each testcase, Print the total number of different arrangement.

-----Constraints-----
- $1 \leq T \leq 20000$
- $1 \leq N \leq 1e9$
- $1 \leq M \leq 1e14$

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

-----Sample Output:-----
1
64

# cook your dish here
p = (int)(1e9+7)
for _ in range(int(input())):
    n,m =map(int,input().split())
    if n%2!=0:
        n=(n-1)//2
    else:
        n=n//2
    b=n*(n+1)
    ans=pow(m,b,p)
    print(ans)


Solve in Python:
You have initially a string of N characters, denoted by A1,A2...AN. You have to print the size of the largest subsequence of string A such that all the characters in that subsequence are distinct ie. no two characters in that subsequence should be same.

A subsequence of string A is a sequence that can be derived from A by deleting some elements  and without changing the order of the remaining elements.

-----Input-----
First line contains T, number of testcases. Each testcase consists of a single string in one line. Each character of the string will be a small alphabet(ie. 'a' to 'z').

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

-----Constraints-----
- 1 ≤ T ≤ 10
- Subtask 1 (20 points):1 ≤ N ≤ 10
- Subtask 2 (80 points):1 ≤ N ≤ 105

-----Example-----
Input:
2
abc
aba

Output:
3
2

-----Explanation-----
For first testcase, the whole string is a subsequence which has all distinct characters.

In second testcase, the we can delete last or first 'a' to get the required subsequence.

t=int(input())
for _ in range(t):
 n=input()
 l1=[]
 for i in n:
  if i not in l1:
   l1.append(i)
 print(len(l1))


Solve in Python:
You have invented a time-machine which has taken you back to ancient Rome. Caeser is impressed with your programming skills and has appointed you to be the new information security officer.

Caeser has ordered you to write a Caeser cipher to prevent Asterix and Obelix from reading his emails.

A Caeser cipher shifts the letters in a message by the value dictated by the encryption key. Since Caeser's emails are very important, he wants all encryptions to have upper-case output, for example:

If key = 3
"hello" -> KHOOR
If key = 7
"hello" -> OLSSV

Input will consist of the message to be encrypted and the encryption key.

import string

def caeser(message, key=1):
    letters = string.ascii_lowercase
    mask = letters[key:] + letters[:key]
    trantab = str.maketrans(letters, mask)
    return message.translate(trantab).upper()


Solve in Python:
You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists.

We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.

Example 1:

Input:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
Output: [20,24]
Explanation:
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].

Note:

The given list may contain duplicates, so ascending order means >= here.
1 k
 -105 value of elements 5.
For Java users, please note that the input type has been changed to List<List<Integer>>. And after you reset the code template, you'll see this point.

from functools import reduce
 class Solution:
     def smallestRange(self, nums):
         """
         :type nums: List[List[int]]
         :rtype: List[int]
         """
         k = len(nums)
         idx = [0]*k

         dic = collections.defaultdict(list)

         for i in range(k):
             dic[nums[i][0]].append(i)

         mi, ma = min(dic.keys()), max(dic.keys())

         ret = (mi, ma)
         while True:
             for i in dic[mi]:
                 idx[i] += 1
                 if idx[i]==len(nums[i]):
                     return ret
                 dic[nums[i][idx[i]]].append(i)
             dic.pop(mi)
             mi, ma = min(dic.keys()), max(dic.keys())
             if ma-mi<ret[1]-ret[0]:
                 ret = (mi, ma)


Solve in Python:
You have managed to intercept an important message and you are trying to read it.

You realise that the message has been encoded and can be decoded by switching each letter with a corresponding letter.

You also notice that each letter is paired with the letter that it coincides with when the alphabet is reversed.

For example: "a" is encoded with "z", "b" with "y", "c" with "x", etc

You read the first sentence:
```
"r slkv mlylwb wvxlwvh gsrh nvhhztv"
```

After a few minutes you manage to decode it:
```
"i hope nobody decodes this message"
```
Create a function that will instantly decode any of these messages

You can assume no punctuation or capitals, only lower case letters, but remember spaces!

def decode(message):
    res=""
    c=0
    for i in range(0, len(message)):
        if message[i]=="a":
            res+="z"
        elif message[i]=="z":
            res+="a"
        elif message[i]=="b":
            res+="y"
        elif message[i]=="y":
            res+="b"
        elif message[i]=="c":
            res+="x"
        elif message[i]=="x":
            res+="c"
        elif message[i]=="d":
            res+="w"
        elif message[i]=="w":
            res+="d"
        elif message[i]=="e":
            res+="v"
        elif message[i]=="v":
            res+="e"
        elif message[i]=="f":
            res+="u"
        elif message[i]=="u":
            res+="f"
        elif message[i]=="g":
            res+="t"
        elif message[i]=="t":
            res+="g"
        elif message[i]=="h":
            res+="s"
        elif message[i]=="s":
            res+="h"
        elif message[i]=="i":
            res+="r"
        elif message[i]=="r":
            res+="i"
        elif message[i]=="j":
            res+="q"
        elif message[i]=="q":
            res+="j"
        elif message[i]=="k":
            res+="p"
        elif message[i]=="p":
            res+="k"
        elif message[i]=="l":
            res+="o"
        elif message[i]=="o":
            res+="l"
        elif message[i]=="m":
            res+="n"
        elif message[i]=="n":
            res+="m"
        else:
            res+=" "
    return res


Solve in Python:
You have n dices each one having s sides numbered from 1 to s.
How many outcomes add up to a specified number k?

For example if we roll four normal six-sided dices we
have four outcomes that add up to 5.

(1, 1, 1, 2)
(1, 1, 2, 1)
(1, 2, 1, 1)
(2, 1, 1, 1)

def outcome(n, s, k):
    return n <= k <= n*s and (n in (1, k) or sum(outcome(n-1, s, k-x-1) for x in range(min(s, k-n+1))))


Solve in Python:
You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.

For each move, you could choose any m (1 ≤ m ≤ n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines  at the same time .

Given an integer array representing the number of dresses in each washing machine from left to right on the line, you should find the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.

Example1

Input: [1,0,5]

Output: 3

Explanation:
1st move:    1     0     1     1     4
2nd move:    1     2     1     3
3rd move:    2     1     2     2     2

Example2

Input: [0,3,0]

Output: 2

Explanation:
1st move:    0     1     2     0
2nd move:    1     2 --> 0    =>    1     1     1

Example3

Input: [0,2,0]

Output: -1

Explanation:
It's impossible to make all the three washing machines have the same number of dresses.

Note:

The range of n is [1, 10000].
The range of dresses number in a super washing machine is [0, 1e5].

class Solution:
     def findMinMoves(self, machines):
         """
         :type machines: List[int]
         :rtype: int
         """
         N = len(machines)
         if sum(machines)%N!=0: return -1
         avg = sum(machines)//N

         result = 0
         toNext = 0
         for i in range(N):
             fromPrev = toNext
             toNext = fromPrev+machines[i]-avg
             if fromPrev<0 and toNext>0:
                 result = max(result,-fromPrev+toNext)
             else:
                 result = max(result,abs(fromPrev),abs(toNext))

         return result


Solve in Python:
You have n  tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.

Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".

Example 2:
Input: tiles = "AAABBC"
Output: 188

Example 3:
Input: tiles = "V"
Output: 1

Constraints:

1 <= tiles.length <= 7
tiles consists of uppercase English letters.

class Solution:
    def numTilePossibilities(self, tiles: str) -> int:
        res = set()
        def dfs(path, t):
            if path not in res:
                if path:
                    res.add(path)
                for i in range(len(t)):
                    dfs(path+t[i], t[:i] + t[i+1:])

        dfs('', tiles)
        return len(res)


Solve in Python:
You have recently discovered that horses travel in a unique pattern - they're either running (at top speed) or resting (standing still).

Here's an example of how one particular horse might travel:

```
The horse Blaze can run at 14 metres/second for 60 seconds, but must then rest for 45 seconds.

After 500 seconds Blaze will have traveled 4200 metres.
```

Your job is to write a function that returns how long a horse will have traveled after a given time.

####Input:

* totalTime - How long the horse will be traveling (in seconds)

* runTime - How long the horse can run for before having to rest (in seconds)

* restTime - How long the horse have to rest for after running (in seconds)

* speed - The max speed of the horse (in metres/second)

def travel(total_time, run_time, rest_time, speed):
  runs, extra = divmod(total_time, run_time + rest_time)

  return (runs * run_time + min(extra, run_time)) * speed


Solve in Python:
You have stumbled across the divine pleasure that is owning a dog and a garden. Now time to pick up all the cr@p! :D

Given a 2D array to represent your garden, you must find and collect all of the dog cr@p - represented by '@'.

You will also be given the number of bags you have access to (bags), and the capactity of a bag (cap). If there are no bags then you can't pick anything up, so you can ignore cap.

You need to find out if you have enough capacity to collect all the cr@p and make your garden clean again.

If you do, return 'Clean', else return 'Cr@p'.

Watch out though - if your dog is out there ('D'), he gets very touchy about being watched. If he is there you need to return 'Dog!!'.

For example:

x=
[[\_,\_,\_,\_,\_,\_]
 [\_,\_,\_,\_,@,\_]
 [@,\_,\_,\_,\_,\_]]

bags = 2, cap = 2

return  --> 'Clean'

def crap(garden, bags, cap):
    s = "".join(["".join(i) for i in garden])
    return "Dog!!" if "D" in s else "Clean" if s.count("@") <= bags*cap else "Cr@p"


Solve in Python:
You have the `radius` of a circle with the center in point `(0,0)`.

Write a function that calculates the number of points in the circle where `(x,y)` - the cartesian coordinates of the points - are `integers`.

Example: for `radius = 2` the result should be `13`.

`0 <= radius <= 1000`

![](http://i.imgur.com/1SMov3s.png)

def points(radius):
    cnt = radius * 4 + 1
    r2 = radius * radius
    for i in range(1, radius + 1):
        for j in range(1, radius + 1):
            if (i * i + j * j <= r2):
                cnt += 4
    return cnt


Solve in Python:
You have three piles of candies: red, green and blue candies:  the first pile contains only red candies and there are $r$ candies in it,  the second pile contains only green candies and there are $g$ candies in it,  the third pile contains only blue candies and there are $b$ candies in it.

Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.

Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.

-----Input-----

The first line contains integer $t$ ($1 \le t \le 1000$) — the number of test cases in the input. Then $t$ test cases follow.

Each test case is given as a separate line of the input. It contains three integers $r$, $g$ and $b$ ($1 \le r, g, b \le 10^8$) — the number of red, green and blue candies, respectively.

-----Output-----

Print $t$ integers: the $i$-th printed integer is the answer on the $i$-th test case in the input.

-----Example-----
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8

Output
1
2
2
10
5
9

-----Note-----

In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.

In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.

In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.

a = int(input())
for i in range(a):
    x, y, z = map(int, input().split())
    x, y, z = sorted([x, y, z])
    k = z - y
    if k == 0:
        y += x//2
        print(y)
    elif k > x:
        y += x
        print(y)
    else:
        x -= z - y
        y = z
        z += x//2
        print(z)


Solve in Python:
You have to build a pyramid.

This pyramid should be built from characters from a given string.

You have to create the code for these four methods:
```python
watch_pyramid_from_the_side(characters):

watch_pyramid_from_above(characters):

count_visible_characters_of_the_pyramid(characters):

count_all_characters_of_the_pyramid(characters):
```

The first method ("FromTheSide") shows the pyramid as you would see from the side.
The second method ("FromAbove") shows the pyramid as you would see from above.
The third method ("CountVisibleCharacters") should return the count of all characters, that are visible from outside the pyramid.
The forth method ("CountAllCharacters") should count all characters of the pyramid. Consider that the pyramid is completely solid and has no holes or rooms in it.

Every character will be used for building one layer of the pyramid. So the length of the given string will be the height of the pyramid. Every layer will be built with stones from the given character. There is no limit of stones.
The pyramid should have perfect angles of 45 degrees.

Example: Given string: "abc"

Pyramid from the side:
```
  c
 bbb
aaaaa
```
Pyramid from above:
```
aaaaa
abbba
abcba
abbba
aaaaa
```
Count of visible stones/characters:
```
25
```
Count of all used stones/characters:
```
35
```

There is no meaning in the order or the choice of the characters. It should work the same for example "aaaaa" or "54321".

Hint: Your output for the side must always be a rectangle! So spaces at the end of a line must not be deleted or trimmed!

If the string is null or empty, you should exactly return this value for the watch-methods and -1 for the count-methods.

Have fun coding it and please don't forget to vote and rank this kata! :-)

I have created other katas. Have a look if you like coding and challenges.

def watch_pyramid_from_the_side(characters):
    if not characters : return characters
    baseLen = len(characters)*2-1
    return '\n'.join( ' '*(i) + characters[i]*(baseLen-2*i) + ' '*(i) for i in range(len(characters)-1,-1,-1) )

def watch_pyramid_from_above(characters):
    if not characters : return characters
    baseLen = len(characters)*2-1
    return '\n'.join( characters[0:min(i,baseLen-1-i)] + characters[min(i,baseLen-1-i)]*(baseLen-2*min(i,baseLen-1-i)) + characters[0:min(i,baseLen-1-i)][::-1] for i in range(baseLen) )

def count_visible_characters_of_the_pyramid(characters):
    return -1 if not characters else (len(characters)*2-1)**2

def count_all_characters_of_the_pyramid(characters):
    return -1 if not characters else sum( (2*i+1)**2 for i in range(len(characters)) )


Solve in Python:
You have to create a function named reverseIt.

Write your function so that in the case a string or a number is passed in as the data , you will return the data in reverse order. If the data is any other type, return it as it is.

Examples of inputs and subsequent outputs:
```
"Hello" -> "olleH"

"314159" -> "951413"

[1,2,3] -> [1,2,3]
```

def reverse_it(data):
    return data[::-1] if isinstance(data, str) else int(str(data)[::-1]) if isinstance(data, int) and not isinstance(data, bool) else float(str(data)[::-1]) if isinstance(data, float) else data


Solve in Python:
You have to create a function that converts integer given as string into ASCII uppercase letters.

All ASCII characters have their numerical order in table.

For example,

```
from ASCII table, character of number 65 is "A".
```

Numbers will be next to each other, So you have to split given number to two digit long integers.

For example,

```
'658776' to [65, 87, 76] and then turn it into 'AWL'.
```

def convert(number):
    return ''.join(chr(int(f'{e1}{e2}')) for e1,e2 in zip(*[iter(number)]*2))


Solve in Python:
You have to create a function which receives 3 arguments: 2 numbers, and the result of an unknown operation performed on them (also a number).

Based on those 3 values you have to return a string, that describes which operation was used to get the given result.

The possible return strings are:
  `"addition"`,
  `"subtraction"`,
  `"multiplication"`,
  `"division"`.

## Example:
```
calcType(1, 2, 3) -->   1 ? 2 = 3   --> "addition"
```

## Notes
* In case of division you should expect that the result of the operation is obtained by using `/` operator on the input values - no manual data type conversion or rounding should be performed.
* Cases with just one possible answers are generated.
* Only valid arguments will be passed to the function.

from operator import add as addition, sub as subtraction, mul as multiplication, truediv as division

def calc_type(a, b, res):
    return next(
        name for name in ['addition', 'subtraction', 'multiplication', 'division']
        if globals()[name](a, b) == res
    )


Solve in Python:
You have to create a function,named `insertMissingLetters`, that takes in a `string` and outputs the same string processed in a particular way.

The function should insert **only after the first occurrence** of each character of the input string, all the **alphabet letters** that:

-**are NOT** in the original string
-**come after** the letter of the string you are processing

Each added letter should be in `uppercase`, the letters of the original string will always be in `lowercase`.

Example:

`input`: "holly"

`missing letters`: "a,b,c,d,e,f,g,i,j,k,m,n,p,q,r,s,t,u,v,w,x,z"

`output`: "hIJKMNPQRSTUVWXZoPQRSTUVWXZlMNPQRSTUVWXZlyZ"

You don't need to validate input, the input string will always contain a certain amount of lowercase letters  (min 1 / max 50).

def insert_missing_letters(s):
    alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; res = ""; memo = {}
    for char in s:
        if char not in memo: memo[char] = 1
        else: memo[char] += 1
        if memo[char] == 1:
            res += char + "".join(sorted(list(set(alph[alph.index(char.upper())+1:])-set(s.upper()))))
        else: res += char
    return res


Solve in Python:
You have to create a method "compoundArray" which should take as input two int arrays of different length and return one int array with numbers of both arrays shuffled one by one.
```Example:
Input - {1,2,3,4,5,6} and {9,8,7,6}
Output - {1,9,2,8,3,7,4,6,5,6}
```

from itertools import zip_longest
def compound_array(a, b):
    mx = []
    for a,b in zip_longest(a,b):
        mx.append(a)
        mx.append(b)
    return list(filter(lambda x:x!=None, mx))


Solve in Python:
You have to rebuild a string from an enumerated list.
For this task, you have to check if input is correct beforehand.

* Input must be a list of tuples
* Each tuple has two elements.
* Second element is an alphanumeric character.
* First element is the index of this character into the reconstructed string.
* Indexes start at 0 and have to match with output indexing: no gap is allowed.
* Finally tuples aren't necessarily ordered by index.

If any condition is invalid, the function should return `False`.

Input example:
```python
[(4,'y'),(1,'o'),(3,'t'),(0,'m'),(2,'n')]
```
Returns

```python
'monty'
```

def denumerate(enum_list):
    try:
        nums = dict(enum_list)
        maximum = max(nums) + 1
        result = ''.join(nums[a] for a in range(maximum))
        if result.isalnum() and len(result) == maximum:
            return result
    except (KeyError, TypeError, ValueError):
        pass
    return False


Solve in Python:
You have to write a function that describe Leo:
```python
def leo(oscar):
  pass
```

if oscar was (integer) 88, you have to return "Leo finally won the oscar! Leo is happy".
if oscar was 86, you have to return "Not even for Wolf of wallstreet?!"
if it was not 88 or 86 (and below 88) you should return "When will you give Leo an Oscar?"
if it was over 88 you should return "Leo got one already!"

def leo(oscar):
    if oscar <= 88:
        return {86: 'Not even for Wolf of wallstreet?!',
                88: 'Leo finally won the oscar! Leo is happy'}.get(
            oscar, 'When will you give Leo an Oscar?')
    return 'Leo got one already!'


Solve in Python:
You have to write two methods to *encrypt* and *decrypt* strings.
Both methods have two parameters:
```
1. The string to encrypt/decrypt
2. The Qwerty-Encryption-Key (000-999)
```

The rules are very easy:
```
The crypting-regions are these 3 lines from your keyboard:
1. "qwertyuiop"
2. "asdfghjkl"
3. "zxcvbnm,."

If a char of the string is not in any of these regions, take the char direct in the output.
If a char of the string is in one of these regions: Move it by the part of the key in the
region and take this char at the position from the region.
If the movement is over the length of the region, continue at the beginning.
The encrypted char must have the same case like the decrypted char!
So for upperCase-chars the regions are the same, but with pressed "SHIFT"!

The Encryption-Key is an integer number from 000 to 999. E.g.: 127

The first digit of the key (e.g. 1) is the movement for the first line.
The second digit of the key (e.g. 2) is the movement for the second line.
The third digit of the key (e.g. 7) is the movement for the third line.

(Consider that the key is an integer! When you got a 0 this would mean 000. A 1 would mean 001. And so on.)
```

You do not need to do any prechecks. The strings will always be not null
and will always have a length > 0. You do not have to throw any exceptions.

An Example:
```
Encrypt "Ball" with key 134
1. "B" is in the third region line. Move per 4 places in the region. -> ">" (Also "upperCase"!)
2. "a" is in the second region line. Move per 3 places in the region. -> "f"
3. "l" is in the second region line. Move per 3 places in the region. -> "d"
4. "l" is in the second region line. Move per 3 places in the region. -> "d"
--> Output would be ">fdd"
```

*Hint: Don't forget: The regions are from an US-Keyboard!*
*In doubt google for "US Keyboard."*

This kata is part of the Simple Encryption Series:
Simple Encryption #1 - Alternating Split
Simple Encryption #2 - Index-Difference
Simple Encryption #3 - Turn The Bits Around
Simple Encryption #4 -...

encrypt = lambda s, k: code(s, k)
decrypt = lambda s, k: code(s, k, -1)

def code(text, key, m=1):
    keys, r = [int(e) * m for e in str(key).rjust(3, '0')], []
    for c in text:
        for i, a in enumerate(['qwertyuiop', 'asdfghjkl', 'zxcvbnm,.']):
            if c in a: c = a[(a.index(c) + keys[i]) % len(a)]
        for i, a in enumerate(['QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM<>']):
            if c in a: c = a[(a.index(c) + keys[i]) % len(a)]
        r.append(c)
    return ''.join(r)


Solve in Python:
You have two arguments: ```string``` - a string of random letters(only lowercase) and ```array``` - an array of strings(feelings). Your task is to return how many specific feelings are in the ```array```.

For example:

```
string -> 'yliausoenvjw'
array -> ['anger', 'awe', 'joy', 'love', 'grief']
output -> '3 feelings.' // 'awe', 'joy', 'love'

string -> 'griefgriefgrief'
array -> ['anger', 'awe', 'joy', 'love', 'grief']
output -> '1 feeling.' // 'grief'

string -> 'abcdkasdfvkadf'
array -> ['desire', 'joy', 'shame', 'longing', 'fear']
output -> '0 feelings.'
```

If the feeling can be formed once - plus one to the answer.

If the feeling can be formed several times from different letters - plus one to the answer.

Eeach letter in ```string``` participates in the formation of all feelings. 'angerw' -> 2 feelings: 'anger' and 'awe'.

from collections import Counter

def count_feelings(s, arr):
    count = sum(1 for f in arr if not Counter(f) - Counter(s))
    return '{} feeling{}.'.format(count, '' if count == 1 else 's')


Solve in Python:
You have two arrays in this kata, every array contain only unique elements. Your task is to calculate number of elements in first array which also are in second array.

def match_arrays(v, r):
    return sum(1 for x in v if x in r)

# DON'T remove
verbose = False # set to True to diplay arrays being tested in the random tests


Solve in Python:
You have unweighted tree of $n$ vertices. You have to assign a positive weight to each edge so that the following condition would hold:

  For every two different leaves $v_{1}$ and $v_{2}$ of this tree, bitwise XOR of weights of all edges on the simple path between $v_{1}$ and $v_{2}$ has to be equal to $0$.

Note that you can put very large positive integers (like $10^{(10^{10})}$).

It's guaranteed that such assignment always exists under given constraints. Now let's define $f$ as the number of distinct weights in assignment.

 [Image] In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is $0$. $f$ value is $2$ here, because there are $2$ distinct edge weights($4$ and $5$).

[Image] In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex $1$ and vertex $6$ ($3, 4, 5, 4$) is not $0$.

What are the minimum and the maximum possible values of $f$ for the given tree? Find and print both.

-----Input-----

The first line contains integer $n$ ($3 \le n \le 10^{5}$) — the number of vertices in given tree.

The $i$-th of the next $n-1$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$) — it means there is an edge between $a_{i}$ and $b_{i}$. It is guaranteed that given graph forms tree of $n$ vertices.

-----Output-----

Print two integers — the minimum and maximum possible value of $f$ can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.

-----Examples-----
Input
6
1 3
2 3
3 4
4 5
5 6

Output
1 4

Input
6
1 3
2 3
3 4
4 5
4 6

Output
3 3

Input
7
1 2
2 7
3 4
4 7
5 6
6 7

Output
1 6

-----Note-----

In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.  [Image]

In the second example, possible assignments for each minimum and maximum are described in picture below. The $f$ value of...

import sys
input = sys.stdin.readline

n = int(input())

neigh = [[] for i in range(n)]
l = []
for i in range(n - 1):
    a, b = list(map(int, input().split()))
    a -= 1
    b -= 1
    neigh[a].append(b)
    neigh[b].append(a)
    l.append((a,b))

#Max
edges = set()
for a, b in l:
    if len(neigh[a]) == 1:
        a = -1
    if len(neigh[b]) == 1:
        b = -1
    if a > b:
        a, b = b, a
    edges.add((a,b))

MAX = len(edges)

#Min
leafDepth = []
visited = [False] * n
from collections import deque
q = deque()
q.append((0,0))
while q:
    nex, d = q.popleft()
    if not visited[nex]:
        visited[nex] = True

        if len(neigh[nex]) == 1:
            leafDepth.append(d)
        for v in neigh[nex]:
            q.append((v,d+1))

MIN = 1
corr = leafDepth.pop() % 2
for d in leafDepth:
    if d % 2 != corr:
        MIN = 3

#Out
print(MIN, MAX)


Solve in Python:
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.

Example 1:

Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
Output: true

Example 2:

Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
Output: false

Example 3:

Input: n = 2, leftChild = [1,0], rightChild = [-1,-1]
Output: false

Example 4:

Input: n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1]
Output: false

Constraints:

1 <= n <= 10^4
leftChild.length == rightChild.length == n
-1 <= leftChild[i], rightChild[i] <= n - 1

class Solution:
    def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
        indegree = [0]*n
        outdegree = [0]*n
        visited = [False]*n

        possible_roots = []
        for i in range(n):
            if leftChild[i] != -1:
                outdegree[i] += 1
                indegree[leftChild[i]] += 1
            if rightChild[i] != -1:
                outdegree[i] += 1
                indegree[rightChild[i]] += 1

        for i in range(n):
            if indegree[i] == 0 and outdegree[i] <= 2:
                possible_roots.append(i)
                # check for more than one root node
                if len(possible_roots) > 1:
                    return False

            if outdegree[i] > 2:
                return False

        if not possible_roots:
            return False

        queue = deque()
        queue.append(possible_roots[0])
        while queue:
            node = queue.popleft()
            if visited[node]:
                return False

            visited[node] = True

            lc = leftChild[node]
            rc = rightChild[node]
            if lc != -1:
                queue.append(lc)
            if rc != -1:
                queue.append(rc)

        return all(visited)


Solve in Python:
You just got done with your set at the gym, and you are wondering how much weight you could lift if you did a single repetition. Thankfully, a few scholars have devised formulas for this purpose (from [Wikipedia](https://en.wikipedia.org/wiki/One-repetition_maximum)) :

### Epley

### McGlothin

### Lombardi

Your function will receive a weight `w` and a number of repetitions `r` and must return your projected one repetition maximum. Since you are not sure which formula to use and you are feeling confident, your function will return the largest value from the three formulas shown above, rounded to the nearest integer. However, if the number of repetitions passed in is `1` (i.e., it is already a one rep max), your function must return `w`. Also, if the number of repetitions passed in is `0` (i.e., no repetitions were completed), your function must return `0`.

def calculate_1RM(w, r):
    if r == 0: return 0
    if r == 1: return w

    return round(max([
      w * (1 + r / 30),                 # Epley
      100 * w / (101.3 - 2.67123 * r),  # McGlothin
      w * r**0.10                       # Lombardi
      ]))


Solve in Python:
You just took a contract with the Jedi council. They need you to write a function, `greet_jedi()`, which takes two arguments (a first name and a last name), works out the corresponding *Jedi name*, and returns a string greeting the Jedi.

A person's *Jedi name* is the first three letters of their last name followed by the first two letters of their first name. For example:
```python
>>> greet_jedi('Beyonce', 'Knowles')
'Greetings, master KnoBe'
```
Note the capitalization: the first letter of each name is capitalized. Your input may or may not be capitalized. Your function should handle it and return the Jedi name in the correct case no matter what case the input is in:
```python
>>> greet_jedi('grae', 'drake')
'Greetings, master DraGr'
```
You can trust that your input names will always be at least three characters long.

If you're stuck, check out the [python.org tutorial](https://docs.python.org/3/tutorial/introduction.html#strings) section on strings and search "slice".

def greet_jedi(first, last):
    return 'Greetings, master {}'.format(last[:3].capitalize()+first[:2].capitalize())


Solve in Python:
You know combinations: for example,
if you take 5 cards from a 52 cards deck you have 2,598,960 different combinations.

In mathematics the number of x combinations you can take from a set of n elements
is called the binomial coefficient of n and x, or more often `n choose x`.
The formula to compute `m = n choose x` is: `m = n! / (x! * (n - x)!)`
where ! is the factorial operator.

You are a renowned poster designer and painter. You are asked to provide 6 posters
all having the same design each in 2 colors. Posters must all have a different color combination and you have the choice of 4 colors: red, blue, yellow, green.
How many colors can you choose for each poster?

The answer is two since `4 choose 2 = 6`. The combinations will be:
{red, blue}, {red, yellow}, {red, green}, {blue, yellow}, {blue, green}, {yellow, green}.

Now same question but you have 35 posters to provide and 7 colors available. How many colors for each poster?
If you take combinations `7 choose 2` you will get 21 with the above formula.
But 21 schemes aren't enough for 35 posters. If you take `7 choose 5` combinations you will get 21 too.
Fortunately if you take `7 choose 3` or `7 choose 4` combinations you get 35 and so each poster will have a different combination of
3 colors or 5 colors. You will take 3 colors because it's less expensive.

Hence the problem is:

knowing `m` (number of posters to design),
knowing `n` (total number of available colors),
let us
search `x` (number of colors for each poster so that each poster has a unique combination of colors and the number of combinations is exactly the same as the number of posters).

In other words we must find **x** such as `n choose x = m (1)` for a given m and a given n;
`m >= 0 and n > 0`. If many x are solutions give as result the smallest x.
It can happen that when m is given at random there are no x satisfying `equation (1)` then
return -1.

Examples:
```
checkchoose(6, 4) --> 2
checkchoose(4, 4) --> 1
checkchoose(4, 2) --> -1
checkchoose(35, 7) --> 3
checkchoose(36, 7)...

def checkchoose(m, n):
    c = 1
    for x in range(n // 2 + 1):
        if c == m: return x
        c = c * (n-x) // (x+1)
    else: return -1


Solve in Python:
You know how sometimes you write the the same word twice in a sentence, but then don't notice that it happened? For example, you've been distracted for a second. Did you notice that *"the"* is doubled in the first sentence of this description?

As as aS you can see, it's not easy to spot those errors, especially if words differ in case, like *"as"* at the beginning of the sentence.

Write a function that counts the number of sections repeating the same word (case insensitive). The occurence of two or more equal words next after each other count as one.

**Example:**
```
"dog cat"                 --> 0
"dog DOG cat"             --> 1
"apple dog cat"           --> 0
"pineapple apple dog cat" --> 0
"apple     apple dog cat" --> 1
"apple dog apple dog cat" --> 0
"dog dog DOG dog dog dog" --> 1
"dog dog dog dog cat cat" --> 2
"cat cat dog dog cat cat" --> 3
```

def count_adjacent_pairs(st):
    words = st.lower().split(' ')
    currentWord = None
    count = 0
    for i, word in enumerate(words):
        if i+1 < len(words):
            if word == words[i+1]:
                if word != currentWord:
                    currentWord = word
                    count += 1
            else:
                currentWord = None

    return count


Solve in Python:
You like playing chess tournaments online.

In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").

The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.

After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.

Compute the maximum score you can get by cheating in the optimal way.

-----Input-----

Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) — the number of test cases. The description of the test cases follows.

The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) – the number of games played and the number of outcomes that you can change.

The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.

It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.

-----Output-----

For each testcase, print a single integer – the maximum score you can get by cheating in the optimal way.

-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW

Output
7
11
6
26
46
0
1
6

-----Note-----

Explanation of the first testcase. Before changing any outcome, the score is...

import sys
readline = sys.stdin.readline

T = int(readline())
Ans = [None]*T

for qu in range(T):
    N, K = list(map(int, readline().split()))
    S = [1 if s == 'W' else 0 for s in readline().strip()]
    if all(s == 0 for s in S):
        Ans[qu] = max(0, 2*K-1)
        continue

    ans = 0
    ctr = 0
    st = []
    L = []
    res = 0
    hh = False
    for i in range(N):
        s = S[i]
        if s == 1:
            if i == 0 or S[i-1] == 0:
                ans += 1
            else:
                ans += 2
            if ctr:
                st.append(ctr)
                ctr = 0
            hh = True
        else:
            if hh:
                ctr += 1
            else:
                res += 1
    res += ctr
    st.sort()
    J = []
    for s in st:
        J.extend([2]*(s-1) + [3])
    J.extend([2]*res)
    Ans[qu] = ans + sum(J[:min(len(J), K)])
print('\n'.join(map(str, Ans)))


Solve in Python:
You like the way the Python `+` operator easily handles adding different numeric types, but you need a tool to do that kind of addition without killing your program with a `TypeError` exception whenever you accidentally try adding incompatible types like strings and lists to numbers.

You decide to write a function `my_add()` that takes two arguments. If the arguments can be added together it returns the sum. If adding the arguments together would raise an error the function should return `None` instead.

For example, `my_add(1, 3.414)` would return `4.414`, but `my_add(42, " is the answer.")` would return `None`.

Hint: using a `try` / `except` statement may simplify this kata.

def my_add(a, b):
    # Your code here.
    try:
      return a + b
    except TypeError:
      print("None")


Solve in Python:
You like tracking airplane flights a lot. Specifically, you maintain history of an airplane’s flight at several instants and record them in your notebook. Today, you have recorded N such records h1, h2, ..., hN, denoting the heights of some airplane at several instants. These records mean that airplane was first flying on height h1, then started changing its height to h2, then from h2 to h3 and so on. The airplanes are usually on cruise control while descending or ascending, so
you can assume that plane will smoothly increase/decrease its height from hi to hi + 1 with a constant speed. You can see that during this period, the airplane will cover all possible heights in the range [min(hi, hi+1), max(hi, hi+1)] (both inclusive). It is easy to see that the plane will be at all possible heights in the range exactly a single instant of time during this ascend/descend.

You are interested in finding the maximum integer K such that the plane was at some height exactly K times during the flight.

-----Input-----
There is a single test case.
First line of the input contains an integer N denoting the number of records of heights of the plane.
Second line contains N space separated integers denoting h1, h2, ..., hN.

-----Output-----
Output a single maximum integer K in one line, such that the plane was at some height exactly K times during the flight.

-----Constraints-----
- hi ≠ hi+1

-----Subtasks-----
Subtask #1: (30 points)
- 1 ≤ N ≤ 1000
- 1 ≤ hi ≤ 1000

Subtask #2: (70 points)
- 1 ≤ N ≤ 105
- 1 ≤ hi ≤ 109

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

Output:
3

-----Explanation-----

The flight can be draw as:

3  /\/
2 /
1

There are infinitely many heights at which the plane was 3 times during the flight, for example 2.5, 2.1. Notice that the plane was only 2 times at height 2. Moreover, there are no height at which the plane was more than 3 times, so the answer is 3.

def f(n):

 s = list(map(int, input().split()))
 low = []
 high = []

 for i in range(n - 1):
  low.append(min(s[i], s[i+1]))
  high.append(max(s[i], s[i+1]))
 low.sort()
 high.sort()
 curr = mx = 0
 i = j = 0
 n -= 1
 while i < n and j < n:
  if low[i] < high[j]:
   i += 1
   curr += 1
  else:
   j += 1
   curr -= 1
  mx = max(mx, curr)

 return mx

n = int(input())
print(f(n))


Solve in Python:
You love coffee and want to know what beans you can afford to buy it.

The first argument to your search function will be a number which represents your budget.

The second argument will be an array of coffee bean prices.

Your 'search' function should return the stores that sell coffee within your budget.

The search function should return a string of prices for the coffees beans you can afford. The prices in this string are to be sorted in ascending order.

def search(budget, prices):
    return ','.join(map(str, sorted(filter(float(budget).__ge__, prices))))