Solve in Python:
Implement a function which
creates a **[radix tree](https://en.wikipedia.org/wiki/Radix_tree)** (a space-optimized trie [prefix tree])
in which each node that is the only child is merged with its parent [unless a word from the input ends there])
from a given list of words
using dictionaries (aka hash maps or hash tables) where:

1. The dictionary keys are the nodes.
2. Leaf nodes are empty dictionaries.
3. The value for empty input is an empty dictionary.
4. Words are all lowercase or empty strings.
5. Words can contain duplicates.

### Examples:

```python
>>> radix_tree()
{}

>>> radix_tree("")
{}

>>> radix_tree("", "")
{}

>>> radix_tree("radix", "tree")
{"radix": {}, "tree": {}}

>>> radix_tree("ape", "apple")
{"ap": {"e": {}, "ple": {}}}

>>> radix_tree("apple", "applet", "apple", "ape")
{"ap": {"ple": {"t": {}}, "e": {}}}

>>> radix_tree("romane", "romanus", "romulus", "rubens", "rubicon", "rubicundus")
{"r": {"om": {"an": {"e": {}, "us": {}}, "ulus": {}},
       "ub": {"ens": {}, "ic": {"on": {}, "undus": {}}}}}

>>> radix_tree("appleabcd", "apple")
{"apple": {"abcd": {}}}
```

from functools import reduce

def splitAlong(xs, ys):
    i = 0
    try:
        while xs[i] == ys[i]:
            i += 1
    except IndexError:
        pass
    return (xs[:i], xs[i:], ys[i:])

def insert(tree, word):
    for key, val in tree.items():
        pref, wt, kt = splitAlong(word, key)
        if pref:
            if kt:
                del tree[key]
                tree[pref] = {wt: {}, kt: val} if wt else {kt: val}
            else:
                insert(tree[pref], wt)
            return tree
    if word:
        tree[word] = {}
    return tree

def radix_tree(*words):
    return reduce(insert, words, {})


Solve in Python:
Implement a function which behaves like the 'uniq -c' command in UNIX.

It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance together with the number of times a duplicate elements occurred in the original array.

Example:

```python
['a','a','b','b','c','a','b','c'] --> [('a',2),('b',2),('c',1),('a',1),('b',1),('c',1)]
```

def uniq_c(seq):
    m = []
    n,i = len(seq),0
    while i<n:
        c = seq[i]
        j = i+1
        while j<n and seq[j]==c: j += 1
        m.append((c,j-i))
        i = j
    return m


Solve in Python:
Implement a function which behaves like the uniq command in UNIX.

It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance.

Example:

```
["a", "a", "b", "b", "c", "a", "b", "c"]  =>  ["a", "b", "c", "a", "b", "c"]
```

def uniq(seq):
    result = []
    for q in seq:
        if result and result[-1] == q:
            continue
        result.append(q)
    return result


Solve in Python:
Implement a function which convert the given boolean value into its string representation.

def boolean_to_string(b):
    if b == True:
      return str("True")
    return str("False")


Solve in Python:
Implement a function which multiplies two numbers.

#your code hered
def multiply(a,b):
    return a*b


Solve in Python:
Implement a function which takes a string, and returns its hash value.

Algorithm steps:

* `a` := sum of the ascii values of the input characters
* `b` := sum of every difference between the consecutive characters of the input (second char minus first char, third minus second, ...)
* `c` := (`a` OR `b`) AND ((NOT `a`) shift left by 2 bits)
* `d` := `c` XOR (32 * (`total_number_of_spaces` + 1))
* return `d`

**Note**: OR, AND, NOT, XOR are bitwise operations.

___

### Examples

```
input = "a"
a = 97
b = 0
result = 64

input = "ca"
a = 196
b = -2
result = -820
```

___

Give an example why this hashing algorithm is bad?

def string_hash(s):
    a, b = sum(ord(x) for x in s), sum(ord(y) - ord(x) for x, y in zip(s, s[1:]))
    return (a | b) & (~a << 2) ^ (32 * (s.count(" ") + 1))


Solve in Python:
Implement a function, `multiples(m, n)`, which returns an array of the first `m` multiples of the real number `n`. Assume that `m` is a positive integer.

Ex.
```
multiples(3, 5.0)
```
should return
```
[5.0, 10.0, 15.0]
```

def multiples(m, n):
    answer = []
    i = 1
    while i <= m:
        x = n * i
        answer.append(x)
        i+=1
    return answer


Solve in Python:
Implement a function, so it will produce a sentence out of the given parts.

Array of parts could contain:
- words;
- commas in the middle;
- multiple periods at the end.

Sentence making rules:
- there must always be a space between words;
- there must not be a space between a comma and word on the left;
- there must always be one and only one period at the end of a sentence.

**Example:**

def make_sentences(parts):
    n = ''
    parts = [i for i in parts if i != '.']
    for i in parts:
        if i == ',':
            n = n[:-1] + ', '
        else:
            n += i + ' '
    return n[:-1]+'.'


Solve in Python:
Implement a function/class, which should return an integer if the input string is in one of the formats specified below, or `null/nil/None` otherwise.

Format:
* Optional `-` or `+`
* Base prefix `0b` (binary), `0x` (hexadecimal), `0o` (octal), or in case of no prefix decimal.
* Digits depending on base

Any extra character (including whitespace) makes the input invalid, in which case you should return `null/nil/None`.

Digits are case insensitive, but base prefix must be lower case.

See the test cases for examples.

import re

def to_integer(string):
    try: return eval(''.join(e for e in re.match(r'\A([-+]?)(?:(0b[01]+)|(0o[0-7]+)|(0x[0-9a-fA-F]+)|0*(\d+))\Z',string).groups() if e))
    except: return None


Solve in Python:
Implement a magic directory with buildDict, and search methods.

For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary.

For the method search, you'll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.

Example 1:

Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False

Note:

You may assume that all the inputs are consist of lowercase letters a-z.
For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details.

class MagicDictionary:

     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.tier=[None]*27

     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         for word in dict:
             p=self.tier
             for c in word:
                 t=ord(c)-ord('a')
                 if not p[t]:
                     p[t]=[None]*27
                 p=p[t]
             p[26]=1

     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         def func(w):
             p=self.tier
             for c in w:
                 t=ord(c)-ord('a')
                 if not p[t]:
                     return False
                 p=p[t]
             return p[26]==1
         pool='abcdefghijklmnopqrstuvwxyz'
         for i in range(len(word)):
             for cc in pool:
                 if cc!=word[i]:
                     tt=word[:i]+'%c'%cc+word[i+1:]
                     if func(tt):
                         return True
         return False

 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


Solve in Python:
Implement a method that accepts 3 integer values a, b, c. The method should return true if a triangle can be built with the sides of given length and false in any other case.

(In this case, all triangles must have surface greater than 0 to be accepted).

def is_triangle(a, b, c):
    if(abs(a+b)<=c or abs(a-b) >= c):
        return False
    elif(abs(c+b)<=a or abs(c-b) >= a):
        return False
    elif(abs(c+a)<=b or abs(c-a) >=b):
        return False
    elif(a<=0 or b<= 0 or c <= 0):
        return False
    return True


Solve in Python:
Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

       Only the space character ' ' is considered as whitespace character.
       Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

class Solution:
     def myAtoi(self, str):
         """
         :type str: str
         :rtype: int
         """
         str = str.lstrip()
         if not str:
             return 0

         sign = -1 if str[0] == '-' else 1
         if str[0] in ['+', '-']:
             str = str[1:]

         i, res = 0, 0
         while i < len(str) and str[i].isdigit():
             res = res * 10 + ord(str[i]) - ord('0')
             i += 1

         return max(-2**31, min(2**31-1, sign * res))


Solve in Python:
Implement function which will return sum of roots of a quadratic equation rounded to 2 decimal places, if there are any possible roots, else return **None/null/nil/nothing**. If you use discriminant,when discriminant = 0, x1 = x2 = root => return sum of both roots. There will always be valid arguments.

Quadratic equation - https://en.wikipedia.org/wiki/Quadratic_equation

roots=lambda a,b,c:None if b*b<a*c*4else round(-b/a,2)


Solve in Python:
Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
             the decimal part is truncated, 2 is returned.

class Solution:
     def mySqrt(self, x):
         """
         :type x: int
         :rtype: int
         """
         return int(x**0.5)


Solve in Python:
Implement pow(x, n), which calculates x raised to the power n (xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Note:

       -100.0 < x < 100.0
       n is a 32-bit signed integer, within the range [−231, 231 − 1]

class Solution:
     def myPow(self, x, n):
         """
         :type x: float
         :type n: int
         :rtype: float
         """
         if n<0:return 1/self.myPow(x,-n)
         elif n==0:return 1
         elif n>1000:return self.myPow(self.myPow(x,1000),n//1000)*self.myPow(x,n%1000)
         else: return x*self.myPow(x,n-1)


Solve in Python:
Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

class Solution:
     def strStr(self, haystack, needle):
         """
         :type haystack: str
         :type needle: str
         :rtype: int
         """
         if not needle:
             return 0

         for i in range(0, len(haystack)-len(needle)+1):
             match = True
             for j in range(len(needle)):
                 if haystack[i+j] != needle[j]:
                     match = False
                     break
             if match:
                 return i

         return -1


Solve in Python:
Implement the StreamChecker class as follows:

StreamChecker(words): Constructor, init the data structure with the given words.
query(letter): returns true if and only if for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.

Example:
StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary.
streamChecker.query('a');          // return false
streamChecker.query('b');          // return false
streamChecker.query('c');          // return false
streamChecker.query('d');          // return true, because 'cd' is in the wordlist
streamChecker.query('e');          // return false
streamChecker.query('f');          // return true, because 'f' is in the wordlist
streamChecker.query('g');          // return false
streamChecker.query('h');          // return false
streamChecker.query('i');          // return false
streamChecker.query('j');          // return false
streamChecker.query('k');          // return false
streamChecker.query('l');          // return true, because 'kl' is in the wordlist

Note:

1 <= words.length <= 2000
1 <= words[i].length <= 2000
Words will only consist of lowercase English letters.
Queries will only consist of lowercase English letters.
The number of queries is at most 40000.

from collections import defaultdict
class StreamChecker:

    def __init__(self, words):
        tr = lambda: defaultdict(tr)
        self.trie = tr()
        for w in words:
            cur_trie = self.trie[w[0]]
            for i in range(1, len(w)):
                cur_trie = cur_trie[w[i]]
            cur_trie['end'] = True
        self.tail = []

    def query(self, letter):
        self.tail = [node[letter] for node in self.tail + [self.trie] if letter in node]
        for node in self.tail:
            if 'end' in node:
                return True
        return False

# Your StreamChecker object will be instantiated and called as such:
# obj = StreamChecker(words)
# param_1 = obj.query(letter)


Solve in Python:
Implement the [Polybius square cipher](http://en.wikipedia.org/wiki/Polybius_square).

Replace every letter with a two digit number. The first digit is the row number, and the second digit is the column number of following square. Letters `'I'` and `'J'` are both 24 in this cipher:

table#polybius-square {width: 100px;}
table#polybius-square td {background-color: #2f2f2f;}
table#polybius-square th {background-color: #3f3f3f;}

12345
1ABCDE
2FGHI/JK
3LMNOP
4QRSTU
5VWXYZ

Input will be valid (only spaces and uppercase letters from A to Z), so no need to validate them.

## Examples

```python
polybius('A')  # "11"
polybius('IJ') # "2424"
polybius('CODEWARS') # "1334141552114243"
polybius('POLYBIUS SQUARE CIPHER') # "3534315412244543 434145114215 132435231542"
```

table = {char: str(i + 10 * j + 11)
            for j, row in enumerate("ABCDE FGHIK LMNOP QRSTU VWXYZ".split())
            for i, char in enumerate(row)}

def polybius(text):
    return "".join(table.get(char, " ") for char in text.replace("J", "I"))


Solve in Python:
Implement the class ProductOfNumbers that supports two methods:
1. add(int num)

Adds the number num to the back of the current list of numbers.

2. getProduct(int k)

Returns the product of the last k numbers in the current list.
You can assume that always the current list has at least k numbers.

At any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.

Example:
Input
["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]

Output
[null,null,null,null,null,null,20,40,0,null,32]

Explanation
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
productOfNumbers.add(3);        // [3]
productOfNumbers.add(0);        // [3,0]
productOfNumbers.add(2);        // [3,0,2]
productOfNumbers.add(5);        // [3,0,2,5]
productOfNumbers.add(4);        // [3,0,2,5,4]
productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20
productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40
productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0
productOfNumbers.add(8);        // [3,0,2,5,4,8]
productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32

Constraints:

There will be at most 40000 operations considering both add and getProduct.
0 <= num <= 100
1 <= k <= 40000

class ProductOfNumbers:

    def __init__(self):
        self.products = []

    def add(self, num: int) -> None:

        if num == 0:
            self.products = []
        else:
            self.products.append(num if not len(self.products) else self.products[-1] * num)

    def getProduct(self, k: int) -> int:
        if k > len(self.products):
            return 0
        elif k == len(self.products):
            return self.products[-1]
        else:
            return self.products[-1] // self.products[-k-1]

# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)


Solve in Python:
Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:
1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)

Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).

2. getValue(int row, int col)

Returns the current value of the coordinate (row,col) from the rectangle.

Example 1:
Input
["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue","getValue"]
[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]
Output
[null,1,null,5,5,null,10,5]
Explanation
SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]);
// The initial rectangle (4x3) looks like:
// 1 2 1
// 4 3 4
// 3 2 1
// 1 1 1
subrectangleQueries.getValue(0, 2); // return 1
subrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);
// After this update the rectangle looks like:
// 5 5 5
// 5 5 5
// 5 5 5
// 5 5 5
subrectangleQueries.getValue(0, 2); // return 5
subrectangleQueries.getValue(3, 1); // return 5
subrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);
// After this update the rectangle looks like:
// 5   5   5
// 5   5   5
// 5   5   5
// 10  10  10
subrectangleQueries.getValue(3, 1); // return 10
subrectangleQueries.getValue(0, 2); // return 5

Example 2:
Input
["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue"]
[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]
Output
[null,1,null,100,100,null,20]
Explanation
SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);
subrectangleQueries.getValue(0, 0); // return 1
subrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);
subrectangleQueries.getValue(0, 0); // return 100
subrectangleQueries.getValue(2, 2); // return...

class SubrectangleQueries:
    rectangle = [[]]

    def __init__(self, rectangle):
        self.rectangle = rectangle

    def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
        while(row1 <= row2):
            self.rectangle[row1][col1:col2+1] = [newValue] * len(self.rectangle[row1][col1:col2+1])
            row1 += 1

    def getValue(self, row: int, col: int) -> int:
        return (self.rectangle[row][col])

# Your SubrectangleQueries object will be instantiated and called as such:
# obj = SubrectangleQueries(rectangle)
# obj.updateSubrectangle(row1,col1,row2,col2,newValue)
# param_2 = obj.getValue(row,col)


Solve in Python:
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)

Stores the tweetName at the recorded time (in seconds).

2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)

Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>,  [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).

Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]

Output
[null,null,null,null,[2],[2,1],null,[4]]

Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10);                             // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120);                            // All tweets correspond...

class TweetCounts:

    def __init__(self):
        self.tweets = dict()

    def recordTweet(self, tweetName: str, time: int) -> None:
        self.tweets.setdefault(tweetName, []).append(time)

    def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:
        if freq == \"minute\": seconds = 60
        elif freq == \"hour\": seconds = 3600
        else: seconds = 86400

        ans = [0] * ((endTime - startTime)//seconds + 1)
        for t in self.tweets[tweetName]:
            if startTime <= t <= endTime: ans[(t-startTime)//seconds] += 1
        return ans

# Your TweetCounts object will be instantiated and called as such:
# obj = TweetCounts()
# obj.recordTweet(tweetName,time)
# param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)


Solve in Python:
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

For example:

```python
unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
unique_in_order('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
unique_in_order([1,2,2,3,3])       == [1,2,3]
```

def unique_in_order(iterable):
    return [ ch for i, ch in enumerate(iterable) if i == 0 or ch != iterable[i - 1] ]


Solve in Python:
Implement the function which should return `true` if given object is a vowel (meaning `a, e, i, o, u`), and `false` otherwise.

import re

def is_vowel(string):
    return bool(re.match('^[aeiou]\Z', string, re.IGNORECASE))


Solve in Python:
Implementing the class MajorityChecker, which has the following API:

MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:

0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray

Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.

Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2

Constraints:

1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000

class MajorityChecker:

    def __init__(self, arr: List[int]):
        self.arr = arr
        self.data = defaultdict(list)
        for i,num in enumerate(arr):
            self.data[num] += [i]

    def query(self, left: int, right: int, threshold: int) -> int:
        counter = defaultdict(int)
        for _ in range(32):
            index = random.randint(left, right)
            counter[self.arr[index]] += 1
        max_cnts = sorted([(value,key) for key,value in list(counter.items())], reverse=True)[:2]

        for value,key in max_cnts:
            i = bisect.bisect_left(self.data[key],  left)
            j = bisect.bisect_right(self.data[key], right)
            if j - i >= threshold:
                return key
        return -1

# Your MajorityChecker object will be instantiated and called as such:
# obj = MajorityChecker(arr)
# param_1 = obj.query(left,right,threshold)


Solve in Python:
Impliment the reverse function, which takes in input n and reverses it. For instance, `reverse(123)` should return `321`. You should do this without converting the inputted number into a string.

def reverse(n):
    r = 0
    while n:
        r = r*10 + n%10
        n //= 10
    return r


Solve in Python:
Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.

You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming an n × n grid, surrounded entirely by walls. At the end of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:

 The sound of clashing rocks will awaken the door!

Being a very senior adventurer, you immediately realize what this means. In the room next door lies an infinite number of magical rocks. There are four types of rocks:   '^': this rock moves upwards;  '<': this rock moves leftwards;  '>': this rock moves rightwards;  'v': this rock moves downwards.

To open the door, you first need to place the rocks on some of the tiles (one tile can be occupied by at most one rock). Then, you select a single rock that you have placed and activate it. The activated rock will then move in its direction until it hits another rock or hits the walls of the room (the rock will not move if something already blocks it in its chosen direction). The rock then deactivates. If it hits the walls, or if there have been already 10^7 events of rock becoming activated, the movements end. Otherwise, the rock that was hit becomes activated and this procedure is repeated.

If a rock moves at least one cell before hitting either the wall or another rock, the hit produces a sound. The door will open once the number of produced sounds is at least x. It is okay for the rocks to continue moving after producing x sounds.

The following picture illustrates the four possible scenarios of moving rocks.

 Moves at least one cell, then hits another rock. A sound is produced, the hit rock becomes activated.

 [Image]

 Moves at least one cell, then hits the wall (i.e., the side of the room). A sound is produced, the movements end.

 [Image]

 Does not move because a rock...


Solve in Python:
In 17th century our Chef was a Wizard. He asked his small son "Anshu" to bring him the secret of the Magical Mountain. The boy after travelling a lot reached the Mountain.

The description of the Mountain was as follows:
- Mountain contains N magical stones. Each of them has a unique number.
- Mountain was divided into many levels, where at ith level atmost 2^i stones can be found.
- Between stones there exist a magical path containing lava.
- A stone can be connected with maximum of three stones.
- Peak of the mountain contains stone with number 1.
- If Stone 1 is first connected to stone 2 and then to 3. Assume 2 is to the left of 3.

Now, to get the secret of the mountain, Anshu started climbing from the left. On the way he used his magical wand to protect him from lava. But, while climbing he came to know that he is able to see only the one stone at each level. After reaching the peak he slided down and did the the same process. These stones that he saw shows the secret of the mountain, if they are placed in a non decreasing order on a sunny day. Anshu doesn't remember the stones number that he saw. Help him in recollecting them and getting the secret to his father.

The mountain looks like this

-----Input-----
- First line contains T the number of test cases.
- First line of each test test case contains N.
- Next N-1 lines contains X and Y the stones which are connected.

-----Output-----
- Output the required non decreasing sequence.

-----Constraints and Subtasks-----
- 1 <= T <= 10
- 1 <= X, Y <= N
Subtask 1: 20 points
- 3<=N<=100
Subtask 2: 30 points
- 3<=N<=10000
Subtask 3: 50 points
- 3<=N<=100000

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

Output:
1 2 3 4 5

for t in range(eval(input())):

  n = eval(input())

  a = [ [] for i in range(n+1) ]

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

  vis = [0] * (n+1)
  vis[1] = 1

  ans = [1]

  t1 = [1]
  t2 = []

  while len(t1) > 0 :
    for u in t1:
      for x in a[u]:
        if vis[x] == 0 :
          vis[x] = 1
          t2.append(x)
    if len(t2) > 1 :
      ans.append(t2[0])
      ans.append(t2[-1])
    if len(t2) == 1 :
      ans.append(t2[0])

    t1 = t2
    t2 = []

  for x in sorted(ans):
    print(x, end=' ')

  print('')


Solve in Python:
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.

We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.

We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:

```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) =  b * s(t) * i(t) - a * i(t)
(3) r'(t) =  a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.

We can transform equations `(1), (2), (3)` in finite differences
    (https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
    (http://www.codewars.com/kata/56347fcfd086de8f11000014)

```
(I)    S[k+1] = S[k] - dt * b * S[k] * I[k]
(II)   I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III)  R[k+1] = R[k] + dt * I[k] *a
```

The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.

The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).

# Example:

```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```

# Notes:

- You will pass the tests if
`abs(actual - expected) <= 1`

- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

![alternative text](http://i.imgur.com/xB6VSqzm.png)

def epidemic( tm, n, s0, i0, b, a ):
    S = { 0: s0 }
    I = { 0: i0 }
    dt = ( tm/n )
    for k in range( n ):
        S[k+1] = S[k] - (tm/n) * b * S[k] * I[k]
        I[k+1] = I[k] + (tm/n) * (b * S[k] * I[k] - a * I[k])

    return int( I[ max( I, key= lambda key: I[key] ) ] )


Solve in Python:
In ACM-ICPC contests, there are usually three people in a team. For each person in the team, you know their scores in three skills - hard work, intelligence and persistence.
You want to check whether it is possible to order these people (assign them numbers from 1 to 3) in such a way that for each 1 ≤ i ≤ 2, i+1-th person is stricly better than the i-th person.
A person x is said to be better than another person y if x doesn't score less than y in any of the skills and scores more than y in at least one skill.
Determine whether such an ordering exists.

-----Input-----
The first line fo the input contains an integer T denoting the number of test cases.
Each test consists of three lines. Each of these lines contains three space separated integers s1, s2 and s3 denoting the scores of one member of the team in each of the three skills, in the given order.

-----Output-----
For each test case, output a single line containing "yes" if such an ordering exists or "no" if doesn't exist (without quotes).

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ s1, s2, s3 ≤ 100

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

Output
yes
no
yes

-----Explanation-----
Test Case 1: We can order them as (3, 2, 1). Person 3 is better than Person 2 because his scores in the first two skills are not lesser than Person 2's. And in skill 3, Person 3 scores higher. Similarly, Person 2 is better than Person 1. He scores more than Person 1 in every skill, in fact.

def is_better(x, y):
 # print("x y", x, y)
 for i in range(3):
  if s[y][i] > s[x][i]:
   # print("sd", i, s[y][i], s[x][i])
   return 0

 for i in range(3):
  if s[x][i] > s[y][i]:
   # print("sank")
   return 1

 # print("mon")
 return 0

t = int(input())

for _ in range(t):
 # print("t", _)
 s = []

 for i in range(3):
  s.append([int(x) for x in input().split()])

 # print(s)

 f = -1
 m = -1

 flag = 1

 # if(f == -1):
 if(is_better(0, 1) and is_better(0, 2)):
  f = 0
 elif(is_better(1, 0) and is_better(1, 2)):
  f = 1
 elif(is_better(2, 0) and is_better(2, 1)):
  f = 2
 else:
  flag = 0

 if(f != -1):
  temp = [0, 1, 2]
  temp.remove(f)

  if(is_better(temp[0], temp[1])):
   m = temp[0]
  elif(is_better(temp[1], temp[0])):
   m = temp[1]
  else:
   flag = 0

 if(flag == 0):
  print("no")
 else:
  print("yes")


Solve in Python:
In Byteland there are N cities, numbered 1 through N. Some pairs of cities are connected by bi-directional roads in such a way that starting from any one city you can visit all other cities either directly or indirectly.

Chef is currently at city A and wants to visit all other cities in Byteland. Chef can only move according to following rule.

If Chef is at city A then he continues to move from city A to city B, city B to city C (provided A is directly connected to B, B is directly connected to C) and so on unless there are no more cities leading from current city.

If so he jumps back to previous city and repeat the same tour with other cities leading from it which are not visited. Chef repeat this step unless all cities are not visited.

Help Chef to count number of ways in which he can visit all other cities . As this number can be large print it 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.
- The first line of each test case contains a single integer N denoting the number of cities in Byteland.
-  Next N-1 lines contain two space-separated integers u and v denoting there is bi-directional road between city numbered u and v.
-  Next line contains a single integer A denoting the city number where Chef is present.

-----Output-----
- For each test case, output a single line containing number of ways in which Chef can visit all cities modulo 109+7.

-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ N ≤ 105
- 1 ≤ A ≤ N

-----Subtasks-----
Subtask #1 : (10 points)
- 1 ≤ N ≤ 5
Subtask #2 : (30 points)
- 1 ≤ N ≤ 100
Subtask #3 : (60 points)
- 1 ≤ N ≤ 105

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

Output:
2
4

-----Explanation-----
Example case 1. Chef can visit cities in two ways according to the problem: 1-2-3 and 1-3-2
Example case 1. Chef can visit cities in four ways according to the problem:

1-2-4-5-3
1-2-5-4-3
1-3-2-4-5
1-3-2-5-4

import sys
sys.setrecursionlimit(10**8)

MOD = 10**9+7

fac = [0]*(10**5+1)
def pre() :
 fac[0] = 1
 for i in range(1,10**5+1) :
  fac[i] = fac[i-1]*i
  fac[i] = fac[i]%MOD

def dfs(gp , vertex , visited , deg , ans) :
 visited[vertex] = 1
 stack = []
 stack.append(vertex)
 while len(stack)>0 :
  vertex = stack.pop()
  ans = ans%MOD * fac[deg[vertex]]%MOD
  ans %= MOD
  for i in gp[vertex] :
   if not visited[i] :
    visited[i] = 1
    if vertex in gp[i] :
     deg[i] -= 1
    stack.append(i)
 return ans%MOD

pre()
for __ in range(eval(input())) :
 n = eval(input())
 deg = [0]*(n+1)
 st = [[] for __ in range(n+1)]
 for _ in range(n-1) :
  a , b = list(map(int,sys.stdin.readline().split()))
  st[a].append(b)
  st[b].append(a)
  deg[a] += 1
  deg[b] += 1
 k = eval(input())
 visited = [0]*(n+1)
 print(dfs(st ,k,visited,deg , 1)%MOD)


Solve in Python:
In ChefLand, there is a mountain range consisting of $N$ hills (numbered $1$ through $N$) in a straight line. Let's denote the height of the $i$-th hill from the left by $h_i$.
Ada is working on the water supply system of ChefLand. On some of the hills, she wants to place water reservoirs; then, for each reservoir, she will decide in which direction the water should flow from it — either to the left or to the right (water may not flow in both directions from the same reservoir). From a reservoir on a hill with height $h$, water flows in the chosen direction until it reaches the first hill that is strictly higher than $h$; all hills before this hill (including the hill containing the reservoir) are therefore supplied with water.
For example, suppose we have hills with heights $[7, 2, 3, 5, 8]$. If we place a reservoir on the hill with height $5$, and pump water from it to the left, then the hills with heights $2$, $3$ and $5$ are supplied with water.
Help Ada find the minimum numer of reservoirs needed to provide water to all the hills if she chooses the directions optimally.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $h_1, h_2, \dots, h_N$.

-----Output-----
For each test case, print a single line containing one integer — the minimum required number of reservoirs.

-----Constraints-----
- $2 \le N \le 10^5$
- $1 \le h_i \le 10^9$ for each valid $i$
- $h_i \neq h_j $ for any valid $i \neq j$
- the sum of $N$ over all test cases does not exceed $5 \cdot 10^5$

-----Example Input-----
1
6
4 16 32 6 8 2

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

-----Explanation-----
Example case 1: We can place reservoirs on the second and third hill, pumping water to the left and right respectively.

# cook your dish here
#import math
def res(n):
	l=len(n)
	maxx=max(n)
	i=0
	i=n.index(maxx)
	if(i==0 or i==l-1):
		return 1
	else:
		return 1+min(res(n[:i]),res(n[i+1:]))

t=int(input())
while(t>0):
	t-=1
	n=int(input())
	#k,r=map(int,input().split())
	l=list(map(int,input().split()))
	print(res(l))


Solve in Python:
In Chefland, there is a monthly robots competition. In the competition, a grid table of N rows and M columns will be used to place robots. A cell at row i and column j in the table is called cell (i, j). To join this competition, each player will bring two robots to compete and each robot will be placed at a cell in the grid table. Both robots will move at the same time from one cell to another until they meet at the same cell in the table. Of course they can not move outside the table. Each robot has a movable range. If a robot has movable range K, then in a single move, it can move from cell (x, y) to cell (i, j) provided (|i-x| + |j-y| <= K). However, there are some cells in the table that the robots can not stand at, and because of that, they can not move to these cells. The two robots with the minimum number of moves to be at the same cell will win the competition.

Chef plans to join the competition and has two robots with the movable range K1 and K2, respectively. Chef does not know which cells in the table will be used to placed his 2 robots, but he knows that there are 2 cells (1, 1) and (1, M) that robots always can stand at. Therefore, he assumes that the first robot is at cell (1, 1) and the other is at cell (1, M). Chef wants you to help him to find the minimum number of moves that his two robots needed to be at the same cell and promises to give you a gift if he wins the competition.

-----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 4 space-separated integers N M K1 K2 denoting the number of rows and columns in the table and the movable ranges of the first and second robot of Chef.
-  The next N lines, each line contains M space-separated numbers either 0 or 1 denoting whether the robots can move to this cell or not (0 means robots can move to this cell, 1 otherwise). It makes sure that values in cell (1, 1) and cell (1, M) are 0.

-----Output-----
For each...

import sys

def spaces(a,n,m,k,visit1,visit2,dist,position):
 queue = [position]
 lastedit = []
 dist[position[0]][position[1]] = 0
 while queue!=[]:
  point = queue[0]
  i = point[0]
  j = point[1]
  #print 'point',i,j
  if visit1[i][j]==False:
   visit1[i][j] = True
   startx = max(i-k,0)
   endx = min(i+k,n-1)
   for x in range(startx,endx+1):
    starty = max(0,j+abs(x-i)-k)
    endy = min(m-1,j-abs(x-i)+k)
    for y in range(starty,endy+1):
     if (a[x][y]==0 and visit1[x][y]==False):
      if visit2[x][y]==True:
       lastedit.append([x,y])
      #print x,y,
      if dist[x][y]>dist[i][j]+1:
       dist[x][y]=dist[i][j]+1
       queue.append([x,y])
  #print queue,dist
  queue = queue[1:]
  #print
 return lastedit

for t in range(int(input())):
 n,m,k1,k2 = list(map(int,input().split()))
 a = []
 for i in range(n):
  a.append(list(map(int,input().split())))
 #print a
 value = sys.maxsize
 listing = []
 visit1 = [[False for i in range(m)]for j in range(n)]
 visit2 = [[False for i in range(m)]for j in range(n)]
 dist1 = [[sys.maxsize for i in range(m)]for j in range(n)]
 dist2 = [[sys.maxsize for i in range(m)]for j in range(n)]
 if k1<=k2:
  spaces(a,n,m,k1,visit1,visit2,dist1,[0,0])
 else:
  spaces(a,n,m,k2,visit1,visit2,dist1,[0,m-1])
  listing = spaces(a,n,m,k1,visit2,visit1,dist2,[0,0])
 if k1<k2:
  listing = spaces(a,n,m,k2,visit2,visit1,dist2,[0,m-1])
 #print visit1
 #sprint visit2
 if k1==k2:
  if dist1[0][m-1]==sys.maxsize:
   print('-1')
  else:
   print(int((dist1[0][m-1]+1)/2))
 else:
  d = len(listing)
  for i in range(d-1,-1,-1):
   x = listing[i][0]
   y = listing[i][1]
   if visit1[x][y]==True and dist2[x][y]<value:
    value = dist2[x][y]
  if value!=sys.maxsize:
   print(value)
  else:
   print('-1')


Solve in Python:
In Chefland, types of ingredients are represented by integers and recipes are represented by sequences of ingredients that are used when cooking. One day, Chef found a recipe represented by a sequence $A_1, A_2, \ldots, A_N$ at his front door and he is wondering if this recipe was prepared by him.
Chef is a very picky person. He uses one ingredient jar for each type of ingredient and when he stops using a jar, he does not want to use it again later while preparing the same recipe, so ingredients of each type (which is used in his recipe) always appear as a contiguous subsequence. Chef is innovative, too, so he makes sure that in each of his recipes, the quantity of each ingredient (i.e. the number of occurrences of this type of ingredient) is unique ― distinct from the quantities of all other ingredients.
Determine whether Chef could have prepared the given recipe.

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

-----Output-----
For each test case, print a single line containing the string "YES" if the recipe could have been prepared by Chef or "NO" otherwise (without quotes).

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 10^3$
- $1 \le A_i \le 10^3$ for each valid $i$

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

-----Example Output-----
YES
NO
NO

-----Explanation-----
Example case 1: For each ingredient type, its ingredient jar is used only once and the quantities of all ingredients are pairwise distinct. Hence, this recipe could have been prepared by Chef.
Example case 2: The jar of ingredient $4$ is used twice in the recipe, so it was not prepared by Chef.

# your code goes here
def fun(l):
 t=[]
 s=list(set(l))
 for i in s:
  t.append(l.count(i))
 #print(t)
 #print(len(t),len(set(t)))
 if len(t)==len(set(t)):
  #print(1)
  return 1
 #print(0)
 return 0

for _ in range(int(input())):
 n=int(input())
 l=[int(i) for i in input().split()]
 s=0
 if fun(l)==0:
  print("NO")
 else:
  for i in range(n-1):
   if l[i]!=l[i+1]:
    s+=1
  if s==len(set(l))-1:
   print("YES")
  else:
   print("NO")


Solve in Python:
In Ciel's restaurant, a waiter is training.
Since the waiter isn't good at arithmetic, sometimes he gives guests wrong change.
Ciel gives him a simple problem.
What is A-B (A minus B) ?

Surprisingly, his answer is wrong.
To be more precise, his answer has exactly one wrong digit.
Can you imagine this?
Can you make the same mistake in this problem?

-----Input-----

An input contains 2 integers A and B.

-----Output-----

Print a wrong answer of A-B.
Your answer must be a positive integer containing the same number of digits as the correct answer, and exactly one digit must differ from the correct answer.
Leading zeros are not allowed.
If there are multiple answers satisfying the above conditions, anyone will do.

-----Constraints-----

1 ≤ B < A ≤ 10000

-----Sample Input-----
5858 1234

-----Sample Output-----
1624

-----Output details-----

The correct answer of 5858-1234 is 4624.
So, for instance, 2624, 4324, 4623, 4604 and 4629 will be accepted, but 0624, 624, 5858, 4624 and 04624 will be rejected.

-----Notes-----

The problem setter is also not good at arithmetic.

a, b = [int(x) for x in input().split()]
r = list(str(a-b))
if r[0] == "1":
 r[0] = "2"
else:
 r[0]="1"
print("".join(r))


Solve in Python:
In Dark Souls, players level up trading souls for stats. 8 stats are upgradable this way: vitality, attunement, endurance, strength, dexterity, resistance, intelligence, and faith. Each level corresponds to adding one point to a stat of the player's choice. Also, there are 10 possible classes each having their own starting level and stats:

```
Warrior     (Level 4):  11, 8, 12, 13, 13, 11, 9, 9
Knight      (Level 5):  14, 10, 10, 11, 11, 10, 9, 11
Wanderer    (Level 3):  10, 11, 10, 10, 14, 12, 11, 8
Thief       (Level 5):  9, 11, 9, 9, 15, 10, 12, 11
Bandit      (Level 4):  12, 8, 14, 14, 9, 11, 8, 10
Hunter      (Level 4):  11, 9, 11, 12, 14, 11, 9, 9
Sorcerer    (Level 3):  8, 15, 8, 9, 11, 8, 15, 8
Pyromancer  (Level 1):  10, 12, 11, 12, 9, 12, 10, 8
Cleric      (Level 2):  11, 11, 9, 12, 8, 11, 8, 14
Deprived    (Level 6):  11, 11, 11, 11, 11, 11, 11, 11
```

From level 1, the necessary souls to level up each time up to 11 are `673`, `690`, `707`, `724`, `741`, `758`, `775`, `793`, `811`, and `829`. Then from 11 to 12 and onwards the amount is defined by the expression `round(pow(x, 3) * 0.02 + pow(x, 2) * 3.06 + 105.6 * x - 895)` where `x` is the number corresponding to the next level.

Your function will receive a string with the character class and a list of stats. It should calculate which level is required to get the desired character build and the amount of souls needed to do so. The result should be a string in the format: `'Starting as a [CLASS], level [N] will require [M] souls.'` where `[CLASS]` is your starting class, `[N]` is the required level, and `[M]` is the amount of souls needed respectively.


Solve in Python:
In English and programming, groups can be made using symbols such as `()` and `{}` that change meaning. However, these groups must be closed in the correct order to maintain correct syntax.

Your job in this kata will be to make a program that checks a string for correct grouping. For instance, the following groups are done correctly:

```
({})
[[]()]
[{()}]
```

The next are done incorrectly:
```
{(})
([]
[])
```

A correct string cannot close groups in the wrong order, open a group but fail to close it, or close a group before it is opened.

Your function will take an input string that may contain any of the symbols `()`, `{}` or `[]` to create groups.

It should return `True` if the string is empty or otherwise grouped correctly, or `False` if it is grouped incorrectly.

def group_check(s):
    while "{}" in s or "()" in s or "[]" in s:
       s = s.replace("{}","").replace("()","").replace("[]","")
    return not s


Solve in Python:
In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.

Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.

You need to output the sentence after the replacement.

Example 1:

Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"

Note:

The input will only have lower-case letters.
 1
 1
 1
 1

class Solution:
     def replaceWords(self, dt, sentence):
         """
         :type dict: List[str]
         :type sentence: str
         :rtype: str
         """
         trie = {}
         for w in dt:
             t = trie
             for c in w:
                 if c not in t:  t[c] = {}
                 t = t[c]
             t['#'] = w

         # result = []

 #         for word in sentence.split():
 #             result.append(self.replace(word, trie))

 #         return " ".joinresult

 #     OR
         return  " ".join([ self.replace(i, trie) for i in sentence.split() ])

     def replace( self, word, trie ):
         cur = trie
         for letter in word:
             if letter not in cur: break
             cur = cur[letter]
             if "#" in cur:
                 return cur['#']
         return word

         setenceAsList = sentence.split(" ")
         for i in range(len(setenceAsList)):
             for j in dt:
                 if setenceAsList[i].startswith(j):
                     setenceAsList[i] = j
         return " ".join(setenceAsList)

         arrs = sentence.split()
         for i in range(len(arrs)):
             w = arrs[i]
             for j in range(len(arrs[i])):
                 cur = w[:j]
                 if cur in dt:
                     arrs[i] = cur
                     break
         return ' '.join(arrs)


Solve in Python:
In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographically smallest one.

-----Constraints-----
 - 1 \leq N,K \leq 3 × 10^5
 - N and K are integers.

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

-----Output-----
Print the (X/2)-th (rounded up to the nearest integer) lexicographically smallest sequence listed in FEIS, with spaces in between, where X is the total number of sequences listed in FEIS.

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

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

There are 12 sequences listed in FEIS: (1),(1,1),(1,2),(1,3),(2),(2,1),(2,2),(2,3),(3),(3,1),(3,2),(3,3).
The (12/2 = 6)-th lexicographically smallest one among them is (2,1).


Solve in Python:
In India, every individual is charged with income tax on the total income each year. This tax is applied to specific ranges of income, which are called income tax slabs. The slabs of income tax keep changing from year to year. This fiscal year (2020-21), the tax slabs and their respective tax rates are as follows:Total income (in rupees)Tax rateup to Rs. 250,0000%from Rs. 250,001 to Rs. 500,0005%from Rs. 500,001 to Rs. 750,00010%from Rs. 750,001 to Rs. 1,000,00015%from Rs. 1,000,001 to Rs. 1,250,00020%from Rs. 1,250,001 to Rs. 1,500,00025%above Rs. 1,500,00030%
See the sample explanation for details on how the income tax is calculated.
You are given Chef's total income: $N$ rupees (Rs.). Find his net income. The net income is calculated by subtracting the total tax (also called tax reduction) from the total income. Note that you do not need to worry about any other kind of tax reductions, only the one described above.

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

-----Output-----
For each test case, print a single line containing one integer — Chef's net income.

-----Constraints-----
- $1 \le T \le 10^3$
- $0 \le N \le 10^7$
- $N$ is a multiple of $100$

-----Example Input-----
2
600000
250000

-----Example Output-----
577500
250000

-----Explanation-----
Example case 1: We know that the total income is Rs. $6$ lakh ($1$ lakh rupees = $10^5$ rupees). The total tax for each slab is calculated as follows:
- Up to $2.5$ lakh, the tax is Rs. $0$, since the tax rate is $0$ percent.
- From above Rs. $2.5$ lakh to Rs. $5$ lakh, the tax rate is $5$ percent. Therefore, this tax is $0.05 \cdot (500,000-250,000)$, which is Rs. $12,500$.
- From above Rs. $5$ lakh to Rs. $6$ lakh, the tax rate is $10$ percent. Therefore, this tax is $0.10 \cdot (600,000-500,000)$, which is Rs. $10,000$.
- Summing them up, we get that the total tax on...


Solve in Python:
In JavaScript, ```if..else``` is the most basic condition statement,
it consists of three parts:```condition, statement1, statement2```, like this:
```python
if condition: statementa
else:         statementb
```
It means that if the condition is true, then execute the statementa, otherwise execute the statementb.If the statementa or statementb more than one line, you need to add ```{``` and ```}``` at the head and tail of statement in JS, to keep the same indentation on Python and to put a `end` in Ruby where it indeed ends.

An example, if we want to judge whether a number is odd or even, we can write code like this:
```python
def odd_even(n):
    if n%2: return "odd number"
    else:   return "even number"
```

If there is more than one condition to judge, we can use the compound if...else statement. an example:
```python
def old_young(age):
    if age<16:        return "children"
    elif (age<50): return "young man" #use "else if" if needed
    else:             return "old man"
```
This function returns a different value depending on the parameter age.

Looks very complicated? Well, JS and Ruby also support the ```ternary operator``` and Python has something similar too:
```python
statementa if condition else statementb
```
Condition and statement separated by "?", different statement separated by ":" in both Ruby and JS; in Python you put the condition in the middle of two alternatives.
The two examples above can be simplified with ternary operator:
```python
def odd_even(n):
    return "odd number" if n%2 else "even number"
def old_young(age):
    return "children" if age<16 else "young man" if age<50 else "old man"
```

## Task:
Complete function `saleHotdogs`/`SaleHotDogs`/`sale_hotdogs`, function accept 1  parameters:`n`, n is the number of customers to buy hotdogs, different numbers have different prices (refer to the following table), return a number that the customer need to pay how much money.
```
+---------------+-------------+
|  numbers n    |...

sale_hotdogs=lambda n:100*n if n<5 else 90*n if n>=10 else 95*n


Solve in Python:
In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition.

You may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.

Example 1:

Input: [1,4], 2
Output: 4
Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. This poisoned status will last 2 seconds until the end of time point 2. And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds. So you finally need to output 4.

Example 2:

Input: [1,2], 2
Output: 3
Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned. This poisoned status will last 2 seconds until the end of time point 2. However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status. Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3. So you finally need to output 3.

Note:

You may assume the length of given time series array won't exceed 10000.
You may assume the numbers in the Teemo's attacking time series and his poisoning time duration per attacking are non-negative integers, which won't exceed 10,000,000.

class Solution:
     def findPoisonedDuration(self, timeSeries, duration):
         """
         :type timeSeries: List[int]
         :type duration: int
         :rtype: int
         """

         l = len(timeSeries)
         if l == 0:
             return 0
         if l == 1:
             return duration

         T = 0
         i = 1
         while i < l:
             if timeSeries[i]-timeSeries[i-1] >= duration:
                 T += duration
             else:
                 T += timeSeries[i]-timeSeries[i-1]
             i += 1
         T += duration
         return T


Solve in Python:
In LeetCode Store, there are some kinds of items to sell. Each item has a price.

However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.

You are given the each item's price, a set of special offers, and the number we need to buy for each item.
The job is to output the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers.

Each special offer is represented in the form of an array, the last number represents the price you need to pay for this special offer, other numbers represents how many specific items you could get if you buy this offer.

You could use any of special offers as many times as you want.

Example 1:

Input: [2,5], [[3,0,5],[1,2,10]], [3,2]
Output: 14
Explanation:
There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.

Example 2:

Input: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1]
Output: 11
Explanation:
The price of A is $2, and $3 for B, $4 for C.
You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C.
You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C.
You cannot add more items, though only $9 for 2A ,2B and 1C.

Note:

There are at most 6 kinds of items, 100 special offers.
For each item, you need to buy at most 6 of them.
You are not allowed to buy more items than you want, even if that would lower the overall price.

"""
 https://leetcode.com/problems/shopping-offers/description/
 """

 class Solution:
     def shoppingOffers(self, price, special, needs):
         """
         :type price: List[int]
         :type special: List[List[int]]
         :type needs: List[int]
         :rtype: int
         """
         number_of_items = len(price)
         states = {}

         for offer in special:
             offer_state = offer[0:number_of_items]
             offer_price = offer[-1]

             offer_state_key = self.convert_to_key(offer_state)

             if offer_state_key in states:
                 offer_price = min(offer_price, states[offer_state_key]["price"])

             states[offer_state_key] = {
                 "price": offer_price,
                 "state": offer_state
             }

         return self.compute_best_price(states, {}, needs, price)

     def convert_to_key(self, state):
         return "".join(str(i) for i in state)

     def compute_worst_price(self, needs, individual_prices):
         price = 0
         for i,v in enumerate(needs):
             price += needs[i] * individual_prices[i]

         return price

     def compute_best_price(self, original_offers, all_states, needs, individual_prices):
         if needs == [0] * len(needs):
             return 0

         needs_key = self.convert_to_key(needs)

         # If the state already exists - return
         if needs_key in all_states:
             return all_states[needs_key]["price"]

         # Compute
         best_price = self.compute_worst_price(needs, individual_prices)
         new_needs = []
         for offer_key in original_offers.keys():
             offer = original_offers[offer_key]
             valid_new_state = False
             new_needs = []
             for i, item_quantity in enumerate(offer["state"]):
                 quantity_left_for_item = needs[i] - item_quantity

                 if quantity_left_for_item < 0:
                     valid_new_state = False
                     break
             ...


Solve in Python:
In Math, an improper fraction is a fraction where the numerator (the top number) is greater than or equal to the denominator (the bottom number) For example: ```5/3``` (five third).

A mixed numeral is a whole number and a fraction combined into one "mixed" number. For example: ```1 1/2``` (one and a half) is a mixed numeral.

## Task

Write a function `convertToMixedNumeral` to convert the improper fraction into a mixed numeral.

The input will be given as a ```string``` (e.g. ```'4/3'```).

The output should be a ```string```, with a space in between the whole number and the fraction (e.g. ```'1 1/3'```).  You do not need to reduce the result to its simplest form.

For the purpose of this exercise, there will be no ```0```, ```empty string``` or ```null``` input value. However, the input can be:

- a negative fraction
- a fraction that does not require conversion
- a fraction that can be converted into a whole number

## Example

def convert_to_mixed_numeral(frac):
    numerator, denominator = (int(a) for a in frac.split('/'))
    quo, rem = divmod(abs(numerator), denominator)
    signed_quo = -quo if numerator < 0 else quo
    if quo == 0:    # fraction doesn't require conversion
        return frac
    elif rem == 0:  # fraction converted to whole number
        return '{}'.format(signed_quo)
    return '{}{}/{}'.format(
        '{} '.format(signed_quo) if quo > 0 else '', rem, denominator
    )


Solve in Python:
In Programmers Army Land, people have started preparation as sports day is scheduled next week.
You are given a task to form 1 team of $k$ consecutive players, from a list of sports player whose powers are given to you.
You want your team to win this championship, so you have to chose your $k$ team players optimally i.e. there must not be any other $k$ consecutive team players who have their total power greater than your team members total power.

-----Input:-----
- The first line of the input contains a single integer $T$. $T$ denoting the number of test cases. The description of $T$ test cases is as follows.
- The next line of the input contains 2 space separated integers $N$ and $K$. $N$ denotes the total number of players and $K$ denotes the number of players allowed in a team.
- The next line of the input contains $N$ space-separated integers $A1, A2, A3...An$ where $ith$ number denotes power of $ith$ player.
Note: power of players can also be negative

-----Output:-----
- For each test-case print the total power that your selected team have(each test case output must be printed on a new line).

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

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

-----Sample Output:-----
12

def call(lst,m):
    maxsum= sum(lst[0:m])
    j=0
    maxs=0
    for i in range(m,len(lst)):
        maxs = max(maxsum,maxs)
        #print(maxsum,lst[j],lst[i])
        maxsum -= lst[j]
        maxsum += lst[i]
        j = j+1
    maxs = max(maxsum,maxs)
    return maxs
t = int(input())
while(t):
    t = t-1
    n,m = map(int,input().split())
    lst = list(map(int,input().split()))
    print(call(lst,m))


Solve in Python:
In Russia regular bus tickets usually consist of 6 digits. The ticket is called lucky when the sum of the first three digits equals to the sum of the last three digits. Write a function to find out whether the ticket is lucky or not. Return true if so, otherwise return false. Consider that input is always a string. Watch examples below.

def is_lucky(ticket):
    try:
        if ticket == '':
            return False
        else:
            idk = [int(x) for x in ticket]
            first = sum(idk[0:3])
            second = sum(idk[3:6])
            if first == second:
                return True
            else:
                return False
    except:
        return False


Solve in Python:
In Russia, there is an army-purposed station named UVB-76 or "Buzzer" (see also https://en.wikipedia.org/wiki/UVB-76). Most of time specific "buzz" noise is being broadcasted, but on very rare occasions, the buzzer signal is interrupted and a voice transmission in Russian takes place. Transmitted messages have always the same format like this:

 MDZHB 01 213 SKIF 38 87 23 95

or:

 MDZHB 80 516 GANOMATIT 21 23 86 25

Message format consists of following parts:

 Initial keyword "MDZHB";
 Two groups of digits, 2 digits in first and 3 in second ones;
 Some keyword of arbitrary length consisting only of uppercase letters;
 Final 4 groups of digits with 2 digits in each group.

Your task is to write a function that can validate the correct UVB-76 message. Function should return "True" if message is in correct format and "False" otherwise.

import re
validate = lambda msg: bool(re.match('^MDZHB \d\d \d\d\d [A-Z]+ \d\d \d\d \d\d \d\d$', msg))


Solve in Python:
In Scala, an underscore may be used to create a partially applied version of an infix operator using placeholder syntax. For example, `(_ * 3)` is a function that multiplies its input by 3. With a bit of manipulation, this idea can be extended to work on any arbitrary expression.

Create an value/object named `x` that acts as a placeholder in an arithmetic expression. The placeholder should support the four basic integer arithmetic operations: addition, subtraction, multiplication, and integral (floor) division. When the expression with placeholders is called, it should fill the placeholders in the expression from left to right (regardless of operator precedence) with the values it is given.

Here are a few examples:
```
calling (x + 3)       with [1]   gives 1 + 3               = 4
calling (10 - x)      with [4]   gives 10 - 4              = 6
calling (x + 2 * x)   with [1 3] gives 1 + 2 * 3   = 1 + 6 = 7
calling ((x + 2) * x) with [1 3] gives (1 + 2) * 3 = 3 * 3 = 9
calling (4 * (x / 2)) with [5]   gives 4 * (5 / 2) = 4 * 2 = 8
```

All inputs and outputs to/from the expression will be integer types. All expressions tested in this kata will be valid, i.e. there will be no division by zero and the number of values passed in will always be the same as the number of placeholders.

Note: `eval` and `exec` are disabled

# a skeleton class with required operators provided for convenience
# feel free to use another approach
import operator

def placeholdify(other):
    if not isinstance(other, Placeholder):
        return Placeholder(lambda: other, 0)
    return other

def make_bin_op(op):
    def __op__(self, other):
        other = placeholdify(other)
        return Placeholder(
            lambda *args: op(self(*args[:self.n]), other(*args[self.n:])),
            self.n + other.n
        )
    return __op__

def make_bin_rop(op):
    def __rop__(self, other):
        other = placeholdify(other)
        return Placeholder(
            lambda *args: op(other(*args[:other.n]), self(*args[other.n:])),
            self.n + other.n
        )
    return __rop__

class Placeholder:
    def __init__(self, f, n):
        self.f = f
        self.n = n
    def __call__(self, *args):
        return self.f(*args)
    __add__ = make_bin_op(operator.add)
    __sub__ = make_bin_op(operator.sub)
    __mul__ = make_bin_op(operator.mul)
    __floordiv__ = make_bin_op(operator.floordiv)
    __radd__ = make_bin_rop(operator.add)
    __rsub__ = make_bin_rop(operator.sub)
    __rmul__ = make_bin_rop(operator.mul)
    __rfloordiv__ = make_bin_rop(operator.floordiv)

x = Placeholder(lambda x: x, 1)


Solve in Python:
In Snakeland, there are some snakes and mongooses. They are lined up in a row. The information about how exactly they are lined up it is provided to you by a string of length n. If the i-th character of this string is 's', then it means that there is a snake at the i-th position, whereas the character 'm' denotes a mongoose.
You might have heard about the age-old rivalry between hares and tortoises, but in Snakeland, the rivalry between snakes and mongooses is much more famous. The snakes and the mongooses want to hold a final poll in which the ultimate winner of this age-old battle will be decided. If the snakes get more votes than the mongooses, they will be the ultimate winners. Similarly, if the mongooses get more votes than snakes, they will be the ultimate winners. Obviously, each animal is loyal to their species, i.e. each snake will vote for the snakes to be the ultimate champions and each mongoose for the mongooses.

Tomorrow's the election day. Before the elections, the mongooses decided to cheat. They planned that each mongoose will eat at most one of its neighbor snakes. Two animals are said to be neighbors of each other if they are consecutive to each other in the row. After this, the elections will be held. The mongooses planned in such a way that the number of snakes eaten is maximized. Can you find out who will win the final poll? Output "snakes", "mongooses" or "tie" correspondingly.

-----Input-----
First line of the input contains an integer T denoting the number of test cases. The description of T test cases follow.
The only line of each test case contains a string consisting of characters 's' and 'm'.

-----Output-----
For each test case output a single line containing "snakes", "mongooses" or "tie" correspondingly (without quotes).

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ |s| ≤ 100

-----Example-----
Input
4
sm
ssm
sms
ssmmmssss

Output
mongooses
tie
tie
snakes

-----Explanation-----
Example 1. The mongoose will eat the snake. Only the mongoose will be left. So, on the election day,...

# cook your dish here
for i in range(int(input())):
 x=input()
 c=x.count('s')
 d=x.count('m')
 i=0
 while i<len(x)-1:
  if x[i]=='s' and x[i+1]=='m' or x[i]=='m' and x[i+1]=='s':
   i+=2
   c-=1
  else:
   i+=1
 if c>d:
  print("snakes")
 elif d>c:
  print("mongooses")
 else:
  print("tie")


Solve in Python:
In Spanish, the conjugated verb changes by adding suffixes and according to the person we're talking about. There's something similar in English when we talk about "She", "He"or "It" (3rd person singular):

With the verb "run":

**He / She / It runS**

As you can see, the rule (at least with regular verbs) is to add the suffix  "-s" in the 3rd person singular. In Spanish it works the same way but we need to remove the **infinitive suffix** and add a specific suffix to all the others persons (I, You, He/She/It, We, You, They).

Verbs in Spanish and the infinitive suffix.
--

In Spanish we assume a verb is on its infitive form when it has one of the infinitives suffixes (**AR**, **ER** or **IR**) at the end:

- Com**er** -> to eat

- Camin**ar** -> to walk

- Viv**ir** -> to live

## How to conjugate

For conjugating in Spanish, we need to remove the infinitive suffix (**ar**, **er** *or* **ir**) and add the personal suffixes corresponding to the person we're talking to. In this kata we'll conjugate the verbs to its **presente indicativo** (simple present) form.

Personal suffixes
--
The personal suffixes changes depending of the **Infinitive suffix**.

If the infinitive suffix is **AR** the personal suffixes are:

- first person singular (Yo / I): -**o**
- second person singular (Tú / You): -**as**
- third person singular (Él, Ella / He, She): -**a**
- first person plural (Nosotros / We): -**amos**
- second person plural (Vosotros / You): -**áis**
- third person plural (Ellos / They): -**an**

If the infinitive suffix is **ER**:
- first person singular (Yo / I): -**o**
- second person singular (Tú / You): -**es**
- third person singular (Él, Ella / He, She): -**e**
- first person plural (Nosotros / We): -**emos**
- second person plural (Vosotros / You): -**éis**
- third person plural (Ellos / They): -**en**

If the infinitive suffix is **IR**:
- first person singular (Yo / I): -**o**
- second person singular (Tú / You): -**es**
- third person singular (Él, Ella / He, She): -**e**
- first person plural...


Solve in Python:
In a 1 million by 1 million grid, the coordinates of each grid square are (x, y) with 0 <= x, y < 10^6.
We start at the source square and want to reach the target square.  Each move, we can walk to a 4-directionally adjacent square in the grid that isn't in the given list of blocked squares.
Return true if and only if it is possible to reach the target square through a sequence of moves.

Example 1:
Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]
Output: false
Explanation:
The target square is inaccessible starting from the source square, because we can't walk outside the grid.

Example 2:
Input: blocked = [], source = [0,0], target = [999999,999999]
Output: true
Explanation:
Because there are no blocked cells, it's possible to reach the target square.

Note:

0 <= blocked.length <= 200
blocked[i].length == 2
0 <= blocked[i][j] < 10^6
source.length == target.length == 2
0 <= source[i][j], target[i][j] < 10^6
source != target

class Solution:
    def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:

        #Column and row of source and target (used for escape condition)
        sc, sr = source
        tc, tr = target
        R, C = 10**6, 10**6

        def dist(r1,c1,r2,c2):
            '''Calculates Manhattan distance from (r1,c1) to (r2,c2)'''
            return abs(r2-r1)+abs(c2-c1)

        #Two priority queues: one starting from target and one from source
        #Two visited sets: one for nodes visited by path from target and the other from source
        q = [[(0,*source[::-1])], [(0,*target[::-1])]]
        v = [set(),set()]
        b = set((tuple(b[::-1]) for b in blocked))

        if (tuple(source) in b) or (tuple(target) in b):
            return False

        #if source and target can reach 200 distance from their origin
        #it is safe to say 200 blocked spaces cannot contain them
        source_escape = False
        target_escape = False

        while q[0] and q[1]:

            index = 0 if len(q[0]) <= len(q[1]) else 1

            d, r, c = heapq.heappop(q[index])

            for i, j in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
                if (0 <= i < R) and (0 <= j < C) and ((i,j) not in b) and ((i,j) not in v[index]):

                    if (i,j) in v[1-index]:
                        return True

                    v[index].add((i,j))
                    r_target, c_target = q[1-index][0][1:]
                    heapq.heappush(q[index], (dist(i,j,r_target,c_target), i, j))

            if not source_escape and not index:
                source_escape = dist(r, c, sr, sc) > 200
            if not target_escape and index:
                target_escape = dist(r, c, tr, tc) > 200

            if source_escape and target_escape:
                return True

        return False


Solve in Python:
In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.
At the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city's skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example.
What is the maximum total sum that the height of the buildings can be increased?
Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
  [2, 4, 5, 7],
  [9, 2, 6, 3],
  [0, 3, 1, 0] ]

The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]

The grid after increasing the height of buildings without affecting skylines is:

gridNew = [ [8, 4, 8, 7],
            [7, 4, 7, 7],
            [9, 4, 8, 7],
            [3, 3, 3, 3] ]

Notes:

1 < grid.length = grid[0].length <= 50.
All heights grid[i][j] are in the range [0, 100].
All buildings in grid[i][j] occupy the entire grid cell: that is, they are a 1 x 1 x grid[i][j] rectangular prism.

class Solution:
    def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
        # Pad with inf to make implementation easier
        INF = -10_000
        n = len(grid)

        total = 0
        max_rows = [max(row, default=INF) for row in grid]
        # Transpose the grid to make max less cumbersome
        max_cols = [max(col, default=INF) for col in zip(*grid)]

        for i, best_row in enumerate(max_rows):
            for j, best_col in enumerate(max_cols):
                new_height = min(best_row, best_col)
                total += new_height - grid[i][j]

        return total


Solve in Python:
In a 2D grid of 0s and 1s, we change at most one 0 to a 1.
After, what is the size of the largest island? (An island is a 4-directionally connected group of 1s).
Example 1:
Input: [[1, 0], [0, 1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.

Example 2:
Input: [[1, 1], [1, 0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
Input: [[1, 1], [1, 1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.

Notes:

1 <= grid.length = grid[0].length <= 50.
0 <= grid[i][j] <= 1.

DIRECTIONS = [(0, 1), (0, -1), (1, 0), (-1, 0)]
class Solution:
    def largestIsland(self, grid: List[List[int]]) -> int:
        N = len(grid)

        def move(x, y):
            ans = []
            for mv_x, mv_y in DIRECTIONS:
                x_ = x + mv_x
                y_ = y + mv_y
                if 0 <= x_ < N and 0 <= y_ < N:
                    ans.append((x_, y_))
            return ans

        # return area of the island
        def dfs(x, y, idx):
            ans = 1
            grid[x][y] = idx
            for i, j in move(x, y):
                if grid[i][j] == 1:
                    ans += dfs(i, j, idx)
            return ans

        idx = 2
        areas = {0: 0}
        for i in range(N):
            for j in range(N):
                if grid[i][j] == 1:
                    areas[idx] = dfs(i, j, idx)
                    idx += 1

        ans = max(areas.values())
        for i in range(N):
            for j in range(N):
                if grid[i][j] == 0:
                    cands = set(grid[x][y] for x, y in move(i, j))
                    ans = max(ans, sum(areas[idx] for idx in cands) + 1)
        return ans


Solve in Python:
In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank space.  These characters divide the square into contiguous regions.
(Note that backslash characters are escaped, so a \ is represented as "\\".)
Return the number of regions.

Example 1:
Input:
[
  " /",
  "/ "
]
Output: 2
Explanation: The 2x2 grid is as follows:

Example 2:
Input:
[
  " /",
  "  "
]
Output: 1
Explanation: The 2x2 grid is as follows:

Example 3:
Input:
[
  "\\/",
  "/\\"
]
Output: 4
Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.)
The 2x2 grid is as follows:

Example 4:
Input:
[
  "/\\",
  "\\/"
]
Output: 5
Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.)
The 2x2 grid is as follows:

Example 5:
Input:
[
  "//",
  "/ "
]
Output: 3
Explanation: The 2x2 grid is as follows:

Note:

1 <= grid.length == grid[0].length <= 30
grid[i][j] is either '/', '\', or ' '.

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

        N = len(grid)
        base = N * (N + 1)
        parent = [i for i in range(2 * base)]

        def find(x):
            if parent[x] != parent[parent[x]]:
                parent[x] = find(parent[x])
            return parent[x]

        def union(x, y):
            parent[find(x)] = find(y)
            return find(y)

        for i in range(N):
            for j in range(N):
                up, down, left, right = i * N + j, (i + 1) * N + j, base + i * (N + 1) + j, base + i * (N + 1) + j + 1

                if grid[i][j] == '/':
                    union(up, left)
                    union(down, right)
                elif grid[i][j] == '\\\\':
                    union(up, right)
                    union(down, left)
                else:
                    union(up, left)
                    union(down, right)
                    union(left, right)

        comp = set()
        for i in range(2 * base):
            comp.add(find(i))

        return len(comp)


Solve in Python:
In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.
Return the element repeated N times.

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

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

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

Note:

4 <= A.length <= 10000
0 <= A[i] < 10000
A.length is even

class Solution:
    def repeatedNTimes(self, A: List[int]) -> int:
        #N = len(A)/2
        #for num in A:
         #   if A.count(num) == N:
          #      return num
        check = set()
        for num in A:
            if num in check:
                return num
            check.add(num)


Solve in Python:
In a bizarre game of chess ,knight was so drunk, that instead of his usual move he started walking straight. In every move Knight jumps on 2n steps forward (n is number of block that he had travelled so far from starting) but after that he has to take either 1 step forward or backward.
Now the Knight needs to get to position X so King (i.e. You) needs to decide the order of his backward or forward step in such a way that he can reach its destination in minimum number of steps. Remember he always travels in a straight line and the length of the board is infinite.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases, for each test case enter value X ( i.e. destination)
Note : initially knight is at n = 1.

-----Output-----
For each test case the output should be string of numbers 1 & 2 where 1 denotes backward step and 2 denote the forward step
Note : for no solution print 0.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ X ≤ 10^10

-----Example-----
Input:
2
17
10
Output:
2111
0

-----Explanation-----
Case 1 : starting from  n = 1 , knight moves to n = 3 ('2') , 5 ('1') , 9 ('1') , 17 ('1') i.e. string printed is 2 1 1 1
Case 2 : no solution is possible

t=int(input())
while t:
 x=int(input())
 ans=''
 if(x &1):
  cc=['2' if x =='1' else '1' for x in list(bin(x)[2:-1])]
  for x in cc:
   ans = ans + str(x)
  print(ans)
 else:
  print('0')
 t = t-1


Solve in Python:
In a country called Chef Land, there was a lot of monetary fraud, so Chefu, the head of the country, decided to choose new denominations of the local currency ― all even-valued coins up to an integer $N$ should exist. After a few days, a citizen complained that there was no way to create an odd value, so Chefu decided that he should also introduce coins with value $1$. Formally, you are given an integer $N$; for $v = 1$ and each even positive integer $v \le N$, coins with value $v$ exist.
You are also given an integer $S$. To handle transactions quickly, find the minimum number of coins needed to pay a price $S$.

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

-----Output-----
For each test case, print a single line containing one integer ― the minimum number of coins.

-----Constraints-----
- $1 \le T \le 10,000$
- $1 \le S \le 10^9$
- $2 \le N \le 10^9$
- $N$ is even

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

-----Example Input-----
4
2 2
1 14
30 10
31 4

-----Example Output-----
1
1
3
9

-----Explanation-----
Example case 1: One coin with value $2$ is sufficient.
Example case 2: We need to use one coin with value $1$.
Example case 3: We need $3$ coins, each with value $10$.
Example case 4: We can use seven coins with value $4$, one coin with value $2$ and one coin with value $1$.

for i in range(int(input())):
 n,k=list(map(int,input().split()))
 t=0
 if n%2!=0:
  n-=1
  t+=1
 t+=(n//k)
 if n%k!=0:
  t+=1
 print(t)


Solve in Python:
In a country popular for train travel, you have planned some train travelling one year in advance.  The days of the year that you will travel is given as an array days.  Each day is an integer from 1 to 365.
Train tickets are sold in 3 different ways:

a 1-day pass is sold for costs[0] dollars;
a 7-day pass is sold for costs[1] dollars;
a 30-day pass is sold for costs[2] dollars.

The passes allow that many days of consecutive travel.  For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8.
Return the minimum number of dollars you need to travel every day in the given list of days.

Example 1:
Input: days = [1,4,6,7,8,20], costs = [2,7,15]
Output: 11
Explanation:
For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.
In total you spent $11 and covered all the days of your travel.

Example 2:
Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
Output: 17
Explanation:
For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.
In total you spent $17 and covered all the days of your travel.

Note:

1 <= days.length <= 365
1 <= days[i] <= 365
days is in strictly increasing order.
costs.length == 3
1 <= costs[i] <= 1000

class Solution:
    def mincostTickets(self, days: List[int], costs: List[int]) -> int:

        cost = [0 for j in range(366)]

        for i in range(len(cost)):
            if(i in days):
                cost[i] = min((cost[i-1] if i-1>=0 else 0) + costs[0],
                              (cost[i-7] if i-7>=0 else 0) + costs[1],
                              (cost[i-30] if i-30>=0 else 0) + costs[2])
            else:
                cost[i] = cost[max(i-1,0)]

        return cost[365]

#         cost = [0 for j in range(days)]

#         for i, d in enumerate(days):
#             if(d <= 7):
#                 cost[i] = cost[i-1] + c[0] # take day pass
#             if(d <= 30): # choose between day pass and month pass
#                 cost[i] = min(cost[i-1]+c[0], cost)


Solve in Python:
In a cricket game, an over is a set of six valid deliveries of balls performed by one player ― the bowler for this over.
Consider a cricket game with a series of $N$ overs (numbered $1$ through $N$) played by $K$ players (numbered $1$ through $K$). Each player may be the bowler for at most $L$ overs in total, but the same player may not be the bowler for any two consecutive overs. Assign exactly one bowler to each over in such a way that these rules are satisfied or determine that no such assignment exists.

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

-----Output-----
For each test case:
- If there is no valid assignment of bowlers to overs, print a single line containing the integer $-1$.
- Otherwise, print a single line containing $N$ space-separated integers. For each valid $i$, the $i$-th of these integers should be the number of the player assigned as the bowler for the $i$-th over.

-----Constraints-----
- $1 \le T \le 30$
- $1 \le N, K, L \le 10,000$

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

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

-----Explanation-----
Example case 1: The following is a valid assignment:
- Bowler 1 bowls the $1$-st over.
- Bowler 2 bowls the $2$-nd and $4$-th overs.
- Bowler 3 bowls the $3$-rd over.
It is valid since no bowler bowls more than $2$ overs and each two consecutive overs have different bowlers.
Example case 2: There is no valid assignment in which each of $4$ players bowls at most $1$ over out of $5$.

for _ in range(int(input())):
 N ,K, L = input().split(" ")
 N, K, L = int(N), int(K), int(L)
 if K * L < N or (K == 1 and N > 1):
  print(-1)
 else:
  print(*[int(i%K)+1 for i in range(N)])


Solve in Python:
In a deck of cards, each card has an integer written on it.
Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:

Each group has exactly X cards.
All the cards in each group have the same integer.

Example 1:
Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].

Example 2:
Input: deck = [1,1,1,2,2,2,3,3]
Output: false´
Explanation: No possible partition.

Example 3:
Input: deck = [1]
Output: false
Explanation: No possible partition.

Example 4:
Input: deck = [1,1]
Output: true
Explanation: Possible partition [1,1].

Example 5:
Input: deck = [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2].

Constraints:

1 <= deck.length <= 10^4
0 <= deck[i] < 10^4

class Solution:
    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        from collections import Counter

        cards = Counter(deck)

        min_cnt = min(cards.values())

        for i in range(2, min_cnt+1):
            divided = [v%i for v in list(cards.values())]
            if not any(divided):
                return True

        return False


Solve in Python:
In a directed graph, we start at some node and every turn, walk along a directed edge of the graph.  If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop.
Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node.  More specifically, there exists a natural number K so that for any choice of where to walk, we must have stopped at a terminal node in less than K steps.
Which nodes are eventually safe?  Return them as an array in sorted order.
The directed graph has N nodes with labels 0, 1, ..., N-1, where N is the length of graph.  The graph is given in the following form: graph[i] is a list of labels j such that (i, j) is a directed edge of the graph.
Example:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Here is a diagram of the above graph.

Note:

graph will have length at most 10000.
The number of edges in the graph will not exceed 32000.
Each graph[i] will be a sorted list of different integers, chosen within the range [0, graph.length - 1].

class Solution:
    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        visited = {}
        departures = [-1] * len(graph)
        res = []
        def _dfs(node):
            visited[node] = 1
            neighbors = graph[node]

            for neighbor in neighbors:
                if neighbor not in visited:
                    if _dfs(neighbor):
                        return True
                else:
                    if departures[neighbor] == -1:
                        return True

            departures[node] = 1
            return False

        for i in range(0, len(graph)):
            if not _dfs(i):
                res.append(i)
        return res


Solve in Python:
In a far away country called AlgoLandia, there are `N` islands numbered `1` to `N`. Each island is denoted by `k[i]`. King Algolas, king of AlgoLandia, built `N - 1` bridges in the country. A bridge is built between islands `k[i]` and `k[i+1]`. Bridges are two-ways and are expensive to build.

The problem is that there are gangs who wants to destroy the bridges. In order to protect the bridges, the king wants to assign elite guards to the bridges. A bridge between islands `k[i]` and `k[i+1]` is safe when there is an elite guard in island `k[i]` or `k[i+1]`. There are already elite guards assigned in some islands.

Your task now is to determine the minimum number of additional elite guards that needs to be hired to guard all the bridges.

### Note:
You are given a sequence `k` with `N` length.
`k[i] = true`, means that there is an elite guard in that island; `k[i] = false` means no elite guard. It is guaranteed that AlgoLandia have at least `2` islands.

### Sample Input 1
```
k = [true, true, false, true, false]
```

### Sample Output 1
```
0
```

### Sample Input 2
```
k = [false, false, true, false, false]
```
### Sample Output 2
```
2
```

def find_needed_guards(k):
    return sum(len(i)//2 for i in ''.join([('*',' ')[i] for i in k]).split())


Solve in Python:
In a fictitious city of CODASLAM there were many skyscrapers. The mayor of the city decided to make the city beautiful and for this he decided to arrange the skyscrapers in descending order of their height, and the order must be strictly decreasing but he also didn’t want to waste much money so he decided to get the minimum cuts possible. Your job is to output the minimum value of cut that is possible to arrange the skyscrapers in descending order.

-----Input-----

*First line of input is the number of sky-scrappers in the city
*Second line of input is the height of the respective sky-scrappers

-----Output-----

* Your output should be the minimum value of cut required to arrange these sky-scrappers in descending order.

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

Output:
8

By:
Chintan,Asad,Ashayam,Akanksha

#!/usr/bin/env python

def main():
 N = int(input())
 while True:
  try:
   X = input()
  except:
   break
  H = list(map(int, X.split()))
  C = 0
  while H:
   e = H.pop(0)
   H2, C1, C2 = list(H), e, 0
   for i in range(len(H2)):
    if H2[i] > e-1:
     C2 += H2[i]-(e-1)
     H2[i] = e-1
   #print C+C2, H2, C+C1, H
   if C1 <= C2:
    C += C1
   else:
    C += C2
    H = H2
  print(C)

main()