Сайт: https://easyoffer.ru/
Все каналы: t.me/+xGeAw6ckJ4liYzQy
Контакт для рекламы: @sendme_ads
Post #2433
118
This post (sticker, poll or similar) has no web preview. Open in Telegram
- 💊 2
PY @easy_python_task
This post (sticker, poll or similar) has no web preview. Open in Telegram

Input: root = [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
from collections import deque
class Solution:
def isCompleteTree(self, root: TreeNode) -> bool:
if not root:
return True
queue = deque([root])
nullNodeFound = False
while queue:
node = queue.popleft()
if not node:
nullNodeFound = True
else:
if nullNodeFound:
return False
queue.append(node.left)
queue.append(node.right)
return True
Input: arr = [1,2,3,4]
Output: "23:41"
from itertools import permutations
def largestTimeFromDigits(arr):
max_time = -1
for perm in permutations(arr):
hours = perm[0] * 10 + perm[1]
minutes = perm[2] * 10 + perm[3]
if hours < 24 and minutes < 60:
max_time = max(max_time, hours * 60 + minutes)
if max_time == -1:
return ""
return f"{max_time // 60:02}:{max_time % 60:02}"
Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we do not need any insertions.
class Solution:
def lcs(self, s1, s2, m, n, memo):
if m == 0 or n == 0:
return 0
if memo[m][n] != -1:
return memo[m][n]
if s1[m - 1] == s2[n - 1]:
memo[m][n] = 1 + self.lcs(s1, s2, m - 1, n - 1, memo)
else:
memo[m][n] = max(self.lcs(s1, s2, m - 1, n, memo), self.lcs(s1, s2, m, n - 1, memo))
return memo[m][n]
def minInsertions(self, s: str) -> int:
n = len(s)
sReverse = s[::-1]
memo = [[-1] * (n + 1) for _ in range(n + 1)]
return n - self.lcs(s, sReverse, n, n, memo)
Input: candies = 7, num_people = 4
Output: [1,2,3,1]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0,0].
On the third turn, ans[2] += 3, and the array is [1,2,3,0].
On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
n = num_people
p = int((2 * candies + 0.25)**0.5 - 0.5)
remaining = int(candies - (p + 1) * p * 0.5)
rows, cols = p // n, p % n
d = [0] * n
for i in range(n):
d[i] = (i + 1) * rows + int(rows * (rows - 1) * 0.5) * n
if i < cols:
d[i] += i + 1 + rows * n
d[cols] += remaining
return d
Input: s = "abcd"
Output: 0
Explanation: There is no repeating substring.
class Solution:
def search(self, L, n, S):
seen = set()
for start in range(n - L + 1):
tmp = S[start:start + L]
if tmp in seen:
return start
seen.add(tmp)
return -1
def longestRepeatingSubstring(self, S):
n = len(S)
left, right = 1, n
while left <= right:
L = left + (right - left) // 2
if self.search(L, n, S) != -1:
left = L + 1
else:
right = L - 1
return left - 1
Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]
Output: 1
Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.
The tree structure of the employees in the company is shown.
class Solution:
def __init__(self):
self.maxTime = float('-inf')
def DFS(self, adjList, informTime, curr, time):
self.maxTime = max(self.maxTime, time)
for adjacent in adjList[curr]:
self.DFS(adjList, informTime, adjacent, time + informTime[curr])
def numOfMinutes(self, n, headID, manager, informTime):
adjList = [[] for _ in range(n)]
for i in range(n):
if manager[i] != -1:
adjList[manager[i]].append(i)
self.DFS(adjList, informTime, headID, 0)
return self.maxTime
Input: nums = [3,6,9,12]
Output: 4
class Solution:
def longestArithSeqLength(self, nums: List[int]) -> int:
if not nums:
return 0
dp = [{} for _ in range(len(nums))]
max_length = 0
for i in range(len(nums)):
for j in range(i):
diff = nums[i] - nums[j]
if diff in dp[j]:
dp[i][diff] = dp[j][diff] + 1
else:
dp[i][diff] = 2 # Start a new sequence
max_length = max(max_length, dp[i][diff])
return max_length
Input: source = "abc", target = "abcbc"
Output: 2
def minSubsequences(source, target):
subsequences_count = 0
target_index = 0
while target_index < len(target):
source_index = 0
subsequences_count += 1
start_index = target_index
while source_index < len(source) and target_index < len(target):
if source[source_index] == target[target_index]:
target_index += 1
source_index += 1
if target_index == start_index:
return -1
return subsequences_count
Input: nums = [1,-1,5,-2,3], k = 3
Output: 4
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.
class Solution:
def maxSubArrayLen(self, nums: List[int], k: int) -> int:
prefixSum = 0
longestSubarray = 0
indices = {}
for i, num in enumerate(nums):
prefixSum += num
if prefixSum == k:
longestSubarray = i + 1
if prefixSum - k in indices:
longestSubarray = max(longestSubarray, i - indices[prefixSum - k])
if prefixSum not in indices:
indices[prefixSum] = i
return longestSubarray
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
def floodFill(image, sr, sc, color):
original_color = image[sr][sc]
if original_color == color:
return image
def dfs(x, y):
if x < 0 or x >= len(image) or y < 0 or y >= len(image[0]) or image[x][y] != original_color:
return
image[x][y] = color
dfs(x + 1, y)
dfs(x - 1, y)
dfs(x, y + 1)
dfs(x, y - 1)
dfs(sr, sc)
return image
Input: ransomNote = "a", magazine = "b"
Output: false
import random
class Solution:
def __init__(self, nums: list[int]):
self.array = nums[:]
self.original = nums[:]
def reset(self) -> list[int]:
self.array = self.original[:]
return self.original
def shuffle(self) -> list[int]:
for i in range(len(self.array)):
rand_index = random.randint(i, len(self.array) - 1)
self.array[i], self.array[rand_index] = self.array[rand_index], self.array[i]
return self.array
Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output: 3
Explanation: We translate img1 to right by 1 unit and down by 1 unit.
class Solution:
def shiftAndCount(self, xShift, yShift, M, R):
leftShiftCount = 0
rightShiftCount = 0
rRow = 0
for mRow in range(yShift, len(M)):
rCol = 0
for mCol in range(xShift, len(M)):
if M[mRow][mCol] == 1 and M[mRow][mCol] == R[rRow][rCol]:
leftShiftCount += 1
if M[mRow][rCol] == 1 and M[mRow][rCol] == R[rRow][mCol]:
rightShiftCount += 1
rCol += 1
rRow += 1
return max(leftShiftCount, rightShiftCount)
def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:
maxOverlaps = 0
for yShift in range(len(A)):
for xShift in range(len(A)):
maxOverlaps = max(maxOverlaps, self.shiftAndCount(xShift, yShift, A, B))
maxOverlaps = m
Input: target = [1,3], n = 3
Output: ["Push","Push","Pop","Push"]
Explanation: Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = [1].
Read 2 from the stream and push it to the stack. s = [1,2].
Pop the integer on the top of the stack. s = [1].
Read 3 from the stream and push it to the stack. s = [1,3].
class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
ans = []
i = 0
for num in target:
while i < num - 1:
ans.append("Push")
ans.append("Pop")
i += 1
ans.append("Push")
i += 1
return ans
Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
Output: 6
from collections import deque
def openLock(deadends, target):
def neighbors(node):
for i in range(4):
x = int(node[i])
for d in (-1, 1):
y = (x + d) % 10
yield node[:i] + str(y) + node[i+1:]
dead = set(deadends)
queue = deque([('0000', 0)])
visited = {'0000'}
while queue:
node, steps = queue.popleft()
if node == target:
return steps
if node in dead:
continue
for neighbor in neighbors(node):
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, steps + 1))
return -1
Input: s = "011101"
Output: 5
Explanation:
All possible ways of splitting s into two non-empty substrings are:
left = "0" and right = "11101", score = 1 + 4 = 5
left = "01" and right = "1101", score = 1 + 3 = 4
left = "011" and right = "101", score = 1 + 2 = 3
left = "0111" and right = "01", score = 1 + 1 = 2
left = "01110" and right = "1", score = 2 + 1 = 3
class Solution:
def maxScore(self, s: str) -> int:
ones = s.count('1')
zeros = ans = 0
for i in range(len(s) - 1):
if s[i] == '1':
ones -= 1
else:
zeros += 1
ans = max(ans, zeros + ones)
return ans
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
parent_x, parent_y = None, None
depth_x, depth_y = -1, -1
def dfs(node, parent, depth):
nonlocal parent_x, parent_y, depth_x, depth_y
if not node:
return
if node.val == x:
parent_x, depth_x = parent, depth
elif node.val == y:
parent_y, depth_y = parent, depth
else:
dfs(node.left, node, depth + 1)
dfs(node.right, node, depth + 1)
dfs(root, None, 0)
return depth_x == depth_y and parent_x != parent_y
Input: s = "(()"
Output: 2
def is_valid(s: str) -> bool:
stack = []
for char in s:
if char == '(':
stack.append('(')
elif stack and stack[-1] == '(':
stack.pop()
else:
return False
return len(stack) == 0
def longest_valid_parentheses(s: str) -> int:
maxlen = 0
for i in range(len(s)):
for j in range(i + 2, len(s) + 1, 2):
substring = s[i:j]
if is_valid(substring):
maxlen = max(maxlen, j - i)
return maxlen
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
length = len(nums)
L = [1] * length
R = [1] * length
answer = [1] * length
for i in range(1, length):
L[i] = nums[i - 1] * L[i - 1]
for i in range(length - 2, -1, -1):
R[i] = nums[i + 1] * R[i + 1]
for i in range(length):
answer[i] = L[i] * R[i]
return answer