diff --git a/1260. Shift 2D Grid/1260. Shift 2D Grid.py b/1260. Shift 2D Grid/1260. Shift 2D Grid.py new file mode 100644 index 0000000..299ac44 --- /dev/null +++ b/1260. Shift 2D Grid/1260. Shift 2D Grid.py @@ -0,0 +1,47 @@ +""" +Given a 2D grid of size m x n and an integer k. You need to shift the grid k times. + +In one shift operation: + +Element at grid[i][j] moves to grid[i][j + 1]. +Element at grid[i][n - 1] moves to grid[i + 1][0]. +Element at grid[m - 1][n - 1] moves to grid[0][0]. +Return the 2D grid after applying shift operation k times. + + + +Example 1: + + +Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1 +Output: [[9,1,2],[3,4,5],[6,7,8]] +Example 2: + + +Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4 +Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]] +Example 3: + +Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9 +Output: [[1,2,3],[4,5,6],[7,8,9]] + + +Constraints: + +m == grid.length +n == grid[i].length +1 <= m <= 50 +1 <= n <= 50 +-1000 <= grid[i][j] <= 1000 +0 <= k <= 100 +""" +class Solution: + def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + m,n = len(grid), len(grid[0]) + k = k % (m*n) + temp = [grid[i][j] for i in range(m) for j in range(n)] + temp = temp[-k:] + temp[:-k] + result = [] + for i in range(m): + result.append(temp[i*n:i*n+n]) + return result \ No newline at end of file diff --git a/700. Search in a Binary Search Tree/700. Search in a Binary Search Tree.py b/700. Search in a Binary Search Tree/700. Search in a Binary Search Tree.py index 8abc48e..80687b7 100644 --- a/700. Search in a Binary Search Tree/700. Search in a Binary Search Tree.py +++ b/700. Search in a Binary Search Tree/700. Search in a Binary Search Tree.py @@ -20,8 +20,6 @@ Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null. """ - - # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): @@ -29,17 +27,17 @@ # self.left = left # self.right = right class Solution: - def searchBST(self, root: TreeNode, val: int) -> TreeNode: - if not root: - return None + def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if not root: return None q = collections.deque() q.append(root) while q: node = q.popleft() if node.val == val: return node - if node.left: - q.append(node.left) - if node.right: + elif node.val < val and node.right: q.append(node.right) + else: + if node.left: + q.append(node.left) return None \ No newline at end of file