I found an interesting problem on https://codeforces.com/problemset/problem/999/F:
There are $n$ players sitting at the card table. Each player has a favorite number. The favorite number of the $j$-th player is $f_j$.

There are $k \cdot n$ cards on the table. Each card contains a single integer: the $i$-th card contains number $c_i$. Also, you are given a sequence $h_1, h_2, \dots, h_k$. Its meaning will be explained below.

The players have to distribute all the cards in such a way that each of them will hold exactly $k$ cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals $h_t$ if the player holds $t$ cards containing his favorite number. If a player gets no cards with his favorite number (i.e., $t=0$), his joy level is $0$.

Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence $h_1, \dots, h_k$ is the same for all the players.

-----Input-----

The first line of input contains two integers $n$ and $k$ ($1 \le n \le 500, 1 \le k \le 10$) — the number of players and the number of cards each player will get.

The second line contains $k \cdot n$ integers $c_1, c_2, \dots, c_{k \cdot n}$ ($1 \le c_i \le 10^5$) — the numbers written on the cards.

The third line contains $n$ integers $f_1, f_2, \dots, f_n$ ($1 \le f_j \le 10^5$) — the favorite numbers of the players.

The fourth line contains $k$ integers $h_1, h_2, \dots, h_k$ ($1 \le h_t \le 10^5$), where $h_t$ is the joy level of a player if he gets exactly $t$ cards with his favorite number written on them. It is guaranteed that the condition $h_{t - 1} < h_t$ holds for each $t \in [2..k]$.

-----Output-----

Print one integer — the maximum possible total joy levels of the players among all possible card distributions.

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

Output
21

Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3

Output
0

-----Note-----

In the first example, one possible optimal card distribution is the following:  Player $1$ gets cards with...

I tried it in Python, but could not do it. Can you solve it?

from queue import Queue
import sys
import math
import os.path

# CONFIG
sys.setrecursionlimit(10**9)

# LOG
def log(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

# INPUT
def ni():
    return list(map(int, input().split()))

def nio(offset):
    return [int(x) + offset for x in input().split()]

def nia():
    return list(map(int, input().split()))

# CONVERT
def toString(aList, sep=" "):
    return sep.join(str(x) for x in aList)

def mapInvertIndex(aList):
    return {k: v for v, k in enumerate(aList)}

def countMap(arr):
    m = {}
    for x in arr:
        m[x] = m.get(x,0) + 1
    return m

def sortId(arr):
    return sorted(list(range(arr)), key=lambda k: arr[k])

# MAIN

n, k = ni()
c = nia()
f = nia()
h = nia()
h.insert(0,0)

cc = countMap(c)
cf = countMap(f)

n1 = n+1
k1 = k+1

nk1 = n*k+1
dp = [[0]*nk1 for _ in range(n1)]

for ni in range(1,n1):
    for ki in range(1,nk1):
        mficount = min(k,ki) + 1
        for kii in range(mficount):
            # log(ni,ki, kii, dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
            dp[ni][ki] = max(dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
    # log(dp[ni])

# log(n,k)
# log("c", cc)
# log("f", cf)
# log("h", h)
# log(dp)

res = 0

for fk,fv in list(cf.items()):
    # log(fk, fv, cc.get(fk,0))
    res += dp[fv][cc.get(fk,0)]

print(res)


I found an interesting problem on https://leetcode.com/problems/assign-cookies/:
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

Note:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.

Example 1:

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

Output: 1

Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.

Example 2:

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

Output: 2

Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def findContentChildren(self, g, s):
         """
         :type g: List[int]
         :type s: List[int]
         :rtype: int
         """
         g.sort(), s.sort()
         count = 0
         i = 0
         while count < len(g) and i < len(s):
             if s[i] >= g[count]:
                 count += 1
             i+=1
         return count


I found an interesting problem on https://leetcode.com/problems/combination-sum-ii/:
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

       All numbers (including target) will be positive integers.
       The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

I tried it in Python, but could not do it. Can you solve it?

 class Solution:
     def combinationSum2(self, candidates, target):
         """
         :type candidates: List[int]
         :type target: int
         :rtype: List[List[int]]
         """
         if len(candidates)==0:
             return []

         candidates = sorted(candidates)
         print(candidates)

         results = []

         def find(curr_comb, curr_sum, candidates): #靠副作用填充results
             #curr_comb = curr_comb[:]
             for i,cand in enumerate(candidates):

                 if (cand+curr_sum) < target:
                     new_curr_comb = curr_comb[:]
                     new_curr_comb.append(cand)
                     find(new_curr_comb, curr_sum+cand, candidates[i+1:])
                 elif (cand+curr_sum) == target:
                     new_curr_comb = curr_comb[:]
                     new_curr_comb.append(cand)
                     if new_curr_comb not in results:
                         results.append(new_curr_comb)
                     #print(curr_comb, curr_sum, cand, 'target:',target)
                 else:
                     break

         find([], 0, candidates)

         return results


I found an interesting problem on https://leetcode.com/problems/combination-sum-iii/:
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

       All numbers will be positive integers.
       The solution set must not contain duplicate combinations.

Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]

Example 2:

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def combinationSum3(self, k, n):
         """
         :type k: int
         :type n: int
         :rtype: List[List[int]]
         """
         to_return = []
         self.backtrack(to_return, [], k, n, 1)
         return to_return

     def backtrack(self, to_return, temp, k, n, start):
         total = sum(temp)

         if total > n:
             return
         if len(temp) == k and total == n:
             to_return.append(temp[:])
             return

         for i in range(start, 10):
             temp.append(i)
             self.backtrack(to_return, temp, k, n, i + 1)
             temp.pop()


I found an interesting problem on https://leetcode.com/problems/compare-version-numbers/:
Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Example 1:

Input: version1 = "0.1", version2 = "1.1"
Output: -1

Example 2:

Input: version1 = "1.0.1", version2 = "1"
Output: 1

Example 3:

Input: version1 = "7.5.2.4", version2 = "7.5.3"
Output: -1

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def compareVersion(self, version1, version2):
         """
         :type version1: str
         :type version2: str
         :rtype: int
         """

         if version1 == version2:
             return 0
         else:
             version1_nums = version1.split('.')
             version2_nums = version2.split('.')
             len1, len2 = len(version1_nums), len(version2_nums)
             end = max(len1, len2 )
             version1_nums.extend([0]*(end - len1))
             version2_nums.extend([0]*(end - len2))
             for i in range(end):
                 if int(version1_nums[i]) < int(version2_nums[i]):
                     return -1
                 elif int(version1_nums[i]) > int(version2_nums[i]):
                     return 1
             return 0


I found an interesting problem on https://leetcode.com/problems/course-schedule/:
There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 1:

Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
             To take course 1 you should have finished course 0. So it is possible.

Example 2:

Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
             To take course 1 you should have finished course 0, and to take course 0 you should
             also have finished course 1. So it is impossible.

Note:

       The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
       You may assume that there are no duplicate edges in the input prerequisites.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def canFinish(self, numCourses, prerequisites):
         """
         :type numCourses: int
         :type prerequisites: List[List[int]]
         :rtype: bool
         """
         from collections import deque
         class Vertex(object):
             def __init__(self):
                 self.inDegree = 0
                 self.visited = False
                 self.adjList = []
                 self.invAdjList = []
             def info(self):
                 print(self.adjList)
                 print(self.invAdjList, self.inDegree)
                 print(self.visited)
         #initialization
         vertices = []
         for _ in range(numCourses):
             vertices.append(Vertex())

         for i in prerequisites:
             pre = i[0]
             post = i[1]
             vertices[pre].adjList.append(post)
             vertices[post].inDegree += 1
             vertices[post].invAdjList.append(pre)

         #BFS
         q = deque()
         coursesLearned = []
         for i in range(numCourses):
             if vertices[i].inDegree == 0:
                 q.append(i)

         while q:
             course = q.popleft()
             coursesLearned.append(course)
             vertices[course].visited = True
             for c2 in vertices[course].adjList:
                 vertices[c2].inDegree -= 1
                 if vertices[c2].inDegree == 0:
                     q.append(c2)
         return len(coursesLearned) == numCourses


I found an interesting problem on https://leetcode.com/problems/dungeon-game/:
table.dungeon, .dungeon th, .dungeon td {
  border:3px solid black;
}

 .dungeon th, .dungeon td {
    text-align: center;
    height: 70px;
    width: 70px;
}

The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).

In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.

Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.

For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.

                       -2 (K)
                       -3
                       3

                       -5
                       -10
                       1

                       10
                       30
                       -5 (P)

Note:

       The knight's health has no upper bound.
       Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         num_rows = len(dungeon)
         num_cols = len(dungeon[0])
         INF = float('inf')
         for ri in range(num_rows - 1, -1, -1):
             for ci in range(num_cols - 1, -1, -1):
                 if ri == num_rows - 1 and ci == num_cols - 1:
                     need = -dungeon[ri][ci] + 1
                 else:
                     down = INF if ri == num_rows - 1 else dungeon[ri+1][ci]
                     right = INF if ci == num_cols - 1 else dungeon[ri][ci + 1]
                     need = min(down, right) - dungeon[ri][ci]
                 dungeon[ri][ci] = max(need, 1)
         return dungeon[0][0]


I found an interesting problem on https://leetcode.com/problems/generate-parentheses/:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def generateParenthesis(self, n):
         """
         :type n: int
         :rtype: List[str]
         """
         if n == 0:
             return [""]
         if n == 1:
             return ["()"]
         results = []

         for i in range(1, 2*n, 2):
             first = self.generateParenthesis(int((i-1)/2))
             second = self.generateParenthesis(int((2*n-i-1)/2))
             results += ["("+u+")"+v for u in first for v in second]
         return  results


I found an interesting problem on https://leetcode.com/problems/gray-code/:
The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

Example 1:

Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2

For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.

00 - 0
10 - 2
11 - 3
01 - 1

Example 2:

Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
             A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
             Therefore, for n = 0 the gray code sequence is [0].

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def grayCode(self, n):
         """
         :type n: int
         :rtype: List[int]
         """
         return [i >> 1 ^ i for i in range(1 << n)]


I found an interesting problem on https://leetcode.com/problems/insert-interval/:
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

I tried it in Python, but could not do it. Can you solve it?

# Definition for an interval.
 # class Interval:
 #     def __init__(self, s=0, e=0):
 #         self.start = s
 #         self.end = e

 class Solution:
     def insert(self, intervals, newInterval):
         """
         :type intervals: List[Interval]
         :type newInterval: Interval
         :rtype: List[Interval]
         """
         if not intervals:
             return [newInterval]
         v = []
         a =newInterval.start
         b =newInterval.end
         flag =0
         s=a
         e=b
         for i in intervals:
             if i.start<=a<=i.end:
                 s = i.start
             if i.start<=b<=i.end:
                 e = i.end
                 v.append(Interval(s,e))
                 flag =1
             if not flag and i.start >b:
                 v.append(Interval(s,e))
                 flag =1
             if i.end<a or i.start>b:
                 v.append(i)
         if not flag:
             v.append(Interval(s,e))
         return v


I found an interesting problem on https://leetcode.com/problems/letter-combinations-of-a-phone-number/:
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def letterCombinations(self, digits):
         """
         :type digits: str
         :rtype: List[str]
         """
         interpret_digit = {
             '1': '',
             '2': 'abc',
             '3': 'def',
             '4': 'ghi',
             '5': 'jkl',
             '6': 'mno',
             '7': 'pqrs',
             '8': 'tuv',
             '9': 'wxyz',
             '0': ' '}
         all_combinations = [''] if digits else []
         for digit in digits:
             current_combinations = list()
             for letter in interpret_digit[digit]:
                 for combination in all_combinations:
                     current_combinations.append(combination + letter)
             all_combinations = current_combinations
         return all_combinations


I found an interesting problem on https://leetcode.com/problems/linked-list-cycle/:
Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Constraints:

The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if head is None:
            return False

        slow, fast = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False


I found an interesting problem on https://leetcode.com/problems/longest-valid-parentheses/:
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

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

Constraints:

0 <= s.length <= 3 * 104
s[i] is '(', or ')'.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        memo ={}
        n =len(s)
        def dp(i):
            if i<=0:
                return 0
            if i in memo:
                return memo[i]
            if (s[i-1],s[i])==('(',')'):
                memo[i]=dp(i-2)+2
            elif (s[i-1],s[i])==(')',')') and i-dp(i-1)-1>=0 and s[i-dp(i-1)-1]=='(':
                memo[i]=dp(i-1)+2+dp(i-dp(i-1)-2)
            else:
                memo[i]=0
            return memo[i]
        ret = 0
        for i in range(n-1,0,-1):
            ret = max(ret, dp(i))
        return ret


I found an interesting problem on https://leetcode.com/problems/majority-element-ii/:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

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

Example 2:

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

I tried it in Python, but could not do it. Can you solve it?

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

         if nums == []:
             return []

         dct = {}
         for el in nums:
             if el in dct:
                 dct[el] += 1
             else:
                 dct[el] = 1

         fin = []
         for key in dct:
             if dct[key] > (len(nums) // 3):
                 fin.append(key)

         return fin


I found an interesting problem on https://leetcode.com/problems/make-array-strictly-increasing/:
Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing.
In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j].
If there is no way to make arr1 strictly increasing, return -1.

Example 1:
Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
Output: 1
Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].

Example 2:
Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1]
Output: 2
Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7].

Example 3:
Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
Output: -1
Explanation: You can't make arr1 strictly increasing.

Constraints:

1 <= arr1.length, arr2.length <= 2000
0 <= arr1[i], arr2[i] <= 10^9

I tried it in Python, but could not do it. Can you solve it?

import bisect
from functools import lru_cache

class Solution:
    def makeArrayIncreasing(self, A: List[int], B: List[int]) -> int:
        B = sorted(set(B))
        b2idx = {b: i for i, b in enumerate(B)}

        @lru_cache(None)
        def find_larger_value_in_B(val):
            if val >= B[-1]:
                return float('inf')
            if val in b2idx:
                return B[b2idx[val] + 1]
            return B[bisect.bisect_right(B, val)]

        @lru_cache(None)
        def min_last_value_given_operations(n, ops):
            if ops < 0:
                return float('inf')
            elif n == 0:
                return float('-inf')
            elif ops > n:
                return min_last_value_given_operations(n, n)

            skip_op = min_last_value_given_operations(n - 1, ops)
            if skip_op == float('inf'):
                return float('inf')
            return min(
                A[n - 1] if skip_op < A[n - 1] else float('inf'),
                find_larger_value_in_B(min_last_value_given_operations(n - 1, ops - 1)),
            )

        last_success = -1
        for ops in range(min(len(A), len(B)), -1, -1):
            if min_last_value_given_operations(len(A), ops) == float('inf'):
                break
            last_success = ops

        return last_success


I found an interesting problem on https://leetcode.com/problems/maximal-rectangle/:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

Example:

Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def maximalRectangle(self, matrix):
         """
         :type matrix: List[List[str]]
         :rtype: int
         """
         if not matrix:
             return 0
         m = len(matrix)
         n = len(matrix[0])
         ans = 0
         heights = [0]*(n+1)

         for i in range(m):
             for j in range(n):
                 heights[j] = heights[j] + 1 if matrix[i][j] == '1' else 0
             stack = [-1]
             for i in range(n + 1):
                 while heights[i] < heights[stack[-1]]:
                     h = heights[stack.pop()]
                     w = i - stack[-1] - 1
                     ans = max(ans, w*h)
                 stack.append(i)
         return ans


I found an interesting problem on https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/:
Given an array A of integers, we must modify the array in the following way: we choose an i and replace A[i] with -A[i], and we repeat this process K times in total.  (We may choose the same index i multiple times.)
Return the largest possible sum of the array after modifying it in this way.

Example 1:
Input: A = [4,2,3], K = 1
Output: 5
Explanation: Choose indices (1,) and A becomes [4,-2,3].

Example 2:
Input: A = [3,-1,0,2], K = 3
Output: 6
Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2].

Example 3:
Input: A = [2,-3,-1,5,-4], K = 2
Output: 13
Explanation: Choose indices (1, 4) and A becomes [2,3,-1,5,4].

Note:

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

I tried it in Python, but could not do it. Can you solve it?

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

        for i in range(K) :
            check = min(A)
            t = A.index(check)
            A[t] = -A[t]

        return sum(A)


I found an interesting problem on https://leetcode.com/problems/merge-intervals/:
Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considerred overlapping.

I tried it in Python, but could not do it. Can you solve it?

# Definition for an interval.
 # class Interval:
 #     def __init__(self, s=0, e=0):
 #         self.start = s
 #         self.end = e

 class Solution:
     def merge(self, intervals):
         si = sorted(intervals, key=lambda x: (x.start, x.end))
         cur = 1  # index of current tuple
         while cur < len(si):
             # check intersection of current and previous tuple
             # if end of previous is less than begin of current
             # there are the intersection, we should merge them
             # into the bigger interval
             if si[cur - 1].end >= si[cur].start:
                 # change end of the interval(tuple)
                 si[cur - 1] = Interval(si[cur - 1].start, max(si[cur - 1].end, si[cur].end))
                 # delete unnecessary interval(tuple)
                 del si[cur]
             # there are no intersection, go to the next tuple
             else:
                 cur += 1
         return si


I found an interesting problem on https://leetcode.com/problems/minimum-path-sum/:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Example:

Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def minPathSum(self, grid):
         """
         :type grid: List[List[int]]
         :rtype: int
         """
         height = len(grid)
         width = len(grid[0])
         step_num = (height + width) - 2
         for step in range(1, step_num+1):
             for row in range(height):
                 col = step - row
                 if 0 <= row < height and 0 <= col < width:
                     if not row:
                         grid[row][col] += grid[row][col-1]
                     elif not col:
                         grid[row][col] += grid[row-1][col]
                     else:
                         grid[row][col] += min(grid[row][col-1], grid[row-1][col])
         return grid[-1][-1]


I found an interesting problem on https://leetcode.com/problems/number-of-1-bits/:
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Note:

Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer -3.

Example 1:
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:
Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:
Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Constraints:

The input must be a binary string of length 32.

Follow up: If this function is called many times, how would you optimize it?

I tried it in Python, but could not do it. Can you solve it?

class Solution:
    def hammingWeight(self, n: int) -> int:

        onebits = 0
        while n > 0:
            if n & 1 == 1:
                onebits += 1
            n = n >> 1
        return onebits


I found an interesting problem on https://leetcode.com/problems/parsing-a-boolean-expression/:
Return the result of evaluating a given boolean expression, represented as a string.
An expression can either be:

"t", evaluating to True;
"f", evaluating to False;
"!(expr)", evaluating to the logical NOT of the inner expression expr;
"&(expr1,expr2,...)", evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ...;
"|(expr1,expr2,...)", evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ...

Example 1:
Input: expression = "!(f)"
Output: true

Example 2:
Input: expression = "|(f,t)"
Output: true

Example 3:
Input: expression = "&(t,f)"
Output: false

Example 4:
Input: expression = "|(&(t,f,t),!(t))"
Output: false

Constraints:

1 <= expression.length <= 20000
expression[i] consists of characters in {'(', ')', '&', '|', '!', 't', 'f', ','}.
expression is a valid expression representing a boolean, as given in the description.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
    def parseBoolExpr(self, expression: str) -> bool:
        stack = []
        for ch in expression:
            if ch == ',':
                continue
            if ch != ')':
                stack.append(ch)
            else:
                temp = ''
                while stack[-1] != '(':
                    temp += stack.pop()
                stack.pop()
                if stack[-1] == '&':
                    res = 't' if temp.count('f') == 0 else 'f'
                elif stack[-1] == '|':
                    res = 'f' if temp.count('t') == 0 else 't'
                else:
                    res = 't' if temp == 'f' else 'f'
                stack[-1] = res
        return True if stack[-1] == 't' else False


I found an interesting problem on https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/:
Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums.
Formally, we can partition the array if we can find indexes i+1 < j with (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1])

Example 1:
Input: A = [0,2,1,-6,6,-7,9,1,2,0,1]
Output: true
Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1

Example 2:
Input: A = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false

Example 3:
Input: A = [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4

Constraints:

3 <= A.length <= 50000
-10^4 <= A[i] <= 10^4

I tried it in Python, but could not do it. Can you solve it?

class Solution:
    def canThreePartsEqualSum(self, A: List[int]) -> bool:
        s = sum(A)
        if s%3 != 0:
            return False
        ps = s//3
        count = 0
        for x in A:
            ps -= x
            if not ps:
                ps = s//3
                count+=1
        return count >= 3


I found an interesting problem on https://leetcode.com/problems/pascals-triangle-ii/:
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

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

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def getRow(self, rowIndex):
         """
         :type rowIndex: int
         :rtype: List[int]
         """
         if rowIndex < 0:
             return list()
         if rowIndex == 0:
             return list([1])
         l = list([1])
         for i in range(1,rowIndex+1):
             pre_value = l[0] #1
             for j in range(1,i):#j = 3
                 temp = l[j] #1
                 l[j] = pre_value+l[j] #4
                 pre_value = temp #1
             l.append(1)
         return l


I found an interesting problem on https://leetcode.com/problems/pascals-triangle/:
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

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

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def generate(self, numRows):
         """
         :type numRows: int
         :rtype: List[List[int]]
         """
         A = []
         for i in range(numRows):
             A.append([1 for _ in range(i+1)])
             for j in range(1, i):
                 A[i][j] = A[i-1][j-1] + A[i-1][j]
         return A


I found an interesting problem on https://leetcode.com/problems/permutations-ii/:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

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

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def permuteUnique(self, nums):
         """
         :type nums: List[int]
         :rtype: List[List[int]]
         """
         res = []
         nums.sort()
         def swap(a, i, j):
             temp = a[i]
             a[i] = a[j]
             a[j] = temp

         def helper(index, path):
             if index == len(nums) - 1:
                 res.append(path.copy())
             for i in range(index, len(nums)):
                 if i != index and path[i] == path[index]:
                     continue
                 swap(path, index, i)
                 helper(index + 1, path.copy())

         helper(0, nums)
         return res


I found an interesting problem on https://leetcode.com/problems/permutations/:
Given a collection of distinct integers, return all possible permutations.

Example:

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

I tried it in Python, but could not do it. Can you solve it?

class Solution:

     def permute(self, nums):
         """
         :type nums: List[int]
         :rtype: List[List[int]]
         """

         res = []

         self.dfs(nums, [], res)

         return res

     def dfs(self, nums, path, res):
         if not nums:
             res.append(path)

         for i in range(len(nums)):
             self.dfs(nums[:i] + nums[i+1:], path+[nums[i]], res)


I found an interesting problem on https://leetcode.com/problems/plus-one/:
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def plusOne(self, digits):
         plus = 1
         for i in range(len(digits)-1, -1, -1):
             if digits[i] + plus > 9:
                 digits[i] = 0
                 plus = 1
             else:
                 digits[i] = digits[i] + plus
                 plus = 0
         if plus == 1:
             digits.insert(0, 1)
         return digits


I found an interesting problem on https://leetcode.com/problems/reverse-bits/:
Reverse bits of a given 32 bits unsigned integer.

Note:

Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.
Follow up:

If this function is called many times, how would you optimize it?

Example 1:

Input: n = 00000010100101000001111010011100
Output:    964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: n = 11111111111111111111111111111101
Output:   3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.

Constraints:

The input must be a binary string of length 32

I tried it in Python, but could not do it. Can you solve it?

class Solution:
    def reverseBits(self, n: int) -> int:
        a = bin(n)[2:]
        z = "0"*(32 - len(a)) + a
        t = z[::-1]
        return int(t, 2)


I found an interesting problem on https://leetcode.com/problems/reverse-words-in-a-string/:
Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:

Input: s = "  hello world  "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:

Input: s = "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Example 4:

Input: s = "  Bob    Loves  Alice   "
Output: "Alice Loves Bob"
Example 5:

Input: s = "Alice does not even like bob"
Output: "bob like even not does Alice"

Constraints:

1 <= s.length <= 104
s contains English letters (upper-case and lower-case), digits, and spaces ' '.
There is at least one word in s.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(s.split()[::-1])


I found an interesting problem on https://leetcode.com/problems/search-for-a-range/:
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def searchRange(self, nums, target):
         """
         :type nums: List[int]
         :type target: int
         :rtype: List[int]
         """
         s, e = -1, -1
         l, u = 0, len(nums)
         if not nums or target > nums[u-1] or target < nums[l]:
             return [s, e]
         m = (l+u)//2
         while u > l:
             if nums[m] > target:
                 u = m
                 m = (l+u)//2
             elif nums[m] < target:
                 l = m+1
                 m = (l+u)//2
             else:
                 s = e = m
                 while 0 < s and nums[s-1] == nums[s]:
                     s-=1
                 while e < len(nums)-1 and nums[e+1] == nums[e]:
                     e+=1
                 break
         return [s, e]


I found an interesting problem on https://leetcode.com/problems/spiral-matrix-ii/:
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

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

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def generateMatrix(self, n):
         """
         :type n: int
         :rtype: List[List[int]]
         """

         left = 0
         top = 0
         right = n - 1
         bottom = n - 1

         res = [[0 for _ in range(n)] for _ in range(n)]

         num = 1

         while left < right and top < bottom:
             for i in range(left, right):
                 res[top][i] = num
                 num += 1
             for i in range(top, bottom):
                 res[i][right] = num
                 num += 1
             for i in range(right, left, -1):
                 res[bottom][i] = num
                 num += 1
             for i in range(bottom, top, -1):
                 res[i][left] = num
                 num += 1
             left += 1
             right -= 1
             top += 1
             bottom -= 1
         if left == right and top == bottom:
             res[left][top] = num

         return res


I found an interesting problem on https://leetcode.com/problems/spiral-matrix/:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

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

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def spiralOrder(self, matrix):
         """
         :type matrix: List[List[int]]
         :rtype: List[int]
         """
         if not matrix:
             return matrix
         res = []
         row = len(matrix)
         col = len(matrix[0])
         left = 0
         right = col - 1
         down = row - 1
         up = 0
         direction = 0
         while True:
             if direction == 0:
                 for i in range(left, right + 1):
                     res.append(matrix[up][i])
                 up += 1
             if direction == 1:
                 for i in range(up, down + 1):
                     res.append(matrix[i][right])
                 right -= 1
             if direction == 2:
                 for i in reversed(range(left, right+1)):
                     res.append(matrix[down][i])
                 down -= 1
             if direction == 3:
                 for i in reversed(range(up, down + 1)):
                     res.append(matrix[i][left])
                 left += 1
             direction = (direction + 1) % 4
             if left > right or up > down:
                 return res


I found an interesting problem on https://leetcode.com/problems/subsets-ii/:
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

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

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def subsetsWithDup(self, nums):
         """
         :type nums: List[int]
         :rtype: List[List[int]]
         """
         result = []
         res = []

         self.df(nums, 0, result, res)
         return res

     def df(self, nums, idx, result, res):
         if idx > len(nums):
             return
         if result not in res:
             res.append(result)

         for i in range(idx, len(nums)):
             self.df(nums, i+1, sorted(result + [nums[i]]), res)


I found an interesting problem on https://leetcode.com/problems/subsets/:
Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

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

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def subsets(self, nums):
         """
         :type nums: List[int]
         :rtype: List[List[int]]
         """
         subsets = [[]]
         for v in nums:
             extra = []
             for s in subsets:
                 extra.append(s+[v])
             subsets += extra
         return subsets


I found an interesting problem on https://leetcode.com/problems/substring-with-concatenation-of-all-words/:
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.

Example 2:

Input:
s = "wordgoodstudentgoodword",
words = ["word","student"]
Output: []

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def findSubstring(self, s, words):
         """
         :type s: str
         :type words: List[str]
         :rtype: List[int]
         """
         lword = len(words[0])
         n = len(words)
         lwords = n * lword
         if not s or not lwords:
             return

         res = []
         dic = {}
         for key in words:
             dic[key] = [0, 0]
         for key in words:
             dic[key][1] += 1
         for k in range(lword):
             i = k
             while i <= len(s)-lwords:
                 if not s[i:i+lword] in list(dic.keys()):
                     i += lword
                     continue
                 j = 0
                 start = i
                 while s[i:i+lword] in list(dic.keys()) and i<len(s):
                     key = s[i:i+lword]
                     dic[key][0] += 1
                     while dic[key][0] > dic[key][1]:
                         dic[s[start:start+lword]][0] -= 1
                         j -= 1
                         start += lword
                     j += 1
                     i += lword
                     if j==n:
                         res.append(start)
                         dic[s[start:start+lword]][0] -= 1
                         j -= 1
                         start += lword
                 for key in list(dic.keys()):
                     dic[key][0] = 0
         return res


I found an interesting problem on https://leetcode.com/problems/the-skyline-problem/:
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .

The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.

For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].

Notes:

       The number of buildings in any input list is guaranteed to be in the range [0, 10000].
       The input list is already sorted in ascending order by the left x position Li.
       The output list must be sorted by the x position.
       There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...]

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def getSkyline(self, buildings):
         """
         :type buildings: List[List[int]]
         :rtype: List[List[int]]
         """
         edges = []
         for left, right, height in buildings:
             edges.append((left, -height, right))
             edges.append((right, 0, None))

         edges.sort()
         pq = [(0, float('inf'))]
         skyline = [(0, 0)]
         print(edges)
         for left, negheight, right in edges:
             while pq[0][1] <= left:
                 heapq.heappop(pq)
             if negheight:
                 heapq.heappush(pq, (negheight, right))
             if skyline[-1][1] != -pq[0][0]:
                 skyline.append([left, -pq[0][0]])

         return skyline[1:]


I found an interesting problem on https://leetcode.com/problems/triangle/:
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:

Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

I tried it in Python, but could not do it. Can you solve it?

class Solution:
 	def minimumTotal(self, triangle):
 		self._min_cache = {}
 		for i in reversed(list(range(len(triangle)))):
 			for j in reversed(list(range(len(triangle[i])))):
 				self.get_minimum_sum(triangle, i, j)
 		return self.get_minimum_sum(triangle, 0, 0)

 	def get_minimum_sum(self, triangle, level_i, item_j):
 		if ((level_i, item_j) in self._min_cache):
 			return self._min_cache[(level_i, item_j)]
 		if level_i < 0 or level_i >= len(triangle):
 			return 0
 		level = triangle[level_i]

 		if item_j<0 or item_j>len(level):
 			return 0

 		item = level[item_j]

 		min_v = item+min(self.get_minimum_sum(triangle,level_i+1,item_j),
 					    self.get_minimum_sum(triangle,level_i+1,item_j+1))
 		self._min_cache[(level_i, item_j)] = min_v

 		return min_v


I found an interesting problem on https://leetcode.com/problems/two-sum/:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def twoSum(self, nums, target):
         '''
         type nums:array
         type target:integer
         rtype :List
         '''
         d = {}
         for i, num in enumerate(nums):
             if target - num in d:
                 return[d[target - num], i]
             d[num] = i


I found an interesting problem on https://leetcode.com/problems/unique-paths-ii/:
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

Note: m and n will be at most 100.

Example 1:

Input:
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

I tried it in Python, but could not do it. Can you solve it?

class Solution:
     def uniquePathsWithObstacles(self, obstacleGrid):
         """
         :type obstacleGrid: List[List[int]]
         :rtype: int
         """
         m = len(obstacleGrid)
         n = len(obstacleGrid[0])
         mat = [[0] * n for _ in range(m)]
         if not obstacleGrid[0][0]:
             mat[0][0] = 1
         for row in range(m):
             for col in range(n):
                 if col == 0 and row == 0:
                     mat[row][col] = obstacleGrid[row][col] * -1 + 1
                 elif obstacleGrid[row][col] == 1:
                     mat[row][col] == 0
                 else:
                     mat[row][col] = mat[row - 1][col] + mat[row][col - 1]
         return mat[m - 1][n - 1]


I found an interesting problem on https://open.kattis.com/problems/contacttracing:
A deadly virus is sweeping across the globe! You are part of an elite group of programmers tasked with tracking the spread of the virus. You have been given the timestamps of people entering and exiting a room. Now your job is to determine how the virus will spread. Hurry up, time is of the essence!

There are $N$ people in this scenario, numbered from $1$ to $N$. Every day, the $i$th person enters and exits the room at time $s_ i$ and $t_ i$ respectively. At the beginning of the $1$st day, there are $C$ people infected with the virus, whose indices will be given in the input.

When an infected person comes into contact with an uninfected person, the uninfected person will become infected at the start of the next day. Hence, they can only start spreading the infection from the next day onward. An infected person will always remain infected.

Two people are in contact with each other if they are in the room at the same time. This includes cases where one person leaves and another person enters at the exact same time. Also, if a person enters and exits the room at the same time ($s_ i$ = $t_ i$), they are considered to be in contact with everyone in the room at that time. Due to safe-distancing requirements, no more than $50$ people can be in the room at one time.

Your job is to print the indices of the people who will be infected after $D$ days. This includes people who came into contact with an infected person on the $D$th day but will only become infected at the start of the $D+1$th day.

Given below are the visualizations for sample inputs $1$ and $2$.

Note: In sample $2$, person $2$ and $4$ will get infected after day $1$. They can only spread the infection to person $3$ and $5$ on day $2$. For $D = 1$, the infected people are $1$, $2$, $4$. If $D$ had been $2$, person $3$ and $5$ would have also been infected.

-----Input-----
The first line contains two integers, $1 \le N \le 20000$, and $1 \le D \le 50000$, the number of people and number of days respectively.

The second line contains an integer $1...

I tried it in Python, but could not do it. Can you solve it?

a=int(input())
b=list(map(int,input().split(" ")))
if b.count(1)>=1 and b.count(2)>=1:
    b.remove(1)
    b.remove(2)
    b.sort(reverse=True)
    b.insert(0,2)
    b.insert(1,1)
    print (*b,sep=" ")
else:
    print (*b,sep=" ")


I found an interesting problem on https://www.codechef.com/BGS12020/problems/BSPSTR:
Teddy and Freddy are two friends. Teddy has a pile of strings of size $N$. Each string $Si$ in the pile has length less or equal to $100$ ($len(Si) \leq 100$).
Teddy and Freddy like playing with strings. Teddy gives Freddy a string $B$ of size $M$.
Teddy and Freddy like playing with strings. Teddy gives Freddy a string $B$ of size $M$.
He asks Freddy to find the count of the unique substrings of $B$ present in pile of strings of size $N$.
Freddy is busy with the some task, so he asks for your help.Help Freddy by giving the unique substrings of $B$ present in pile of strings of size $N$.
Note: The substrings having same permutation of characters are considered same.

-----Input:-----
- First line will contain $N$, number of strings. Then the strings follow.
- Next $N$ lines will contain a string
- $N+2$ line contains the $M$ - length of string B
- Following line contains the string B

-----Output:-----
For each testcase, output in a single line number of unique strings of B.

-----Constraints-----
- $1 \leq N \leq 100$
- $2 \leq len(Si) \leq 100$
- $2 \leq M \leq 100$

-----Sample Input:-----
4
a
abc
abcd
abcde
5
aaaaa

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

-----Sample Input:-----
4
a
aa
aaa
aaaa
5
aaaaa

-----Sample Output:-----
4

-----EXPLANATION:-----
TestCase 1: Only substring of $aaaaa$ that is present in the pile of strings is $a$. So the answer is 1

I tried it in Python, but could not do it. Can you solve it?

has = [input() for _ in range(int(input()))]
lens = int(input())
B = input()
cnt = 0
alls = set()
for i in range(lens):
 for j in range(i, lens):
  curr = B[i:j+1]
  if curr in alls:continue
  cnt += curr in has
  alls.add(curr)
print(cnt)


I found an interesting problem on https://www.codechef.com/BTCD2012/problems/KMIN:
Jack and Jill got into a serious fight. Jack didn't not belive Jill when she said that her memory was far better than the others. He asked her to prove it as follows :-

-  Jack would dictate a long list of numbers to her. At any point after he has dictated  at least "k" numbers, he can ask her what is the k-th minimum number (the k-th number if the numbers are arranged in increasing order) in the list so far.
-  She succeeds in proving herself if she can tell the k-th minimum number every time he asks.
-  The number of queries (dictate a new number or ask her the k-th minimum of the numbers given till then) has to be pre-decided before he starts asking.

Jill succeeded in proving herself by convincing Jack quite a few times. Now, Jill remembered that Jack had claimed that he was good at programming. It's her turn to ask him to prove his skill. Jack doesn't want to lose to her and comes to you for help. He asks you to make the program for him.

-----Input-----
Jill has agreed to let Jack decide the format of the input and here's what he has decided. First line of the input contains n, the number of queries. Next line contains k. Next n lines contain a query each, say q. If  q >= 0  then the number is being 'dictated' to the system and needs to be remembered. If q = -1, then your program should return the k-th minimum number presented so far . It is given that 'q' can be -1 only if at least k numbers have already been given.

-----Output-----
For every q = -1, you have to output the k-th minimum number given as input so far (not counting -1 as an input)

-----Example-----
Input1:
6
2
3
2
-1
-1
1
-1

Output1:
3
3
2

Input2:
10
5
3
6
1
4
2
9
3
1
0
-1

Output2:
3

I tried it in Python, but could not do it. Can you solve it?

import operator
N = eval(input());
N = int(N);
k = eval(input());
k = int(k);
list= [];
for i in range(k):
 a=eval(input());
 a=int(a);
 list.append(a);
list.sort()
for i in range(k,N):
 a=eval(input())
 a=int(a)
 if(a>=0):
  if(a<list[k-1]):
    list.pop()
    list.append(a)
    list.sort()
 else:
    print(list[k-1])


I found an interesting problem on https://www.codechef.com/BTCH2020/problems/CHEFKIT:
Chef loves cooking. Also, he is very hygienic. Hence, Chef grows his own vegetables in his mini kitchen garden. He has $M$ lanes in which he grows vegetables. The $ith$  lane has $Ai$ vegetables growing in it.

Vegetables in $ith$ lane become edible on day $Di$ and day $Di+1$(that is, the vegetables are edible only on days $Di$ and $Di+1$,where $Di+1$ is the next day of $Di$).   For Example, if $Di$ is 2, then vegetable is edible on day 2 and day 3 only.   If not collected in these days, they cannot be cooked.

Also, Chef is a lone worker. Hence, with respect to his capacity, he can collect only $V$ vegetables per day.
But, Chef is a hard worker, and is willing to work every day, starting from day 1.

Chef is busy sowing the seeds. So, he assigns you the task to find out the maximum number of vegetables he can collect, provided that he collects optimally.

-----Input:-----
- First line contains of 2 space separated integers $M$ and $V$, number of lanes and capacity of Chef.
- Next $M$ lines follow
- Each $ith$ line contains 2 space separated integers, $Di$ and $Ai$, the day when the vegetable of the $ith$ lane become edible and the number of vegetables in that lane.

-----Output:-----
For each testcase, output in a single integer, that is the maximum number of vegetables that can be cooked

-----Constraints-----
- $1 \leq M,V \leq 3000$
- $1 \leq Di,Ai \leq 3000$

-----Subtasks-----
- 20 points : $1 \leq M \leq 100$
- 30 points : $1 \leq M \leq 1000$
- 50 points : $Original  Constraints$

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

-----Sample Output 1:-----
11

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

-----Sample Output 2:-----
9

-----EXPLANATION:-----
In the first sample, in order to obtain the optimal answer, you should do the following:-
- On day 1, collect 4 vegetables from lane 1
- On day 2, collect 2 vegetables from lane 1 and 2 vegetables from lane 2
- On day 3, collect 3 vegetables from lane 2
In the first sample, in order to obtain the optimal answer, you should do the following:-
- On day 1, collect...

I tried it in Python, but could not do it. Can you solve it?

from sys import stdin,stdout
input=stdin.readline
print=stdout.write
m,v=map(int,input().split())
a=[]
t=0
for i in range(m):
 x,y=map(int,input().split())
 a.append([x,y])
a.sort()
d=0
re=0
equip=0
for x,y in a:
 if d<x:
  d=x
  if y<=v:
   equip+=y
   re=v-y
   if y==v:
    d+=1
    re=0
  elif y>v and y<2*v:
   equip+=y
   d+=1
   re=2*v-y
  else:
   equip+=2*v
   d+=2
   re=0
 elif d==x:
  if re==0:
   if y<=v:
    equip+=y
    re=v-y
    if y==v:
     d+=1
     re=0
   elif y>=v and y<2*v:
    equip+=y
    d+=1
    re=2*v-y
   else:
    equip+=2*v
    d+=2
    re=0
  else:
   if y<re:
    equip+=y
    re-=y
   elif y==re:
    equip+=y
    re=0
    d+=1
   elif y>re:
    d+=1
    equip+=re
    y-=re
    if y<v:
     equip+=y
     re=v-y
    elif y>=v:
     equip+=v
     re=0
     d+=1
 elif d==x+1:
  if re==0:
   if y<v:
    equip+=y
    re=v-y
   elif y>=v:
    equip+=v
    re=0
    d+=1
  else:
   if y<=re:
    equip+=y
    re-=y
    if re==0:d+=1
   elif y>re:
    equip+=re
    re=0
    d+=1
print(str(equip))


I found an interesting problem on https://www.codechef.com/CDST2016/problems/CDS1:
Ram has invented a magic sequence. Each element of the sequence is defined by the same recursive definition - take some linear combination of previous elements (whose coefficients are fixed) and add to them the n-th powers of some integers. Formally: Xn = Xn-1*a1 + ... + Xn-i*ai + b1*d1^n + ... + bj*dj^n, for some integer constants p,q,a1,...,ap,b1,..., bq,d1,..., dq. Of course, as the values can quickly grow, he computed them modulo a fixed value: 10^6. He wrote many consecutive values of the sequence, but then he lost most of his work. All he has now, is 10 consecutive values taken from somewhere in the sequence (he doesn't know at what n they begin), and the recursive rule. And he would like to recover the sequence, or at the very least, to be able to write the next 10 values taken from the sequence.

-----Input-----
First, two integers, 0<=p<=4, 0<=q<=4. Then come the descriptions of the coefficients, -100 <= a1,...,ap,b1,..., bq,d1,..., dq <= 100. Then, the following 10 integers are Xn,X(n+1),...,X(n+9) for some unknown n.

-----Output-----
10 integers - X(n+10),X(n+11),...,X(n+19)

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

1 1

1

1

1

11 12 13 14 15 16 17 18 19 20

Output:

21 22 23 24 25 26 27 28 29 30

Input:

1 1

1

1

2

1 3 7 15 31 63 127 255 511 1023

Output:

2047 4095 8191 16383 32767 65535 131071 262143 524287 48575

Input:

2 0

1 1

1 1 2 3 5 8 13 21 34 55

Output:

89 144 233 377 610 987 1597 2584 4181 6765

I tried it in Python, but could not do it. Can you solve it?

p,q=list(map(int,input().split()))
if(p!=0):
 a=list(map(int,input().split()))
if(q!=0):
 b=list(map(int,input().split()))
 d=list(map(int,input().split()))
s=list(map(int,input().split()))
for i in range(10):
 c=0
 for j in range(1,p+1):
  c+=s[len(s)-j]*a[j-1]
 for k in range(0,q):
  c+=b[k]*d[k]**(i+10)
 s.append(c%10**6)
s=list([str(x) for x in s])
print(' '.join(s[10:21]))


I found an interesting problem on https://www.codechef.com/CHLG2020/problems/PATTE1:
Rashmi loves the festival of Diwali as she gets to spend time with family and enjoy the festival. Before she can fully enjoy the festival she needs to complete the homework assigned by her teacher. Since Rashmi is smart , she has solved all the problems but is struck at one tricky pattern question.
Your Task is to help Rashmi solve the problem so that she can enjoy the festival with her family.
The Problem she is struck on is defined like this:
Given an integer N you need to generate the pattern according to following example:
Example:

Input:

3
Output:

1 4 10

2 5 11

4 10 22

3 6 12

-----Input:-----
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The next line of each contains T space separated integers N.

-----Output:-----
For each N print the required pattern.

-----Constraints:-----
$1 \leq T \leq 10^5$
$1 \leq N \leq 30$

-----Sample Input:-----
2
3 5

-----Sample Output:-----
1 4 10

2 5 11

4 10 22

3 6 12

1 4 10 22 46

2 5 11 23 47

4 10 22 46 94

3 6 12 24 48

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

4

-----Sample Output:-----
1 4 10 22

2 5 11 23

4 10 22 46

3 6 12 24

I tried it in Python, but could not do it. Can you solve it?

l=[1]
for i in range(32):
    l.append(l[-1]+(3*(2**i)))
m=[]
for i in range(33):
    m.append(l[i]+1)

n=[]
for i in range(33):
    n.append(m[i]*2)

o=[]
for i in range(33):
    o.append(m[i]+1)

t=int(input())
inp=[int(i) for i in input().split()]
for j in range(t):
    y=inp[j]
    for i in range(y):
        print(l[i],end=" ")
    print()
    for i in range(y):
        print(m[i],end=" ")
    print()
    for i in range(y):
        print(n[i],end=" ")
    print()
    for i in range(y):
        print(o[i],end=" ")
    print()
    # cook your dish here


I found an interesting problem on https://www.codechef.com/COOK19/problems/DAILY:
A daily train consists of N cars. Let's consider one particular car. It has 54 places numbered consecutively from 1 to 54, some of which are already booked and some are still free. The places are numbered in the following fashion:

The car is separated into 9 compartments of 6 places each, as shown in the picture. So, the 1st compartment consists of places 1, 2, 3, 4, 53 and 54, the 2nd compartment consists of places 5, 6, 7, 8, 51 and 52, and so on.

A group of X friends wants to buy tickets for free places, all of which are in one compartment (it's much funnier to travel together). You are given the information about free and booked places in each of the N cars. Find the number of ways to sell the friends exactly X tickets in one compartment (note that the order in which the tickets are sold doesn't matter).

-----Input-----
The first line of the input contains two integers X and N (1 ≤ X ≤ 6, 1 ≤ N ≤ 10) separated by a single space. Each of the following N lines contains the information about one car which is a string of length 54 consisting of '0' and '1'. The i-th character (numbered from 1) is '0' if place i in the corresponding car is free, and is '1' if place i is already booked.

-----Output-----
Output just one integer -- the requested number of ways.

-----Example-----
Input:
1 3
100101110000001011000001111110010011110010010111000101
001010000000101111100000000000000111101010101111111010
011110011110000001010100101110001011111010001001111010

Output:
85

Input:
6 3
100101110000001011000001111110010011110010010111000101
001010000000101111100000000000000111101010101111111010
011110011110000001010100101110001011111010001001111010

Output:
1

Input:
3 2
000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000

Output:
360

Explanation:
In the first test case, any of the free places can be sold. In the second test case, the only free compartment in the train is compartment 3 in the first car (places 9, 10, 11, 12, 49 and 50 are all free). In the third...

I tried it in Python, but could not do it. Can you solve it?

x,n=list(map(int,input().split()))
ways=0
def permute(n,k):
 way=1
 if n==k:
  return 1

 for i in range(n-k+1,n+1):
  way*=i

 return way

def combine(n,k):
 if n==k:
  return 1
 p=factorial(k)
 way=permute(n,k)
 return way/p
def factorial(n):
 x=1
 for i in range(2,n+1):
  x*=i

 return x

for _ in range(n):
 cart=input().strip()
 compartment=[6 for _ in range(9)]
 num=0
 for i in range(36):
  if cart[i]=='1':
   compartment[num]-=1

  if (i+1)%4==0:
   num+=1
 num-=1
 for i in range(36,54):
  if cart[i]=='1':
   compartment[num]-=1

  if (i+1)%2==0:
   num-=1

 for seat in compartment:
  if seat>=x:
   ways+=combine(seat,x)

print(ways)


I found an interesting problem on https://www.codechef.com/COSQ2020/problems/PRGOTHAM:
Gotham City is again under attack. This time Joker has given an open challenge to solve the following problem in order to save Gotham. Help Batman in protecting Gotham by solving the problem.
You are given two strings A and B composed of lowercase letters of Latin alphabet. B can be obtained by removing some characters from A(including 0). You are given an array containing any random permutation of numbers $1$ to $N$, where $N$ is the length of the string A. You have to remove the letters of A in the given order of indices. Note that after removing one letter, the indices of other letters do not change. Return the maximum number of indices you can remove in the given order such that B is still obtainable from A.

-----Input:-----
- First two lines contains the strings A and B respectively.
- The third line contains a random permutation of numbers from $1$ to $N$ representing some order of indices of string A.

-----Output:-----
Print a single number denoting the maximum number of indices you can remove in the given order such that B is still obtainable from A.

-----Constraints-----
- $1 \leq |B| \leq |A| \leq 200000$

-----Sample Input #1:-----
xxyxxy
xyy
1 5 4 6 3 2

-----Sample Output #1:-----
3

-----Sample Input #2:-----
jphokenixr
joker
2 9 3 7 8 1 6 5 4 10

-----Sample Output #2:-----
5

-----EXPLANATION:-----
For the first example removing characters in order,
xxyxxy => _xyxxy => _xyx_y => _xy__y.
If we remove any other element now then we can not obtain 'xxy'. So the ans is 3.

I tried it in Python, but could not do it. Can you solve it?

try:
    A,B,data = list(input()),input(),list(map(int,input().split()))
    print(len(A)-len(B))
except:
    pass


I found an interesting problem on https://www.codechef.com/CSTR2020/problems/SUBTRACT:
Ayush is learning how to decrease a number by one, but he does it wrong with a number consisting of two or more digits. Ayush subtracts one from a number by the following algorithm:
if the last digit of the number is non-zero, he decreases the number by one.
if the last digit of the number is zero, he divides the number by 10.
You are given an integer number n
Ayush will subtract one from it k times. Your task is to print the result after all k subtractions.
It is guaranteed that the result will be a positive integer number.
Input
The first line of the input contains two integers n and k (2 ≤ n ≤ 10^9, 1 ≤ k ≤ 50) -- the number from which Ayush will subtract and the number of subtractions respectively.
Output
Print one integer number — the result of the decreasing n by one k times.
It is guaranteed that the result will be a positive integer number.
EXAMPLE
Sample Input 1
512 4
Sample Output 1
50
Sample Input 2
1000000000 9
Sample Output 2
1

I tried it in Python, but could not do it. Can you solve it?

n,k=map(int,input().split())
for i in range(k):
	if(n%10==0):
		n//=10
	else:
		n-=1
print(n)


I found an interesting problem on https://www.codechef.com/CZEN2020/problems/ALCHH:
$Alien$ likes to give challenges to $Codezen$ team to check their implementation ability, this time he has given a string $S$ and asked to find out whether the given string is a $GOOD$ string or not.
According to the challenge $GOOD$ String is a string that has at least $3$ consecutive vowels and at least $5$ different consonants.
For example $ACQUAINTANCES$  is a $ GOOD $String ,as it contains $3$ consecutive vowels  $UAI$ and $5$ different consonants $ {C, Q, N, T, S} $
but  $ACQUAINT $ is  not ,as it contain $3$ vowels but have only $ 4$ different consonants
${C, Q, N, T}$.

-----Input:-----
A string input is given from Standard Input that consists of only capital letters.

-----Output:-----
Output  a single line  that  is either $GOOD$  (if string is a good string ) or $-1$(if string is not good).

-----Constraints-----
- $8 \leq S \leq 1000$

-----Sample Input 1:-----
AMBITIOUSNESS

-----Sample Output 2:-----
GOOD

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

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

I tried it in Python, but could not do it. Can you solve it?

s="AEIOU"
v=0
c=0
a=3
n=input()
if len(list(set(n)))<8:
 print(-1)
else:
 for i in range(0,len(n)):
  if i!=len(n)-2:
   k=n[i:i+3]
   if k in s:
    c=c+1
    break
 for y in set(n):
  if y not in s:
   v=v+1
 if v>=5 and c>0:
  print("GOOD")
 else:
  print(-1)


I found an interesting problem on https://www.codechef.com/CZEN2020/problems/RGSPY:
$Riggi$   is a spy of $KBI$ and he is on a secret mission, he is spying an Underworld Don  $Anit$.
$Riggi$  is spying him since 5 years and he is not able to find  any evidence against $Anit$.
$KBI$ told $Riggi$ they will send him a code string in a special format that will inform him whether he  has continue or return back from mission.
According to $KBI$  firstly  he  has to find what is the original string and then he has to check string is palindrome or not .
If its a palindrome then he has to leave the mission and return back else continue spying $Anit$.
Rules to find original string :
1:-If in Code string any integer(N) followed by a string of alphabets that starts with '+' and  ends with '-' then he has to repeat that string N times  , like 3+acg- = acgacgacg.
2:-If there is no integer present before string then print the string is repeated 1 time.
like bc=bc.
Example of conversion from  Code string  to original string  : 2+ac-3+kb-j=acackbkbkbj

-----Input:-----
- Code string $S$ is taken as input  .

-----Output:-----
- Print  string $Continue$ if code string $S$ is not a palindrome else print $Return$ .

-----Constraints-----
- $1 \leq S \leq 1000$
- $1 \leq N \leq 1000$

-----Sample Input 1:-----
3+xy-bb3+yx-

-----Sample Output 1:-----
Return

-----Sample Input 2:-----
3+xy-bb3+xy-

-----Sample Output 2:-----
Continue

-----EXPLANATION:-----
Sample 1:- original string will be xyxyxybbyxyxyx which is  a palindrome hence print $Return$.
Sample 2:- original string will be xyxyxybbxyxyxy which is not a palindrome hence print
$Continue$.

I tried it in Python, but could not do it. Can you solve it?

# cook your dish here
s=input()
i=0
l=len(s)
orig=''
st=[]
flag=False
while(i<l):
    if(s[i].isdigit()):
        num=int(s[i])

    elif(s[i].isalpha()):
        if(flag==False):
            orig+=s[i]
        else:st.append(s[i])
    elif(s[i]=='+'):
        flag=True
        st.clear()

    elif(s[i]=='-'):
        orig+=("".join(st))*num
        flag=False

    i+=1
if(orig==orig[::-1]):
    print("Return")
else:
    print("Continue")


I found an interesting problem on https://www.codechef.com/FULU2020/problems/ONE23:
Guys don’t misinterpret this it is three only.

-----Input:-----
- First line will contain an integer $X$.

-----Output:-----
A single line containing the answer to the problem modulo 1000000007.

-----Constraints-----
- $1 \leq X < 10^5$

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

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

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

-----Sample Output 2:-----
14

I tried it in Python, but could not do it. Can you solve it?

# your code goes here
n=int(input())
s=0
for i in range(1,4):
 s+=pow(n,i)
print(s%1000000007)


I found an interesting problem on https://www.codechef.com/FULU2020/problems/SIFTING:
A greek once sifted some numbers. And it did something wonderful!

-----Input:-----
- First line will contain an integer $N$

-----Output:-----
Output in a single line answer to the problem.

-----Constraints-----
- $1 \leq N \leq 10^5$

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

-----Sample Output 1:-----
4

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

-----Sample Output 2:-----
8

I tried it in Python, but could not do it. Can you solve it?

# cook your dish here
a=int(input())
b=0
for x in range(1, a+1):
    c=0
    for y in range(1,x):
        if x%y==0:
            c=c+1
    if c==1: b=b+1
print(b)


I found an interesting problem on https://www.codechef.com/FULU2020/problems/TAX:
Is the MRP of my new shoes exclusive or inclusive of taxes?

-----Input:-----
- First line will contain an integer $P$

-----Output:-----
For each testcase, print either 'Inclusive' or 'Exclusive' without quotes.

-----Constraints-----
- $100 \leq P \leq 999$

-----Sample Input 1:-----
123

-----Sample Output 1:-----
Exclusive

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

-----Sample Output 2:-----
Inclusive

I tried it in Python, but could not do it. Can you solve it?

# cook your dish here
from sys import stdin,stdout
def main():
    cases = stdin.readline()
    if(int(cases[2])^int(cases[1])^int(cases[0])):
        print("Inclusive")
        return
    print("Exclusive")
def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://www.codechef.com/GACE2020/problems/CCH1:
Ash like soup very much! So, on the Raksha Bandhan day, his sister gave him a soup maker as a gift. Soup maker in the ith hour will make volume  Vi liters of soup and pours it in a bowl.
Each hour, the Volume of soup in every bowl is reduced due to evaporation. More precisely, when the temperature on a given hour is Ti, the Volume of soup in every bowl will reduce its volume by Ti. If this would reduce the volume of soup to or below zero, Bowl gets empty. All bowls are independent of each other.
Note that the Volume of soup in every bowl made in an hour i already lose part of its volume at the same hour. In an extreme case, this may mean that there is no soup left in the bowl at the end of a particular hour.
You are given the initial volumes of soup in bowls and the temperature on each hour. Determine the total volume of soup evaporated in each hour.
Input
The first line contains a single integer N (1 ≤ N ≤ 10^5) — the number of hours.
The second line contains N integers V 1, V 2, …, V N (0 ≤ V i ≤ 10^9), where V i is the initial volume of soup made in an hour i.
The third line contains N integers T 1, T 2, …, T N (0 ≤ T i ≤ 10^9), where T i is the temperature in an hour i.
Output
Output a single line with N integers, where the i-th integer represents the total volume of soup melted in an hour i.
Examples
Input
3
10 10 5
5 7 2
Output
5 12 4
Input
5
30 25 20 15 10
9 10 12 4 13
Output
9 20 35 11 25
Note
In the first sample, In the first hour, 10 liters of soup is prepared, which evaporates to the size of 5 at the same hour. In the second hour, another 10 liters of soup is made. Since it is a bit warmer than the hour before, the first bowl gets empty while the second bowl shrinks to 3. At the end of the second hour, only one bowl with 3 liters soup is left. In the third hour, another bowl with less volume of soup is made, but as the temperature dropped too, both bowls survive till the end of the hour.

I tried it in Python, but could not do it. Can you solve it?

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

sop=[int(i) for i in input().split()]
tem=[int(j) for j in input().split()]
for i in range(x):
    sm=0
    for j in range(i+1):
        if (sop[j] >= tem[i]):
            sm+=tem[i]
            sop[j]-=tem[i]
        else:
            sm+=sop[j]
            sop[j]=0
    print(sm,end=" ")


I found an interesting problem on https://www.codechef.com/IARCSJUD/problems/AVERAGE:
You are given a sequence of integers $a_1, a_2, ..., a_N$. An element ak is said to be an average element if there are indices $i, j$ (with $i \neq  j$) such that $a_k = \frac{a_i + a_j}{2}$.
In the sequence
371022171537102217153 \quad 7 \quad 10 \quad 22 \quad 17 \quad 15
for $i=1, j=5$ and $k=3$, we get $a_k = \frac{a_i + a_j}{2}$. Thus $a_3 = 10$ is an average element in this sequence. You can check that $a_3$ is the only average element in this sequence.
Consider the sequence
371031837103183 \quad 7 \quad 10 \quad 3 \quad 18
With $i=1, j=4$ and $k=1$ we get $a_k = \frac{a_i + a_j}{2}$. Thus $a_1=3$ is an average element. We could also choose $i=1, j=4$ and $k=4$ and get $a_k = \frac{a_i + a_j}{2}$. You can check that $a_1$ and $a_4$ are the only average elements of this sequence.
On the other hand, the sequence
38111730381117303 \quad 8 \quad 11 \quad 17 \quad 30
has no average elements.
Your task is to count the number of average elements in the given sequence.

-----Input:-----
The first line contains a single integer $N$ indicating the number of elements in the sequence. This is followed by $N$ lines containing one integer each (Line $i+1$ contains $a_i$). (You may assume that $a_i + a_j$ would not exceed MAXINT for any $i$ and $j$).

-----Output:-----
The output must consist of a single line containing a single integer $k$ indicating the number of average elements in the given sequence.

-----Constraints:-----
- You may assume that $1 \leq N \leq 10000$.
- In $30 \%$ of the inputs $1 \leq N \leq 200$.
- In $60 \%$ of the inputs $1 \leq N \leq 5000$.

-----Sample Input 1:-----
6
3
7
10
17
22
15

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

-----Sample Input 2:-----
5
3
7
10
3
18

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

-----Sample Input 3;-----
5
3
8
11
17
30

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

I tried it in Python, but could not do it. Can you solve it?

N = int(input())
numbs = []
dic = {}
e1 = set()
for i in range(N):
    numbs.append(int(input()))
    dic[numbs[i]] = 0
    e1.add(numbs[i])
for i in range(N):
    dic[numbs[i]] = dic[numbs[i]] + 1
s = set()
avg_ele = 0
for i in range(N-1):
    for j in range(i+1, N):
        avg = (numbs[i] + numbs[j])/2
        if avg in e1 and avg not in s:
            avg_ele += dic[avg]
            s.add(avg)
print(avg_ele)


I found an interesting problem on https://www.codechef.com/IARCSJUD/problems/BUFFALOE:
Ramu was a lazy farmer. He had inherited a fairly large farm and a nice house from his father. Ramu leased out the farm land to others and earned a rather handsome income. His father used to keep a buffalo at home and sell its milk but the buffalo died a few days after his father did.
Ramu too wanted to make some money from buffaloes, but in a quite a different way. He decided that his future lay in speculating on buffaloes. In the market in his village, buffaloes were bought and sold everyday. The price fluctuated over the year, but on any single day the price was always the same.
He decided that he would buy buffaloes when the price was low and sell them when the price was high and, in the process, accummulate great wealth. Unfortunately his house had space for just one buffalo and so he could own at most one buffalo at any time.
Before he entered the buffalo market, he decided to examine to examine the variation in the price of buffaloes over the last few days and determine the maximum profit he could have made. Suppose, the price of a buffalo over the last $10$ days varied as
1012811111012151310101281111101215131010\quad  12\quad  8\quad  11\quad  11\quad  10\quad  12\quad  15\quad  13\quad  10
Ramu is a lazy fellow and he reckoned that he would have been willing to visit the market at most $5$ times (each time to either buy or sell a buffalo) over the last $10$ days. Given this, the maximum profit he could have made is $9$ rupees. To achieve this, he buys a buffalo on day $1$, sells it on day $2$, buys one more on day $3$ and sells it on day $8$. If he was a little less lazy and was willing to visit the market $6$ times, then he could have made more money. He could have bought on day $1$, sold on day $2$, bought on day $3$, sold on day $4$, bought on day $6$ and sold on day $8$ to make a profit of $10$ rupees.
Your task is help Ramu calculate the maximum amount he can earn by speculating on buffaloes, given a history of daily buffalo prices over a period and a limit on how many times Ramu is willing to...

I tried it in Python, but could not do it. Can you solve it?

try:
 n,k = map(int,input().split())
 x = [int(input()) for _ in range(n)]
 k = k//2
 dp = [0]*(k+1)
 for i in range(k+1):
  dp[i] = [0]*n
 #print(dp)
 for i in range(1,k+1):
  #print("*",dp[i-1][0])
  diff = (-1)*x[0]
  for j in range(1,n):
   diff = max(dp[i-1][j]-x[j],diff)
   dp[i][j] = max(dp[i][j-1],diff+x[j])
 print(dp[k][n-1])
except:
 pass


I found an interesting problem on https://www.codechef.com/IARCSJUD/problems/CYCLEPER:
We consider permutations of the numbers $1,..., N$ for some $N$. By permutation we mean a rearrangment of the number $1,...,N$. For example
24517638245176382 \quad 4 \quad 5 \quad 1 \quad 7 \quad 6 \quad 3 \quad 8
is a permutation of $1,2,...,8$. Of course,
12345678123456781 \quad 2 \quad 3 \quad 4 \quad 5 \quad 6 \quad 7 \quad 8
is also a permutation of $1,2,...,8$.
We can "walk around" a permutation in a interesting way and here is how it is done for the permutation above:
Start at position $1$. At position $1$ we have $2$ and so we go to position $2$. Here we find $4$ and so we go to position $4$. Here we find $1$, which is a position that we have already visited. This completes the first part of our walk and we denote this walk by  ($1$ $2$ $4$ $1$). Such a walk is called a cycle. An interesting property of such walks, that you may take for granted, is that the position we revisit will always be the one we started from!
We continue our walk by jumping to first unvisited position, in this case position $3$ and continue in the same manner. This time we find $5$ at position $3$ and so we go to position $5$ and find $7$ and we go to position $7$ and find $3$ and thus we get the cycle ($3$ $5$ $7$ $3$). Next we start at position $6$ and get ($6$ $6$), and finally we start at position $8$ and get the cycle ($8$ $8$). We have exhausted all the positions. Our walk through this permutation consists of $4$ cycles.
One can carry out this walk through any permutation and obtain a set of cycles as the result. Your task is to print out the cycles that result from walking through a given permutation.

-----Input:-----
The first line of the input is a positive integer $N$ indicating the length of the permutation. The next line contains $N$ integers and is a permutation of $1,2,...,N$.

-----Output:-----
The first line of the output must contain a single integer $k$ denoting the number of cycles in the permutation. Line $2$ should describe the first cycle, line $3$ the second cycle and so on and line $k+1$ should describe...

I tried it in Python, but could not do it. Can you solve it?

n=int(input())
arr=[0]+[int(x) for x in input().split()]
used=[]
ans=[]
for i in range (1,n+1) :
    d=[]
    start,end=i,arr[i]
    if i not in used :
       d.append(i)
       used.append(i)
       while(True) :
        d.append(end)
        if end==start :
            break
        else :
            used.append(end)
            end=arr[end]
    if len(d)>0 :
        ans.append(d)
print(len(ans))
for i in ans :
    print(*i)


I found an interesting problem on https://www.codechef.com/IARCSJUD/problems/FINDNUMS:
This is a rather simple problem to describe. You will be given three numbers $S, P$ and $k$. Your task is to find if there are integers $n_1, n_2,...,n_k$ such that $n_1 + n_2 +...+ n_k = S$, $n_1 \cdot n_2 \cdot ... \cdot n_k = P$. If such integers exist, print them out. If no such sequence of integers exist, then print "NO".
For example if $S=11, P=48$ and $k=3$ then $3, 4$ and $4$ is a solution. On the other hand, if $S=11, P=100$ and $k=3$, there is no solution and you should print "NO".

-----Input:-----
A single line with three integers $S, P$ and $k$.

-----Output:-----
A single word "NO" or a seqence of $k$ integers $n_1, n_2,..., n_k$ on a single line. (The $n_i$'s must add up to $S$ and their product must be $P$).

-----Constraints:-----
- $1 \leq k \leq 4$.
- $1 \leq S \leq 1000$.
- $1 \leq P \leq 1000$.

-----Sample input 1:-----
11 48 3

-----Sample output 1:-----
3 4 4

-----Sample input 2:-----
11 100 3

-----Sample output 2:-----
NO

I tried it in Python, but could not do it. Can you solve it?

import math

def part(n, k):
    def _part(n, k, pre):
        if n <= 0:
            return []
        if k == 1:
            if n <= pre:
                return [[n]]
            return []
        ret = []
        for i in range(min(pre, n), 0, -1):
            ret += [[i] + sub for sub in _part(n-i, k-1, i)]
        return ret
    return _part(n, k, n)

S, P, k=map(int, input().split())
factors=[]

for i in range(1, int(math.sqrt(P))+1):
    if(P%i==0 and P//i!=i):
        factors.append(i)
        factors.append(P//i)
    elif(P%i==0 and P//i==i):
        factors.append(i)

arr=part(S, k)
flag=-1
#print(part(S, k))

for i in arr:
    temp=i
    cnt=0;  prod=1

    for j in temp:
        if(j in factors):
            cnt+=1
        prod*=j

    if(cnt==k and prod==P):
        print(*temp)
        flag=0
        break
    else:
        flag=1

if(flag!=0):
    print("NO")


I found an interesting problem on https://www.codechef.com/IARCSJUD/problems/GREATESC:
Heroes in Indian movies are capable of superhuman feats. For example, they can jump between buildings, jump onto and from running trains, catch bullets with their hands and teeth and so on. A perceptive follower of such movies would have noticed that there are limits to what even the superheroes can do. For example, if the hero could directly jump to his ultimate destination, that would reduce the action sequence to nothing and thus make the movie quite boring. So he typically labours through a series of superhuman steps to reach his ultimate destination.
In this problem, our hero has to save his wife/mother/child/dog/… held captive by the nasty villain on the top floor of a tall building in the centre of Bombay/Bangkok/Kuala Lumpur/…. Our hero is on top of a (different) building. In order to make the action "interesting" the director has decided that the hero can only jump between buildings that are "close" to each other. The director decides which pairs of buildings are close enough and which are not.
Given the list of buildings, the identity of the building where the hero begins his search, the identity of the building where the captive (wife/mother/child/dog…) is held, and the set of pairs of buildings that the hero can jump across, your aim is determine whether it is possible for the hero to reach the captive. And, if he can reach the captive he would like to do so with minimum number of jumps.
Here is an example. There are $5$ buildings, numbered $1,2,...,5$, the hero stands on building $1$ and the captive is on building $4$. The director has decided that buildings $1$ and $3$, $2$ and $3, 1$ and $2, 3$ and $5$ and $4$ and $5$ are close enough for the hero to jump across. The hero can save the captive by jumping from $1$ to $3$ and then from $3$ to $5$ and finally from $5$ to $4$. (Note that if $i$ and $j$ are close then the hero can jump from $i$ to $j$ as well as from $j$ to $i$.). In this example, the hero could have also reached $4$ by jumping from $1$ to $2, 2$ to $3, 3$ to $5$ and finally from $5$...

I tried it in Python, but could not do it. Can you solve it?

# cook your dish here
from collections import deque
def bfs(graph,u,t):
    queue = deque([u])
    level = {u: 0}
    while queue:
        ver = queue.popleft()
        for v in graph[ver]:
            if v not in level:
                queue.append(v)
                level[v] = level[ver] + 1
    return level.get(t,0)
try:
    n,e = map(int,input().split())
    graph = {}
    for i in range(1,n+1):
        graph[i] = []
    for _ in range(e):
        a,b = map(int,input().split())
        graph[a].append(b)
        graph[b].append(a)
    s,t = map(int,input().split())
    p = bfs(graph,s,t)
    print(p)

except:
    pass


I found an interesting problem on https://www.codechef.com/IARCSJUD/problems/LONGPALI:
As we all know, a palindrome is a word that equals its reverse. Here are some examples of palindromes: malayalam, gag, appa, amma.
We consider any sequence consisting of the letters of the English alphabet to be a word. So axxb,abbba and bbbccddx are words for our purpose. And aaabbaaa, abbba and bbb are examples of palindromes.
By a subword of a word, we mean a contiguous subsequence of the word. For example the subwords of the word abbba are a, b, ab, bb, ba, abb, bbb, bba, abbb, bbba and abbba.
In this task you will given a word and you must find the longest subword of this word that is also a palindrome.
For example if the given word is abbba then the answer is abbba. If the given word is abcbcabbacba then the answer is bcabbacb.

-----Input:-----
The first line of the input contains a single integer $N$ indicating the length of the word. The following line contains a single word of length $N$, made up of the letters a,b,…, z.

-----Output:-----
The first line of the output must contain a single integer indicating the length of the longest subword of the given word that is a palindrome. The second line must contain a subword that is a palindrome and which of maximum length. If there is more than one subword palindrome of maximum length, it suffices to print out any one.

-----Constraints:-----
- $1 \leq N \leq 5000$.
- You may assume that in $30 \%$ of the inputs $1 \leq N \leq 300$.

-----Sample Input 1:-----
5
abbba

-----Sample Output 1:-----
5
abbba

-----Sample Input 2:-----
12
abcbcabbacba

-----Sample Output 2:-----
8
bcabbacb

I tried it in Python, but could not do it. Can you solve it?

from itertools import combinations
N = int(input())
st = input()
mx = ""
ans = False
a = [st[x:y] for x, y in combinations(range(len(st) + 1), r = 2)]
for i in a:
    for j in range(len(i)//2):
        if i[j]==i[-1-j]:
            ans = True
        else:
            ans = False
            break
    if ans == True:
        if len(mx) < len(i):
            mx = i
print(len(mx))
print(mx)