Solve in Python:
Given a list of white pawns on a chessboard (any number of them, meaning from 0 to 64 and with the possibility to be positioned everywhere), determine how many of them have their backs covered by another.
Pawns attacking upwards since we have only white ones.

Please remember that a pawn attack(and defend as well) only the 2 square on the sides in front of him. https://en.wikipedia.org/wiki/Pawn_(chess)#/media/File:Pawn_(chess)_movements.gif

This is how the chess board coordinates are defined:
ABCDEFGH8♜♞♝♛♚♝♞♜7♟♟♟♟♟♟♟♟65432♙♙♙♙♙♙♙♙1♖♘♗♕♔♗♘♖

def covered_pawns(pawns):
    board = [[0]*8 for _ in range(8)]
    for c,r in pawns:
        board[8 - int(r)][ord(c) - 97] = 1
    return sum(board[i][j] and (j and board[i+1][j-1] or 7-j and board[i+1][j+1]) for i in range(7) for j in range(8))


Solve in Python:
Given a list of words, each word consists of English lowercase letters.
Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2.  For example, "abc" is a predecessor of "abac".
A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.
Return the longest possible length of a word chain with words chosen from the given list of words.

Example 1:
Input: ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: one of the longest word chain is "a","ba","bda","bdca".

Note:

1 <= words.length <= 1000
1 <= words[i].length <= 16
words[i] only consists of English lowercase letters.

class Solution:
    def longestStrChain(self, words: List[str]) -> int:
        # sort by decreasing length
        # define vector L of length len(words) such that it's the longest
        # word chain starting from that word
        # then recuriosn is L_k = 1 if it is not predecessor of any 1 longer words
        # otherwise it is 1 + max L_j for j such that k is predecessor of them

        lengths = [len(word) for word in words]
        wordsSorted = [x for _,x in sorted(zip(lengths,words),reverse = True)]

        print(wordsSorted)
        L = [1]*len(wordsSorted)
        maxLength = max(lengths)
        for k in range(0, len(L)):
            lenWord = len(wordsSorted[k])
            for l in range(k):
                if len(wordsSorted[l]) == lenWord+1 and (set(wordsSorted[l]) & set(wordsSorted[k])) == set(wordsSorted[k]):
                    L[k] = max(L[k], 1 + L[l])
        return(max(L))


Solve in Python:
Given a list of words, list of  single letters (might be repeating) and score of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).
It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.

Example 1:
Input: words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]
Output: 23
Explanation:
Score  a=1, c=9, d=5, g=3, o=2
Given letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23.
Words "dad" and "dog" only get a score of 21.
Example 2:
Input: words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]
Output: 27
Explanation:
Score  a=4, b=4, c=4, x=5, z=10
Given letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27.
Word "xxxz" only get a score of 25.
Example 3:
Input: words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]
Output: 0
Explanation:
Letter "e" can only be used once.

Constraints:

1 <= words.length <= 14
1 <= words[i].length <= 15
1 <= letters.length <= 100
letters[i].length == 1
score.length == 26
0 <= score[i] <= 10
words[i], letters[i] contains only lower case English letters.

class Solution:
#     def maxScoreWords(self, words, letters, score):
#         self.max_score = 0
#         words_score = [sum(score[ord(c)-ord('a')] for c in word) for word in words]
#         words_counter = [collections.Counter(word) for word in words]

#         def dfs(i, curr_score, counter):
#             if curr_score + sum(words_score[i:]) <= self.max_score:
#                 return
#             self.max_score = max(self.max_score, curr_score)
#             for j, wcnt in enumerate(words_counter[i:], i):
#                 if all(n <= counter.get(c,0) for c,n in wcnt.items()):
#                     dfs(j+1, curr_score+words_score[j], counter-wcnt)

#         dfs(0, 0, collections.Counter(letters))
#         return self.max_score

    def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
        def solve(idx, counter):
            if idx == len(words):
                return 0

            wc = collections.Counter(words[idx])
            if all(counter[key] >= wc[key] for key in wc):
                return max(
                    sum(score[ord(c)-ord('a')] for c in words[idx]) + solve(idx+1, counter-wc),
                    solve(idx+1, counter)
                )
            else:
                return solve(idx+1, counter)

        return solve(0, collections.Counter(letters))


Solve in Python:
Given a long number, return all the possible sum of two digits of it.

For example, `12345`: all possible sum of two digits from that number are:

    [ 1 + 2, 1 + 3, 1 + 4, 1 + 5, 2 + 3, 2 + 4, 2 + 5, 3 + 4, 3 + 5, 4 + 5 ]

Therefore the result must be:

    [ 3, 4, 5, 6, 5, 6, 7, 7, 8, 9 ]

# Solution 1
def digits(num):
    return [int(a)+int(b) for i,a in enumerate(str(num)) for b in str(num)[(i+1):]]

# Solution 2
def digits(num):
    from itertools import combinations
    return [int(a)+int(b) for a,b in combinations(str(num), 2)]


Solve in Python:
Given a lowercase string that has alphabetic characters only and no spaces, return the highest value of consonant substrings. Consonants are any letters of the alphabet except `"aeiou"`.

We shall assign the following values: `a = 1, b = 2, c = 3, .... z = 26`.

For example, for the word "zodiacs", let's cross out the vowels. We get: "z **~~o~~** d **~~ia~~** cs"

For C: do not mutate input.

More examples in test cases. Good luck!

If you like this Kata, please try:

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

[Vowel-consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)

import re
import string

scores = {c: i for i, c in enumerate(string.ascii_lowercase, 1)}

def solve(s):
    return max(sum(map(scores.get, x)) for x in re.findall('[^aeiou]+', s))


Solve in Python:
Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell.
Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m-1, n-1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.

Example 1:
Input:
grid =
[[0,0,0],
 [1,1,0],
 [0,0,0],
 [0,1,1],
 [0,0,0]],
k = 1
Output: 6
Explanation:
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).

Example 2:
Input:
grid =
[[0,1,1],
 [1,1,1],
 [1,0,0]],
k = 1
Output: -1
Explanation:
We need to eliminate at least two obstacles to find such a walk.

Constraints:

grid.length == m
grid[0].length == n
1 <= m, n <= 40
1 <= k <= m*n
grid[i][j] == 0 or 1
grid[0][0] == grid[m-1][n-1] == 0

from collections import deque

class Solution:
    def shortestPath(self, grid: List[List[int]], k: int) -> int:
        q = deque()
        cur = (0, 0, k, 0)
        visited = set()
        q.append(cur)
        visited.add(cur)
        m = len(grid)
        n = len(grid[0])

        diffs = [(1,0),(-1,0),(0,1),(0,-1)]

        while len(q) != 0:
            i, j, l, s = q.popleft()
            # print(i, j)
            if i == m-1 and j == n-1:
                return s

            for d in diffs:
                n_i = i + d[0]
                n_j = j + d[1]
                # print(\"n: \", n_i, n_j)
                if 0 <= n_i < m and 0 <= n_j < n:
                    if grid[n_i][n_j] and l != 0 and (n_i, n_j, l-1) not in visited:
                        q.append((n_i, n_j, l-1, s+1))
                        visited.add((n_i, n_j, l-1))
                    elif not grid[n_i][n_j] and (n_i, n_j, l) not in visited:
                        q.append((n_i, n_j, l, s+1))
                        visited.add((n_i, n_j, l))

        return -1


Solve in Python:
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

Example 1:
Input: matrix =
[
  [0,1,1,1],
  [1,1,1,1],
  [0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is  1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.

Example 2:
Input: matrix =
[
  [1,0,1],
  [1,1,0],
  [1,1,0]
]
Output: 7
Explanation:
There are 6 squares of side 1.
There is 1 square of side 2.
Total number of squares = 6 + 1 = 7.

Constraints:

1 <= arr.length <= 300
1 <= arr[0].length <= 300
0 <= arr[i][j] <= 1

class Solution:
    def countSquares(self, matrix: List[List[int]]) -> int:
        dp = [[matrix[i][j] for j in range(len(matrix[0]))] for i in range(len(matrix))]
        for i in range(1, len(matrix)):
            for j in range(1, len(matrix[0])):
                if matrix[i][j] == 0:
                    continue
                if dp[i-1][j] != 0 and dp[i][j-1] != 0 and dp[i-1][j-1] != 0:
                    dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1
        count = 0
        for row in dp:
            count += sum(row)
        return count


Solve in Python:
Given a m * n matrix mat and an integer K, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for i - K <= r <= i + K, j - K <= c <= j + K, and (r, c) is a valid position in the matrix.

Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], K = 1
Output: [[12,21,16],[27,45,33],[24,39,28]]

Example 2:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], K = 2
Output: [[45,45,45],[45,45,45],[45,45,45]]

Constraints:

m == mat.length
n == mat[i].length
1 <= m, n, K <= 100
1 <= mat[i][j] <= 100

from itertools import accumulate
class Solution:
    def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]:
        A = mat.copy()
        for i in range(len(A)):
            A[i] = [0]+list(accumulate(A[i]))
        Ans = [[0 for i in range(len(A[0]))] for j in range(len(A))]
        for i in range(len(A)):
            for j in range(1,len(A[0])):
                #print(max(0,i-K),min(len(A),i+K))
                for p in range(max(0,i-K),min(len(A)-1,i+K)+1):
                    #print(A[p],p)
                    #print(min(j+K,len(A[0])),max(0,j-K))
                    Ans[i][j] += A[p][min(j+K,len(A[0])-1)]-A[p][max(0,j-K-1)]
        for i in range(len(Ans)):
            Ans[i] = Ans[i][1:]
        return Ans


Solve in Python:
Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge.
Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.
Binary matrix is a matrix with all cells equal to 0 or 1 only.
Zero matrix is a matrix with all cells equal to 0.

Example 1:

Input: mat = [[0,0],[0,1]]
Output: 3
Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.

Example 2:
Input: mat = [[0]]
Output: 0
Explanation: Given matrix is a zero matrix. We don't need to change it.

Example 3:
Input: mat = [[1,1,1],[1,0,1],[0,0,0]]
Output: 6

Example 4:
Input: mat = [[1,0,0],[1,0,0]]
Output: -1
Explanation: Given matrix can't be a zero matrix

Constraints:

m == mat.length
n == mat[0].length
1 <= m <= 3
1 <= n <= 3
mat[i][j] is 0 or 1.

class Solution:
    def minFlips(self, mat: List[List[int]]) -> int:
        m = len(mat)
        n = len(mat[0])

        start = sum(val << (i*n + j) for i, row in enumerate(mat) for j, val in enumerate(row))

        queue = collections.deque([(start, 0)])
        seen = { start }

        dirs = [[0, 0], [0,1], [1, 0], [0, -1], [-1, 0]]
        while queue:
            # print(queue)
            current, d = queue.popleft()
            if current == 0:
                return d

            # for each index in matrix find neighbour
            for i in range(len(mat)):
                for j in range(len(mat[0])):
                    next_state = current

                    # importants dirs has [0, 0] we need flip the current element and neigbour
                    for dir_ in dirs:
                        new_i = i + dir_[0]
                        new_j = j + dir_[1]

                        if new_i >= 0 and new_i < len(mat) and new_j >= 0 and new_j < len(mat[0]):
                            next_state ^= (1 << (new_i * n + new_j )) # 0 xor 1 = 1, 1 xor 1 = 0

                    if next_state not in seen:
                        seen.add(next_state)
                        queue.append((next_state, d + 1))

        return -1


Solve in Python:
Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:

1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])
3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])
4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])

Notice that there could be some invalid signs on the cells of the grid which points outside the grid.
You will initially start at the upper left cell (0,0). A valid path in the grid is a path which starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path doesn't have to be the shortest.
You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.
Return the minimum cost to make the grid have at least one valid path.

Example 1:

Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
Output: 3
Explanation: You will start at point (0, 0).
The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
The total cost = 3.

Example 2:

Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
Output: 0
Explanation: You can follow the path from (0, 0) to (2, 2).

Example 3:

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

Example 4:
Input: grid = [[2,2,2],[2,2,2]]
Output: 3

Example 5:
Input: grid = [[4]]
Output: 0

Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 100

from collections import deque

class Solution:
    def minCost(self, grid: List[List[int]]) -> int:
        right, left, down, up = (0, 1), (0, -1), (1, 0), (-1, 0)

        direction_map = {
            1: right,
            2: left,
            3: down,
            4: up
        }

        directions = [right, left, down, up]
        visited = set()

        def in_bounds(i, j):
            return 0 <= i < len(grid) and 0 <= j < len(grid[i])

        def dfs(i, j):
            # not in bounds
            if not in_bounds(i, j) or (i, j) in visited:
                return []

            visited.add((i, j))

            sign = grid[i][j]
            direction = direction_map[sign]
            next_i, next_j = i + direction[0], j + direction[1]
            return [(i, j)] + dfs(next_i, next_j)

        reachable = dfs(0, 0)
        curr_cost = 0
        while reachable:
            next_reachable = []
            for (i, j) in reachable:
                if i == len(grid) - 1 and j == len(grid[i]) - 1:
                    return curr_cost

                for d in directions:
                    next_reachable += dfs(i + d[0], j + d[1])
            reachable = next_reachable
            curr_cost += 1

        return -1


Solve in Python:
Given a m x n matrix mat and an integer threshold. Return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.

Example 1:

Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
Output: 2
Explanation: The maximum side length of square with sum less than 4 is 2 as shown.

Example 2:
Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
Output: 0

Example 3:
Input: mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
Output: 3

Example 4:
Input: mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
Output: 2

Constraints:

1 <= m, n <= 300
m == mat.length
n == mat[i].length
0 <= mat[i][j] <= 10000
0 <= threshold <= 10^5

class Solution:
    def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
        dp = [[0 for _ in range(len(mat[0]) + 1)]for r in range(len(mat) + 1)]

        for r in range(1, len(mat) + 1):
            for c in range(1, len(mat[r-1]) + 1):
                dp[r][c] += mat[r-1][c-1]
                if not r and not c:
                    continue
                elif not r:
                    dp[r][c] += dp[r][c-1]
                    continue
                elif not c:
                    dp[r][c] += dp[r-1][c]
                    continue
                dp[r][c] += dp[r][c-1] + dp[r-1][c] - dp[r-1][c-1]

        # print(dp)
        highest = -1
        for r in range(1, len(dp)):
            r0= r1 = r
            c0= c1 = 1
            while r1 < len(dp) and c1 < len(dp[0]):

                result = dp[r1][c1] + dp[r0-1][c0-1] - dp[r1][c0-1] - dp[r0-1][c1]

                # print(f'r0:{r0} r1:{r1} c0:{c0} c1:{c1} result:{result}')
                if result <= threshold:
                    highest = max(r1-r0, highest)
                    r1 += 1
                    c1 +=1
                else:
                    r1 -=1
                    c0 +=1
                r1 = max(r0+1,r1)
                c1 = max(c0+1,c1)

        return highest + 1


Solve in Python:
Given a mathematical equation that has `*,+,-,/`, reverse it as follows:

```Haskell
solve("100*b/y") = "y/b*100"
solve("a+b-c/d*30") = "30*d/c-b+a"
```

More examples in test cases.

Good luck!

Please also try:

[Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)

[Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)

def solve(eq):
    #
    # implemantation takes advantage of abscence of spaces
    #
    leq = (eq.replace('*', ' * ')
             .replace('/', ' / ')
             .replace('+', ' + ')
             .replace('-', ' - ')
             .split(' '))

    out = ''.join(leq[::-1])

    return out


Solve in Python:
Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column.  Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.
Return the maximum number of rows that have all values equal after some number of flips.

Example 1:
Input: [[0,1],[1,1]]
Output: 1
Explanation: After flipping no values, 1 row has all values equal.

Example 2:
Input: [[0,1],[1,0]]
Output: 2
Explanation: After flipping values in the first column, both rows have equal values.

Example 3:
Input: [[0,0,0],[0,0,1],[1,1,0]]
Output: 2
Explanation: After flipping values in the first two columns, the last two rows have equal values.

Note:

1 <= matrix.length <= 300
1 <= matrix[i].length <= 300
All matrix[i].length's are equal
matrix[i][j] is 0 or 1

class Solution(object):
    def maxEqualRowsAfterFlips(self, matrix):
        patterns = collections.Counter()
        for row in matrix:
            patterns[tuple(row)]+=1
            flip = [1-c for c in row]
            patterns[tuple(flip)]+=1
        return max(patterns.values())


Solve in Python:
Given a matrix represented as a list of string, such as
```
###.....
..###...
....###.
.....###
.....###
....###.
..###...
###.....
```
write a function
```if:javascript
`rotateClockwise(matrix)`
```
```if:ruby,python
`rotate_clockwise(matrix)`
```
that return its 90° clockwise rotation, for our example:

```
#......#
#......#
##....##
.#....#.
.##..##.
..####..
..####..
...##...
```
>  /!\  You must return a **rotated copy** of `matrix`! (`matrix` must be the same before and after calling your function)
> Note that the matrix isn't necessarily a square, though it's always a rectangle!
> Please also note that the equality `m == rotateClockwise(rotateClockwise(rotateClockwise(rotateClockwise(m))));` (360° clockwise rotation), is not always true because `rotateClockwise([''])` => `[]` and `rotateClockwise(['','',''])` => `[]` (empty lines information is lost)

def rotate_clockwise(matrix):
    if not len(matrix): return []
    res = []
    for x in range(len(matrix[0])):
        temp = []
        for y in range(len(matrix)-1,-1,-1):
            temp.append(matrix[y][x])
        res.append(''.join(temp))
    return res


Solve in Python:
Given a mixed array of number and string representations of integers, add up the string integers and subtract this from the total of the non-string integers.

Return as a number.

def div_con(x):
    return sum([a for a in x if isinstance(a, int)]) - sum([int(a) for a in x if not isinstance(a, int)])


Solve in Python:
Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise.
Return the number of negative numbers in grid.

Example 1:
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: There are 8 negatives number in the matrix.

Example 2:
Input: grid = [[3,2],[1,0]]
Output: 0

Example 3:
Input: grid = [[1,-1],[-1,-1]]
Output: 3

Example 4:
Input: grid = [[-1]]
Output: 1

Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        i = 0
        j = 0
        count = 0
        while i < len(grid):
            while j < len(grid[i]):
                print(grid[i][j])
                if grid[i][j] < 0:
                    count+=1
                j+=1

            i+=1
            j = 0
        return count


Solve in Python:
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.

Note:
You may assume k is always valid, 1 ≤ k ≤ n2.

class Solution:
     def kthSmallest(self, matrix, k):
         """
         :type matrix: List[List[int]]
         :type k: int
         :rtype: int
         """
         from heapq import heappush, heappop
         n = len(matrix[0])
         heap = []
         for i in range(n):
             heappush(heap, (matrix[0][i], 0, i))
         for _ in range(k-1):
             v, x, y= heappop(heap)
             if x == n - 1:
                 continue
             heappush(heap, (matrix[x+1][y], x+1, y))
         return heappop(heap)[0]


Solve in Python:
Given a name, turn that name into a perfect square matrix (nested array with the amount of arrays equivalent to the length of each array).

You will need to add periods (`.`) to the end of the name if necessary, to turn it into a matrix.

If the name has a length of 0, return `"name must be at least one letter"`

## Examples

"Bill" ==> [ ["B", "i"],
             ["l", "l"] ]

"Frank" ==> [ ["F", "r", "a"],
              ["n", "k", "."],
              [".", ".", "."] ]

from math import ceil
from re import findall

def matrixfy(name):
    if not name:
        return "name must be at least one letter"

    n = ceil(len(name)**0.5)
    name = name.ljust(n*n, ".")

    return [ list(s) for s in findall("."*n, name) ]


Solve in Python:
Given a natural number n, we want to know in how many ways we may express these numbers as product of other numbers.

For example the number
```python
 18 = 2 x 9 = 3 x 6 = 2 x 3 x 3 # (we do not consider the product 18 x 1), (3 ways)
```

See this example a bit more complicated,
```python
60 = 2 x 30 = 3 x 20 =  4 x 15 = 5 x 12 = 6 x 10 = 2 x 2 x 15 = 2 x 3 x 10 = 2 x 5 x 6 =  3 x 4 x 5 = 2 x 2 x 3 x 5 (10 ways)
```
We need the function ```prod_int_part()```, that receives a number n, and ouputs the amount of total different products with all the products of max length sorted in this way:

1) each product will be expressed in a list of its factors in incresing order from left to right

2) if there is more than one list-product, these lists should be ordered by the value of the first term, if two lists have the same term equal thay should be ordered by the value of the second term.

Let's see some cases:
```python
prod_int_part(18) == [3, [2, 3, 3]]

prod_int_part(60) == [10, [2, 2, 3, 5]
```

If we have only one list-product with the maximum length, there is no use to have it with two nested braces, so the result will be like this case:
```python
prod_int_part(54) == [6, [2, 3, 3, 3]]
```

Now, let's see examples when ```n``` cannot be partitioned:
```python
prod_int_part(37) == [0, []]

prod_int_part(61) == [0, []]
```
Enjoy it!!

def product_way(n, start=2):
    result = 0
    for i in range(start, n//2+1):
        if n%i == 0 and i<=n/i:
            result += 1 + product_way(n//i, i)
    return result

def prod_int_part(n):
    x = product_way(n, 2)
    y = []
    m = n
    for i in range(2, n//2+1):
        if n%i == 0:
            while (m%i == 0):
                m /= i
                y.append(i)
    return [x, y]


Solve in Python:
Given a nested list of integers represented as a string, implement a parser to deserialize it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Note:
You may assume that the string is well-formed:

String is non-empty.
String does not contain white spaces.
String contains only digits 0-9, [, - ,, ].

Example 1:

Given s = "324",

You should return a NestedInteger object which contains a single integer 324.

Example 2:

Given s = "[123,[456,[789]]]",

Return a NestedInteger object containing a nested list with 2 elements:

1. An integer containing value 123.
2. A nested list containing two elements:
    i.  An integer containing value 456.
    ii. A nested list with one element:
         a. An integer containing value 789.

# """
 # This is the interface that allows for creating nested lists.
 # You should not implement it, or speculate about its implementation
 # """
 #class NestedInteger:
 #    def __init__(self, value=None):
 #        """
 #        If value is not specified, initializes an empty list.
 #        Otherwise initializes a single integer equal to value.
 #        """
 #
 #    def isInteger(self):
 #        """
 #        @return True if this NestedInteger holds a single integer, rather than a nested list.
 #        :rtype bool
 #        """
 #
 #    def add(self, elem):
 #        """
 #        Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
 #        :rtype void
 #        """
 #
 #    def setInteger(self, value):
 #        """
 #        Set this NestedInteger to hold a single integer equal to value.
 #        :rtype void
 #        """
 #
 #    def getInteger(self):
 #        """
 #        @return the single integer that this NestedInteger holds, if it holds a single integer
 #        Return None if this NestedInteger holds a nested list
 #        :rtype int
 #        """
 #
 #    def getList(self):
 #        """
 #        @return the nested list that this NestedInteger holds, if it holds a nested list
 #        Return None if this NestedInteger holds a single integer
 #        :rtype List[NestedInteger]
 #        """

 class Solution:
     def convertListToNestedInteger(self, nestList):
         if type(nestList) == type(0):
             return NestedInteger(nestList)
         rtype = NestedInteger()
         for item in nestList:
             if type(item) == type(0):
                 rtype.add(item)
             else:
                 nestedList = self.convertListToNestedInteger(item)
                 rtype.add(nestedList)
         return rtype

     def deserializeHelper(self, st):
         if len(st) > 0:
             if st[0] != '[':
                 return int(st)
         assert(len(st) > 1)
         assert(st[0] == '[')
         assert(st[-1] == ']')
        ...


Solve in Python:
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

Follow up:

It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount  in c++ or in any other language.

Credits:Special thanks to @ syedee  for adding this problem and creating all test cases.

class Solution:
     def countBits(self, num):
         """
         :type num: int
         :rtype: List[int]
         """
         ans = [0]
         while len(ans) < num + 1:
             ans += [1 + x for x in ans]
         # len(ans) > num
         return ans[:num+1]


Solve in Python:
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:

Each of the array element will not exceed 100.
The array size will not exceed 200.

Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.

class Solution:
     def canPartition(self, nums):
         """
         :type nums: List[int]
         :rtype: bool
         """

         if len(nums) < 2:
             return False

         s = sum(nums)
         if s % 2 != 0:
             return False

         s = s // 2
         nums.sort()
         mem = dict()

         return self.dp(nums, 0, s, mem)

     def dp(self, nums, start, s, mem):

         if s == 0:
             return True

         if start >= len(nums):
             return False

         state = mem.get((start, s), None)
         if state is not None:
             return state

         res = False
         if nums[start] > s:
             res = False

         else:
             res = self.dp(nums, start+1, s-nums[start], mem) or self.dp(nums, start+1, s, mem)

         mem[(start, s)] = res
         return res


Solve in Python:
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

class Solution:
     def thirdMax(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """

         """
         if len(nums) == 2 or len(nums) == 1:
             return max(nums)

         maxes = [nums[0], nums[1], nums[2]]
         maxes.sort() # ascending

         for i in range(3, len(nums)):
             pos = self.findPos(nums[i], maxes)
             if pos != None:
                 maxes[pos] = nums[i]

         if maxes[0] == maxes[1] or maxes[1] == maxes[2]:
             return maxes[2]
         else:
             return maxes[0]

     def findPos(self, val, maxes):
         maxPos = None
         for ind, aMax in enumerate(maxes):
             if val > aMax:
                 maxPos = ind

         return maxPos
         """

         maxes = []

         for i in nums:
             if self.isNew(i, maxes):
                 if len(maxes) < 3:
                     maxes.append(i)
                     maxes.sort() # ascending
                 else:
                     pos = self.findPos(i, maxes)
                     if pos != None:
                         maxes[pos] = i
                         maxes.sort()

         if len(maxes) == 3:
             return maxes[0]
         else:
             return maxes[-1]

     def isNew(self, val, maxes):
         isNew = True
         for i in maxes:
             if val == i:
                 isNew = False
         return isNew

     def findPos(self, val, maxes):
         for ind, aMax in enumerate(maxes):
             if val > aMax:
                 return ind

         return None


Solve in Python:
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

Example 1:

Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

Example 2:

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

Note:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.

class Solution:
     def findShortestSubArray(self, nums):

         diction = {}

         for i in nums:
             if i not in diction:
                 diction[i] = 1
             else:
                 diction[i] += 1

         degree = max(list(diction.values()))

         if degree == 1:
             return 1

         max_value = []

         for i in diction:
             if diction[i] == degree:
                 max_value.append(i)

         min_length = 10000000000

         for i in max_value:
             head = 0
             tail = 0
             for j in range(len(nums)):
                 if nums[j] == i:
                     head = j
                     break
             for j in range(len(nums)-1,-1,-1):
                 if nums[j] == i:
                     tail = j
                     break
             if min_length > tail - head + 1:
                 min_length = tail - head + 1

         return min_length


Solve in Python:
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.

Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.

Could you do this in O(n) runtime?

Example:

Input: [3, 10, 5, 25, 2, 8]

Output: 28

Explanation: The maximum result is 5 ^ 25 = 28.

class Solution:
     def findMaximumXOR(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         ans = 0
         for bit in range(31, -1, -1) :
             ans = (ans << 1) | 1
             pre = set()
             for n in nums :
                 p = (n >> bit) & ans
                 if p in pre :
                     break
                 pre.add(ans ^ p)
             else :
                 ans ^= 1
         return ans


Solve in Python:
Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

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

 class Solution:
 	def currentmax(self,root):
 		leftval = 0
 		if root.left != None:
 			leftval = self.currentmax(root.left)
 			leftval = 0 if leftval < 0 else leftval
 		rightval = 0
 		if root.right != None:
 			rightval = self.currentmax(root.right)
 			rightval = 0 if rightval < 0 else rightval
 		currentnode = leftval + rightval + root.val
 		if self.flag == 0:
 			self.ans = currentnode
 			self.flag = 1
 		else:
 			self.ans = self.ans if self.ans > currentnode else currentnode
 		return root.val + (leftval if leftval > rightval else rightval)
 	def maxPathSum(self, root):
 		self.ans = 0
 		self.flag = 0
 		self.currentmax(root)
 		return self.ans


Solve in Python:
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.

Example:

Input:
[1,2,3]

Output:
3

Explanation:
Only three moves are needed (remember each move increments two elements):

[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

class Solution:
     def minMoves(self, nums):
         """
         :type nums: List[int]
         :rtype: int

         let’s define sum as the sum of all the numbers, before any moves;
             minNum as the min number int the list;
             n is the length of the list;

         After, say m moves, we get all the numbers as x , and we will get the following equation

         sum + m * (n - 1) = x * n
         and actually,

           x = minNum + m
         and finally, we will get

           sum - minNum * n = m
         So, it is clear and easy now.
         """
         tt = 0
         mx = nums[0]
         n = 0
         for x in nums:
             tt += x
             n += 1
             if x < mx:
                 mx = x
         return tt - mx * n


Solve in Python:
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.

You may assume the array's length is at most 10,000.

Example:

Input:
[1,2,3]

Output:
2

Explanation:
Only two moves are needed (remember each move increments or decrements one element):

[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

class Solution:
     def minMoves2(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         mid = len(nums) // 2
         tar = sorted(nums)[mid]
         return sum([abs(x - tar) for x in nums])


Solve in Python:
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
    Note that "i" comes before "love" due to a lower alphabetical order.

Example 2:

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively.

Note:

You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Input words contain only lowercase letters.

Follow up:

Try to solve it in O(n log k) time and O(n) extra space.

class Solution:
     def topKFrequent(self, words, k):
         """
         :type words: List[str]
         :type k: int
         :rtype: List[str]
         """
         from collections import Counter
         return [item[0] for item in sorted(Counter(words).items(),key = lambda x: (-x[1],x[0])) [:k]]


Solve in Python:
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.  You may assume the given string consists of lowercase English letters only and its length  will not exceed 10000.

Example 1:

Input: "abab"

Output: True

Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"

Output: False

Example 3:

Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

class Solution:
     def repeatedSubstringPattern(self, s):
         """
         :type s: str
         :rtype: bool
         """
         return any(s[:i] * (len(s) // i) == s for i in range(1, len(s) // 2 + 1) if len(s) % i == 0)


Solve in Python:
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.

Note:

Input contains only lowercase English letters.
Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted.
Input length is less than 50,000.

Example 1:

Input: "owoztneoer"

Output: "012"

Example 2:

Input: "fviefuro"

Output: "45"


Solve in Python:
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

       The same word in the dictionary may be reused multiple times in the segmentation.
       You may assume the dictionary does not contain duplicate words.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

class Solution:
     def wordBreak(self, s, wordDict):
         """
         :type s: str
         :type wordDict: List[str]
         :rtype: bool
         """
         ok = [True]
         for i in range(1, len(s)+1):
             ok += (any(ok[j] and s[j:i] in wordDict for j in range(i))),
             print(ok)
         return ok[-1]


Solve in Python:
Given a non-empty string s, you may delete at most one character.  Judge whether you can make it a palindrome.

Example 1:

Input: "aba"
Output: True

Example 2:

Input: "abca"
Output: True
Explanation: You could delete the character 'c'.

Note:

The string will only contain lowercase characters a-z.
The maximum length of the string is 50000.

class Solution:
     def validPalindrome(self, s):
         """
         :type s: str
         :rtype: bool
         """
         if s == s[::-1]:
             return True
         r = s[::-1]
         for i in range(0, len(s)):
             if r[i] == s[i]:
                 continue
             else:
                 break
         r = r[:i] + r[i+1:]
         if r == r[::-1]:
             return True
         s = s[:i] + s[i+1:]
         return s == s[::-1]


Solve in Python:
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

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

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99

class Solution:
     def singleNumber(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         a = b = 0
         for c in nums:
             a, b = a&~b&~c|~a&b&c, ~a&b&~c|~a&~b&c
         return b


Solve in Python:
Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

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

Example 2:

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

class Solution:
     def singleNumber(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """

         return(sum(set(nums))*2-sum(nums))


Solve in Python:
Given a non-empty array of unique positive integers A, consider the following graph:

There are A.length nodes, labelled A[0] to A[A.length - 1];
There is an edge between A[i] and A[j] if and only if A[i] and A[j] share a common factor greater than 1.

Return the size of the largest connected component in the graph.

Example 1:
Input: [4,6,15,35]
Output: 4

Example 2:
Input: [20,50,9,63]
Output: 2

Example 3:
Input: [2,3,6,7,4,12,21,39]
Output: 8

Note:

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

class Solution:
    def largestComponentSize(self, A: List[int]) -> int:
        def pfactorization(a):
            N = a
            if a >= 2 and a % 2 == 0:
                Gp[2].append(N)
                Gn[N].append(2)
                while a % 2 == 0:
                    a //= 2
            for d in range(3, math.floor(a**(1/2)) + 1, 2):
                if a % d == 0:
                    Gn[N].append(d)
                    Gp[d].append(N)
                    while a % d == 0:   a //= d
            if a > 1:
                Gp[a].append(N)
                Gn[N].append(a)
        def dfs(curr):
            if curr in seenNodes:   return 0
            seenNodes.add(curr)
            total = 1
            for p in Gn[curr]:
                if p in seenPrimes: continue
                seenPrimes.add(p)
                for owner in Gp[p]: total += dfs(owner)
            return total
        Gp = collections.defaultdict(list)
        Gn = collections.defaultdict(list)
        for a in A: pfactorization(a)   #build our graphs
        seenPrimes, seenNodes = set(), set()
        return max([dfs(a) for a in A])


Solve in Python:
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.

(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .)

Example 1:

Input: N = 10
Output: 9

Example 2:

Input: N = 1234
Output: 1234

Example 3:

Input: N = 332
Output: 299

Note:
N is an integer in the range [0, 10^9].

class Solution:
     def monotoneIncreasingDigits(self, N):
         N = str(N)
         L = len(N)
         for i in range(L - 1):
             if N[i] > N[i + 1]:
                 return self.monotoneIncreasingDigits(int(N[:i] + str(int(N[i]) - 1) + '9' * (L - i - 1)))
         return int(N)


Solve in Python:
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.

    Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99])

Credits:Special thanks to @memoryless for adding this problem and creating all test cases.

class Solution:
     def countNumbersWithUniqueDigits(self, n):
         """
         :type n: int
         :rtype: int
         """
         if n ==0:
             return 1
         elif n == 1:
             return 10
         else:
             return (self.countNumbersWithUniqueDigits(n-1) - self.countNumbersWithUniqueDigits(n-2))*(11-n) + self.countNumbersWithUniqueDigits(n-1)


Solve in Python:
Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.

Note:

The length of num is less than 10002 and will be ≥ k.
The given num does not contain any leading zero.

Example 1:

Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Example 2:

Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Example 3:

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.

class Solution:
     def removeKdigits(self, num, k):
         """
         :type num: str
         :type k: int
         :rtype: str
         """
         while True:
             if k == 0:
                 return num if num != "" else "0"
             if num == "":
                 return "0"
             index = 0
             num_len = len(num)
             while True:
                 if index == num_len - 1:
                     num = num[:-1]
                     k -= 1
                     break
                 if num[index] > num[index + 1]:
                     new_num = num[:index] + num[index+1:]
                     num = new_num.lstrip("0")
                     k -= 1
                     break
                 index += 1


Solve in Python:
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example:

Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
             Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

class Solution:
     def addDigits(self, num):
         """
         :type num: int
         :rtype: int
         """
         if num == 0:return 0
         return (num-1)%9+1


Solve in Python:
Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

Example 1:
Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.

Example 2:
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.

Example 3:
Input: num = 123
Output: 12

Constraints:

0 <= num <= 10^6

class Solution:
    def numberOfSteps (self, num: int) -> int:

        steps = 0

        while num > 0:
            if num%2 == 0:
                num = num//2
                steps += 1
            else:
                num -=1
                steps +=1
        return steps


Solve in Python:
Given a non-negative integer, return an array / a list of the individual digits in order.

Examples:

```
123 => [1,2,3]

1 => [1]

8675309 => [8,6,7,5,3,0,9]
```

def digitize(n):
    return [int(n) for n in str(n)]


Solve in Python:
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1:

Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.

Example 2:

Input: 9973
Output: 9973
Explanation: No swap.

Note:

The given number is in the range [0, 108]

class Solution:
     def maximumSwap(self, num):
         arr = [int(c) for c in str(num)]
         n = len(arr)
         posmax = [0] * n
         posmax[-1] = n-1
         for i in range(n-2, -1, -1):
             if arr[i] > arr[posmax[i+1]]:
                 posmax[i] = i
             else:
                 posmax[i] = posmax[i+1]
         for i in range(n):
             if arr[i] == 9:
                 continue
             j = posmax[i]
             if arr[j] > arr[i]:
                 arr[i], arr[j] = arr[j], arr[i]
                 return int(''.join(map(str, arr)))
         return num


Solve in Python:
Given a non-negative number, return the next bigger polydivisible number, or an empty value like `null` or `Nothing`.

A number is polydivisible if its first digit is cleanly divisible by `1`, its first two digits by `2`, its first three by `3`, and so on. There are finitely many polydivisible numbers.

d, polydivisible, arr = 1, [], list(range(1, 10))
while arr:
    d += 1
    polydivisible.extend(arr)
    arr = [n for x in arr for n in
           range(-(-x*10 // d) * d, (x+1) * 10, d)]

def next_num(n):
    from bisect import bisect
    idx = bisect(polydivisible, n)
    if idx < len(polydivisible):
        return polydivisible[idx]


Solve in Python:
Given a number $n$, give the last digit of sum of all the prime numbers from 1 to $n$ inclusive.

-----Input:-----
- First line contains number of testcase $t$.
- Each testcase contains of a single line of input, number $n$.

-----Output:-----
Last digit of sum of every prime number till n.

-----Constraints-----
- $1 \leq T \leq 10$
- $2 \leq N \leq 10^6$

-----Sample Input:-----
1
10

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

def sumofprimes(n):
  prime=[True]*(n+1)
  p=2
  while(p*p<=n):
    if prime[p]==True:
      i=p*2
      while i<=n:
        prime[i]=False
        i+=p
    p+=1
  sum=0
  for i in range(2,n+1):
    if prime[i]:
      sum+=i
  return sum
def __starting_point():
  for _ in range(int(input())):
    n=int(input())
    print(sumofprimes(n)%10)
__starting_point()


Solve in Python:
Given a number **n**, return the number of positive odd numbers below **n**, EASY!

Expect large Inputs!

def odd_count(n):
    oddListLen = len(range(1,n,2))
    return oddListLen


Solve in Python:
Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two).
The returned string must have no leading zeroes, unless the string is "0".

Example 1:
Input: 2
Output: "110"
Explantion: (-2) ^ 2 + (-2) ^ 1 = 2

Example 2:
Input: 3
Output: "111"
Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3

Example 3:
Input: 4
Output: "100"
Explantion: (-2) ^ 2 = 4

Note:

0 <= N <= 10^9

class Solution:
    def baseNeg2(self, N):
        res = []
        while N != 0:
            m = N %(-2)
            if m == -1:
                m = 1
            N = (N-m) // (-2)
            res.append(str(m))

        return ''.join(res[::-1]) or '0'


Solve in Python:
Given a number `n` we will define its scORe to be `0 | 1 | 2 | 3 | ... | n`, where `|` is the [bitwise OR operator](https://en.wikipedia.org/wiki/Bitwise_operation#OR).

Write a function that takes `n` and finds its scORe.

---------------------
|    n    | scORe n |
|---------|-------- |
| 0       | 0 |
| 1       | 1 |
| 49      | 63 |
| 1000000 | 1048575 |


Solve in Python:
Given a number `n`, make a down arrow shaped pattern.

For example, when `n = 5`, the output would be:

    123454321
     1234321
      12321
       121
        1

and for `n = 11`, it would be:

    123456789010987654321
     1234567890987654321
      12345678987654321
       123456787654321
        1234567654321
         12345654321
          123454321
           1234321
            12321
             121
              1

An important thing to note in the above example is that the numbers greater than 9 still stay single digit, like after 9 it would be 0 - 9 again instead of 10 - 19.

Note: There are spaces for the indentation on the left of each line and no spaces on the right.

Have fun!

def get_a_down_arrow_of(n):
    answer = ""
    for i in range(n, 0, -1):
        spaces = " " * (n - i)
        half1 = "".join(str(x % 10) for x in range(1, i + 1))
        half2 = half1[::-1]
        answer += spaces + half1 + half2[1:] + "\n" * (i > 1)
    return answer


Solve in Python:
Given a number n. Find the last two digits of 5 ^ n ( 5 to the power of n ).
Remember that overflow can occur.

-----Input:-----
- N  — the power in which you need to raise number 5.

-----Output:-----
Last two digits of 5^n.

-----Constraints-----
- $2 \leq N \leq 2.1018$

-----Sample Input:-----
2

-----Sample Output:-----
25

def p(x,y,p):
    res=1
    x=x%p
    while(y>0):
        if(y&1):
            res=(res*x)%p
        y=y>>1
        x=(x*x)%p
    return res
def nod(x):
    i=0
    while(x):
        x//=10
        i+=1
    return i
def ltd(n):
    temp=1
    for i in range(1,3):
        temp*=10
        temp=p(5,n,temp)
    for i in range(2-nod(temp)):
        print(0,end="")
    if temp:
        print(temp)
def __starting_point():
    n=int(input())
    ltd(n)
__starting_point()


Solve in Python:
Given a number return the closest number to it that is divisible by 10.

Example input:

```
22
25
37
```

Expected output:

```
20
30
40
```

def closest_multiple_10(i):
    for j in range(int(i-5),int(i+6)):
        if j%10==0:
            i=j
    return i


Solve in Python:
Given a number, return a string with dash``` '-' ```marks before and after each odd integer,  but do not begin or end the string with a dash mark.

Ex:

import re
def dashatize(num):
    try:
        return ''.join(['-'+i+'-' if int(i)%2 else i for i in str(abs(num))]).replace('--','-').strip('-')
    except:
        return 'None'


Solve in Python:
Given a number, write a function to output its reverse digits.  (e.g. given 123 the answer is 321)

Numbers should preserve their sign; i.e. a negative number should still be negative when reversed.

### Examples
```
 123 ->  321
-456 -> -654
1000 ->    1
```

def reverse_number(n):
    return int(str(n)[::-1] if n >=0 else "-"+str(n)[::-1][0:-1])


Solve in Python:
Given a number s in their binary representation. Return the number of steps to reduce it to 1 under the following rules:

If the current number is even, you have to divide it by 2.

If the current number is odd, you have to add 1 to it.

It's guaranteed that you can always reach to one for all testcases.

Example 1:
Input: s = "1101"
Output: 6
Explanation: "1101" corressponds to number 13 in their decimal representation.
Step 1) 13 is odd, add 1 and obtain 14.
Step 2) 14 is even, divide by 2 and obtain 7.
Step 3) 7 is odd, add 1 and obtain 8.
Step 4) 8 is even, divide by 2 and obtain 4.
Step 5) 4 is even, divide by 2 and obtain 2.
Step 6) 2 is even, divide by 2 and obtain 1.

Example 2:
Input: s = "10"
Output: 1
Explanation: "10" corressponds to number 2 in their decimal representation.
Step 1) 2 is even, divide by 2 and obtain 1.

Example 3:
Input: s = "1"
Output: 0

Constraints:

1 <= s.length <= 500
s consists of characters '0' or '1'
s[0] == '1'

class Solution:
    def numSteps(self, s: str) -> int:
        i, mid_zero = 0 , 0
        for j in range(1, len(s)):
            if s[j] == '1':
                mid_zero += j -i - 1
                i = j
        if i == 0:
            return len(s)-1
        return mid_zero + 1 + len(s)


Solve in Python:
Given a palindromic string palindrome, replace exactly one character by any lowercase English letter so that the string becomes the lexicographically smallest possible string that isn't a palindrome.
After doing so, return the final string.  If there is no way to do so, return the empty string.

Example 1:
Input: palindrome = "abccba"
Output: "aaccba"

Example 2:
Input: palindrome = "a"
Output: ""

Constraints:

1 <= palindrome.length <= 1000
palindrome consists of only lowercase English letters.

class Solution:
    def breakPalindrome(self, palindrome: str) -> str:
        if len(palindrome) == 1:
            return ''
        for i, val in enumerate(palindrome):
            if val != 'a' and i != len(palindrome) // 2:
                return palindrome[:i] + 'a' + palindrome[i+1:]
            elif val == 'a' and i == len(palindrome) - 1:
                return palindrome[:-1] + 'b'


Solve in Python:
Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

class Solution:
     def wordPattern(self, pattern, str):
         if not pattern and not str:
             return True
         if not pattern or not str:
             return False

         str_list = str.split()
         if len(pattern) != len(str_list):
             return False

         pattern_table = collections.defaultdict(int)
         str_table = collections.defaultdict(int)
         for idx in range(len(pattern)):
             if pattern_table[pattern[idx]] != str_table[str_list[idx]]:
                 return False
             pattern_table[pattern[idx]] = idx + 1
             str_table[str_list[idx]] = idx + 1

         return True

         """
         :type pattern: str
         :type str: str
         :rtype: bool
         """


Solve in Python:
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that:  $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$.  Among all such subsequences, choose the one whose length, $k$, is as small as possible.

If multiple subsequences satisfy these conditions, you are allowed to find any of them.

A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.

A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$) — the length of the permutation $p$.

The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct) — the elements of the permutation $p$.

The sum of $n$ across the test cases doesn't exceed $10^5$.

-----Output-----

For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$ — its elements.

If multiple subsequences satisfy these conditions, you are allowed to find any of them.

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

Output
2
3 1
3
1 4 2

-----Note-----

In the first test case, there are $4$ subsequences of length at least $2$:  $[3,2]$ which gives us $|3-2|=1$.  $[3,1]$ which gives us $|3-1|=2$.  $[2,1]$ which gives us $|2-1|=1$.  $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.

So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.

import sys

T = int(sys.stdin.readline().strip())
for t in range (0, T):
    n = int(sys.stdin.readline().strip())
    p = list(map(int, sys.stdin.readline().strip().split()))
    ans = [p[0]]
    for i in range(1, n):
        if p[i] != ans[-1]:
            if len(ans) == 1:
                ans.append(p[i])
            else:
                if (ans[-2] - ans[-1]) * (ans[-1] - p[i]) > 0:
                    ans.pop()
                ans.append(p[i])
    print(len(ans))
    print(" ".join(list(map(str, ans))))


Solve in Python:
Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.

Example 1:

Input: 12
Output: 21

Example 2:

Input: 21
Output: -1

class Solution:
     def nextGreaterElement(self, n):
         """
         :type n: int
         :rtype: int
         """
         nums=list(str(n))#因为只有你变成字符串 才可以被分开这样子写
         size=len(nums)
         for i in range(size-1,-1,-1):
             if nums[i-1]<nums[i]:
                 break
         if i>0:#没有明白这儿为什么需要一个这个判断条件呢
             for j in range(size-1,-1,-1):
                 if nums[j]>nums[i-1]:
                     nums[i-1],nums[j]=nums[j],nums[i-1]
                     break
         #上面这儿算是比较明白了
         '''
         230241 230421 230412 要注意的就是这个地方 并不是把4挪到了2的前面就结束了
         '''
         for k in range((size-i)//2):
             nums[i+k],nums[size-k-1]=nums[size-k-1],nums[i+k] #这个就是再换后面的 size-1是一体的 不然会超出范围
             #这一步想明白一点

         ans=int(''.join(nums))
         return n < ans <= 0x7FFFFFFF and ans or -1 #这儿实在是没看懂 神马意思
         #注意这个地方 虽然都是表示无穷大 但是这个是0x7FFFFFFF 不能用float('inf') 是不是因为这个是浮点型的 有可能


Solve in Python:
Given a positive integer K > 2, with prime
factorization:

K = p1^a1 * p2^a2 ... * pn^an

Compute the following:

S = a1*p1 + a2*p2 ... + an*pn.

-----Input-----
A list of <100 integers, one on each line,
all less than $2*10^{18}$.

-----Output-----
For each integer compute the super factor
sum and output it on a single line.

-----Example-----
Input:
6
7
Output:
5
7


Solve in Python:
Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1.
Return the length of N.  If there is no such N, return -1.

Example 1:
Input: 1
Output: 1
Explanation: The smallest answer is N = 1, which has length 1.
Example 2:
Input: 2
Output: -1
Explanation: There is no such positive integer N divisible by 2.
Example 3:
Input: 3
Output: 3
Explanation: The smallest answer is N = 111, which has length 3.

Note:

1 <= K <= 10^5

class Solution:
    def smallestRepunitDivByK(self, K: int) -> int:
        if K % 2 == 0 or K % 5 == 0: return -1
        r = 0
        for N in range(1, K + 1):
            r = (r * 10 + 1) % K
            if not r: return N


Solve in Python:
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.

Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.

Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.

Example 3:
Input: 1000
Output: 262

Note:

1 <= N <= 10^9

class Solution:
    def numDupDigitsAtMostN(self, N: int) -> int:
        # N -> total numbers less than or equal to N
        # We will calculate the integers with all different digits (which are less than/equal to N)
        # Then the answer would be: N - nums_with_different_digits

        # Calculate the number of digits in N
        NN, dd = N, 0
        nums = [] # store the digits
        while(NN):
            dd += 1
            nums.append(NN % 10)
            NN //= 10
        nums.reverse()

        # numbers with less digits than that of N
        numbers = 0
        for i in range(dd-1):
            numbers += 9 * (math.factorial(9) // math.factorial(9-i))

        # find the N-digit numbers (all-different)
        already_visited_digits = set()

        def fac2(n, k):
            return math.factorial(n) // math.factorial(n-k)

        for i,n in enumerate(nums):
            k = 0
            for j in range((1 if i==0 else 0), (n+1 if i==dd-1 else n)):
                if(j in already_visited_digits):
                    continue
                k += 1
            numbers += k * fac2(10-i-1, dd-i-1)
            if n in already_visited_digits:
                # All the numbers with this prefix will have at least one common digit
                break
            already_visited_digits.add(n)

        return N - numbers


Solve in Python:
Given a positive integer `n`, return first n dgits of Thue-Morse sequence, as a string (see examples).

Thue-Morse sequence is a binary sequence with 0 as the first element. The rest of the sequece is obtained by adding the Boolean (binary) complement of a group obtained so far.

```
For example:

0
01
0110
01101001
and so on...
```

![alt](https://upload.wikimedia.org/wikipedia/commons/f/f1/Morse-Thue_sequence.gif)

Ex.:
```python
thue_morse(1);  #"0"
thue_morse(2);  #"01"
thue_morse(5);  #"01101"
thue_morse(10): #"0110100110"
```

- You don't need to test if n is valid - it will always be a positive integer.
- `n` will be between 1 and 10000

[Thue-Morse on Wikipedia](https://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence)

[Another kata on Thue-Morse](https://www.codewars.com/kata/simple-fun-number-106-is-thue-morse) by @myjinxin2015

def thue_morse(n):
    s = "0"
    while len(s)<n:
        s += "".join([str(int(i)^1) for i in s])
    return s[:n]


Solve in Python:
Given a positive integer n and you can do operations as follow:

If n is even, replace n with n/2.
If n is odd, you can replace n with either n + 1 or n - 1.

What is the minimum number of replacements needed for n to become 1?

Example 1:

Input:
8

Output:
3

Explanation:
8 -> 4 -> 2 -> 1

Example 2:

Input:
7

Output:
4

Explanation:
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1

class Solution:
     def integerReplacement(self, n):
         """
         :type n: int
         :rtype: int
         """
         def dfs(n):
             if n==1: return 0
             if n==3: return 2
             if (n & 0x1)==0: return dfs(n>>1)+1
             elif ((n>>1) & 0x1)==0: return dfs(n-1)+1
             else: return dfs(n+1)+1

         return dfs(n)


Solve in Python:
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).

Note: You may assume that n is not less than 2 and not larger than 58.

Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

class Solution:
     def integerBreak(self, n):
         """
         :type n: int
         :rtype: int
         """

         import math
         if n == 2 or n == 3:
             return n-1
         else:
             if n % 3 == 1:
                 m1 = 2
             elif n % 3 == 2:
                 m1 = 1
             else:
                 m1 = 0
             m2 = (n-2*m1) // 3
             return 2**m1 * 3**m2

         # import math
         # if n == 2 or n == 3:
         #     return n - 1
         # else:
         #     x = n/math.e
         #     ans = 0
         #     for y in [math.floor(x), math.ceil(x)]:
         #         x1 = int(n/y)
         #         x2 = x1 + 1
         #         n2 = n - x1*y
         #         n1 = y - n2
         #         ans = max(ans, (x1**n1) * (x2**n2))
         #     return int(ans)


Solve in Python:
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.
Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.

Example 1:
Input: n = 22
Output: 2
Explanation: 22 in binary is "10110".
The first adjacent pair of 1's is "10110" with a distance of 2.
The second adjacent pair of 1's is "10110" with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.

Example 2:
Input: n = 5
Output: 2
Explanation: 5 in binary is "101".

Example 3:
Input: n = 6
Output: 1
Explanation: 6 in binary is "110".

Example 4:
Input: n = 8
Output: 0
Explanation: 8 in binary is "1000".
There aren't any adjacent pairs of 1's in the binary representation of 8, so we return 0.

Example 5:
Input: n = 1
Output: 0

Constraints:

1 <= n <= 109

class Solution:
    def binaryGap(self, n: int) -> int:
        bins = ''
        maxv = 0
        i = 0
        pre = None
        while n > 0:
            if n % 2 == 1:
                if pre is not None:
                    maxv = max(maxv,i-pre)
                pre = i
            n //= 2
            i += 1

        return maxv


Solve in Python:
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

class Solution:
     def numSquares(self, n):
         """
         :type n: int
         :rtype: int
         """
         def is_square(n):
             return int(n**0.5) * int(n**0.5) == n

         if is_square(n): return 1
         for i in range(1, int((n**0.5) + 1)):
             if is_square(n - i*i):
                 return 2
         while (n & 3) == 0: n >>= 2
         if n & 7 == 7: return 4
         return 3


Solve in Python:
Given a positive integer n, find the number of non-negative integers less than or equal to n, whose binary representations do NOT contain consecutive ones.

Example 1:

Input: 5
Output: 5
Explanation:
Here are the non-negative integers

Note:
1 9

class Solution:
     def findIntegers(self, num):
         """
         :type num: int
         :rtype: int
         """
         if num<3:
             return num+1
         if num==3:
             return num
         import math
         bits = int(math.log(num,2))
         f = [0]*(bits+1)
         f[0],f[1],f[2] =2,3,4
         for i in range(3,bits+1):
             f[i] = f[i-1]+f[i-2]-1

         g = [0]*(bits+1)
         n = num
         b = 0
         res = [0]*(bits+1)
         while n:
             cur = n%2
             g[b] = cur
             if cur:
                 if not b:
                     res[b] = f[b]
                 elif not res[b-1]:
                     res[b] = f[b]+res[b-1]

                 elif not g[b-1]:
                     res[b] = f[b]+res[b-1]-1
                 else:
                     res[b] = f[b]+f[b-1]-2

             else:
                 res[b] = res[b-1]
             n = int(n/2)
             b = b+1
         #print(g,f,res)
         return res[-1]


Solve in Python:
Given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).

Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.

Example 2:
Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.
Example 3:
Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.

Constraints:

1 <= num <= 10^4
num's digits are 6 or 9.

class Solution:
    def maximum69Number (self, num: int) -> int:
        str_num = list(str(num))
        for i in range(len(str_num)):
            if int(str_num[i]) == 6:
                str_num[i] = '9'
                break
        print(str_num)
        str_num = ''.join(str_num)
        return int(str_num)


Solve in Python:
Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:

Input: 16
Returns: True

Example 2:

Input: 14
Returns: False

Credits:Special thanks to @elmirap for adding this problem and creating all test cases.

class Solution:
     def isPerfectSquare(self, num):
         sign = True
         i = 1
         while(sign):
             if(num == i * i):
                 return True
             elif(num > i * i):
                 i = i + 1
             else:
                 return False


Solve in Python:
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Example 1:

Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101

Example 2:

Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.

Example 3:

Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.

Example 4:

Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.

class Solution:
     def hasAlternatingBits(self, n):
         """
         :type n: int
         :rtype: bool
         """
         bits = bin(n)
         return all(bits[i] != bits[i+1] for i in range(len(bin(n)) - 1) )


Solve in Python:
Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB
    ...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"

class Solution:
     def convertToTitle(self, num):
         res = []

         while num > 0:
             res.append(chr(ord('A') + (num - 1) % 26))
             num = (num - 1) // 26
         res.reverse()
         return "".join(res)

         """
         :type n: int
         :rtype: str
         """


Solve in Python:
Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?
Example 1:
Input: 5
Output: 2
Explanation: 5 = 5 = 2 + 3
Example 2:
Input: 9
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input: 15
Output: 4
Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
Note: 1 <= N <= 10 ^ 9.

import math
class Solution:
    def consecutiveNumbersSum(self, N: int) -> int:
        k = 1.0
        count = 0
        while k <= math.sqrt(2*N + 1/4) - 1/2:
            x = N/k - (k +1)/2
            if x.is_integer():
                count += 1
                print(k, x)
            k += 1
        return count


Solve in Python:
Given a positive number n > 1 find the prime factor decomposition of n.
The result will be a string with the following form :
```
 "(p1**n1)(p2**n2)...(pk**nk)"
```
where ```a ** b``` means ```a``` to the power of ```b```

with the p(i) in increasing order and n(i) empty if
n(i) is 1.
```
Example: n = 86240 should return "(2**5)(5)(7**2)(11)"
```

import math

def primeFactors(n):
    dic_prime = {}
    dic_prime[2] = 0
    while n%2 ==0:
        dic_prime[2] += 1
        n = n/2
    if dic_prime[2] == 0:
        dic_prime.pop(2)

    for i in range(3,int(n+1),2):
        dic_prime[i] = 0
        while n%i ==0:
            dic_prime[i] += 1
            n = n/i
        if n <= 1:
            break
        if dic_prime[i] == 0:
            dic_prime.pop(i)

    output_str = ""
    for k,v in dic_prime.items():
        if v == 1:
            output_str += "({})".format(str(k))
        else:
            output_str +="({}**{})".format(str(k),str(v))

    return output_str


Solve in Python:
Given a random bingo card and an array of called numbers, determine if you have a bingo!

*Parameters*: `card` and `numbers` arrays.

*Example input*:
```
card = [
  ['B', 'I', 'N', 'G', 'O'],
  [1, 16, 31, 46, 61],
  [3, 18, 33, 48, 63],
  [5, 20, 'FREE SPACE', 50, 65],
  [7, 22, 37, 52, 67],
  [9, 24, 39, 54, 69]
]

numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```

*Output*: ```true``` if you have a bingo, ```false``` if you do not.

You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.

### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B':  1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`

### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.

___

## Examples:
```
card:
------------------------------
| B  | I  |   N    | G  | O  |
==============================
| 2  | 17 |   32   | 47 | 74 |
------------------------------
| 14 | 25 |   44   | 48 | 62 |
------------------------------
| 5  | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 |   45   | 59 | 73 |
------------------------------
| 1  | 30 |   33   | 58 | 70 |
------------------------------

numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']

// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```

The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.

def bingo(card, numbers):
    card = card[1:]

    indexes = {
        str(x): (i, j)
        for i, row in enumerate(card)
        for j, x in enumerate(row)
    }
    board = [[0] * 5 for _ in range(5)]
    for n in numbers + [' FREE SPACE']:
        try:
            i, j = indexes[n[1:]]
            board[i][j] = 1
        except KeyError:
            pass
    return (
        any(sum(row) == 5 for row in board)
        or any(sum(row) == 5 for row in zip(*board))
        or all(board[i][i] for i in range(5))
        or all(board[i][4-i] for i in range(5))
    )


Solve in Python:
Given a random string consisting of numbers, letters, symbols, you need to sum up the numbers in the string.

Note:

- Consecutive integers should be treated as a single number. eg, `2015` should be treated as a single number `2015`, NOT four numbers
- All the numbers should be treaded as positive integer. eg, `11-14` should be treated as two numbers `11` and `14`. Same as `3.14`, should be treated as two numbers `3` and `14`
- If no number was given in the string, it should return `0`

Example:

```
str = "In 2015, I want to know how much does iPhone 6+ cost?"
```

 The numbers are `2015`, `6`

Sum is `2021`.

def sum_from_string(string):
    str_nr, all_nr, have_nr = '', [], False
    for item in string + '_':
        if '0' <= item <= '9':
            str_nr += item
            have_nr = True
        else:
            if have_nr:
                all_nr.append(int(str_nr))
                have_nr , str_nr = False, ''
    return sum(all_nr)


Solve in Python:
Given a rational number n

``` n >= 0, with denominator strictly positive```

- as a string (example: "2/3" in Ruby, Python, Clojure, JS, CS, Go)
- or as two strings (example: "2" "3" in Haskell, Java, CSharp, C++, Swift)
- or as a rational or decimal number (example: 3/4, 0.67 in R)
- or two integers (Fortran)

decompose
this number as a sum of rationals with numerators equal to one and without repetitions
(2/3 = 1/2 + 1/6 is correct but not 2/3 = 1/3 + 1/3, 1/3 is repeated).

The algorithm must be "greedy", so at each stage the new rational obtained in the decomposition must have a denominator as small as possible.
In this manner the sum of a few fractions in the decomposition gives a rather good approximation of the rational to decompose.

2/3 = 1/3 + 1/3 doesn't fit because of the repetition but also because the first 1/3 has a denominator bigger than the one in 1/2
in the decomposition 2/3 = 1/2 + 1/6.

### Example:
(You can see other examples in "Sample Tests:")
```
decompose("21/23") or "21" "23" or 21/23 should return

["1/2", "1/3", "1/13", "1/359", "1/644046"] in Ruby, Python, Clojure, JS, CS, Haskell, Go

"[1/2, 1/3, 1/13, 1/359, 1/644046]" in Java, CSharp, C++

"1/2,1/3,1/13,1/359,1/644046" in C, Swift, R
```

### Notes
1) The decomposition of 21/23 as
```
21/23 = 1/2 + 1/3 + 1/13 + 1/598 + 1/897
```
is exact but don't fulfill our requirement because 598 is bigger than 359.
Same for
```
21/23 = 1/2 + 1/3 + 1/23 + 1/46 + 1/69 (23 is bigger than 13)
or
21/23 = 1/2 + 1/3 + 1/15 + 1/110 + 1/253 (15 is bigger than 13).
```

2) The rational given to decompose could be greater than one or equal to one, in which case the first "fraction" will be an integer
(with an implicit denominator of 1).

3) If the numerator parses to zero the function "decompose" returns [] (or "".

4) The number could also be a decimal which can be expressed as a rational.

examples:

`0.6` in Ruby, Python, Clojure,JS, CS, Julia, Go

`"66" "100"` in Haskell, Java, CSharp, C++, C, Swift, Scala,...

from math import ceil
from fractions import Fraction as F
def decompose(n):
    f = F(n)
    ff = int(f)
    result = [str(ff)] if ff else []
    f -= ff
    while f>0:
        x = F(1,int(ceil(f**-1)))
        f -= x
        result.append(str(x))
    return result


Solve in Python:
Given a rectangle of size n x m, find the minimum number of integer-sided squares that tile the rectangle.

Example 1:

Input: n = 2, m = 3
Output: 3
Explanation: 3 squares are necessary to cover the rectangle.
2 (squares of 1x1)
1 (square of 2x2)
Example 2:

Input: n = 5, m = 8
Output: 5

Example 3:

Input: n = 11, m = 13
Output: 6

Constraints:

1 <= n <= 13
1 <= m <= 13

class Solution:
    def tilingRectangle(self, n: int, m: int) -> int:
        if m == n:
            return 1

        if n > m:
            m,n = n,m

        h_i = [0]*n

        visited = {}

        res = [m*n]

        def dfs(height, cnt):
            if cnt > res[0]:
                return

            status = tuple(height)
            if status in visited and visited[status] <= cnt:
                return
            visited[status] = cnt
            complete = True
            start_j = -1
            lowest_h = m+1

            for j in range(n):
                if height[j] < m:
                    complete = False
                if height[j] < lowest_h:
                    start_j = j
                    lowest_h = height[j]

            if complete:
                res[0] = min(res[0], cnt)
                return

            j = start_j
            while j < n and height[j] == lowest_h:
                j += 1
            max_l = min(j-start_j, m-lowest_h)

            for l in range(max_l, 0, -1):
                next_h = list(height)
                for k in range(l):
                    next_h[start_j+k] += l
                dfs(next_h, cnt+1)

        dfs(h_i, 0)
        return res[0]


Solve in Python:
Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.
Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a huge number, return this modulo 10^9 + 7.

Example 1:

Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
Output: 4
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.

Example 2:

Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
Output: 6
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.

Example 3:
Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
Output: 9

Constraints:

2 <= h, w <= 10^9
1 <= horizontalCuts.length < min(h, 10^5)
1 <= verticalCuts.length < min(w, 10^5)
1 <= horizontalCuts[i] < h
1 <= verticalCuts[i] < w
It is guaranteed that all elements in horizontalCuts are distinct.
It is guaranteed that all elements in verticalCuts are distinct.

class Solution:
    def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
        horizontalStrips = [0] + sorted(horizontalCuts) + [h]
        verticalStrips = [0] + sorted(verticalCuts) + [w]

        maxW = max([horizontalStrips[i + 1] - horizontalStrips[i] for i in range(len(horizontalStrips) - 1)])
        maxH = max([verticalStrips[i + 1] - verticalStrips[i] for i in range(len(verticalStrips) - 1)])

        return (maxW * maxH) % ((10 ** 9) + 7)


Solve in Python:
Given a rooted binary tree, return the lowest common ancestor of its deepest leaves.
Recall that:

The node of a binary tree is a leaf if and only if it has no children
The depth of the root of the tree is 0, and if the depth of a node is d, the depth of each of its children is d+1.
The lowest common ancestor of a set S of nodes is the node A with the largest depth such that every node in S is in the subtree with root A.

Example 1:
Input: root = [1,2,3]
Output: [1,2,3]
Explanation:
The deepest leaves are the nodes with values 2 and 3.
The lowest common ancestor of these leaves is the node with value 1.
The answer returned is a TreeNode object (not an array) with serialization "[1,2,3]".

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

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

Constraints:

The given tree will have between 1 and 1000 nodes.
Each node of the tree will have a distinct value between 1 and 1000.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
        def traverse(root, level):
            if root:
                if not root.left and not root.right:
                    return level, root
                else:
                    left_level, left_lca = traverse(root.left, level + 1)
                    right_level, right_lca = traverse(root.right, level + 1)
                    if left_level == right_level:
                        return left_level, root
                    elif left_level > right_level:
                        return left_level, left_lca
                    else:
                        return right_level, right_lca
            return float('-inf'), None

        deepest_level, lca = traverse(root, 0)
        return lca


Solve in Python:
Given a sentence text (A sentence is a string of space-separated words) in the following format:

First letter is in upper case.
Each word in text are separated by a single space.

Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.
Return the new text following the format shown above.

Example 1:
Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.

Example 2:
Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.

Example 3:
Input: text = "To be or not to be"
Output: "To be or to be not"

Constraints:

text begins with a capital letter and then contains lowercase letters and single space between words.
1 <= text.length <= 10^5

class Solution:
    def arrangeWords(self, text: str) -> str:
        if not text:
            return text

        words = text.lower().split(' ')

        words = sorted(words, key = lambda x: len(x))
        words[0] = words[0][0].upper() + words[0][1:]

        return ' '.join(words)


Solve in Python:
Given a sentence that consists of some words separated by a single space, and a searchWord.
You have to check if searchWord is a prefix of any word in sentence.
Return the index of the word in sentence where searchWord is a prefix of this word (1-indexed).
If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.
A prefix of a string S is any leading contiguous substring of S.

Example 1:
Input: sentence = "i love eating burger", searchWord = "burg"
Output: 4
Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.

Example 2:
Input: sentence = "this problem is an easy problem", searchWord = "pro"
Output: 2
Explanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.

Example 3:
Input: sentence = "i am tired", searchWord = "you"
Output: -1
Explanation: "you" is not a prefix of any word in the sentence.

Example 4:
Input: sentence = "i use triple pillow", searchWord = "pill"
Output: 4

Example 5:
Input: sentence = "hello from the other side", searchWord = "they"
Output: -1

Constraints:

1 <= sentence.length <= 100
1 <= searchWord.length <= 10
sentence consists of lowercase English letters and spaces.
searchWord consists of lowercase English letters.

class Solution:
    def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
        arr = sentence.split()
        print(len(arr))
        for i in range(len(arr)):
            print(arr[i][:len(searchWord)])
            if arr[i][:len(searchWord)] == searchWord:
                return i+1
        return -1


Solve in Python:
Given a sequence of items and a specific item in that sequence, return the item immediately following the item specified. If the item occurs more than once in a sequence, return the item after the first occurence. This should work for a sequence of any type.

When the item isn't present or nothing follows it, the function should return nil in Clojure and Elixir, Nothing in Haskell, undefined in JavaScript, None in Python.

```python
next_item([1, 2, 3, 4, 5, 6, 7], 3) # => 4
next_item(['Joe', 'Bob', 'Sally'], 'Bob') # => "Sally"
```

import itertools
def nth(iterable, n, default=None):
    return next(itertools.islice(iterable, n, None), default)

def next_item (xs,item):
     a=itertools.dropwhile(lambda x: x!=item,xs)
     return nth(a,1,None)


Solve in Python:
Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such
that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.

Note: n will be less than 15,000.

Example 1:

Input: [1, 2, 3, 4]

Output: False

Explanation: There is no 132 pattern in the sequence.

Example 2:

Input: [3, 1, 4, 2]

Output: True

Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

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

Output: True

Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].

class Solution:
     def find132pattern(self, nums):
         """
         :type nums: List[int]
         :rtype: bool
         """
         if len(nums) < 3: return False

         low = [float('inf')]
         high = [float('inf')]
         currlow, currhigh = nums[0], nums[0]
         for i in range(1, len(nums)):
             # print(nums[i])
             while nums[i] > high[-1]:
                 low.pop()
                 high.pop()
             if low[-1] < nums[i] < high[-1]:
                 return True
             if nums[i] == currlow or nums[i] == currhigh:
                 continue
             elif nums[i] < currlow:
                 low.append(currlow)
                 high.append(currhigh)
                 currlow, currhigh = nums[i], nums[i]
             elif nums[i] > currhigh:
                 currhigh = nums[i]
             else:
                 return True
             # print(currlow, currhigh)
             # print(low)
             # print(high)

         return False


Solve in Python:
Given a sequence of numbers, find the largest pair sum in the sequence.

For example
```
[10, 14, 2, 23, 19] -->  42 (= 23 + 19)
[99, 2, 2, 23, 19]  --> 122 (= 99 + 23)
```

Input sequence contains minimum two elements and every element is an integer.

def largest_pair_sum(numbers):
    return sorted(numbers)[-2]+max(numbers)


Solve in Python:
Given a set of  N  natural numbers 1,2,3........N and Q query.For each query you have to calculate the total number of subset in which  Ith.
number of set come at Kth postion.Elements of every subset should be in sorted order.
The answer could  be very large so you have to print answer modulo 1e9+7.

-----Input:-----
- The first line of input cotains a single integer T denoting the number of test cases.
- For every test case it contains two number N and Q.
- Next Q line contains two number I and K.

-----Output:-----
For each test case print required answer.

-----Constraints and Subtasks:-----
- 1<=T<=5
- 1<=N, K<=4000
- 1<=Q<=1000000
Subtask 3: 5 points
- 1<=T<=5
- 1<=N, K<=16
- 1<=Q<=1000
Subtask 1: 25 points
- T=1
- 1<=N, K<=4000
- 1<=Q<=100000
Subtask 2: 70 points
- Original Constraints.

-----Example:-----
Input:

1

3 3

1 2

2 1

3 2

Output:

0

2

2

-----Explanation:-----
For N=3

total subsets are:

{1}

{2}

{3}

{1,2}

{1,3}

{2,3}

{1,2,3}

Now we can see that for I=1 and K=2 there is no subset in which 1 come at 2nd position so the answer is Zero for that query.

For 2nd query I=2 and K=1 there are two subset i.e {2,3} and {2} in which 2 come at 1st position.

Same for 3rd querry there is two subset i.e{1,3} and {2,3}.

z=(10**9+7)

fact=[]
fact.append(1)
for i in range(1,4000):
 fact.append(i*fact[i-1]%z)

def factorialMod(n):
 ans=1
 for i in range(1,n+1):
  ans = ans * i % z
 return ans % z

def nCr(n,r):
 if r>n:
  return 0
 return fact[n]*pow(fact[r]*fact[n - r], z - 2, z) % z

for _ in range(0,int(input())):
 n,q = list(map(int,input().split()))
 for __ in range(0,q):
  i,k= list(map(int,input().split()))
  a = nCr(i-1,k-1)
  b = pow(2,n-i,z)
  print((a*b)% z)


Solve in Python:
Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size.
Each person may dislike some other people, and they should not go into the same group.
Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group.
Return true if and only if it is possible to split everyone into two groups in this way.

Example 1:
Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
Explanation: group1 [1,4], group2 [2,3]

Example 2:
Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false

Example 3:
Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
Output: false

Constraints:

1 <= N <= 2000
0 <= dislikes.length <= 10000
dislikes[i].length == 2
1 <= dislikes[i][j] <= N
dislikes[i][0] < dislikes[i][1]
There does not exist i != j for which dislikes[i] == dislikes[j].

from collections import defaultdict
class Solution:
    def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:

        graph = defaultdict(list)

        for _from, to in dislikes:
            graph[_from].append(to)
            graph[to].append(_from)

        colors = {}

        for i in range(1,N+1):
            if i not in colors and i <= len(graph)-1:
                stack = [(i, True)]

                while stack:
                    keys, color = stack.pop()
                    colors[keys] = color

                    for adj in graph[keys]:
                        if adj in colors:
                            if colors[adj] == colors[keys]:

                                return False
                        else:
                            stack.append((adj, not colors[keys]))
        return all([colors[i] != all(colors[j] for j in graph[i]) for i in colors if graph[i]!=[]])