title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Python 3 || recursion, w/ explanation || T/M: 96% / 17%
minesweeper
0
1
```\nclass Solution:\n def updateBoard(self, board, click):\n\n if board[click[0]][click[1]] == \'M\': # <-- handle case that\n board[click[0]][click[1]] = \'X\' ; return board # click is mined\n\n adjacent = lambda x,y : [(x+dx,y+dy) for dx in range(-1,2) for dy in range(-1,2) \n if (dx or dy) and 0 <= x+dx < len(board) and 0 <= y+dy < len(board[0])]\n \n def dfs(x: int,y: int)-> None: # \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013start function\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\n adj = adjacent(x,y)\n \n mines = sum(board[X][Y] == \'M\' for X,Y in adj) # <-- count up adjacent mines \n # to board[x][y]\n if mines:\n board[x][y] = str(mines) # <-- If mines, write count...\n\n else: \n board[x][y] = \'B\' # <-- ... if not, mark it "revealed" \n\n for X,Y in adj:\n if board[X][Y] == \'E\': # <-- explore each adjacent cell\n dfs(X,Y) # if unexplored\n return #\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013end function\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\n \n dfs(*click) # <-- start at click\n\n return board # <-- return updated board\n```\n[https://leetcode.com/problems/minesweeper/submissions/856849255/](http://)\n\n\n\nI\'m not sure time and space on this one. Thoughts?
5
Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))! You are given an `m x n` char matrix `board` representing the game board where: * `'M'` represents an unrevealed mine, * `'E'` represents an unrevealed empty square, * `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), * digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and * `'X'` represents a revealed mine. You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`). Return _the board after revealing this position according to the following rules_: 1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`. 2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively. 3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines. 4. Return the board when no more squares will be revealed. **Example 1:** **Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Example 2:** **Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 50` * `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`. * `click.length == 2` * `0 <= clickr < m` * `0 <= clickc < n` * `board[clickr][clickc]` is either `'M'` or `'E'`.
null
Solution
minesweeper
1
1
```C++ []\nclass Solution {\npublic:\n vector<vector<char>> updateBoard(vector<vector<char>>& A, vector<int>& C) {\n int x=C[0],y=C[1];\n int n=A.size();\n int m=A[0].size();\n if(A[x][y]==\'M\'){\n A[x][y]=\'X\';\n return A;\n }\n vector<int> r={1,1,0,-1,-1,-1,0,1};\n vector<int> c={0,1,1,1,0,-1,-1,-1};\n queue<pair<int,int>> q;\n vector<vector<int>> V(n,vector<int>(m,0));\n q.push({x,y});\n V[x][y]=1;\n \n while(!q.empty()){\n pair<int,int> p=q.front();\n q.pop();\n int cnt=0;\n int x=p.first;\n int y=p.second;\n if(A[x][y]>=\'1\' && A[x][y]<=\'9\'){\n continue;\n }\n for(int k=0;k<8;k++){\n int x1=x+r[k];\n int y1=y+c[k];\n if(x1>=0 && x1<n && y1>=0 && y1<m && A[x1][y1]==\'M\'){\n cnt++;\n }\n }\n if(cnt>0){\n A[x][y]=\'0\'+cnt;\n continue;\n }\n A[x][y]=\'B\';\n for(int k=0;k<8;k++){\n int x1=x+r[k];\n int y1=y+c[k];\n if(x1>=0 && x1<n && y1>=0 && y1<m && V[x1][y1]==0){\n q.push({x1,y1});\n V[x1][y1]=1;\n }\n }\n }\n return A;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n \n def update(board, r, c):\n if board[r][c] == \'M\':\n board[r][c] = \'X\'\n return\n\n neighbors = [(i, j) for i in range(r-1, r+2) for j in range(c-1, c+2) \n if -1 < i < len(board) and -1 < j < len(board[0]) and (i, j) != (r, c)]\n \n mine_count = [board[i][j] for i,j in neighbors].count("M")\n \n if mine_count == 0:\n board[r][c] = \'B\'\n for i,j in neighbors: \n if board[i][j] == "E":\n update(board, i, j)\n else:\n board[r][c] = str(mine_count)\n \n update(board, click[0], click[1])\n return board\n```\n\n```Java []\nclass Solution {\n char[][] board;\n int[][] directions = {{0, 1}, {1, 0}, {1, 1}, {-1, -1}, {-1, 1}, {1, -1}, {0, -1}, {-1, 0}};\n int n;\n int m;\n public char[][] updateBoard(char[][] board, int[] click) {\n this.board = board;\n n = board.length;\n m = board[0].length;\n\n dfs(click[0], click[1]);\n\n return board;\n }\n private void dfs(int x, int y) {\n if(board[x][y] == \'M\') {\n board[x][y] = \'X\';\n } else {\n int count = 0;\n for (int i = 0; i < 8; i++) {\n int r = x + directions[i][0];\n int c = y + directions[i][1];\n\n if ((r < 0 || r >= n || c < 0 || c >= m)) {\n continue;\n }\n if (board[r][c] == \'M\' || board[r][c] == \'X\') {\n count++;\n }\n }\n if (count > 0) {\n board[x][y] = (char) (count + \'0\');\n } else {\n board[x][y] = \'B\';\n for (int i = 0; i < 8; i++) {\n int r = x + directions[i][0];\n int c = y + directions[i][1];\n\n if ((r < 0 || r >= n || c < 0 || c >= m)) {\n continue;\n }\n if (board[r][c] == \'E\') {\n dfs(r, c);\n }\n }\n }\n }\n }\n}\n```\n
3
Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))! You are given an `m x n` char matrix `board` representing the game board where: * `'M'` represents an unrevealed mine, * `'E'` represents an unrevealed empty square, * `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), * digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and * `'X'` represents a revealed mine. You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`). Return _the board after revealing this position according to the following rules_: 1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`. 2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively. 3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines. 4. Return the board when no more squares will be revealed. **Example 1:** **Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Example 2:** **Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 50` * `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`. * `click.length == 2` * `0 <= clickr < m` * `0 <= clickc < n` * `board[clickr][clickc]` is either `'M'` or `'E'`.
null
Python3 recursive solution
minesweeper
0
1
```\nclass Solution:\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n x,y = click[0],click[1]\n options = []\n if board[x][y] == "M":\n board[x][y] = "X"\n else:\n options = [(0,1),(0,-1),(1,0),(1,-1),(1,1),(-1,-1),(-1,0),(-1,1)]\n\n count = 0\n for i,j in options:\n if x+i > -1 and x+i < len(board) and y+j > -1 and y+j < len(board[0]):\n if board[x+i][y+j] == "M":\n count += 1\n if count == 0:\n board[x][y] = "B"\n for i,j in options:\n if x+i > -1 and x+i < len(board) and y+j > -1 and y+j < len(board[0]):\n if board[x+i][y+j] == "M" or board[x+i][y+j] == "E":\n self.updateBoard(board,[x+i,y+j])\n else:\n board[x][y] = str(count)\n\n return board\n```\n**If you like this solution, please upvote for this**
7
Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))! You are given an `m x n` char matrix `board` representing the game board where: * `'M'` represents an unrevealed mine, * `'E'` represents an unrevealed empty square, * `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), * digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and * `'X'` represents a revealed mine. You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`). Return _the board after revealing this position according to the following rules_: 1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`. 2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively. 3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines. 4. Return the board when no more squares will be revealed. **Example 1:** **Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Example 2:** **Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 50` * `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`. * `click.length == 2` * `0 <= clickr < m` * `0 <= clickc < n` * `board[clickr][clickc]` is either `'M'` or `'E'`.
null
dfs solution
minesweeper
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(mn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(mn)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n r,c = click\n directions = [(0,1),(0,-1),(-1,0),(1,0),(1,1),(-1,-1),(1,-1),(-1,1)]\n m = len(board)\n n = len(board[0])\n def dfs(i,j):\n if board[i][j]==\'M\':\n board[i][j]=\'X\'\n return \n elif board[i][j]==\'E\':\n c = 0\n for d in directions:\n x = i+d[0]\n y = j+d[1]\n if 0<=x<m and 0<=y<n and board[x][y]==\'M\':\n c+=1\n if c==0:\n board[i][j]=\'B\'\n for d in directions:\n x = i+d[0]\n y = j+d[1]\n if 0<=x<m and 0<=y<n:\n dfs(x,y)\n else:\n board[i][j]=str(c)\n dfs(r,c)\n return board\n\n\n\n\n```
0
Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))! You are given an `m x n` char matrix `board` representing the game board where: * `'M'` represents an unrevealed mine, * `'E'` represents an unrevealed empty square, * `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), * digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and * `'X'` represents a revealed mine. You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`). Return _the board after revealing this position according to the following rules_: 1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`. 2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively. 3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines. 4. Return the board when no more squares will be revealed. **Example 1:** **Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Example 2:** **Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 50` * `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`. * `click.length == 2` * `0 <= clickr < m` * `0 <= clickc < n` * `board[clickr][clickc]` is either `'M'` or `'E'`.
null
Python Simple
minesweeper
0
1
Using DFS to traverse the board.\n\n# Code\n```\nclass Solution:\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n def get_neighbors(node):\n neighbors = []\n row_delta = [-1, -1, 0, 1, 1, 1, 0, -1]\n col_delta = [0, 1, 1, 1, 0, -1, -1, -1]\n\n for i in range(len(row_delta)):\n row = node[0] + row_delta[i]\n col = node[1] + col_delta[i]\n\n if 0 <= row < len(board) and 0 <= col < len(board[0]):\n neighbors.append((row,col))\n \n return neighbors\n\n def dfs(node):\n if board[node[0]][node[1]] != "E":\n return\n\n neighbors = get_neighbors(node)\n\n mine_count = 0\n for neighbor in neighbors:\n if board[neighbor[0]][neighbor[1]] == "M":\n mine_count += 1\n\n if mine_count == 0:\n board[node[0]][node[1]] = "B"\n for neighbor in neighbors:\n dfs(neighbor)\n else:\n board[node[0]][node[1]] = str(mine_count)\n\n if board[click[0]][click[1]] == "M":\n board[click[0]][click[1]] = "X"\n else:\n dfs(click)\n\n return board\n```
0
Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))! You are given an `m x n` char matrix `board` representing the game board where: * `'M'` represents an unrevealed mine, * `'E'` represents an unrevealed empty square, * `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), * digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and * `'X'` represents a revealed mine. You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`). Return _the board after revealing this position according to the following rules_: 1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`. 2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively. 3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines. 4. Return the board when no more squares will be revealed. **Example 1:** **Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Example 2:** **Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 50` * `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`. * `click.length == 2` * `0 <= clickr < m` * `0 <= clickc < n` * `board[clickr][clickc]` is either `'M'` or `'E'`.
null
Python3 Solution
minimum-absolute-difference-in-bst
0
1
\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def getMinimumDifference(self, root: Optional[TreeNode]) -> int:\n def inorder(node):\n nonlocal min_diff,prev\n if not node:\n return False\n\n inorder(node.left)\n if prev!=None:\n min_diff=min(min_diff,node.val-prev)\n\n prev=node.val\n inorder(node.right) \n\n min_diff=float(\'inf\')\n prev=None\n inorder(root)\n return min_diff \n```
1
Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_. **Example 1:** **Input:** root = \[4,2,6,1,3\] **Output:** 1 **Example 2:** **Input:** root = \[1,0,48,null,null,12,49\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 104]`. * `0 <= Node.val <= 105` **Note:** This question is the same as 783: [https://leetcode.com/problems/minimum-distance-between-bst-nodes/](https://leetcode.com/problems/minimum-distance-between-bst-nodes/)
null
Python | Beats 98.9% using inorder traversal
minimum-absolute-difference-in-bst
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def getMinimumDifference(self, root: Optional[TreeNode]) -> int:\n def inorderTraversal(root):\n res = []\n if root:\n res = inorderTraversal(root.left)\n res.append(root.val)\n res = res + inorderTraversal(root.right)\n return res\n\n def findMinDiff(arr, n):\n \n diff = 10**20\n\n for i in range(n-1):\n if arr[i+1] - arr[i] < diff:\n diff = arr[i+1] - arr[i]\n\n return diff\n\n res = sorted(inorderTraversal(root))\n n = len(res)\n ans = findMinDiff(res,n)\n return ans\n```
2
Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_. **Example 1:** **Input:** root = \[4,2,6,1,3\] **Output:** 1 **Example 2:** **Input:** root = \[1,0,48,null,null,12,49\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 104]`. * `0 <= Node.val <= 105` **Note:** This question is the same as 783: [https://leetcode.com/problems/minimum-distance-between-bst-nodes/](https://leetcode.com/problems/minimum-distance-between-bst-nodes/)
null
Solution
k-diff-pairs-in-an-array
1
1
```C++ []\nclass Solution {\npublic:\n int findPairs(vector<int>& nums, int k) {\n \n int ans=0;\n if(k==0){\n unordered_map<int,int> mp;\n for(auto i: nums) mp[i]++;\n for(auto i: mp) if(i.second>1) ans++;\n return ans;\n }\n sort(nums.begin(),nums.end());\n \n nums.erase(unique(nums.begin(),nums.end()),nums.end());\n int n=nums.size();\n \n int i=1,j=0;\n while(i< n && j<n && i>j){\n int diff=nums[i]-nums[j];\n if(diff==k){\n ans++;\n j++,i++;\n continue;\n }\n else if(diff<k){\n i++;\n }\n else{\n cout<<"hello";\n while(j<n && nums[i]-nums[j]>k && j<=i){\n j++;\n }\n if(i==j)\n i=i+1;\n }\n }\n return ans; \n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n hashmap = collections.Counter(nums)\n numbers = 0\n if k == 0:\n for i in hashmap.values(): \n if i > 1:\n numbers += 1\n return numbers\n for i in hashmap:\n if i + k in hashmap:\n numbers += 1\n return numbers\n```\n\n```Java []\nclass Solution {\n public int findPairs(int[] nums, int k) {\n \n int n = nums.length;\n Arrays.sort(nums);\n \n int i =0;\n int j = i+1;\nint findpairs = 0;\n while(j<n && i<n ){\n if(i==j){\n j++;\n }\n else{\n if(nums[j]-nums[i]==k){\n findpairs++;\n i++;\n while (i < n && nums[i] == nums[i - 1]){\n i++;}\n }else if(nums[j]-nums[i]>k){\n i++;\n }else{\n j++;\n }\n }\n }\n return findpairs;\n }\n}\n```\n
1
Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_. A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true: * `0 <= i, j < nums.length` * `i != j` * `nums[i] - nums[j] == k` **Notice** that `|val|` denotes the absolute value of `val`. **Example 1:** **Input:** nums = \[3,1,4,1,5\], k = 2 **Output:** 2 **Explanation:** There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of **unique** pairs. **Example 2:** **Input:** nums = \[1,2,3,4,5\], k = 1 **Output:** 4 **Explanation:** There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). **Example 3:** **Input:** nums = \[1,3,1,5,4\], k = 0 **Output:** 1 **Explanation:** There is one 0-diff pair in the array, (1, 1). **Constraints:** * `1 <= nums.length <= 104` * `-107 <= nums[i] <= 107` * `0 <= k <= 107`
null
✔️ Python O(n) Solution | 98% Faster | Easy Solution | K-diff Pairs in an Array
k-diff-pairs-in-an-array
0
1
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\nVisit this blog to learn Python tips and techniques and to find a Leetcode solution with an explanation: https://www.python-techs.com/\n\n**Solution:**\n```\nclass Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n cnt=0\n c=Counter(nums)\n \n if k==0:\n for key,v in c.items():\n if v>1:\n cnt+=1\n else:\n for key,v in c.items():\n if key+k in c:\n cnt+=1\n return cnt\n```\n**Thank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.**\n
36
Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_. A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true: * `0 <= i, j < nums.length` * `i != j` * `nums[i] - nums[j] == k` **Notice** that `|val|` denotes the absolute value of `val`. **Example 1:** **Input:** nums = \[3,1,4,1,5\], k = 2 **Output:** 2 **Explanation:** There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of **unique** pairs. **Example 2:** **Input:** nums = \[1,2,3,4,5\], k = 1 **Output:** 4 **Explanation:** There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). **Example 3:** **Input:** nums = \[1,3,1,5,4\], k = 0 **Output:** 1 **Explanation:** There is one 0-diff pair in the array, (1, 1). **Constraints:** * `1 <= nums.length <= 104` * `-107 <= nums[i] <= 107` * `0 <= k <= 107`
null
Best soln beats 100%
encode-and-decode-tinyurl
1
1
# Best Beats 100%\n![Capture.PNG](https://assets.leetcode.com/users/images/9d3e288e-bd93-4957-82e2-5ecbac81575f_1702203790.6520412.png)\n\n# Very Big difference b/w C and Python in C this code beats 100% but this not happen in Python\n\n# Code\n```\nchar* encode(char* longUrl) {\n return longUrl;\n}\nchar* decode(char* shortUrl) {\n return shortUrl;\n}\n```
1
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/). TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the `Solution` class: * `Solution()` Initializes the object of the system. * `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`. * `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object. **Example 1:** **Input:** url = "https://leetcode.com/problems/design-tinyurl " **Output:** "https://leetcode.com/problems/design-tinyurl " **Explanation:** Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. **Constraints:** * `1 <= url.length <= 104` * `url` is guranteed to be a valid URL.
null
Easy Python solution one liner for each func
encode-and-decode-tinyurl
0
1
# Easy python soln\n\n# Code\n```\nclass Codec:\n\n def encode(self, longUrl):\n return longUrl\n\n def decode(self, shortUrl):\n return shortUrl\n```
1
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/). TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the `Solution` class: * `Solution()` Initializes the object of the system. * `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`. * `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object. **Example 1:** **Input:** url = "https://leetcode.com/problems/design-tinyurl " **Output:** "https://leetcode.com/problems/design-tinyurl " **Explanation:** Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. **Constraints:** * `1 <= url.length <= 104` * `url` is guranteed to be a valid URL.
null
Solution
encode-and-decode-tinyurl
1
1
```C++ []\nclass Solution {\npublic:\n\n unordered_map<string, string> um;\n vector<int> digits;\n Solution(): digits(4) {}\n\n string hex = "0123456789abcdef";\n string encode(string longUrl) {\n string encoded;\n for(int d: digits)\n encoded += hex[d];\n int r = 1;\n for(int i=3; i>=0; i--) {\n int s = r+digits[i];\n digits[i] = s%16;\n r = s/16;\n }\n um[encoded] = longUrl;\n cout << encoded << " ";\n return "https://tiny.com/" + encoded;\n }\n string decode(string shortUrl) {\n string encoding = shortUrl.substr(shortUrl.find_last_of("/")+1);\n cout << encoding << " ";\n return um[encoding];\n }\n};\n```\n\n```Python3 []\nclass Codec:\n def __init__(self):\n self.encodeUrl = {}\n self.decodeUrl = {}\n self.base = "https://tinyurl.com/"\n\n def encode(self, longUrl: str) -> str:\n if longUrl not in self.encodeUrl:\n tinyurl = self.base + str(len(self.encodeUrl)+1)\n self.encodeUrl[longUrl] = tinyurl\n self.decodeUrl[tinyurl] = longUrl\n\n return self.encodeUrl[longUrl]\n \n def decode(self, shortUrl: str) -> str:\n return self.decodeUrl[shortUrl]\n```\n\n```Java []\nclass Codec {\n Map<String, String> map = new HashMap<>();\n\n public String encode(String longUrl) {\n String key = "bruh69";\n map.put(key, longUrl);\n return key;\n }\n public String decode(String shortUrl) {\n return map.get(shortUrl);\n }\n}\n```\n
2
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/). TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the `Solution` class: * `Solution()` Initializes the object of the system. * `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`. * `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object. **Example 1:** **Input:** url = "https://leetcode.com/problems/design-tinyurl " **Output:** "https://leetcode.com/problems/design-tinyurl " **Explanation:** Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. **Constraints:** * `1 <= url.length <= 104` * `url` is guranteed to be a valid URL.
null
39ms | Python solution
encode-and-decode-tinyurl
0
1
```\nclass Codec:\n\n def __init__(self) -> None:\n self.hm: Dict[str, str] = dict()\n self.urlCounter: int = 0\n\n def encode(self, longUrl: str) -> str:\n """\n Encodes a URL to a shortened URL.\n """\n encoded = str(self.urlCounter)\n self.hm[encoded] = longUrl\n self.urlCounter += 1\n\n return encoded\n \n\n def decode(self, shortUrl: str) -> str:\n """\n Decodes a shortened URL to its original URL.\n """\n return self.hm[shortUrl]\n \n```
1
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/). TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the `Solution` class: * `Solution()` Initializes the object of the system. * `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`. * `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object. **Example 1:** **Input:** url = "https://leetcode.com/problems/design-tinyurl " **Output:** "https://leetcode.com/problems/design-tinyurl " **Explanation:** Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. **Constraints:** * `1 <= url.length <= 104` * `url` is guranteed to be a valid URL.
null
Explained (Random) Python3 easy understanding
encode-and-decode-tinyurl
0
1
Random string from string.ascii_lowercase + string.digits\n\n# Complexity \n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Codec:\n def __init__(self):\n #Explaination \n self.url_map = {} # dictionary \n self.pool = string.ascii_lowercase + string.digits # pool = abcdefghijklmnopqrstuvwxyz1234567890\n self.random_chars = random.choices(self.pool, k = 5) # random.choices will chose length(k) = 5 string which will be different every time and return in array\n self.random_string = \'\'.join(self.random_chars) # random_string is the len 5 string that we can store to url_map\n \n def encode(self, longUrl: str) -> str:\n \n shortUrl = self.random_string \n self.url_map[shortUrl] = longUrl # Insert in shorturl as key and value = longURL \n return "http://tinyurl.com/" + shortUrl \n \n\n def decode(self, shortUrl: str) -> str:\n\n shortUrl = shortUrl.split(\'/\')[-1] # spliting at 1st occurance of \'/\' from right to left\n return self.url_map[shortUrl]\n```
2
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/). TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the `Solution` class: * `Solution()` Initializes the object of the system. * `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`. * `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object. **Example 1:** **Input:** url = "https://leetcode.com/problems/design-tinyurl " **Output:** "https://leetcode.com/problems/design-tinyurl " **Explanation:** Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. **Constraints:** * `1 <= url.length <= 104` * `url` is guranteed to be a valid URL.
null
joke solution
encode-and-decode-tinyurl
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Codec:\n\n def encode(self, longUrl: str) -> str:\n """Encodes a URL to a shortened URL.\n """\n return longUrl\n \n\n def decode(self, shortUrl: str) -> str:\n """Decodes a shortened URL to its original URL.\n """\n return shortUrl\n \n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.decode(codec.encode(url))\n```
1
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/). TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the `Solution` class: * `Solution()` Initializes the object of the system. * `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`. * `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object. **Example 1:** **Input:** url = "https://leetcode.com/problems/design-tinyurl " **Output:** "https://leetcode.com/problems/design-tinyurl " **Explanation:** Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. **Constraints:** * `1 <= url.length <= 104` * `url` is guranteed to be a valid URL.
null
Python3 proper https:// tin.e/ URL
encode-and-decode-tinyurl
0
1
using the md5 hashing to provide a proper tiny(er)url.\n\nMost implementations being posted are not even valid URLs, like wtf?\n\nProperly is like 3 extra lines compared to the just return the given value. smh\n\n\n```\nimport hashlib\n\n\nclass Codec:\n def __init__(self):\n self.urls = {}\n\n def hash_to(self, s):\n return \'https://tin.e/\' + hashlib.md5(s.encode()).hexdigest()\n\n def encode(self, long_url: str) -> str: # Encodes a URL to a shortened URL.\n hash_key = self.hash_to(long_url)\n self.urls[hash_key] = long_url\n return hash_key\n \n def decode(self, short_url: str) -> str: # Decodes a shortened URL to its original URL.\n return self.urls[short_url]\n```
15
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/). TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the `Solution` class: * `Solution()` Initializes the object of the system. * `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`. * `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object. **Example 1:** **Input:** url = "https://leetcode.com/problems/design-tinyurl " **Output:** "https://leetcode.com/problems/design-tinyurl " **Explanation:** Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. **Constraints:** * `1 <= url.length <= 104` * `url` is guranteed to be a valid URL.
null
535: Solution with step by step explanation
encode-and-decode-tinyurl
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nlong_to_short: a dictionary to store the mapping between long and short URLs.\nshort_to_long: a dictionary to store the mapping between short and long URLs.\nchar_set: a string of characters used to generate short codes.\nbase_url: the base URL used to construct the short URL.\nImplement the encode() method, which takes a long URL as input and returns a short URL as output. The method works as follows:\n\nIf the long URL has already been encoded, return the existing short URL.\nOtherwise, generate a new short URL by randomly selecting 6 characters from the character set and appending them to the base URL.\nIf the short URL has not been used yet, store the mapping between long and short URLs and return the short URL.\nIf the short URL has already been used, generate a new short URL and repeat the process.\nImplement the decode() method, which takes a short URL as input and returns the original long URL as output. The method works by looking up the long URL in the short_to_long dictionary using the short URL as the key.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Codec:\n # Initialize the object of the system\n def __init__(self):\n self.long_to_short = {}\n self.short_to_long = {}\n self.char_set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"\n self.base_url = "http://tinyurl.com/"\n\n # Returns a tiny URL for the given longUrl\n def encode(self, longUrl: str) -> str:\n if longUrl in self.long_to_short:\n # If the long URL has already been encoded, return the existing short URL\n return self.long_to_short[longUrl]\n else:\n # Otherwise, generate a new short URL\n while True:\n # Generate a random 6-character string from the character set\n short_code = "".join(random.choice(self.char_set) for _ in range(6))\n short_url = self.base_url + short_code\n if short_url not in self.short_to_long:\n # If the short URL has not been used yet, store the mapping between long and short URLs\n self.long_to_short[longUrl] = short_url\n self.short_to_long[short_url] = longUrl\n return short_url\n\n # Returns the original long URL for the given shortUrl\n def decode(self, shortUrl: str) -> str:\n return self.short_to_long[shortUrl]\n\n```
4
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/). TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the `Solution` class: * `Solution()` Initializes the object of the system. * `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`. * `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object. **Example 1:** **Input:** url = "https://leetcode.com/problems/design-tinyurl " **Output:** "https://leetcode.com/problems/design-tinyurl " **Explanation:** Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. **Constraints:** * `1 <= url.length <= 104` * `url` is guranteed to be a valid URL.
null
✅ Python Simple Solution using Fixed-length Key
encode-and-decode-tinyurl
0
1
The code creates a fixed-sized key of length 6. For this specific case, I am using the following char-set to generate each char of the key:\n`0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`\n\nThe length of char-set is **62**. With this char-set, we would be able to generate **62^6** combinations i. e around 56 billion keys. The key is randomly generated using the ***random*** library. \n\n```\nfrom random import choice \nclass Codec:\n \n def __init__(self):\n self.charset = \'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\'\n self.urls = {}\n \n def get_key(self):\n return \'\'.join(choice(self.charset) for i in range(6))\n \n def encode(self, longUrl: str) -> str:\n """Encodes a URL to a shortened URL.\n """\n key = self.get_key() \n while key in self.urls: # generate a non-existing key\n key = self.get_key()\n \n self.urls[key] = longUrl\n return "http://tinyurl.com/" + key\n\n def decode(self, shortUrl: str) -> str:\n """Decodes a shortened URL to its original URL.\n """\n key = shortUrl[shortUrl.rindex(\'/\')+1:]\n return self.urls[key] if key in self.urls else \'\'\n\t\t\n```\n\n---\n\n***Please upvote if you find it useful***
12
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/). TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the `Solution` class: * `Solution()` Initializes the object of the system. * `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`. * `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object. **Example 1:** **Input:** url = "https://leetcode.com/problems/design-tinyurl " **Output:** "https://leetcode.com/problems/design-tinyurl " **Explanation:** Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. **Constraints:** * `1 <= url.length <= 104` * `url` is guranteed to be a valid URL.
null
Solution
complex-number-multiplication
1
1
```C++ []\nclass Solution {\n public:\n string complexNumberMultiply(string a, string b) {\n const auto& [A, B] = getRealAndImag(a);\n const auto& [C, D] = getRealAndImag(b);\n return to_string(A * C - B * D) + "+" + to_string(A * D + B * C) + "i";\n }\n private:\n pair<int, int> getRealAndImag(const string& s) {\n const string& real = s.substr(0, s.find_first_of(\'+\'));\n const string& imag = s.substr(s.find_first_of(\'+\') + 1);\n return {stoi(real), stoi(imag)};\n };\n};\n```\n\n```Python3 []\nclass Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n real1,imag1=map(int,num1[:-1].split(\'+\'))\n real2,imag2=map(int,num2[:-1].split(\'+\'))\n real=real1*real2-imag1*imag2\n imag=real1*imag2+real2*imag1\n return str(real)+\'+\'+str(imag)+\'i\'\n```\n\n```Java []\nclass Solution {\n public String complexNumberMultiply(String num1, String num2) {\n StringBuilder sb=new StringBuilder();\n \n int a=Integer.parseInt(num1.substring(0,num1.indexOf(\'+\')));\n int b=Integer.parseInt(num1.substring(num1.indexOf(\'+\')+1,num1.indexOf(\'i\')));//for number a+ib\n \n int c=Integer.parseInt(num2.substring(0,num2.indexOf(\'+\')));\n int d=Integer.parseInt(num2.substring(num2.indexOf(\'+\')+1,num2.indexOf(\'i\')));//for number c+id\n \n sb.append(a*c-b*d);\n sb.append(\'+\'+"");\n sb.append(b*c+a*d);\n sb.append(\'i\');\n \n return sb.toString();\n }\n}\n```\n
1
A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where: * `real` is the real part and is an integer in the range `[-100, 100]`. * `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`. * `i2 == -1`. Given two complex numbers `num1` and `num2` as strings, return _a string of the complex number that represents their multiplications_. **Example 1:** **Input:** num1 = "1+1i ", num2 = "1+1i " **Output:** "0+2i " **Explanation:** (1 + i) \* (1 + i) = 1 + i2 + 2 \* i = 2i, and you need convert it to the form of 0+2i. **Example 2:** **Input:** num1 = "1+-1i ", num2 = "1+-1i " **Output:** "0+-2i " **Explanation:** (1 - i) \* (1 - i) = 1 + i2 - 2 \* i = -2i, and you need convert it to the form of 0+-2i. **Constraints:** * `num1` and `num2` are valid complex numbers.
null
Python Splitting the Number
complex-number-multiplication
0
1
\n# Code\n```\nclass Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n x1,x2 = int(num1.split("+")[0]),int(num2.split("+")[0])\n y1,y2 = int(num1.split("+")[1][:-1]),int(num2.split("+")[1][:-1])\n \n sayi = (x1*x2) - (y1*y2)\n i = (x1*y2) + (x2*y1)\n \n return str(sayi) + "+" + str(i) + "i"\n```
1
A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where: * `real` is the real part and is an integer in the range `[-100, 100]`. * `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`. * `i2 == -1`. Given two complex numbers `num1` and `num2` as strings, return _a string of the complex number that represents their multiplications_. **Example 1:** **Input:** num1 = "1+1i ", num2 = "1+1i " **Output:** "0+2i " **Explanation:** (1 + i) \* (1 + i) = 1 + i2 + 2 \* i = 2i, and you need convert it to the form of 0+2i. **Example 2:** **Input:** num1 = "1+-1i ", num2 = "1+-1i " **Output:** "0+-2i " **Explanation:** (1 - i) \* (1 - i) = 1 + i2 - 2 \* i = -2i, and you need convert it to the form of 0+-2i. **Constraints:** * `num1` and `num2` are valid complex numbers.
null
537: Space 99.29%, Solution with step by step explanation
complex-number-multiplication
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Split num1 and num2 into their real and imaginary parts by finding the position of the + and i symbols in the strings using the index() method.\n\n2. Convert the real and imaginary parts of num1 and num2 from strings to integers using the int() function.\n\n3. Compute the real and imaginary parts of the product using the formula:\n```\nreal_part = (a * c) - (b * d)\nimag_part = (a * d) + (b * c)\n```\nwhere a, b, c, and d are the integers representing the real and imaginary parts of num1 and num2.\n\n4. Combine the real and imaginary parts into a string on the form "real+imaginaryi" using the str() function, where real_part and imag_part are the computed real and imaginary parts of the product.\n\n5. Return the combined string as the output of the complexNumberMultiply method.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n # Split num1 and num2 into real and imaginary parts\n a, b = int(num1[:num1.index("+")]), int(num1[num1.index("+")+1:-1])\n c, d = int(num2[:num2.index("+")]), int(num2[num2.index("+")+1:-1])\n \n # Compute the real and imaginary parts of the product\n real_part = a * c - b * d\n imag_part = a * d + b * c\n \n # Combine the real and imaginary parts to form the result\n result = str(real_part) + "+" + str(imag_part) + "i"\n return result\n\n```
3
A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where: * `real` is the real part and is an integer in the range `[-100, 100]`. * `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`. * `i2 == -1`. Given two complex numbers `num1` and `num2` as strings, return _a string of the complex number that represents their multiplications_. **Example 1:** **Input:** num1 = "1+1i ", num2 = "1+1i " **Output:** "0+2i " **Explanation:** (1 + i) \* (1 + i) = 1 + i2 + 2 \* i = 2i, and you need convert it to the form of 0+2i. **Example 2:** **Input:** num1 = "1+-1i ", num2 = "1+-1i " **Output:** "0+-2i " **Explanation:** (1 - i) \* (1 - i) = 1 + i2 - 2 \* i = -2i, and you need convert it to the form of 0+-2i. **Constraints:** * `num1` and `num2` are valid complex numbers.
null
Python solution Easy and understandable
complex-number-multiplication
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code \nsolution 1 - easy \n```\nclass Solution(object):\n def complexNumberMultiply(self, n1, n2):\n """\n :type num1: str\n :type num2: str\n :rtype: str\n """\n a1,b1=n1.split(\'+\')\n a1=int(a1)\n b1=int(b1[:-1])\n a2,b2=n2.split(\'+\')\n a2=int(a2)\n b2=int(b2[:-1])\n return str(a1*a2-b1*b2)+\'+\'+str(a1*b2+a2*b1)+\'i\'\n```\n\n\n\nsolution 2 - when we need to make our question hard deliberately\uD83E\uDD23\n```\nclass Solution:\n def complexNumberMultiply(self, n1: str, n2: str) -> str:\n n1=n1.split(\'+\')\n n2=n2.split(\'+\')\n a=[n1[0]]\n b=[n2[0]]\n c=\'\'\n d=\'\'\n for i in n1[1]:\n if i==\'i\':\n break\n else:\n c+=i\n for i in n2[1]:\n if i==\'i\':\n break\n else:\n d+=i\n a.append(c)\n b.append(d)\n a1=int(a[0])*int(b[0])-int(a[1])*int(b[1])\n a2=int(a[0])*int(b[1])+int(a[1])*int(b[0])\n c1=str(a1)+\'+\'+str(a2)+\'i\'\n return c1\n```\n
1
A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where: * `real` is the real part and is an integer in the range `[-100, 100]`. * `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`. * `i2 == -1`. Given two complex numbers `num1` and `num2` as strings, return _a string of the complex number that represents their multiplications_. **Example 1:** **Input:** num1 = "1+1i ", num2 = "1+1i " **Output:** "0+2i " **Explanation:** (1 + i) \* (1 + i) = 1 + i2 + 2 \* i = 2i, and you need convert it to the form of 0+2i. **Example 2:** **Input:** num1 = "1+-1i ", num2 = "1+-1i " **Output:** "0+-2i " **Explanation:** (1 - i) \* (1 - i) = 1 + i2 - 2 \* i = -2i, and you need convert it to the form of 0+-2i. **Constraints:** * `num1` and `num2` are valid complex numbers.
null
Python3 simple solution
complex-number-multiplication
0
1
```\nclass Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n a1,b1 = num1.split(\'+\')\n a1 = int(a1)\n b1 = int(b1[:-1])\n a2,b2 = num2.split(\'+\')\n a2 = int(a2)\n b2 = int(b2[:-1])\n return str(a1*a2 + b1*b2*(-1)) + \'+\' + str(a1*b2 + a2*b1) + \'i\'\n```\n**If you like this solution, please upvote for this**
7
A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where: * `real` is the real part and is an integer in the range `[-100, 100]`. * `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`. * `i2 == -1`. Given two complex numbers `num1` and `num2` as strings, return _a string of the complex number that represents their multiplications_. **Example 1:** **Input:** num1 = "1+1i ", num2 = "1+1i " **Output:** "0+2i " **Explanation:** (1 + i) \* (1 + i) = 1 + i2 + 2 \* i = 2i, and you need convert it to the form of 0+2i. **Example 2:** **Input:** num1 = "1+-1i ", num2 = "1+-1i " **Output:** "0+-2i " **Explanation:** (1 - i) \* (1 - i) = 1 + i2 - 2 \* i = -2i, and you need convert it to the form of 0+-2i. **Constraints:** * `num1` and `num2` are valid complex numbers.
null
Python clean solution using Object-Oriented Design
complex-number-multiplication
0
1
One liners are cute but it\'s much better to write understandable code\n\n```python\nclass ComplexNumber:\n def __init__(self, string):\n real, imaginary = string.split(\'+\')\n self.real = int(real)\n self.imaginary = int(imaginary[:-1])\n \n def __mul__(self, other):\n if type(other) is not ComplexNumber:\n raise NotImplementedError\n real = self.real*other.real+self.imaginary*other.imaginary*-1\n imaginary = self.real*other.imaginary+self.imaginary*other.real\n return ComplexNumber(f\'{real}+{imaginary}i\')\n\t\t\t\n\t\t__rmul__ = __mul__\n \n def __str__(self):\n return f\'{self.real}+{self.imaginary}i\'\n \nclass Solution:\n \n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n return str(ComplexNumber(num1)*ComplexNumber(num2))\n```
3
A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where: * `real` is the real part and is an integer in the range `[-100, 100]`. * `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`. * `i2 == -1`. Given two complex numbers `num1` and `num2` as strings, return _a string of the complex number that represents their multiplications_. **Example 1:** **Input:** num1 = "1+1i ", num2 = "1+1i " **Output:** "0+2i " **Explanation:** (1 + i) \* (1 + i) = 1 + i2 + 2 \* i = 2i, and you need convert it to the form of 0+2i. **Example 2:** **Input:** num1 = "1+-1i ", num2 = "1+-1i " **Output:** "0+-2i " **Explanation:** (1 - i) \* (1 - i) = 1 + i2 - 2 \* i = -2i, and you need convert it to the form of 0+-2i. **Constraints:** * `num1` and `num2` are valid complex numbers.
null
Python3 DFS/ Recursive DFS
convert-bst-to-greater-tree
0
1
\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n - DFS - \n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def bstToGst(self, root: TreeNode) -> TreeNode:\n if not root: return None\n stack, val, curr = [], 0, root\n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.right\n curr = stack.pop()\n val += curr.val \n curr.val = val\n curr = curr.left\n return root \n```\n - Recursive DFS -\n``` \n def dfs(node, val):\n if node.right:\n val = dfs(node.right, val)\n val += node.val\n node.val = val\n if node.left:\n val = dfs(node.left, val)\n return val\n dfs(root, 0)\n return root\n```
1
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a _binary search tree_ is a tree that satisfies these constraints: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\] **Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\] **Example 2:** **Input:** root = \[0,null,1\] **Output:** \[1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-104 <= Node.val <= 104` * All the values in the tree are **unique**. * `root` is guaranteed to be a valid binary search tree. **Note:** This question is the same as 1038: [https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/)
null
Python3 easy solution || beats 99% || iterative approach
convert-bst-to-greater-tree
0
1
# Code\n```\nclass Solution:\n def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]: \n stack, summ, node = [], 0, root\n while stack or node:\n while node:\n stack.append(node)\n node = node.right\n node = stack.pop()\n node.val += summ\n summ = node.val\n node = node.left\n return root\n```
1
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a _binary search tree_ is a tree that satisfies these constraints: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\] **Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\] **Example 2:** **Input:** root = \[0,null,1\] **Output:** \[1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-104 <= Node.val <= 104` * All the values in the tree are **unique**. * `root` is guaranteed to be a valid binary search tree. **Note:** This question is the same as 1038: [https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/)
null
✔️ [Python3] IN-ORDER DFS ( •́ .̫ •̀ ), Explained
convert-bst-to-greater-tree
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThere are two important components here. First of all, for conversion, we need to know the sum of elements from the right subtree. And second, additional information about greater nodes from the parent node. So we create a helper function that returns the sum of the all nodes in the subtree, and also it deals with conversion itself using the initial value. What to pass as an initial value is decided by the parent node.\n\nTime: **O(n)**\nSpace: **O(h)** - height of the tree for call stack\n\nRuntime: 80 ms, faster than **95.23%** of Python3 online submissions for Convert BST to Greater Tree.\nMemory Usage: 16.6 MB, less than **77.23%** of Python3 online submissions for Convert BST to Greater Tree.\n\n```\nclass Solution:\n def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n def dfs(node, init):\n if not node: return 0\n \n r_sum = dfs(node.right, init)\n orig, node.val = node.val, node.val + init + r_sum\n l_sum = dfs(node.left, node.val)\n \n return r_sum + orig + l_sum\n \n dfs(root, 0)\n return root\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
11
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a _binary search tree_ is a tree that satisfies these constraints: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\] **Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\] **Example 2:** **Input:** root = \[0,null,1\] **Output:** \[1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-104 <= Node.val <= 104` * All the values in the tree are **unique**. * `root` is guaranteed to be a valid binary search tree. **Note:** This question is the same as 1038: [https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/)
null
Solution
convert-bst-to-greater-tree
1
1
```C++ []\nclass Solution {\npublic:\n TreeNode* convertBST(TreeNode* root) {\n if(root == NULL) return NULL;\n int cs = 0;\n stack<TreeNode*> st;\n TreeNode* curr = root;\n while(curr != NULL or !st.empty())\n {\n while(curr != NULL)\n {\n st.push(curr);\n curr = curr->right;\n }\n curr = st.top();st.pop();\n cs = cs+curr -> val;\n curr->val = cs;\n curr = curr->left;\n }\n return root;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n cursum = 0\n\n def dfs(node):\n if not node:\n return\n nonlocal cursum\n dfs(node.right)\n cursum += node.val\n node.val = cursum\n dfs(node.left)\n\n dfs(root)\n return root\n```\n\n```Java []\nclass Solution {\n int res = 0;\n public TreeNode convertBST(TreeNode root) {\n if(root == null) return null;\n dfs(root);\n return root;\n }\n public void dfs(TreeNode root){\n if(root == null) return;\n dfs(root.right);\n res += root.val;\n root.val = res;\n dfs(root.left);\n }\n}\n```\n
2
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a _binary search tree_ is a tree that satisfies these constraints: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\] **Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\] **Example 2:** **Input:** root = \[0,null,1\] **Output:** \[1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-104 <= Node.val <= 104` * All the values in the tree are **unique**. * `root` is guaranteed to be a valid binary search tree. **Note:** This question is the same as 1038: [https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/)
null
Python 3 | DFS | Stack | 4 different solutions
convert-bst-to-greater-tree
0
1
\n# Code\n\n```python\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n# DFS with global variable\nclass Solution:\n\n def __init__(self):\n self.greater = 0\n\n def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n \n self.dfs(root)\n return root\n\n def dfs(self, node):\n if not node:\n return 0\n\n self.dfs(node.right)\n\n self.greater += node.val\n node.val = self.greater\n\n self.dfs(node.left)\n\n return node\n\n\n# DFS without global variable\nclass Solution:\n def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n \n self.dfs(root, 0)\n return root\n\n def dfs(self, node, carry):\n if not node:\n return carry\n\n carry = self.dfs(node.right, carry)\n\n carry += node.val\n node.val = carry\n \n return self.dfs(node.left, carry)\n\n# Stack\nclass Solution:\n\n def __init__(self):\n self.greater = 0\n\n def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n\n stack = []\n node = root\n while node:\n stack.append(node)\n node = node.right\n \n while stack or node is not None:\n while node:\n stack.append(node)\n node = node.right\n\n node = stack.pop()\n \n self.greater += node.val\n node.val = self.greater\n\n node = node.left\n\n return root\n\n\n# Construct a new tree\n# Not in-place operation\nclass Solution:\n def convertBST(self, root: TreeNode) -> TreeNode:\n new_root, _ = self.convert(root, 0)\n return new_root\n\n\n def convert(self, root, incre):\n if not root:\n return root, incre\n\n right, right_max = self.convert(root.right, incre)\n new_root = TreeNode(root.val + right_max)\n left, left_max = self.convert(root.left, new_root.val)\n\n new_root.left = left\n new_root.right = right\n\n return new_root, left_max\n```
1
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a _binary search tree_ is a tree that satisfies these constraints: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\] **Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\] **Example 2:** **Input:** root = \[0,null,1\] **Output:** \[1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-104 <= Node.val <= 104` * All the values in the tree are **unique**. * `root` is guaranteed to be a valid binary search tree. **Note:** This question is the same as 1038: [https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/)
null
Python. faster than 100.00%. Explained, clear & Easy-understanding solution. O(n). Recursive
convert-bst-to-greater-tree
0
1
A tour of the tree, from right to left.\nAt each step add to the current node the value of the right tree, add to the amount we have accumulated so far the value of the current node, and add to each node in the left sub-tree the amount we have accumulated so far.\t\n\t\n\tclass Solution:\n\t\tdef convertBST(self, root: TreeNode) -> TreeNode:\n\t\t\tsum = 0\n\t\t\t\n\t\t\tdef sol(root: TreeNode) -> TreeNode:\n\t\t\t\tnonlocal sum\n\t\t\t\tif root:\n\t\t\t\t\tsol(root.right)\n\t\t\t\t\troot.val += sum\n\t\t\t\t\tsum = root.val\n\t\t\t\t\tsol(root.left)\n\t\t\t\treturn root\n\t\t\t\n\t\t\treturn sol(root)
13
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a _binary search tree_ is a tree that satisfies these constraints: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\] **Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\] **Example 2:** **Input:** root = \[0,null,1\] **Output:** \[1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-104 <= Node.val <= 104` * All the values in the tree are **unique**. * `root` is guaranteed to be a valid binary search tree. **Note:** This question is the same as 1038: [https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/)
null
python using datetime and timedelta || easy to understand
minimum-time-difference
0
1
```\nfrom datetime import datetime\nclass Solution:\n def findMinDifference(self, t: List[str]) -> int:\n dates = []\n src = datetime.now()\n for time in t:\n h,m = map(int,time.split(\':\'))\n dates.append(datetime(src.year, src.month, src.day, h, m))\n dates.append(datetime(src.year, src.month, src.day+1, h, m))\n dates.sort()\n mini = float(\'inf\')\n # print(dates)\n for i in range(len(dates)-1):\n mini = min((dates[i+1]-dates[i]).seconds,mini)\n return mini//60\n```
1
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
Python3 clean solution using sorting
minimum-time-difference
0
1
\n\n# Code\n```\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n \n def convert(time):\n h=int(time[:2])\n m=int(time[3:])\n return h*60 + m\n \n \n l=[convert(t) for t in timePoints]\n l.sort()\n n=len(l)\n \n res=min(l[i+1]-l[i] for i in range(n-1))\n \n return min(res,1440-(l[-1]-l[0])) #Think in anticlockwise \n \n \n```
3
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
Python Beginner , very easy understanding
minimum-time-difference
1
1
```\nclass Solution:\n def findMinDifference(self, time: List[str]) -> int:\n for i in range(len(time)):\n time[i]=time[i].split(\':\')\n time[i]=[int(time[i][0]),int(time[i][1])]\n\n mini=float(\'inf\')\n time.sort()\n for i in range(1,len(time)):\n mini=min(mini,(time[i][0]-time[i-1][0])*60 +(time[i][1]-time[i-1][1]))\n mini=min(mini,(time[0][0]+23-time[-1][0])*60 +(time[0][1]+60-time[-1][1]))\n return mini\n\t\t```\n\t\t\n\t\tUpvote if helped
1
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
Solution
minimum-time-difference
1
1
```C++ []\nclass Solution {\npublic:\n int findMinDifference(vector<string>& timePoints) {\n vector<int> minutes;\n\n for(int i =0;i<timePoints.size();i++){\n string curr = timePoints[i];\n int hours = stoi (curr.substr(0,2));\n int min = stoi (curr.substr(3,2));\n int totalMin = hours * 60 +min;\n\n minutes.push_back(totalMin);\n }\n sort(minutes.begin(), minutes.end());\n\n int mini = INT_MAX;\n int n = minutes.size();\n for(int i =0;i<n-1;i++){\n int diff = minutes[i+1] - minutes[i];\n mini = min(mini, diff);\n }\n int lastdiff = (minutes[0] + 1440 - minutes[n-1]);\n mini = min(mini, lastdiff);\n return mini;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n if len(timePoints) > 24*60:\n return 0\n \n seconds = []\n for time in timePoints:\n time = time.split(":")\n seconds.append(int(time[0])*60 + int(time[1]))\n\n seconds.sort()\n\n ans = seconds[0] + 24*60 - seconds[-1]\n for i in range(len(seconds) - 1):\n ans = min(ans,seconds[i + 1] - seconds[i])\n \n return ans\n```\n\n```Java []\nclass Solution {\n private int compare1(int[] time1, int[] time2) {\n int totalMin = time2[1] - time1[1];\n int hr = 0;\n if (time1[1] > time2[1]) {\n totalMin += 60;\n hr = -1;\n }\n hr += time2[0] - time1[0];\n if (hr < 0)\n hr += 24;\n return totalMin + hr * 60;\n }\n public int findMinDifference1(List<String> timePoints) {\n int size = timePoints.size();\n int[][] times = new int[size][2];\n for (int i = 0; i < size; ++i) {\n String[] splitTime = timePoints.get(i).split(":");\n times[i][0] = Integer.parseInt(splitTime[0]);\n times[i][1] = Integer.parseInt(splitTime[1]);\n }\n Arrays.sort(times, new Comparator<int[]>() {\n public int compare(int[] a, int[] b) {\n if (a[0] == b[0])\n return a[1] - b[1];\n return a[0] - b[0];\n }\n });\n int minDiff = Integer.MAX_VALUE;\n for (int i = 0, j = 1; j <= size; ++i, ++j)\n minDiff = Math.min(minDiff, compare1(times[i], times[(j % size)]));\n\n return minDiff;\n }\n private int compare(String time1Str, String time2Str) {\n int[] time1 = new int[2];\n int[] time2 = new int[2];;\n\n String[] splitTime = time1Str.split(":");\n time1[0] = Integer.parseInt(splitTime[0]);\n time1[1] = Integer.parseInt(splitTime[1]);\n\n splitTime = time2Str.split(":");\n time2[0] = Integer.parseInt(splitTime[0]);\n time2[1] = Integer.parseInt(splitTime[1]);\n\n int totalMin = time2[1] - time1[1];\n int hr = 0;\n if (time1[1] > time2[1]) {\n totalMin += 60;\n hr = -1;\n }\n hr += time2[0] - time1[0];\n if (hr < 0)\n hr += 24;\n return totalMin + hr * 60;\n }\n public int findMinDifference(List<String> timePoints) {\n int size = 24 * 60;\n boolean[] mark = new boolean[size];\n for (String t : timePoints) {\n int h = (t.charAt(0) - \'0\') * 10 + (t.charAt(1) - \'0\');\n int m = (t.charAt(3) - \'0\') * 10 + (t.charAt(4) - \'0\'); \n if (mark[h * 60 + m])\n return 0;\n mark[h * 60 + m] = true;\n }\n int minDiff = Integer.MAX_VALUE, prev = -1;\n int first = -1;\n for (int i = 0; i < size; ++i) {\n if (!mark[i])\n continue;\n\n if (prev != -1)\n minDiff = Math.min(minDiff, i - prev);\n else\n first = i;\n prev = i;\n }\n return Math.min(minDiff, (1440 - prev) + first);\n }\n}\n```\n
1
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
[python 3] bucket sort, O(n) time, O(1) space
minimum-time-difference
0
1
```\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n M = 1440\n times = [False] * M\n for time in timePoints:\n minute = self.minute(time)\n if times[minute]:\n return 0\n times[minute] = True\n \n minutes = [i for i in range(M) if times[i]]\n return min((minutes[i] - minutes[i-1]) % M for i in range(len(minutes)))\n \n def minute(self, time: str) -> int:\n h, m = map(int, time.split(\':\'))\n return 60*h + m
11
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
Python Solution with Sorting and Two-pointers
minimum-time-difference
0
1
```\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n minutesConvert = []\n\t\t# convert time points to minutes expression\n for time in timePoints:\n t = time.split(":")\n minutes = int(t[0]) * 60 + int(t[1])\n minutesConvert.append(minutes)\n\t\t# sort the minutes by ascending order\n minutesConvert.sort()\n res = float("inf")\n \n left, right = 0, 1\n\t\t# use two points to find the minimum diff in the list\n while right < len(minutesConvert ):\n res = min(res, minutesConvert [right] - minutesConvert [left])\n left += 1\n right += 1\n # edge case: minimum diff could happen between first and last time\n\t\t# just picture a clock in your mind --- it is circle, right?!\n left = 0\n right = len(minutesConvert) - 1\n\t\t# 1440 - minutesConvert[right] is the diff between last time to 00:00\n res = min(res, 1440 - minutesConvert[right] + minutesConvert[left])\n\t\t\n return res\n```\n\nThis question is a bit tricky mainly due to this edge case, as long as we picture the given list as a cycle, should be easy to figure out the solution!\n\n
1
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
Clean Python, O(n) vs O(n log n) Discussion, Shortcut for long inputs
minimum-time-difference
0
1
Why is complexity O(n) or O(n log n): This basically depends on whether you sort via counting sort. Counting sort could be considered an O(n) sorting algorithm for this problem, but it would have 60 x 24 = 1440 buckets. For reference: 530 x log(530) = 1443. Given that 2 <= timePoints.length <= 2 x 10^4, it could make sense to use counting sort for long inputs. Given that 10^4 > 1440, we can have collisions. If timePoints.length > 1440, then we have at least one duplicate time and the difference is always 0.\n\n```\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n def toMinFromZero(t):\n return 60*int(t[:2]) + int(t[3:])\n \n maxMins = 60*24 # number of mins in a day\n if len(timePoints) > maxMins:\n return 0\n \n # we sort the timestamps. Idea: The smallest difference will always be a \n # difference between two neighboring times in the array.\n ts = [toMinFromZero(t) for t in timePoints]\n ts.sort()\n \n diffMin = maxMins\n # calculate the pairwise difference ...\n for i in range(1,len(ts)):\n t_high = ts[i]\n t_low = ts[i-1]\n diffMin = min(diffMin, t_high - t_low)\n # ... and due to the 24 hour clock, don\'t forget the last and first entry with modulo arithmetic\n diffMin = min(diffMin, (ts[0] - ts[-1]) % maxMins)\n \n return diffMin\n```
10
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
539: Solution with step by step explanation
minimum-time-difference
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Convert the list of time points to a list of minutes since midnight by splitting the string into hours and minutes and converting them to integers. Store the result in a variable called minutes.\n2. Sort the list of minutes in ascending order.\n3. Initialize a variable called min_diff to infinity.\n4. Loop through the list of minutes starting from the first element to the second to last element:\nCalculate the difference between the current element and the next element in the list.\nIf the difference is less than min_diff, update min_diff to be the difference.\n5. Calculate the difference between the last element in the list and the first element in the list, accounting for wraparound (i.e., the possibility that the last element in the list is actually earlier in the day than the first element). Store the result in a variable called diff.\n6. If diff is less than min_diff, update min_diff to be diff.\n7. Return min_diff.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n # Convert time points to minutes since midnight and sort the list\n minutes = sorted([int(time[:2]) * 60 + int(time[3:]) for time in timePoints])\n \n # Calculate the minimum difference between adjacent time points\n min_diff = float(\'inf\')\n for i in range(len(minutes) - 1):\n diff = minutes[i+1] - minutes[i]\n if diff < min_diff:\n min_diff = diff\n \n # Calculate the difference between the first and last time points\n diff = (24*60 - minutes[-1] + minutes[0]) % (24*60)\n if diff < min_diff:\n min_diff = diff\n \n return min_diff\n\n```
4
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
Easy & Clear Solution Python 3
minimum-time-difference
0
1
```\nclass Solution:\n def findMinDifference(self, t: List[str]) -> int:\n tab=[]\n for i in t:\n tab.append(int(i[0:2])*60+int(i[3:]))\n tab.sort()\n n=len(tab)\n res=1440+tab[0]-tab[n-1]\n for i in range(1,n):\n res=min(res,(tab[i]-tab[i-1]))\n return res \n```
16
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
Linear Search Approach
single-element-in-a-sorted-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs the given array is sorted hence unique element will not match with its previous and next numbers(if exists).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe search from element at index 1 upto index n-2 that if any element is present that satisfies the above condition and returns the value.\nThen will check the end cases:\n1) For first element we will check it with second element\n2) For last element we will check it with second last element\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n if len(nums)==1: #only unique element\n return nums[0]\n\n if nums[0]!=nums[1]: #check first element\n return nums[0]\n\n for i in range(1,len(nums)-1): #check elements in middle\n if nums[i]!=nums[i-1] and nums[i]!=nums[i+1]:\n return nums[i]\n\n return nums[-1] #only last element will be left\n```
2
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Day 52 || Binary Search || Easiest Beginner Friendly Sol
single-element-in-a-sorted-array
1
1
# Intuition of this Problem:\nSince every element in the sorted array appears exactly twice except for the single element, we know that if we take any element at an even index (0-indexed), the next element should be the same. Similarly, if we take any element at an odd index, the previous element should be the same. Therefore, we can use binary search to compare the middle element with its adjacent elements to determine which side of the array the single element is on.\n\nIf the middle element is at an even index, then the single element must be on the right side of the array, since all the elements on the left side should come in pairs. Similarly, if the middle element is at an odd index, then the single element must be on the left side of the array.\n\nWe can continue this process by dividing the search range in half each time, until we find the single element.\n\n ***Another interesting observation you might have made is that this algorithm will still work even if the array isn\'t fully sorted. As long as pairs are always grouped together in the array (for example, [10, 10, 4, 4, 7, 11, 11, 12, 12, 2, 2]), it doesn\'t matter what order they\'re in. Binary search worked for this problem because we knew the subarray with the single number is always odd-lengthed, not because the array was fully sorted numerically***\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Initialize two pointers, left and right, to the first and last indices of the input array, respectively.\n2. While the left pointer is less than the right pointer:\n - a. Compute the index of the middle element by adding left and right and dividing by 2.\n - b. If the index of the middle element is odd, subtract 1 to make it even.\n - c. Compare the middle element with its adjacent element on the right:\n - i. If the middle element is not equal to its right neighbor, the single element must be on the left side of the array, so update the right pointer to be the current middle index.\n - ii. Otherwise, the single element must be on the right side of the array, so update the left pointer to be the middle index plus 2.\n1. When the left and right pointers converge to a single element, return that element.\n<!-- Describe your approach to solving the problem. -->\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n int singleNonDuplicate(vector<int>& nums) {\n int left = 0, right = nums.size() - 1;\n while (left < right) {\n int mid = (left + right) / 2;\n if (mid % 2 == 1) {\n mid--;\n }\n if (nums[mid] != nums[mid + 1]) {\n right = mid;\n } else {\n left = mid + 2;\n }\n }\n return nums[left];\n }\n};\n```\n```Java []\nclass Solution {\n public int singleNonDuplicate(int[] nums) {\n int left = 0, right = nums.length - 1;\n while (left < right) {\n int mid = (left + right) / 2;\n if (mid % 2 == 1) {\n mid--;\n }\n if (nums[mid] != nums[mid + 1]) {\n right = mid;\n } else {\n left = mid + 2;\n }\n }\n return nums[left];\n }\n}\n\n```\n```Python []\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n left, right = 0, len(nums) - 1\n while left < right:\n mid = (left + right) // 2\n if mid % 2 == 1:\n mid -= 1\n if nums[mid] != nums[mid + 1]:\n right = mid\n else:\n left = mid + 2\n return nums[left]\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(logn)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
456
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Most easy three lines solution
single-element-in-a-sorted-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n s=sum(nums)\n a=set(nums)\n l=list(a)\n o=sum(l)\n\n return (2*o-s)\n```
1
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Binary Search || Python3
single-element-in-a-sorted-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(logn)\n\n- Space complexity:O(1)\n\n# Code\n```\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n if len(nums)==1:\n return nums[0]\n low=0\n high=len(nums)-1\n if nums[low]!=nums[low+1]:\n return nums[low]\n if nums[high]!=nums[high-1]:\n return nums[high]\n while low<=high:\n mid=low+(high-low)//2\n if nums[mid]!=nums[mid-1] and nums[mid]!=nums[mid+1]:\n return nums[mid]\n elif(nums[mid]==nums[mid+1] and mid%2==0) or (nums[mid]==nums[mid-1] and mid%2!=0):\n low=mid+1\n else:\n high=mid-1\n return -1\n```
1
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Solution
single-element-in-a-sorted-array
1
1
```C++ []\nclass Solution {\npublic:\n int singleNonDuplicate(vector<int>& nums) {\n ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL);\n\n int l=0,r=nums.size()-1,mid;\n while(l<r){\n mid=(l+r)/2;\n if(mid%2){\n if(nums[mid]!=nums[mid+1]) l=mid+1;\n else r=mid;\n }else{\n if(nums[mid]==nums[mid+1]) l=mid+1;\n else r=mid;\n }\n }\n return nums[l];\n }\n};\n```\n\n```Python3 []\nf=open(\'user.out\',\'w\')\ntry:\n while True:\n nums=list(map(int,input()[1:-1].split(\',\')))\n n=len(nums)-1\n a,b,i=0,n,n//2\n try:\n while True:\n if nums[i]==nums[i-1]:\n if i%2==0: b=i-2\n else: a=i+1\n elif nums[i]==nums[i+1]:\n if i%2==0: a=i+2\n else: b=i-1\n else: \n print(nums[i],file=f)\n break\n i=(a+b)//2\n except: print(nums[i],file=f)\nexcept:\n f.close()\n exit()\n```\n\n```Java []\nclass Solution {\n public int singleNonDuplicate(int[] nums) {\n int left = 0, right = nums.length - 1;\n while (left < right) {\n int mid = (left + right) / 2;\n if (mid % 2 == 1) {\n mid--;\n }\n if (nums[mid] != nums[mid + 1]) {\n right = mid;\n } else {\n left = mid + 2;\n }\n }\n return nums[left];\n }\n}\n```\n
1
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Using Binary Search
single-element-in-a-sorted-array
0
1
# Intuition\nsince it sorted array, hence binary search is the first thing that comes to mind. \n\n# Approach\nInitialization is same as binary search. \n\nWhen you find the mid-index, we try to point the mid-index always to the second value of any number pair. which is done in the first **if** block inside the **while** loop.\n\nThen we check if this value is distinct or not by comparing it with its adjacent values.\n\n**Lets talk about reducing the search space:**\nIf every value is in pair apart from one, length of sub-array containing a single value will always be odd. ****Always remember**** difference between (start and mid-value) or (mid-value and end) will be even if it contains the single value. Hence we reduce the size of the array accordoingly. \n\n\n# Code\n```\nclass Solution:\n def singleNonDuplicate(self, arr: List[int]) -> int:\n i = 0\n j = len(arr) - 1\n while i < j:\n m = (i+j) // 2\n if m < j and arr[m] == arr[m+1]:\n m = m + 1\n if arr[m] != arr[m-1] and arr[m] != arr[m+1]:\n return arr[m]\n elif abs(m-i) % 2 == 0:\n j = m - 1\n else:\n i = m + 1 \n return arr[i]\n\n```
1
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
|| 🐍 Python3 Easiest ✔ Solution 🔥 ||
single-element-in-a-sorted-array
0
1
# Approach\n1. Variable `n` is assigned the value of first number in list.\n2. A `for` loop is used to iterate through list from index 1 while we `XOR (^)` the numbers with `n`.\n - Since the numbers are in pair the `XOR` function will eliminate the pairs and only the unique element remains.\n\n# Complexity\n- Time complexity : $$O(n)$$\n- Space complexity : $$O(1)$$\n\n# Code\n```python []\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n n= nums[0]\n for i in nums[1:]:\n n^= i\n return n\n```\n---\n\n### Happy Coding \uD83D\uDC68\u200D\uD83D\uDCBB\n\n---\n\n### If this solution helped you then do consider Upvoting \u2B06.\n#### Lets connect on LinkedIn : [Om Anand](https://www.linkedin.com/in/om-anand-38341a1ba/) \uD83D\uDD90\uD83D\uDE00\n---\n\n### Comment your views/corrections \uD83D\uDE0A\n
1
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Simple to understanding python solution
single-element-in-a-sorted-array
0
1
```python []\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n l, r = 0, len(nums) - 1\n\n while l <= r:\n m_l = m_r = m = (l + r) // 2\n if m > 0 and nums[m-1] == nums[m]:\n m_l = m - 1\n elif m + 1 < len(nums) and nums[m+1] == nums[m]:\n m_r = m + 1\n\n if (m_l - l) % 2 == 1:\n r = m_l - 1\n elif (r - m_r) % 2 == 1:\n l = m_r + 1\n else:\n return nums[m]\n\n```
1
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Easiest python solution using binary search type logic
single-element-in-a-sorted-array
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in this algorithm is binary search. The key observation is that if an element is not the single non-duplicate, then it should be equal to its neighbor element, i.e., either the previous or the next element. Therefore, the elements will always appear in pairs, except for the single non-duplicate.\n\nWe start by initializing two pointers, l and h, to the start and end of the input list, respectively. Then we keep dividing the list into two halves, and for each mid point mid, we check if nums[mid] is the single non-duplicate or not.\n\nIf nums[mid] is not the single non-duplicate, we use its neighboring element to determine which half of the list to search next. If nums[mid] is equal to nums[mid+1], then we know that the single non-duplicate is in the right half, and we adjust the l pointer to mid+1 or the h pointer to mid-1 accordingly. If nums[mid] is not equal to nums[mid+1], then we know that the single non-duplicate is in the left half, and we adjust the l pointer to mid-1 or the h pointer to mid+1 accordingly.\n\nWe repeat the above process until we find the single non-duplicate or until the l and h pointers meet, in which case we return the element at the l pointer as the single non-duplicate.\n# Complexity\n- Time complexity:$$O(log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n # Initialize the left pointer to the beginning of the array\n l = 0\n # Get the length of the array\n n = len(nums)\n # Initialize the right pointer to the end of the array\n h = n-1 \n \n # Perform binary search\n while l < h:\n # Find the middle index\n mid = (l+h)//2\n \n # If the element at the middle index is not equal to the element to its left or right, we\'ve found the single element\n if nums[mid] != nums[mid-1] and nums[mid] != nums[mid+1]:\n return nums[mid]\n \n # If the element at the middle index is equal to the element to its right, the single element must be to the right\n if nums[mid] == nums[mid+1]:\n # If the index of the middle element is even, we know that all the elements to the left are in pairs\n # and we should search for the single element to the right of the middle element\n if mid %2 == 0:\n l = mid+1\n # If the index of the middle element is odd, we know that all the elements to the left are not in pairs\n # and the single element must be to the left of the middle element\n else:\n h = mid -1\n # If the element at the middle index is not equal to the element to its right, the single element must be to the left\n else:\n # If the index of the middle element is even, we know that all the elements to the left are not in pairs\n # and the single element must be to the left of the middle element\n if mid %2 == 0:\n h = mid -1\n # If the index of the middle element is odd, we know that all the elements to the left are in pairs\n # and we should search for the single element to the right of the middle element\n else:\n l = mid +1\n \n # If l==h, we\'ve found the single element\n return nums[l]\n\n```
1
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
75% faster O(n), 83% less mem.
single-element-in-a-sorted-array
0
1
# Intuition\nXOR\'em all\n\n# Approach\nI know, I know. I should implement bisect to get O(log n)...\nBut It would be a nice loffow up "what if input is not sorter", isn\'t it?\n\nIf you like it, please up-vote. Thank you!\n\n# Complexity\n- Time complexity: $$O(n)$$, yet 75% faster\n\n- Space complexity: $$O(1)$$, 82% less mem\n\n# Code\n```\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n return reduce(operator.xor, nums, 0)\n```
1
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
python 2 pointer solution - easy for beginners
reverse-string-ii
0
1
# Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n temp = []\n first = 0\n last = k-1 \n while (first <= len(s)-1): \n if last > len(s)-1:\n last = len(s) - 1\n while(last >= first): \n temp.append(s[last]) \n last = last - 1\n first = first + k \n last = first + (k-1)\n while(last >= first):\n if first > len(s)-1:\n break\n temp.append(s[first]) \n first = first + 1 \n last = first + (k-1) \n return \'\'.join(temp)\n \n\n```
1
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
85% faster solution using Stack and Python
reverse-string-ii
0
1
# Intuition\n`2*k` is a strong clue for traversing through the string. This clue will help to divide the string into 2 stacks. Then the the job is to merge the two stacks. Before merging, reverse the subsring that matches the requirement of problem statement.\n\n# Approach\n- Divide the problem into 3 stacks. \n- one for reversed\n- one for non reversed\n- one for merging\n- Reverse of substring is done by a helper function.\n- concatenate the elements of the merged stack and return\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n``` python\nclass Solution:\n def reverseStr(self, s: str, k: int):\n\n def reverse_word(x): return x[::-1]\n\n final_string = ""\n if len(s) <= k:\n final_string = reverse_word(s)\n return final_string\n\n stack_non_reversed: list = []\n stack_reversed: list = []\n stack_final: list = []\n\n for i in range(0, len(s), 2*k):\n temp = s[i:i+k]\n stack_non_reversed.append(temp)\n\n for item in stack_non_reversed:\n stack_reversed.append(reverse_word(item))\n\n stack_non_reversed.clear()\n\n for i in range(k, len(s), 2*k):\n temp = s[i:i+k]\n stack_non_reversed.append(temp)\n\n for i, item in enumerate(stack_reversed):\n stack_final.append(item)\n if i > len(stack_non_reversed)-1:\n continue\n stack_final.append(stack_non_reversed[i])\n\n for item in stack_final:\n final_string += item\n\n return final_string\n\n```
1
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
✅Python3 33ms 🔥🔥 easiest solution
reverse-string-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith help of blocks of string we can solve this.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- divide string in 2k blocks.\n- if length is less than k then reverse remainning and return.\n- now in 2k length blocks, get first k block of string.\n- reverse it and store.\n- now append rest of k symbols as it is.\n- do this till remainning length is greater than k.\n- now at end when length is less than k, reverse remanning and append them.\n- return from function.\n- return answer.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(2N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n ans = ""\n def helper(org=s):\n nonlocal ans\n n = 2*k\n if len(org)<k:\n ans += org[::-1]\n return\n else:\n while len(org) > k:\n t = org[0:n]\n org = org[n:]\n x = t[0:k]\n t = t[k:]\n ans += x[::-1] + t\n if len(org) <=k:\n ans += org[::-1]\n return\n helper()\n return ans\n```\n# Please like and comment below.\n# :-)
3
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
✅ Easiest | | 6 lines Solution | | C++ | | Python ✅
reverse-string-ii
0
1
# C++\n```\nclass Solution {\npublic:\n string reverseStr(string s, int k) {\n int l = 0,r = min(k,(int)s.length());\n\n while(l < s.length()){\n reverse(s.begin() + l,s.begin() + r);\n l += 2 * k;\n r = min(l + k,(int)s.length());\n }\n return s;\n }\n};\n```\n\n# Pyhton \n\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n l, r = 0, min(k, len(s))\n\n while l < len(s):\n # Reverse the substring from index l to r\n s = s[:l] + s[l:r][::-1] + s[r:]\n \n # Move to the next pair of substrings\n l += 2 * k\n r = min(l + k, len(s))\n\n return s\n\n```
3
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
Python3 Simple Solution (6 lines)
reverse-string-ii
0
1
# Intuition\nThink of loop and iteration.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIncremenet a variable by concatenating the substring of string.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n i = 0\n S = \'\'\n while i < len(s):\n S += s[i:i + k][::-1]\n S += s[i + k:i + k + k]\n i += k + k\n return S\n```
1
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
Python3 Easy Solution With Comments
reverse-string-ii
0
1
\n# Approach\nThe reverseStr function takes two inputs, a string s and an integer k. It first converts the input string to a list of characters using the list() function. Then, it initializes a variable n to the length of the input string.\n\nThe function uses a while loop to iterate through the string with a step of 2k. In each iteration, it reverses the first k characters using list slicing and the [::-1] notation to reverse the order of the elements. If there are fewer than k characters left, the function reverses all of them. Finally, the function skips the next 2k characters by incrementing the index i by 2k.\n\nAfter the loop completes, the function converts the list of characters back to a string using the join() method with an empty delimiter. The resulting string is returned as the output of the function.\n\n\n# Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n # convert the string to a list of characters\n s_list = list(s)\n n = len(s)\n i = 0\n while i < n:\n # reverse the first k characters\n if i + k <= n:\n s_list[i:i+k] = s_list[i:i+k][::-1]\n # if fewer than k characters left, reverse all of them\n else:\n s_list[i:] = s_list[i:][::-1]\n # skip the next 2k characters\n i += 2 * k\n # convert the list of characters back to a string\n return \'\'.join(s_list)\n\n\n\n\n\n\n```
1
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
easy to understand python solution
reverse-string-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n i = 0\n while i < len(s):\n s = s[:i]+s[i:i+k][::-1]+s[i+k:]\n i = i + 2 * k\n return s\n \n```
1
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
Simple and easy Python solution
reverse-string-ii
0
1
My concept is to for loop and split every 4 letter as a group,\neach group will reverse first 2 letter and add remaining letter.\neach loop Add word to the empty string call "sentence"\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n sentence = ""\n for x in range(0, len(s), k+k):\n word = s[x:x+k+k]\n sentence += word[0:k][::-1]+word[k:] \n return sentence\n```
6
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
Python3, string ->List ->string
reverse-string-ii
0
1
```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n # Convert the input string into a list of characters\n mylist = list(s)\n \n # Iterate through the list with a step size of 2k\n for i in range(0, len(mylist), k + k):\n # Reverse the sublist of characters within the range of i to i + k\n mylist[i:k + i] = reversed(mylist[i:k + i])\n \n # Join the reversed list of characters back into a string and return it\n return "".join(mylist)\n\n```
4
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
Python 97.68% beats 4line Code || Easy
reverse-string-ii
0
1
**If you got help from this,... Plz Upvote .. it encourage me**\n\n# Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n s = list(s)\n for i in range(0,len(s),2*k):\n s[i:i+k] = reversed(s[i:i+k])\n return "".join(s)\n```
5
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
Solution
reverse-string-ii
1
1
```C++ []\nclass Solution {\npublic:\n string reverseStr(string s, int k) {\n int len = s.size();\n\n int left = 0, right = 0;\n for(int i = 0; i < len; i += 2*k) {\n left = i;\n right = min(left + k - 1, len - 1);\n\n while(left <= right) {\n char tmp = move(s[left]);\n s[left++] = move(s[right]);\n s[right--] = move(tmp);\n }\n }\n return move(s);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n temp = []\n while s:\n temp.append(s[:k])\n s = s[k:]\n for i in range(0, len(temp), 2):\n temp[i] = temp[i][::-1]\n return \'\'.join(temp)\n```\n\n```Java []\nclass Solution {\n public String reverseStr(String s, int k) {\n char[] arr = s.toCharArray();\n int n = arr.length;\n for (int i = 0; i < n; i += 2 * k) {\n int left = i;\n int right = Math.min(i + k - 1, n - 1);\n while (left < right) {\n char temp = arr[left];\n arr[left++] = arr[right];\n arr[right--] = temp;\n }\n }\n return new String(arr);\n}\n}\n```\n
1
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
✅ Explained - Simple and Clear Python3 Code✅
reverse-string-ii
0
1
# Intuition\nThe problem requires us to reverse the first k characters for every 2k characters in a given string. To solve this, we can iterate over the string and use a list to store the reversed segments. By considering the pattern of reversing every 2k characters, we can determine the positions where the reversal needs to occur.\n\n\n# Approach\n1.\tInitialize an empty list, "tab," to store the reversed segments of the string.\n2.\tIterate over the characters in the string using a for loop.\n3.\tFor each character at index i, check if (i//k)%2 is equal to 0. This condition ensures that we are within the first k characters of every 2k segment.\n4.\tIf the condition is true, insert the character at index i in the "tab" list, using the formula (i-i%k). This ensures that the first k characters are reversed and inserted at the correct position.\n5.\tIf the condition is false, append the character to the end of the "tab" list.\n6.\tOnce the loop is complete, initialize an empty string, "res," to store the final result.\n7.\tIterate over the elements in the "tab" list and concatenate them to the "res" string.\n8.\tReturn the "res" string as the reversed string with the specified pattern.\n\n\n\n# Complexity\n- Time complexity:\nThe algorithm iterates over each character in the string once, resulting in a time complexity of O(n), where n is the length of the string.\n\n\n- Space complexity:\nWe use additional space to store the reversed segments in the "tab" list. The space complexity is O(n), where n is the length of the string, as the size of the list grows linearly with the input.\n\n\n# Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n tab=[]\n for i in range(len(s)):\n if (i//k)%2==0:\n tab.insert(i-i%k,s[i])\n else:\n tab.append(s[i])\n res=""\n for t in tab:\n res+=t\n return res\n```
6
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
Simple Python recursion solution (Beginner Friendly)
reverse-string-ii
0
1
```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n def reverse1(s, k):\n if len(s)<k:\n return s[::-1]\n if len(s)>=k and len(s)<=2*k:\n s1 = s[:k]; s2 = s[k:]\n s1 = list(s1)\n i = 0; j = len(s1)-1\n while(i<j):\n temp = s1[i]; s1[i] = s1[j]; s1[j] = temp\n i+=1; j-=1\n s1 = \'\'.join(s1)\n return s1+s2\n else:\n return reverse1(s[:(2*k)], k) + reverse1(s[(2*k):], k)\n s = reverse1(s, k)\n return s\n```
1
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
Easy to understand Python solution to reverse string
reverse-string-ii
0
1
\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n l = list(s)\n for i in range(0, len(l), 2 * k):\n start = i\n end = min(i + k - 1, len(l) - 1) \n while start < end:\n l[start], l[end] = l[end], l[start]\n start += 1\n end -= 1\n\n return \'\'.join(l)\n\n```
2
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
Python easy solution
reverse-string-ii
0
1
\n def reverseStr(self, s: str, k: int) -> str:\n s= list(s)\n for i in range(0,len(s),2*k):\n s[i:i+k] = s[i:i+k][::-1]\n return "".join(s)
4
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. **Example 1:** **Input:** s = "abcdefg", k = 2 **Output:** "bacdfeg" **Example 2:** **Input:** s = "abcd", k = 2 **Output:** "bacd" **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 104`
null
Python short and clean.
01-matrix
0
1
# Approach\nDo a two pass on the entire matrix, considering `left and top` while going `top-left to bottom-right`; `right and bottom` while going `bottom-right to top-left` corner.\n\n# Complexity\n- Time complexity: $$O(m \\cdot n)$$\n\n- Space complexity: $$O(m \\cdot n)$$\n\nwhere $$m \\times n$$ is the dimensions of `mat`.\n\n# Code\n```python\nclass Solution:\n def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:\n m, n = len(mat), len(mat[0])\n dists = [[inf] * n for _ in range(m)]\n\n get_at = lambda x, y: dists[x][y] if 0 <= x < m and 0 <= y < n else inf\n\n # top-left to bottom-right\n for i, j in product(range(m), range(n)):\n dists[i][j] = mat[i][j] and min(dists[i][j], min(get_at(i - 1, j), get_at(i, j - 1)) + 1)\n \n # bottom-right to top-left\n for i, j in product(range(m - 1, -1, -1), range(n - 1, -1, -1)):\n dists[i][j] = mat[i][j] and min(dists[i][j], min(get_at(i + 1, j), get_at(i, j + 1)) + 1)\n \n return dists\n\n\n```
1
Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_. The distance between two adjacent cells is `1`. **Example 1:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Example 2:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[1,2,1\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `mat[i][j]` is either `0` or `1`. * There is at least one `0` in `mat`.
null
Easiest Solution
01-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n if not mat or not mat[0]:\n return []\n\n m, n = len(mat), len(mat[0])\n queue = deque()\n MAX_VALUE = m * n\n \n # Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 0:\n queue.append((i, j))\n else:\n mat[i][j] = MAX_VALUE\n \n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n \n while queue:\n row, col = queue.popleft()\n for dr, dc in directions:\n r, c = row + dr, col + dc\n if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1:\n queue.append((r, c))\n mat[r][c] = mat[row][col] + 1\n \n return mat\n```
1
Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_. The distance between two adjacent cells is `1`. **Example 1:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Example 2:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[1,2,1\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `mat[i][j]` is either `0` or `1`. * There is at least one `0` in `mat`.
null
Solution
01-matrix
1
1
```C++ []\nclass Solution {\npublic:\n vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {\n int n=mat.size();\n int m=mat[0].size();\n int t=m+n;\n int top,left;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(!mat[i][j])continue;\n left=t;top=t;\n if(i>0)top=mat[i-1][j];\n if(j>0)left=mat[i][j-1];\n mat[i][j]=min(top,left)+1;\n }\n }\n for(int i=n-1;i>=0;i--){\n for(int j=m-1;j>=0;j--){\n if(!mat[i][j])continue;\n left=t;top=t;\n if(i+1<n)top=mat[i+1][j];\n if(j+1<m)left=mat[i][j+1];\n mat[i][j] = min(mat[i][j], min(left,top) + 1);\n }\n }\n return mat;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:\n m, n = len(matrix), len(matrix[0])\n for i, row in enumerate(matrix):\n for j, cell in enumerate(row):\n if cell:\n top = matrix[i-1][j] if i else float(\'inf\')\n left = matrix[i][j-1] if j else float(\'inf\')\n matrix[i][j] = min(top, left) + 1\n for i in reversed(range(m)):\n for j in reversed(range(n)):\n if cell := matrix[i][j]:\n bottom = matrix[i+1][j] if i < m - 1 else float(\'inf\')\n right = matrix[i][j+1] if j < n - 1 else float(\'inf\')\n matrix[i][j] = min(cell, bottom + 1, right + 1)\n return matrix\n```\n\n```Java []\nclass Solution {\n public int[][] updateMatrix(int[][] matrix) {\n int rowLast = matrix.length - 1;\n int colLast = matrix[0].length - 1;\n\n int[] row = matrix[0];\n int[] prevRow;\n if (row[0] == 1) \n row[0] = rowLast + colLast + 2;\n for (int c = 1; c <= colLast; c++) \n if (row[c] == 1)\n row[c] = row[c - 1] + 1;\n for (int r = 1; r <= rowLast; r++) { \n prevRow = row;\n row = matrix[r];\n if (row[0] == 1) \n row[0] = prevRow[0] + 1;\n for (int c = 1; c <= colLast; c++) \n if (row[c] == 1)\n row[c] = Math.min(row[c - 1], prevRow[c]) + 1;\n }\n row = matrix[rowLast];\n for (int c = colLast - 1; c >= 0; c--) \n if (row[c] > 1)\n row[c] = Math.min(row[c], row[c + 1] + 1);\n for (int r = rowLast - 1; r >= 0; r--) { \n prevRow = row;\n row = matrix[r];\n if (row[colLast] > 1) \n row[colLast] = Math.min(row[colLast], prevRow[colLast] + 1);\n for (int c = colLast - 1; c >= 0; c--) \n if (row[c] > 1)\n row[c] = Math.min(row[c], Math.min(row[c + 1], prevRow[c]) + 1);\n }\n return matrix;\n }\n}\n```\n
1
Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_. The distance between two adjacent cells is `1`. **Example 1:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Example 2:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[1,2,1\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `mat[i][j]` is either `0` or `1`. * There is at least one `0` in `mat`.
null
✅ 94.87% Multi-source BFS + Queue
01-matrix
1
1
# Problem Understanding\n\nIn the "01 Matrix Distance" problem, we are given a binary matrix, where each cell contains either a 0 or a 1. The task is to transform this matrix such that each cell contains the shortest distance to a cell with a 0.\n\nFor instance, given the matrix:\n\n$$\n\\text{mat} = \n\\begin{bmatrix}\n0 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n1 & 1 & 1 \\\\\n\\end{bmatrix}\n$$\n\nThe output should be:\n\n$$\n\\text{output} = \n\\begin{bmatrix}\n0 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n1 & 2 & 1 \\\\\n\\end{bmatrix}\n$$\n\n---\n\n# Live Coding BFS?\nhttps://youtu.be/HuZ3u2sRIPY\n\n# Approach: Multi-source BFS\n\nTo solve the "01 Matrix Distance" problem, we employ a multi-source BFS approach, starting our traversal from all the cells containing 0s and updating the distances of all adjacent cells.\n\n## Key Data Structures:\n- **Matrix**: Represents the given binary matrix.\n- **Queue**: Used to hold cells for BFS traversal.\n \n## Enhanced Breakdown:\n\n1. **Initialization**:\n - Create a queue and initialize it with all cells containing 0s. These will be our BFS starting points. \n - Set all cells containing 1s to a large value which acts as a placeholder indicating that the cell hasn\'t been visited yet.\n\n2. **BFS Traversal**:\n - Dequeue a cell and explore its neighboring cells (top, down, left, right).\n - If the distance to the current cell plus one is less than the value in the neighboring cell, update the neighboring cell\'s distance and enqueue it for further processing.\n\n3. **Wrap-up**:\n - Once all cells have been visited and updated, return the transformed matrix.\n\n---\n\n# Example:\n\nWe\'ll use the example:\n\n$$\n\\text{mat} = \n\\begin{bmatrix}\n0 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n1 & 1 & 1 \\\\\n\\end{bmatrix}\n$$\n\nWe want to debug the function to visualize how the matrix gets updated at each step.\n\n### Initialization:\n\nFirst, we determine the size of the matrix:\n\n$$ m = 3 $$ (rows) and $$ n = 3 $$ (columns).\n\n`MAX_VALUE` is set to $$ m \\times n = 9 $$.\n\nNext, we iterate over the matrix. For every cell that has a `1`, we set it to `MAX_VALUE` (i.e., 9). Every cell with a `0` gets appended to the queue.\n\nAt this point, the matrix looks like:\n\n$$\n\\begin{bmatrix}\n0 & 0 & 0 \\\\\n0 & 9 & 0 \\\\\n9 & 9 & 9 \\\\\n\\end{bmatrix}\n$$\n\nAnd the queue contains: `[(0,0), (0,1), (0,2), (1,0), (1,2)]`.\n\n### BFS Traversal:\n\nWe start the BFS traversal by dequeuing the first element in the queue, which is `(0,0)`.\n\nWe then check its neighboring cells in the directions `[(1, 0), (-1, 0), (0, 1), (0, -1)]`.\n\nFor `(0,0)`, the valid neighbors are `(1,0)` and `(0,1)`.\n\nSince `(1,0)` has a value of `0`, we don\'t need to update its value or enqueue it. Similarly, `(0,1)` already has a value of `0`, so it\'s not enqueued or updated either.\n\nThe matrix, at this point, looks like:\n\n$$\n\\begin{bmatrix}\n0 & 0 & 0 \\\\\n0 & 9 & 0 \\\\\n9 & 9 & 9 \\\\\n\\end{bmatrix}\n$$\n\nAnd the queue is: `[(0,1), (0,2), (1,0), (1,2)]`.\n\nThe process continues, dequeuing `(0,1)` and checking its neighbors. \n\n`(1,1)` will be updated to `1` (from `9`) and enqueued.\n\nThis BFS process continues until the queue is empty.\n\n### Final State:\n\nAfter processing all the elements in the queue, the matrix is transformed to:\n\n$$\n\\begin{bmatrix}\n0 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n1 & 2 & 1 \\\\\n\\end{bmatrix}\n$$\n\nThis matrix represents the shortest distance of each cell to the nearest 0.\n\n---\n\n# Complexity:\n\n**Time Complexity:** \n- $$O(m \\times n)$$ - Since each cell in the matrix is processed once.\n\n**Space Complexity:** \n- $$O(m \\times n)$$ - In the worst case, all cells might be added to the queue.\n\n---\n\n# Performance:\n\nHere\'s a performance table sorted by runtime (ms):\n\n| Language | Runtime (ms) | Runtime Beat (%) | Memory (MB) | Memory Beat (%) |\n|------------|--------------|------------------|-------------|-----------------|\n| **Java** | 13 | 82.79% | 45.4 | 85.31% |\n| **Rust** | 17 | 94.87% | 3.2 | 48.72% |\n| **Go** | 57 | 79.72% | 7.7 | 50.35% |\n| **C++** | 69 | 81.1% | 30.1 | 90.12% |\n| **JavaScript** | 131 | 90.56% | 49.2 | 94.94% |\n| **C#** | 214 | 71.30% | 72.2 | 11.57% |\n| **Python3** | 521 | 88.62% | 19 | 84.36% |\n\n\nThis table provides a quick glance at the performance of different implementations. \n\n![p2.png](https://assets.leetcode.com/users/images/56691326-506d-4c53-b5cb-c6cab5893cf0_1692232793.5870304.png)\n\n\n# Code\n\n``` python []\nclass Solution:\n def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n if not mat or not mat[0]:\n return []\n\n m, n = len(mat), len(mat[0])\n queue = deque()\n MAX_VALUE = m * n\n \n # Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 0:\n queue.append((i, j))\n else:\n mat[i][j] = MAX_VALUE\n \n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n \n while queue:\n row, col = queue.popleft()\n for dr, dc in directions:\n r, c = row + dr, col + dc\n if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1:\n queue.append((r, c))\n mat[r][c] = mat[row][col] + 1\n \n return mat\n```\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {\n if (mat.empty() || mat[0].empty())\n return {};\n\n int m = mat.size(), n = mat[0].size();\n queue<pair<int, int>> queue;\n int MAX_VALUE = m * n;\n \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (mat[i][j] == 0) {\n queue.push({i, j});\n } else {\n mat[i][j] = MAX_VALUE;\n }\n }\n }\n \n vector<pair<int, int>> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n \n while (!queue.empty()) {\n auto [row, col] = queue.front(); queue.pop();\n for (auto [dr, dc] : directions) {\n int r = row + dr, c = col + dc;\n if (r >= 0 && r < m && c >= 0 && c < n && mat[r][c] > mat[row][col] + 1) {\n queue.push({r, c});\n mat[r][c] = mat[row][col] + 1;\n }\n }\n }\n \n return mat;\n }\n};\n```\n``` Rust []\nuse std::collections::VecDeque;\n\nimpl Solution {\n pub fn update_matrix(mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> {\n let m = mat.len();\n let n = mat[0].len();\n let mut queue = VecDeque::new();\n let max_value = m * n as usize;\n let mut result = mat.clone();\n \n for i in 0..m {\n for j in 0..n {\n if mat[i][j] == 0 {\n queue.push_back((i, j));\n } else {\n result[i][j] = max_value as i32;\n }\n }\n }\n \n let directions = [(1, 0), (-1, 0), (0, 1), (0, -1)];\n \n while let Some((row, col)) = queue.pop_front() {\n for (dr, dc) in &directions {\n let r = row as i32 + dr;\n let c = col as i32 + dc;\n if r >= 0 && r < m as i32 && c >= 0 && c < n as i32 && result[r as usize][c as usize] > result[row][col] + 1 {\n queue.push_back((r as usize, c as usize));\n result[r as usize][c as usize] = result[row][col] + 1;\n }\n }\n }\n \n result\n }\n}\n```\n``` Go []\nfunc updateMatrix(mat [][]int) [][]int {\n if mat == nil || len(mat) == 0 || len(mat[0]) == 0 {\n return [][]int{}\n }\n\n m, n := len(mat), len(mat[0])\n queue := make([][]int, 0)\n MAX_VALUE := m * n\n\n for i := 0; i < m; i++ {\n for j := 0; j < n; j++ {\n if mat[i][j] == 0 {\n queue = append(queue, []int{i, j})\n } else {\n mat[i][j] = MAX_VALUE\n }\n }\n }\n\n directions := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}\n\n for len(queue) > 0 {\n cell := queue[0]\n queue = queue[1:]\n for _, dir := range directions {\n r, c := cell[0]+dir[0], cell[1]+dir[1]\n if r >= 0 && r < m && c >= 0 && c < n && mat[r][c] > mat[cell[0]][cell[1]]+1 {\n queue = append(queue, []int{r, c})\n mat[r][c] = mat[cell[0]][cell[1]] + 1\n }\n }\n }\n\n return mat\n}\n```\n``` Java []\nclass Solution {\n public int[][] updateMatrix(int[][] mat) {\n if (mat == null || mat.length == 0 || mat[0].length == 0)\n return new int[0][0];\n\n int m = mat.length, n = mat[0].length;\n Queue<int[]> queue = new LinkedList<>();\n int MAX_VALUE = m * n;\n \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (mat[i][j] == 0) {\n queue.offer(new int[]{i, j});\n } else {\n mat[i][j] = MAX_VALUE;\n }\n }\n }\n \n int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n \n while (!queue.isEmpty()) {\n int[] cell = queue.poll();\n for (int[] dir : directions) {\n int r = cell[0] + dir[0], c = cell[1] + dir[1];\n if (r >= 0 && r < m && c >= 0 && c < n && mat[r][c] > mat[cell[0]][cell[1]] + 1) {\n queue.offer(new int[]{r, c});\n mat[r][c] = mat[cell[0]][cell[1]] + 1;\n }\n }\n }\n \n return mat;\n }\n}\n```\n``` C# []\npublic class Solution {\n public int[][] UpdateMatrix(int[][] mat) {\n if (mat == null || mat.Length == 0 || mat[0].Length == 0)\n return new int[0][];\n\n int m = mat.Length, n = mat[0].Length;\n Queue<(int, int)> queue = new Queue<(int, int)>();\n int MAX_VALUE = m * n;\n \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (mat[i][j] == 0) {\n queue.Enqueue((i, j));\n } else {\n mat[i][j] = MAX_VALUE;\n }\n }\n }\n \n (int, int)[] directions = {(1, 0), (-1, 0), (0, 1), (0, -1)};\n \n while (queue.Count > 0) {\n (int row, int col) = queue.Dequeue();\n foreach (var (dr, dc) in directions) {\n int r = row + dr, c = col + dc;\n if (r >= 0 && r < m && c >= 0 && c < n && mat[r][c] > mat[row][col] + 1) {\n queue.Enqueue((r, c));\n mat[r][c] = mat[row][col] + 1;\n }\n }\n }\n \n return mat;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number[][]} mat\n * @return {number[][]}\n */\nvar updateMatrix = function(mat) {\n if (!mat || mat.length === 0 || mat[0].length === 0)\n return [];\n\n let m = mat.length, n = mat[0].length;\n let queue = [];\n let MAX_VALUE = m * n;\n \n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (mat[i][j] === 0) {\n queue.push([i, j]);\n } else {\n mat[i][j] = MAX_VALUE;\n }\n }\n }\n \n let directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];\n \n while (queue.length > 0) {\n let [row, col] = queue.shift();\n for (let [dr, dc] of directions) {\n let r = row + dr, c = col + dc;\n if (r >= 0 && r < m && c >= 0 && c < n && mat[r][c] > mat[row][col] + 1) {\n queue.push([r, c]);\n mat[r][c] = mat[row][col] + 1;\n }\n }\n }\n \n return mat;\n};\n```\n\n\nThis problem beautifully showcases the power and elegance of the multi-source BFS technique. Employing BFS in such scenarios ensures efficient and optimal computation, turning intricate challenges into tractable tasks. Dive deep, explore, and let the waves of algorithms guide you through the complexities of the coding world! \uD83D\uDCA1\uD83C\uDF20\uD83D\uDC69\u200D\uD83D\uDCBB\uD83D\uDC68\u200D\uD83D\uDCBB\n
91
Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_. The distance between two adjacent cells is `1`. **Example 1:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Example 2:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[1,2,1\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `mat[i][j]` is either `0` or `1`. * There is at least one `0` in `mat`.
null
Python BFS Easy Solution with Explanation
01-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n###### The goal is to get the nearest `0` for each `1`. So how can we get the nearest `0` for each `1`? Lets use `Multisource BFS` and `Dynamic Programming`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n###### To get the nearest `0` for each `1`, we should treat every `0` as if they are on the same level, make a `BFS` on them and keep track of the distance as we go further. Since we are finding the `nearest zero`, we may need to use pre-calculated distances for the current `1` when all of its neighbours are all `1`.\n###### Lets see this with example\n\n###### Here is the given grid\n\n 0 0 0 \n 0 1 0 \n 1 1 1 \n\n###### Then by taking all zeros and making a `BFS` on them, the nearest distance becomes 1 for all ones other than the backticked `1` found on the thrid row.\n\n 0 0 0 \n 0 1 0 \n 1 `1` 1 \n\n###### The backticked ` \'1\' ` is not adjacent to `0`, so it should use the precalculated distance of the nearest `1` it gets.\n###### So, in here we are using precalculated values to get the nearest distance. This technique is called `Dynamic programming`.\n###### Then we will get this ``grid`` by using the values we calculated for its adjacent `1`\n\n 0 0 0 \n 0 1 0 \n 1 2 1 \n\n\n###### \n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O( V + E)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n \n # it a Multi-source BFS like 994. Rotting Oranges\n # treat every 0 as if they are on the same level and make BFS on them\n def isvalid(row, col):\n if row >= len(mat) or row < 0 or col >= len(mat[0]) or col < 0:\n return False\n return True\n \n # get every zero and add them to a queue\n q, visited = deque(), set()\n for row in range( len(mat)):\n for col in range( len(mat[0])):\n if mat[row][col] == 0:\n q.append([row, col])\n visited.add((row, col))\n \n level = 1 # the distance to the nearest zero starts from 1\n while q:\n size = len(q)\n for _ in range( size ):\n row, col =q.popleft()\n for r, c in [ [1, 0], [-1, 0], [0, 1], [0, -1]]:\n newRow, newCol = row + r, col + c\n if (newRow, newCol) not in visited and isvalid(newRow, newCol):\n mat[newRow][newCol] = level\n q.append([newRow, newCol])\n visited.add( (newRow, newCol))\n level += 1\n \n return mat\n```\n\n\n<br>\n\n## If you find this useful, please give it an upvote.\n<br>\n<br>\n
3
Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_. The distance between two adjacent cells is `1`. **Example 1:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Example 2:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[1,2,1\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `mat[i][j]` is either `0` or `1`. * There is at least one `0` in `mat`.
null
C++/Python BFS w DP vs Forward & backward transversals
01-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt\'s a standard problem which can be solved by BFS.\n2nd approach is much easier which uses forward & backward transversals needs only O(1) SC.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. BFS uses a queue q. Set matrix dp[i][j]=-1\n2. Push all pair (i, j) with mat[i][j]=0 into q, and set dp[i][j]=0\n3. Use standard algorithm BFS, that is a while loop, to proceed the whole process until the queue q is empty.\n\nBFS is a standard algorithm finding shortest path. Using same method can solve Leetcode 934. Shortest Bridge\n\n[Please turn on English subtitles if necessary]\n[https://youtu.be/9Lx7yr-tmfI](https://youtu.be/9Lx7yr-tmfI)\n\nConsider the test case\n```\n[[0,0,1,0,1,1,1,0,1,1],[1,1,1,1,0,1,1,1,1,1],[1,1,1,1,1,0,0,0,1,1],[1,0,1,0,1,1,1,0,1,1],[0,0,1,1,1,0,1,1,1,1],[1,0,1,1,1,1,1,1,1,1],[1,1,1,1,0,1,0,1,0,1],[0,1,0,0,0,1,0,0,1,1],[1,1,1,0,1,1,0,1,0,1],[1,0,1,1,1,0,1,1,1,0]]\n```\nThe process for BSF with dp states\n```\n1:\n 0 0 1 0 1 -1 1 0 1 -1\n 1 1 -1 1 0 1 1 1 -1 -1\n -1 1 -1 1 1 0 0 0 1 -1\n 1 0 1 0 1 1 1 0 1 -1\n 0 0 1 1 1 0 1 1 -1 -1\n 1 0 1 -1 1 1 1 -1 1 -1\n 1 1 1 1 0 1 0 1 0 1\n 0 1 0 0 0 1 0 0 1 -1\n 1 1 1 0 1 1 0 1 0 1\n 1 0 1 1 1 0 1 -1 1 0\n\n-----\n2:\n 0 0 1 0 1 2 1 0 1 2\n 1 1 2 1 0 1 1 1 2 -1\n 2 1 2 1 1 0 0 0 1 2\n 1 0 1 0 1 1 1 0 1 2\n 0 0 1 1 1 0 1 1 2 -1\n 1 0 1 2 1 1 1 2 1 2\n 1 1 1 1 0 1 0 1 0 1\n 0 1 0 0 0 1 0 0 1 2\n 1 1 1 0 1 1 0 1 0 1\n 1 0 1 1 1 0 1 2 1 0\n\n-----\n3:\n 0 0 1 0 1 2 1 0 1 2\n 1 1 2 1 0 1 1 1 2 3\n 2 1 2 1 1 0 0 0 1 2\n 1 0 1 0 1 1 1 0 1 2\n 0 0 1 1 1 0 1 1 2 3\n 1 0 1 2 1 1 1 2 1 2\n 1 1 1 1 0 1 0 1 0 1\n 0 1 0 0 0 1 0 0 1 2\n 1 1 1 0 1 1 0 1 0 1\n 1 0 1 1 1 0 1 2 1 0\n\n-----\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(nm)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(nm)\\to O(1)$$\n# Code\n```\nclass Solution {\npublic:\n using int2=pair<int, int>;\n\n vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {\n int n=mat.size(), m=mat[0].size();\n vector<vector<int>> dp(n, vector<int>(m, -1));\n queue<int2> q;\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if (mat[i][j]==0) {\n q.push({i, j});\n dp[i][j]=0;\n }\n }\n }\n while(!q.empty()){\n auto [i, j]=q.front();\n q.pop();\n int d=dp[i][j];\n // cout<<"("<<i<<","<<j<<")->"<<d<<endl;\n vector<int2> adj={{i, j+1}, {i+1, j}, {i, j-1}, {i-1, j}};\n for(auto [a, b]: adj){\n if (a<0 || a>=n || b<0 || b>=m || dp[a][b]!=-1) continue;\n q.push({a, b});\n dp[a][b]=d+1;\n // cout<<"("<<a<<","<<b<<")->"<<d+1<<endl;\n }\n }\n return dp;\n }\n};\n```\n# Python Code beats 92.34%\n\nUse deque is much faster than queue.Queue!!! The speed changes form 8.56% to 92.34%\n\n```\nclass Solution:\n def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n n, m=len(mat), len(mat[0])\n row=[-1]*m\n dp=[row[:] for _ in range(n)]\n\n q = deque()\n for i in range(n):\n for j in range(m):\n if mat[i][j]==0:\n q.append((i, j))\n dp[i][j]=0\n while q:\n i, j=q.popleft()\n d=dp[i][j]\n adj=[(i, j+1), (i+1, j), (i, j-1), (i-1, j)]\n for (a, b) in adj:\n if a<0 or a>=n or b<0 or b>=m or dp[a][b]!=-1: continue \n q.append((a, b))\n dp[a][b]=d+1\n \n return dp\n```\n# code with 2nd approach using forward & backward transversals TC: O(nm) SC: O(1)\n```\nclass Solution {\npublic:\n vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {\n int n=mat.size(), m=mat[0].size();\n //neo_mat[i][j]=1+min(mat[i-1][j], mat[i][j-1]) if mat[i][j]!=0\n for(int i=0; i<n; i++)\n for(int j=0; j<m; j++){\n int i_prev=(i==0)?1e6:mat[i-1][j];\n int j_prev=(j==0)?1e6:mat[i][j-1];\n mat[i][j]=(mat[i][j]==0)?0:1+min(i_prev, j_prev);\n }\n //neo_mat[i][j]=min(1+min(mat[i+1][j], mat[i][j+1]), mat[i][j])\n \n for(int i=n-1; i>=0; i--)\n for(int j=m-1; j>=0; j--){\n int i_prev=(i==n-1)?1e6:mat[i+1][j];\n int j_prev=(j==m-1)?1e6:mat[i][j+1];\n int tmp=1+min(i_prev, j_prev);\n mat[i][j]=min(tmp, mat[i][j]);\n } \n \n return mat;\n }\n};\n```
6
Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_. The distance between two adjacent cells is `1`. **Example 1:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Example 2:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[1,2,1\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `mat[i][j]` is either `0` or `1`. * There is at least one `0` in `mat`.
null
Python Easy-to-understand solution w Explanation
diameter-of-binary-tree
0
1
### Introduction\nConsider the first given example in the problem description:\n\n![image](https://assets.leetcode.com/users/images/90e976f1-7da7-4f56-914f-749ff330029f_1633924958.2044275.png)\n\nThe maximum depth of the left side of the tree is 2 (1 -> 2 -> 4/5), while the maximum depth of the right side of the tree is 1 (1 -> 3). This, coincidentally, matches well with the given diameter, since we can traverse from the leaf node(s) of one side of the tree to the leaf node(s) of the other side of the tree to obtain the diameter (for example, 3 -> 1 -> 2 -> 4).\n\n---\n\n### Idea 1\n\nThe diameter of a given tree is the **maximum depth of the left side of the tree**, plus the **maximum depth of the right side of the tree**. We can write the following pseudocode:\n\n```python\n# depth() is a pseudocode function we have to implement later\ndiameter = depth(root.left) + depth(root.right)\n```\n\nTo actually write this, we need to find the maximum depth of a given tree. This is simple; for any given tree, we can find the maximum depth of the left side of the tree, the maximum depth of the right side of the tree, and +1 to the maximum of the two depths.\n\n```python\ndef depth(node: Optional[TreeNode]) -> int:\n """\n\tTo find the maximum depth of a given tree.\n\t:param node: The (root) node of the tree.\n\t:returns: The maximum depth of the tree, at the specified node.\n\t"""\n\t# return 1 + max(depth(node.left), depth(node.right)) if node else 0 # one-liner\n\tif not node:\n\t return 0 # the depth of a non-existent node is 0\n\tleft = depth(node.left) # get the depth of the left side of the tree\n\tright = depth(node.right) # get the depth of the right side of the tree\n\treturn 1 + (left if left > right else right) # take the maximum, and +1 for the current node\n```\n\nWe now have everything our pseudocode needs. To put it all together, make sure that we are calculating the diameter from the root node, not the depth.\n\n```python\n# Idea 1 Implementation!\nclass Solution:\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n\t # Implement depth\n\t def depth(node: Optional[TreeNode]) -> int:\n\t\t return 1 + max(depth(node.left), depth(node.right)) if node else 0\n\t\treturn depth(root.left) + depth(root.right) # calculate diameter\n```\n\nAnd that\'s it! Run the code and... WA. >:)\n\n---\n\n### Idea 2\n\nAs it turns out, the maximum diameter of a given tree **need not involve the root node of the tree**. That means, if we only calculated the diamter of a tree from the root node, as our 1st implementation does, we might miss out on another pathway that does not pass through the root node but has a longer diameter. To visualise this, consider the following tree:\n\n![image](https://assets.leetcode.com/users/images/75774378-bb57-4468-802b-bc021439da9b_1633927697.2095265.png)\n\nIf we were to calculate the diameter as per the 1st implementation, the diameter would be 5 (2 -> 1 -> 3 -> 4 -> 6 -> 8). At first glance, this might seem correct, but there is actually a longer pathway with diameter 6 (9 -> 7 -> 5 -> 3 -> 4 -> 6 -> 8)! This is a problem for our 1st implementation since we assume the left side of the tree is involved with the diameter calculation.\n\nThe solution? We need to **calculate the diameter at each node and find the maximum diameter**. This is a simple fix because we just need to account for diameter calculation per call of depth(). This guarantees that we loop through each node in the tree and find the maximum possible diameter.\n\nNote that we **still need to calculate the depth as per 1st implementation**. Since the diameter formula requires the depth value, each node still needs to know the maximum depth of its left side and the maximum depth of its right side.\n\n```python\nclass Solution:\n def __init__(self):\n\t self.diameter = 0 # stores the maximum diameter calculated\n\t\n def depth(self, node: Optional[TreeNode]) -> int:\n """\n This function needs to do the following:\n 1. Calculate the maximum depth of the left and right sides of the given node\n 2. Determine the diameter at the given node and check if its the maximum\n """\n # Calculate maximum depth\n left = self.depth(node.left) if node.left else 0\n right = self.depth(node.right) if node.right else 0\n # Calculate diameter\n if left + right > self.diameter:\n self.diameter = left + right\n # Make sure the parent node(s) get the correct depth from this node\n return 1 + (left if left > right else right)\n \n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n # if not root:\n # return 0\n self.depth(root) # root is guaranteed to be a TreeNode object\n return self.diameter\n```\n\n---\n\n### Final result\n\n![image](https://assets.leetcode.com/users/images/00535fc1-8fab-42d8-9797-d6a10f94c7aa_1633929113.2661655.png)\n\n\nPlease upvote if this has helped you! Appreciate any comments as well :)
204
Given the `root` of a binary tree, return _the length of the **diameter** of the tree_. The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`. The **length** of a path between two nodes is represented by the number of edges between them. **Example 1:** **Input:** root = \[1,2,3,4,5\] **Output:** 3 **Explanation:** 3 is the length of the path \[4,2,1,3\] or \[5,2,1,3\]. **Example 2:** **Input:** root = \[1,2\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-100 <= Node.val <= 100`
null
Depth-First Search✅ | O( n )✅ | (Step by step explanation)✅
diameter-of-binary-tree
0
1
# Intuition\nThe problem is to find the diameter of a binary tree, which is the length of the longest path between any two nodes in a tree. The intuition is to perform a depth-first search (DFS) on the tree to calculate the height of the left and right subtrees for each node and maintain the maximum diameter found so far.\n\n# Approach\nThe approach is to perform a DFS traversal of the binary tree while keeping track of the diameter. For each node, we calculate the height of its left and right subtrees, and the diameter passing through the current node is the sum of the heights of its left and right subtrees plus 2. We update the maximum diameter found so far using the `ans` variable.\n\n1. Initialize the `ans` variable to store the maximum diameter found so far.\n2. Implement a recursive DFS function that takes a node and a reference to `ans` as parameters.\n3. In the DFS function, check if the current node is NULL. If it is, return -1 to indicate an empty subtree.\n4. Calculate the height of the left subtree by calling the DFS function recursively on the left child and store it in the `left` variable.\n5. Calculate the height of the right subtree by calling the DFS function recursively on the right child and store it in the `right` variable.\n6. Update the `ans` variable with the maximum of its current value and 2 plus the sum of `left` and `right`. This represents the diameter passing through the current node.\n7. Return 1 plus the maximum of `left` and `right` as the height of the current subtree.\n8. Initialize the DFS traversal by calling the DFS function with the root node and the `ans` variable.\n9. Finally, return the `ans` as the maximum diameter of the binary tree.\n\n# Complexity\n- Time complexity: O(n)\n - The algorithm performs a depth-first traversal of the binary tree, visiting each node once.\n- Space complexity: O(h), where h is the height of the binary tree\n - The space complexity is determined by the maximum height of the call stack during the recursive DFS traversal.\n - In the worst case, when the tree is skewed (completely unbalanced), the space complexity is O(n).\n - In the best case, when the tree is perfectly balanced, the space complexity is O(log(n)).\n \n# Code\n\n<details open>\n <summary>Python Solution</summary>\n\n```python\nclass Solution:\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n ans = [0]\n\n def dfs(root):\n if root == None:\n return -1\n\n left = dfs(root.left)\n right = dfs(root.right)\n ans[0] = max(ans[0] , 2 + left + right)\n\n return 1 + max(left , right)\n\n dfs(root)\n return ans[0] \n\n \n```\n</details>\n\n<details open>\n <summary>C++ Solution</summary>\n\n```cpp\nclass Solution {\npublic:\n int diameterOfBinaryTree(TreeNode* root) {\n int ans = 0;\n dfs(root , ans);\n \n return ans;\n }\nprivate:\n int dfs(TreeNode* root , int &ans){\n if(root == NULL){\n return -1;\n }\n int left = dfs(root->left , ans);\n int right = dfs(root->right , ans);\n ans = max(ans , 2 + left + right);\n\n return 1 + max(left , right);\n } \n};\n```\n</details>\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/0161dd3b-ad9f-4cf6-8c43-49c2e670cc21_1699210823.334661.jpeg)\n\n
6
Given the `root` of a binary tree, return _the length of the **diameter** of the tree_. The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`. The **length** of a path between two nodes is represented by the number of edges between them. **Example 1:** **Input:** root = \[1,2,3,4,5\] **Output:** 3 **Explanation:** 3 is the length of the path \[4,2,1,3\] or \[5,2,1,3\]. **Example 2:** **Input:** root = \[1,2\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-100 <= Node.val <= 100`
null
Most effective and simple recursive solution
diameter-of-binary-tree
1
1
\n\n# Approach\n- The height function calculates the height of a node in the binary tree.\n- For each node, it calculates the heights of its left and right subtrees (lh and rh).\n- Updates the diameter (ans) by comparing it with the sum of left and right subtree heights.\nuReturns the height of the current node (1 + maximum of left and right subtree heights).\n- The diameterOfBinaryTree function initializes ans to 0 and calls the height function to compute the diameter of the binary tree.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n```C++ []\nclass Solution {\npublic:\n int height(TreeNode* node, int &ans) {\n if(!node) return 0;\n int lh = height(node->left, ans);\n int rh = height(node->right, ans);\n ans = max(ans, lh+rh);\n return 1+ max(lh, rh);\n }\n int diameterOfBinaryTree(TreeNode* root) {\n int ans = 0;\n if(!root) return 0;\n height(root, ans);\n return ans;\n }\n};\n```\n```JAVA []\npublic class Solution {\n public int diameterOfBinaryTree(TreeNode root) {\n int[] ans = new int[1];\n height(root, ans);\n return ans[0];\n }\n \n private int height(TreeNode node, int[] ans) {\n if (node == null) return 0;\n int lh = height(node.left, ans);\n int rh = height(node.right, ans);\n ans[0] = Math.max(ans[0], lh + rh);\n return 1 + Math.max(lh, rh);\n }\n}\n```\n```Python3 []\nclass Solution:\n def diameterOfBinaryTree(self, root: TreeNode) -> int:\n def height(node):\n nonlocal ans\n if not node:\n return 0\n lh = height(node.left)\n rh = height(node.right)\n ans = max(ans, lh + rh)\n return 1 + max(lh, rh)\n \n ans = 0\n height(root)\n return ans\n```\n
1
Given the `root` of a binary tree, return _the length of the **diameter** of the tree_. The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`. The **length** of a path between two nodes is represented by the number of edges between them. **Example 1:** **Input:** root = \[1,2,3,4,5\] **Output:** 3 **Explanation:** 3 is the length of the path \[4,2,1,3\] or \[5,2,1,3\]. **Example 2:** **Input:** root = \[1,2\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-100 <= Node.val <= 100`
null
Smart Approach
diameter-of-binary-tree
0
1
```\nclass Solution:\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n ans=0\n def dia(root):\n nonlocal ans\n if not root:\n return 0\n left=dia(root.left)\n right=dia(root.right)\n ans=max(ans,left+right)\n return 1+max(right,left)\n dia(root)\n return ans\n```
4
Given the `root` of a binary tree, return _the length of the **diameter** of the tree_. The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`. The **length** of a path between two nodes is represented by the number of edges between them. **Example 1:** **Input:** root = \[1,2,3,4,5\] **Output:** 3 **Explanation:** 3 is the length of the path \[4,2,1,3\] or \[5,2,1,3\]. **Example 2:** **Input:** root = \[1,2\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-100 <= Node.val <= 100`
null
Solution
remove-boxes
1
1
```C++ []\nclass Solution {\npublic:\n int dp[101][101][101];\n vector<vector<int>> group;\n\n int getDpVal(int l, int r, int k) {\n if(l > r) return 0;\n if(dp[l][r][k] != 0) return dp[l][r][k];\n int sz = group[l][1];\n int color = group[l][0];\n dp[l][r][k] = getDpVal(l + 1, r, 0) + (k + sz) * (k + sz);\n for(int i = l + 1; i <= r; i++) {\n if(group[i][0] == color) {\n dp[l][r][k] = max(dp[l][r][k], getDpVal(l + 1, i - 1, 0) + getDpVal(i, r, k + sz));\n }\n }\n return dp[l][r][k];\n }\n int removeBoxes(vector<int>& boxes) {\n int n = boxes.size();\n int c = 1;\n for(int i = 1; i < n; i++) {\n if(boxes[i] != boxes[i - 1]) {\n group.push_back({boxes[i - 1], c});\n c = 0;\n }\n c++;\n }\n group.push_back({boxes[n - 1], c});\n return getDpVal(0, group.size() - 1, 0);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def removeBoxes(self, boxes: List[int]) -> int:\n self.counts = []\n self.colors = []\n\n tcol = boxes[0]\n tcnt = 0\n for c in boxes:\n if tcol == c:\n tcnt += 1\n else:\n self.proc(tcol,tcnt)\n tcol = c\n tcnt = 1\n self.proc(tcol,tcnt)\n\n @cache\n def search(i,j,k):\n if i > j:\n return 0\n if i == j:\n return (k + self.counts[i])**2\n opts = []\n opts.append(search(i+1, j, 0) + (self.counts[i] + k)**2)\n for m in range(i+2, j+1):\n if self.colors[m] == self.colors[i]:\n opts.append(search(i+1, m-1, 0) + search(m, j, k+self.counts[i]))\n return max(opts)\n\n return search(0,len(self.colors)-1,0)\n\n def proc(self,col,cnt):\n self.counts.append(cnt)\n self.colors.append(col)\n return\n```\n\n```Java []\nclass Solution {\n public int removeBoxes(int[] boxes) {\n int [][][] dp = new int [boxes.length][boxes.length][boxes.length];\n return dfs(boxes, 0, boxes.length -1, 0, dp);\n }\n private int dfs(int [] boxes, int start, int end, int prefix, int [][][] dp){\n int res = 0;\n int count = 0;\n if(start > end)\n return 0;\n if(start == end)\n return (prefix+1)*(prefix+1);\n if(dp[start][end][prefix] != 0)\n return dp[start][end][prefix];\n int index = start;\n while(index <= end && boxes[index] == boxes[start]){\n index++;\n count++;\n }\n int newStart = index;\n res = (count+prefix)* (count+ prefix) + dfs(boxes, newStart, end, 0, dp);\n while(index <= end){\n if(boxes[index] == boxes[start] && boxes[index-1] != boxes[start]){\n res = Math.max(res, dfs(boxes, newStart, index-1, 0, dp) + dfs(boxes, index, end, count+prefix, dp));\n }\n index++;\n }\n dp[start][end][prefix] = res;\n return res; \n }\n}\n```\n
1
You are given several `boxes` with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points. Return _the maximum points you can get_. **Example 1:** **Input:** boxes = \[1,3,2,2,2,3,4,3,1\] **Output:** 23 **Explanation:** \[1, 3, 2, 2, 2, 3, 4, 3, 1\] ----> \[1, 3, 3, 4, 3, 1\] (3\*3=9 points) ----> \[1, 3, 3, 3, 1\] (1\*1=1 points) ----> \[1, 1\] (3\*3=9 points) ----> \[\] (2\*2=4 points) **Example 2:** **Input:** boxes = \[1,1,1\] **Output:** 9 **Example 3:** **Input:** boxes = \[1\] **Output:** 1 **Constraints:** * `1 <= boxes.length <= 100` * `1 <= boxes[i] <= 100`
null
Python 3 || 11 lines, dp || T/M: 100% / 96%
remove-boxes
0
1
```\nclass Solution:\n def removeBoxes(self, boxes: List[int]) -> int:\n\n boxes = tuple((k, len(list(g))) for k,g in groupby(boxes))\n\n @lru_cache(None)\n def dfs(grps: tuple) -> int:\n \n if not grps: return 0\n (colorL, lenL), grps = grps[0], grps[1:]\n\n res = lenL*lenL + dfs(grps)\n\n for i, (colorR, lenR) in enumerate(grps):\n if colorL == colorR:\n res = max(res, dfs(grps[:i]) + \n dfs(((colorL, lenL+lenR),) + grps[i+1:]))\n\n return res\n\n return dfs(boxes)\n```\n[https://leetcode.com/problems/remove-boxes/submissions/997200969/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N*^4) and space complexity is *O*(*N*^2), in which *N* ~ `len(boxes)`.
4
You are given several `boxes` with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points. Return _the maximum points you can get_. **Example 1:** **Input:** boxes = \[1,3,2,2,2,3,4,3,1\] **Output:** 23 **Explanation:** \[1, 3, 2, 2, 2, 3, 4, 3, 1\] ----> \[1, 3, 3, 4, 3, 1\] (3\*3=9 points) ----> \[1, 3, 3, 3, 1\] (1\*1=1 points) ----> \[1, 1\] (3\*3=9 points) ----> \[\] (2\*2=4 points) **Example 2:** **Input:** boxes = \[1,1,1\] **Output:** 9 **Example 3:** **Input:** boxes = \[1\] **Output:** 1 **Constraints:** * `1 <= boxes.length <= 100` * `1 <= boxes[i] <= 100`
null
546: Solution with step by step explanation
remove-boxes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define the removeBoxes function that takes in a list of boxes and returns an integer representing the maximum score that can be achieved by removing the boxes.\n\n2. Define the inner dp function that takes in the starting index i, ending index j, and the number of boxes k that are identical to the box at index j. The function returns the maximum score that can be achieved for the subarray of boxes starting at index i and ending at index j, given that k boxes are identical to the box at index j.\n\n3. If i > j, then there are no boxes left to remove, so the function returns 0.\n\n4. While there are still boxes in the subarray and the last box is identical to the box before it, we can reduce the sub-problem size by decrementing j and incrementing k.\n\n5. If we have processed all the boxes, then we return the score, which is equal to (k+1)^2.\n\n6. We consider two cases:\n\n 1. Case 1: Remove the last k+1 boxes and recurse on the remaining sub-problem. We compute the score for this case by adding (k+1)^2 to the maximum score that can be achieved for the subarray starting at index i and ending at index j-1, with no identical boxes at the end.\n\n 2. Case 2: Merge the box at index j with some box in the subarray starting at index i and ending at index j-1, and recurse on the two resulting sub-problems. We compute the score for this case by iterating over all possible boxes in the subarray and finding the one that is identical to the box at index j. We then split the subarray into two parts: the subarray starting at index i and ending at index m, which contains the merged boxes, and the subarray starting at index m+1 and ending at index j-1, which contains the remaining boxes. We compute the maximum score for each of these subarrays recursively and add them together.\n\n7. The function returns the maximum score that can be achieved for the entire array of boxes, which is equal to the maximum score that can be achieved for the subarray starting at index 0 and ending at index len(boxes)-1, with no identical boxes at the end.\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeBoxes(self, boxes: List[int]) -> int:\n # dp(i, j, k) := max score of boxes[i..j] if k boxes equal to boxes[j]\n @lru_cache(None)\n def dp(i: int, j: int, k: int) -> int:\n if i > j:\n return 0\n\n # Check if we can reduce the sub-problem size\n while i < j and boxes[j] == boxes[j-1]:\n j -= 1\n k += 1\n\n # If we have processed all the boxes, return the score\n if i == j:\n return (k+1)**2\n\n # Case 1: Remove the last k+1 boxes and recurse on the remaining sub-problem\n ans = (k+1)**2 + dp(i, j-1, 0)\n\n # Case 2: Merge boxes[j] with some box in the subarray i to j-1 and recurse on the two resulting sub-problems\n for m in range(j-1, i-1, -1):\n if boxes[m] == boxes[j]:\n ans = max(ans, dp(i, m, k+1) + dp(m+1, j-1, 0))\n\n return ans\n\n return dp(0, len(boxes)-1, 0)\n\n```
3
You are given several `boxes` with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points. Return _the maximum points you can get_. **Example 1:** **Input:** boxes = \[1,3,2,2,2,3,4,3,1\] **Output:** 23 **Explanation:** \[1, 3, 2, 2, 2, 3, 4, 3, 1\] ----> \[1, 3, 3, 4, 3, 1\] (3\*3=9 points) ----> \[1, 3, 3, 3, 1\] (1\*1=1 points) ----> \[1, 1\] (3\*3=9 points) ----> \[\] (2\*2=4 points) **Example 2:** **Input:** boxes = \[1,1,1\] **Output:** 9 **Example 3:** **Input:** boxes = \[1\] **Output:** 1 **Constraints:** * `1 <= boxes.length <= 100` * `1 <= boxes[i] <= 100`
null
546. Remove Boxes ( 100%°)
remove-boxes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeBoxes(self, boxes: List[int]) -> int:\n\n boxes = tuple((k, len(list(g))) for k,g in groupby(boxes))\n\n @lru_cache(None)\n def dfs(grps: tuple) -> int:\n \n if not grps: return 0\n (colorL, lenL), grps = grps[0], grps[1:]\n\n res = lenL*lenL + dfs(grps)\n\n for i, (colorR, lenR) in enumerate(grps):\n if colorL == colorR:\n res = max(res, dfs(grps[:i]) + \n dfs(((colorL, lenL+lenR),) + grps[i+1:]))\n\n return res\n\n return dfs(boxes)\n```
0
You are given several `boxes` with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points. Return _the maximum points you can get_. **Example 1:** **Input:** boxes = \[1,3,2,2,2,3,4,3,1\] **Output:** 23 **Explanation:** \[1, 3, 2, 2, 2, 3, 4, 3, 1\] ----> \[1, 3, 3, 4, 3, 1\] (3\*3=9 points) ----> \[1, 3, 3, 3, 1\] (1\*1=1 points) ----> \[1, 1\] (3\*3=9 points) ----> \[\] (2\*2=4 points) **Example 2:** **Input:** boxes = \[1,1,1\] **Output:** 9 **Example 3:** **Input:** boxes = \[1\] **Output:** 1 **Constraints:** * `1 <= boxes.length <= 100` * `1 <= boxes[i] <= 100`
null
Simple Solution
remove-boxes
0
1
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach/ -->\n<!-- Describe your approach to solving the problem. -->\n\n<!-- # Complexity\n- Time complexity: -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeBoxes(self, boxes: List[int]) -> int:\n\n @cache\n def rec(i, j, k):\n\n if i > j: return 0\n if i == j: return (k + 1) ** 2\n\n # reducing the current problem\n # (k - R boxes)| R, R, R, R, B, B, Y, Y, R , R, Y, B, B, B | -> (k+3 - R boxes) | R, B, B, Y, Y, R , R, Y, B, B, B |\n while i < j and boxes[i] == boxes[i + 1]:\n i += 1\n k += 1\n\n # R, R, R | R, B, B, Y, Y, R , R, Y, B, B, B |\n\n max_val = (k + 1) ** 2 + rec(i + 1, j, 0)\n\n for m in range(i + 1, j + 1):\n if boxes[i] == boxes[m]:\n # (k+3 - R boxes) | R + (| B, B, Y, Y |) + R , R, Y, B, B, B | -> (| B, B, Y, Y |) + ((k + 4 - R boxes) |R , R, Y, B, B, B |)\n max_val = max(max_val, rec(i + 1, m - 1, 0) + rec(m, j, k + 1))\n\n return max_val\n \n return rec(0, len(boxes) - 1, 0)\n```
0
You are given several `boxes` with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points. Return _the maximum points you can get_. **Example 1:** **Input:** boxes = \[1,3,2,2,2,3,4,3,1\] **Output:** 23 **Explanation:** \[1, 3, 2, 2, 2, 3, 4, 3, 1\] ----> \[1, 3, 3, 4, 3, 1\] (3\*3=9 points) ----> \[1, 3, 3, 3, 1\] (1\*1=1 points) ----> \[1, 1\] (3\*3=9 points) ----> \[\] (2\*2=4 points) **Example 2:** **Input:** boxes = \[1,1,1\] **Output:** 9 **Example 3:** **Input:** boxes = \[1\] **Output:** 1 **Constraints:** * `1 <= boxes.length <= 100` * `1 <= boxes[i] <= 100`
null
Solution
number-of-provinces
1
1
```C++ []\nclass Solution {\npublic:\n int findCircleNum(vector<vector<int>>& isConnected) \n {\n int n = isConnected.size();\n std::vector<int> visited(n, 0);\n int groupCount = 0;\n for (int i = 0; i < n; ++i) \n {\n if (visited[i])\n continue;\n ++groupCount;\n std::stack<int> st;\n st.push(i);\n visited[i] = 1;\n while (!st.empty())\n {\n int city = st.top();\n st.pop();\n for (int j = 0; j < n; ++j)\n {\n if (!isConnected[city][j] || visited[j])\n continue;\n st.push(j);\n visited[j] = 1;\n }\n }\n }\n return groupCount;\n }\n};\n```\n\n```Python3 []\nfrom collections import defaultdict\n\nclass Solution:\n def findCircleNum(self, isConnected: List[List[int]]) -> int:\n def dfs(node):\n for neighbor in range(len(isConnected[node])):\n if isConnected[node][neighbor]and neighbor not in seen:\n seen.add(neighbor)\n dfs(neighbor)\n \n n = len(isConnected)\n\n seen = set()\n ans = 0\n \n for i in range(n):\n if i not in seen:\n ans += 1\n seen.add(i)\n dfs(i)\n \n return ans\n```\n\n```Java []\nclass Solution {\n public int findCircleNum(int[][] isConnected) {\n int result = 0;\n for (int i=0; i<isConnected.length; i++) {\n if (isConnected[i][i] == 1) {\n result++;\n clear(isConnected, i);\n }\n }\n return result;\n }\n private static void clear(int[][] isConnected, int i) {\n int[] edges = isConnected[i];\n if (edges[i] == 1) {\n edges[i] = 0;\n for (int j = 0; j < edges.length; j++) {\n if (edges[j] == 1) {\n edges[j] = 0;\n clear(isConnected, j);\n }\n }\n }\n }\n}\n```\n
2
There are `n` cities. Some of them are connected, while some are not. If city `a` is connected directly with city `b`, and city `b` is connected directly with city `c`, then city `a` is connected indirectly with city `c`. A **province** is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an `n x n` matrix `isConnected` where `isConnected[i][j] = 1` if the `ith` city and the `jth` city are directly connected, and `isConnected[i][j] = 0` otherwise. Return _the total number of **provinces**_. **Example 1:** **Input:** isConnected = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\] **Output:** 2 **Example 2:** **Input:** isConnected = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\] **Output:** 3 **Constraints:** * `1 <= n <= 200` * `n == isConnected.length` * `n == isConnected[i].length` * `isConnected[i][j]` is `1` or `0`. * `isConnected[i][i] == 1` * `isConnected[i][j] == isConnected[j][i]`
null
Union-Find with Path Compression, Python Solution beats 99% memory and 60% runtime
number-of-provinces
0
1
# Complexity\n- Time complexity: O(n ^ 2)\n\n- Space complexity: O(n ^ 2)\n# Code\n```\nclass UnionFind(object):\n\n def __init__(self, parents: list, rank: list):\n self.parents = parents\n self.rank = rank\n\n def find(self, node):\n\n parent = node \n while parent != self.parents[parent]:\n # don\'t get confused by that line\n # this is just a path compression\n self.parents[parent] = self.parents[self.parents[parent]]\n parent = self.parents[parent]\n return parent\n \n def union(self, node1, node2):\n first, second = self.find(node1), self.find(node2)\n if first == second: return 0 \n\n if self.rank[first] > self.rank[second]:\n self.parents[second] = first\n self.rank[first] += self.rank[second]\n else:\n self.parents[first] = second\n self.rank[second] += self.rank[first]\n return 1 \n\nclass Solution:\n\n def findCircleNum(self, isConnected: List[List[int]]) -> int:\n\n parents = [node for node in range(len(isConnected))]\n rank = [1] * len(parents)\n\n unionFind = UnionFind(parents=parents, rank=rank)\n result = len(parents) \n \n for edge1 in range(len(isConnected)):\n for otherEdge in range(len(isConnected)):\n if isConnected[edge1][otherEdge] == 1:\n result -= unionFind.union(edge1, otherEdge)\n return result\n \n```
2
There are `n` cities. Some of them are connected, while some are not. If city `a` is connected directly with city `b`, and city `b` is connected directly with city `c`, then city `a` is connected indirectly with city `c`. A **province** is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an `n x n` matrix `isConnected` where `isConnected[i][j] = 1` if the `ith` city and the `jth` city are directly connected, and `isConnected[i][j] = 0` otherwise. Return _the total number of **provinces**_. **Example 1:** **Input:** isConnected = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\] **Output:** 2 **Example 2:** **Input:** isConnected = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\] **Output:** 3 **Constraints:** * `1 <= n <= 200` * `n == isConnected.length` * `n == isConnected[i].length` * `isConnected[i][j]` is `1` or `0`. * `isConnected[i][i] == 1` * `isConnected[i][j] == isConnected[j][i]`
null
Solution
student-attendance-record-i
1
1
```C++ []\nclass Solution {\npublic:\n bool checkRecord(string s) {\n int absent=0,late=0;\n for(auto i:s){\n if(i==\'A\')\n absent++;\n }\n int cur=0;\n for(auto i:s)\n {\n if(i==\'L\')\n cur++;\n else{\n late=max(late,cur);\n cur=0;\n }\n }\n late=max(late,cur);\n if(absent<2 && late<3)\n return true;\n return false;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def checkRecord(self, s: str) -> bool:\n A_count = 0\n L_count = 0\n for i in s:\n if i == "A":\n A_count += 1\n if A_count == 2:\n return False\n if i == "L":\n L_count += 1\n if L_count > 2:\n return False\n else:\n L_count = 0\n return True\n```\n\n```Java []\nclass Solution {\n public boolean checkRecord(String s) {\n int count=0;\n int count2=0;\n boolean flag1=false;\n boolean flag2=true;\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==\'A\'){\n count++;\n count2=0;\n flag1=false;\n flag2=true;\n }\n if(s.charAt(i)==\'L\' && (flag1==false || flag2==false)){\n count2++;\n flag1=true;\n flag2=false;\n }\n else\n count2=0;\n if(count==2 || count2==3)\n return false;\n }\n return true;\n }\n}\n```\n
1
You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. The student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Return `true` _if the student is eligible for an attendance award, or_ `false` _otherwise_. **Example 1:** **Input:** s = "PPALLP " **Output:** true **Explanation:** The student has fewer than 2 absences and was never late 3 or more consecutive days. **Example 2:** **Input:** s = "PPALLL " **Output:** false **Explanation:** The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'A'`, `'L'`, or `'P'`.
null
Easy to understand Python 1-liner O(n)
student-attendance-record-i
0
1
# Intuition\nFor string problems, see if you can solve them with built-in Python string methods. Often, it\'s much more Pythonic than iteration, even if iteration might have faster runtime. Also, note that we need only check if there is a run of 3 \'L\'s, as a run of more than 3 \'L\'s also contains a run of 3 L\'s.\n\n# Approach\nWe count the number of occurrences of the string \'A\' and check that it is less than 2. We also check that \'LLL\' is not in the string.\n# Complexity\n- Time complexity:\nCounting is $O(n)$ and substring matching is $O(n)$\n\n- Space complexity:\nEverything here is in-place, so $O(1)$.\n\n# Code\n```\nclass Solution:\n def checkRecord(self, s: str) -> bool:\n return s.count(\'A\') < 2 and \'LLL\' not in s\n```
5
You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. The student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Return `true` _if the student is eligible for an attendance award, or_ `false` _otherwise_. **Example 1:** **Input:** s = "PPALLP " **Output:** true **Explanation:** The student has fewer than 2 absences and was never late 3 or more consecutive days. **Example 2:** **Input:** s = "PPALLL " **Output:** false **Explanation:** The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'A'`, `'L'`, or `'P'`.
null
551: Space 92.86%, Solution with step by step explanation
student-attendance-record-i
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize two variables, count_A and count_L, both to 0.\n2. Iterate through each character c in the input string s.\n3. If the character is \'A\', increment count_A and reset count_L to 0.\n4. If the character is \'L\', increment count_L.\n5. If the character is not \'A\' or \'L\', reset count_L to 0.\n6. Check if count_A is greater than or equal to 2 or if count_L is greater than or equal to 3. If either condition is met, return False.\n7. If the iteration completes without returning False, return True.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkRecord(self, s: str) -> bool:\n # Count of \'A\' and consecutive \'L\'s\n count_A, count_L = 0, 0\n \n for c in s:\n if c == \'A\':\n count_A += 1\n count_L = 0\n elif c == \'L\':\n count_L += 1\n else:\n count_L = 0\n \n if count_A >= 2 or count_L >= 3:\n return False\n \n return True\n\n```
5
You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. The student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Return `true` _if the student is eligible for an attendance award, or_ `false` _otherwise_. **Example 1:** **Input:** s = "PPALLP " **Output:** true **Explanation:** The student has fewer than 2 absences and was never late 3 or more consecutive days. **Example 2:** **Input:** s = "PPALLL " **Output:** false **Explanation:** The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'A'`, `'L'`, or `'P'`.
null
Python one line simple solution
student-attendance-record-i
0
1
**Python :**\n\n```\ndef checkRecord(self, s: str) -> bool:\n\treturn False if "LLL" in s or s.count(\'A\') >= 2 else True\n```\n\n**Like it ? please upvote !**
11
You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. The student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Return `true` _if the student is eligible for an attendance award, or_ `false` _otherwise_. **Example 1:** **Input:** s = "PPALLP " **Output:** true **Explanation:** The student has fewer than 2 absences and was never late 3 or more consecutive days. **Example 2:** **Input:** s = "PPALLL " **Output:** false **Explanation:** The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'A'`, `'L'`, or `'P'`.
null
Solution
student-attendance-record-ii
1
1
```C++ []\n#pragma clang attribute push (__attribute__((no_sanitize("address","undefined"))), apply_to=function)\n\nconst int mod = 1E9 + 7;\n\nint dp[2][3][4], ts;\narray<int, 2> t[1024];\n\nofstream out("user.out");\n\nint main() {\n ios::sync_with_stdio(0), cin.tie(0);\n for (int n; cin >> n; ts++) t[ts] = {n, ts};\n sort(t, t + ts, [](auto& x, auto& y) { return x[0] < y[0]; });\n \n for (int a : {0, 1})\n for (int l : {0, 1, 2})\n dp[0][a][l] = 1;\n \n int ti = 0;\n for (int i = 1, lim = t[ts - 1][0]; i <= lim; i++) {\n#pragma unroll\n for (int a : {0, 1}) {\n#pragma unroll\n for (int l : {0, 1, 2}) {\n auto& ans = dp[i & 1][a][l];\n ans = dp[~i & 1][a][0];\n ans += dp[~i & 1][a + 1][0];\n ans -= (ans >= mod) * mod;\n ans += dp[~i & 1][a][l + 1];\n ans -= (ans >= mod) * mod;\n }\n }\n while (t[ti][0] == i)\n t[ti++][0] = dp[i & 1][0][0];\n }\n sort(t, t + ts, [](auto& x, auto& y) { return x[1] < y[1]; });\n for (int i = 0; i < ts; i++)\n out << t[i][0] << "\\n";\n}\n\n#define main main_\n\nclass Solution {\npublic:\n int checkRecord(int n) {\n return 0;\n }\n};\n\n#pragma clang attribute pop\n```\n\n```Python3 []\nimport numpy as np\n\nclass Solution:\n \n def checkRecord(self, n: int) -> int:\n MODULUS = 10**9 + 7\n\n initial_counts = np.array(\n [1, 0, 0, 0, 0, 0], \n dtype=np.int64\n )\n adjacency_matrix = np.array([\n [1, 1, 1, 0, 0, 0],\n [1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n ], dtype=np.int64)\n\n def power(A, exp):\n B = np.identity(len(A), dtype=np.int64)\n for bit in reversed(bin(exp)[2:]):\n if bit == \'1\':\n B = B @ A\n B %= MODULUS\n A = A @ A\n A %= MODULUS\n return B\n\n final_counts = power(adjacency_matrix, n) @ initial_counts\n\n return sum(final_counts) % MODULUS\n```\n\n```Java []\nclass Solution {\n final int MOD = 1000000007;\n final int M = 6;\n\n int[][] mul(int[][] A, int[][] B) {\n int[][] C = new int[M][M];\n for (int i = 0; i < M; i++)\n for (int j = 0; j < M; j++)\n for (int k = 0; k < M; k++)\n C[i][j] = (int) ((C[i][j] + (long) A[i][k] * B[k][j]) % MOD);\n return C;\n }\n int[][] pow(int[][] A, int n) {\n int[][] res = new int[M][M];\n for (int i = 0; i < M; i++)\n res[i][i] = 1;\n while (n > 0) {\n if (n % 2 == 1)\n res = mul(res, A);\n A = mul(A, A);\n n /= 2;\n }\n return res;\n }\n public int checkRecord(int n) {\n int[][] A = {\n {0, 0, 1, 0, 0, 0},\n {1, 0, 1, 0, 0, 0},\n {0, 1, 1, 0, 0, 0},\n {0, 0, 1, 0, 0, 1},\n {0, 0, 1, 1, 0, 1},\n {0, 0, 1, 0, 1, 1},\n };\n return pow(A, n + 1)[5][2];\n }\n}\n```\n
1
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. Any student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Given an integer `n`, return _the **number** of possible attendance records of length_ `n` _that make a student eligible for an attendance award. The answer may be very large, so return it **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 2 **Output:** 8 **Explanation:** There are 8 records with length 2 that are eligible for an award: "PP ", "AP ", "PA ", "LP ", "PL ", "AL ", "LA ", "LL " Only "AA " is not eligible because there are 2 absences (there need to be fewer than 2). **Example 2:** **Input:** n = 1 **Output:** 3 **Example 3:** **Input:** n = 10101 **Output:** 183236316 **Constraints:** * `1 <= n <= 105`
null
Python O(log n) using NumPy
student-attendance-record-ii
0
1
*This is an alternative writeup of [lixx2100\'s solution](https://leetcode.com/problems/student-attendance-record-ii/discuss/101633/Improving-the-runtime-from-O(n)-to-O(log-n)). Credit also to [StefanPochmann](https://leetcode.com/problems/student-attendance-record-ii/discuss/101633/Improving-the-runtime-from-O(n)-to-O(log-n)/105302).*\n\n<hr />\n\nIt\'s helpful to think of the set of rewardable records as a regular language, and a particular student\'s attendence record as belonging to a state in a finite state machine:\n\n![image](https://assets.leetcode.com/users/lxnn/image_1572285162.png)\n\n(For example, if you were late today, but not yesterday, and you\'ve had no absences so far, then you\'re in state *1*. If you are late tomorrow, you move to state *2*.)\n\nThis makes it fairly easy to calculate the number of length-n rewardable records, we can recursively compute the number of length-n records for each of these six states:\n* Base case: The length-zero record, `\'\'`, belongs to state *0*.\n* Recursive case: If we add another day to the record length, each state becomes the sum of all the states with an arrow pointing into it.\n\nExpressed algebraically:\n* We represent the counts for the six states as a vector. For the base-case (*n = 0*), this is *v<sub>0</sub> = [1 0 0 0 0 0]<sup>T</sup>*.\n* We represent the finite-state-machine transitions as a matrix, *A*, where the value of *A<sub>ij</sub>* is the number of arrows from state *j* to state *i*:\n\n![image](https://assets.leetcode.com/users/lxnn/image_1572366038.png)\n\n* The final counts are *v<sub>n</sub> = A<sup>n</sup> v<sub>0</sub>*.\n* We return the sum of the entries of *v<sub>n</sub>*.\n\nWe can compute *A<sup>n</sup>* in *O(log n)* time, as per [problem #50](https://leetcode.com/problems/powx-n/):\n* Compute *(A<sup>1</sup>, A<sup>2</sup>, A<sup>4</sup>, A<sup>8</sup>, ...)* by repeatedly replacing *A* with *A<sup>2</sup>*.\n* Then *A<sup>n</sup>* is the product of all the *A<sup>2^i</sup>* for which the *i*\'th bit of the little-endian binary representation of *n* is *1*.\n\n\n<hr />\n\n# Implementation\n\nFor convenience, I\'ll be using the `numpy` library.\n\n```python\nimport numpy as np\n```\n\nWe represent the state counts as a vector:\n\n```python\ninitial_counts = np.array(\n [1, 0, 0, 0, 0, 0], \n dtype=np.int64\n)\n```\n\nAnd the finite state machine as an adjacency matrix (the number at `(i, j)` being the number of arrows from state `j` to state `i`):\n\n```python\nadjacency_matrix = np.array([\n [1, 1, 1, 0, 0, 0],\n [1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n], dtype=np.int64)\n```\n\nWe now just left-multiply `initial_counts` by `adjacency_matrix` `n` times -- equivalent to left-multiplying `initial_counts` by `power(adjacency_matrix, n)` (the symbol `@` is the NumPy operator for matrix multiplication):\n\n```python\nfinal_counts = power(adjacency_matrix, n) @ initial_counts\n```\n\nAnd finally, return the sum of the counts, modulo `10**9 + 7`:\n\n```python\nMODULUS = 10**9 + 7\nreturn sum(final_counts) % MODULUS\n```\n\nIt\'s in the implementation of the `power` function that we can take the algorithm from **O(n)** to **O(log n)**. The simple way to take the power of a matrix would be to start with an identity matrix, then multiply it by the matrix `n` times (taking the remainder mod `MODULUS` each time to avoid overflow):\n\n```python\ndef power(A, exp):\n B = np.identity(len(A), dtype=np.int64)\n\tfor _ in range(exp):\n\t B = B @ A\n\t\tB %= MODULUS\n return B\n```\n\nInstead, we separate the exponent into a sum of powers of 2 (its binary representation), then multiply in `A` raised to those powers of 2.\n\n```python\ndef power(A, exp):\n B = np.identity(len(A), dtype=np.int64)\n for bit in reversed(bin(exp)[2:]):\n if bit == \'1\':\n B = B @ A\n B %= MODULUS\n A = A @ A\n A %= MODULUS\n return B\n```\n\nPutting it all together:\n\n```python\nimport numpy as np\n\nclass Solution:\n \n def checkRecord(self, n: int) -> int:\n MODULUS = 10**9 + 7\n\n initial_counts = np.array(\n [1, 0, 0, 0, 0, 0], \n dtype=np.int64\n )\n\n adjacency_matrix = np.array([\n [1, 1, 1, 0, 0, 0],\n [1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n ], dtype=np.int64)\n\n def power(A, exp):\n B = np.identity(len(A), dtype=np.int64)\n for bit in reversed(bin(exp)[2:]):\n if bit == \'1\':\n B = B @ A\n B %= MODULUS\n A = A @ A\n A %= MODULUS\n return B\n\n final_counts = power(adjacency_matrix, n) @ initial_counts\n\n return sum(final_counts) % MODULUS\n```\n\nPlease leave a comment if there\'s anything I can clarify.
46
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. Any student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Given an integer `n`, return _the **number** of possible attendance records of length_ `n` _that make a student eligible for an attendance award. The answer may be very large, so return it **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 2 **Output:** 8 **Explanation:** There are 8 records with length 2 that are eligible for an award: "PP ", "AP ", "PA ", "LP ", "PL ", "AL ", "LA ", "LL " Only "AA " is not eligible because there are 2 absences (there need to be fewer than 2). **Example 2:** **Input:** n = 1 **Output:** 3 **Example 3:** **Input:** n = 10101 **Output:** 183236316 **Constraints:** * `1 <= n <= 105`
null
Easy to understand 7 line Python DP Solution
student-attendance-record-ii
0
1
# Intuition\nInitially, I thought that there might be a combinatorics based approach to this problem. However, the fact that there cannot be 3 L\'s in a row makes this hard. The next thing I thought of was DP, and indeed it works well here.\n\n# Approach\nLet $T(i, j, k)$ be the number of attendance records of length $i$ with $j$ trailing L\'s and $k$ absenses. We require $j< 3$ and $k < 2$, as per the problem. Then, we observe that $T(i, \\cdot, \\cdot)$ is related to $T(i-1,\\cdot,\\cdot)$ through the following 6 relations:\n1. $T(i,0,0) = T(i-1, 0, 0) + T(i-1, 1, 0) + T(i-2, 2, 0)$. This corresponds to placing a \'H\', which resets the second parameter.\n2. $T(i, 0, 1) = T(i-1, 0, 0) + T(i-1, 1, 0) + T(i-2, 2, 0) + T(i-1, 0, 1) + T(i-1, 1, 1) + T(i-2, 2, 1)$. This corresponds to either placing a \'A\', which increments the last parameter, or placing a \'H\' when one \'A\' has already been placed previously.\n3. $T(i, 1, 0) = T(i-1, 0, 0)$. This corresponds to placing the first \'L\'.\n4. $T(i, 1, 1) = T(i-1, 0, 1)$. This corresponds to placing the first \'L\'.\n5. $T(i, 2, 0) = T(i-1, 1, 0)$. This corresponds to placing the second \'L\'.\n6. $T(i, 2, 1) = T(i-1, 1, 1)$. This corresponds to placing the second \'L\'.\n\nWe initialize $T(0,0,0)=T(0,0,1)=T(0,1,0)=1$, and return the sum of $T(n,j,k)$ for all possible $j,k$. By reusing some computations and adding the modulo operator, we can do this fairly quickly and in-place.\n\nThe operations correspond to a matrix operator, and I attempted to diagonalize it to make exponentiation easy, but the eigenvalues are all complex, which makes it a bit complicated. Thus, I stuck with the naive iterative computation of the above.\n# Complexity\n- Time complexity:\n$O(n)$ - constant number of operations for each of the $n$ iterations\n\nI think this can be improved to $O(log(n))$, since this is a linear recurrence, so we can use matrix multiplication and repeated squaring, but I think that\'s more annoying than it\'s worth.\n\n- Space complexity:\n$O(1)$ - can be done in place\n\n# Code\n```\nclass Solution:\n def checkRecord(self, n: int) -> int:\n mod = 10**9 + 7\n T = [[1, 1], [1, 0], [0, 0]]\n for i in range(1, n):\n t_0_0 = (T[0][0] + T[1][0] + T[2][0]) % mod\n t_0_1 = (t_0_0 + T[0][1] + T[1][1] + T[2][1]) % mod\n T = [[t_0_0, t_0_1], T[0], T[1]]\n return (sum(T[0]) + sum(T[1]) + sum(T[2])) % mod\n```
2
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. Any student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Given an integer `n`, return _the **number** of possible attendance records of length_ `n` _that make a student eligible for an attendance award. The answer may be very large, so return it **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 2 **Output:** 8 **Explanation:** There are 8 records with length 2 that are eligible for an award: "PP ", "AP ", "PA ", "LP ", "PL ", "AL ", "LA ", "LL " Only "AA " is not eligible because there are 2 absences (there need to be fewer than 2). **Example 2:** **Input:** n = 1 **Output:** 3 **Example 3:** **Input:** n = 10101 **Output:** 183236316 **Constraints:** * `1 <= n <= 105`
null
Top-Down DP - Python - Memoization - O(n)
student-attendance-record-ii
0
1
# Approach\nFirst solve the problem for only P and Ls.\nThis means, we have `n - 1` options for ending in Ps `(...LP, ...PP)`.\nThis also means, we have `n - 1` options for ending in Ls `(...LL, ...PL)`\n\nThis gives us for `n = 2 * helper(n - 1)`.\n\nBut we also have to incorporate constraints: No three `L` can follow each other.\n\nTherefore we need to exclude these from our total amount.\n\nWe will find that `...PLLL` are not valid options for the `n - 1` route ending on `L`. \nSo these options from `n - 4` need to be excluded once from the total amount - leaving us with:\n\n`n = 2 * helper(n - 1) - helper(n - 4)`\n\nWe can recursively calculate these results and fill our `dp` memoization dictionary.\n\nLast we have to introduce our `A` options into the total.\nWe can only introduce `A` once into a valid sequence, but on top of that every position in the sequence is valid: `...PAP...`, `...APP...` etc.\n\nThis means we can iterate through the positions `i` of the sequence `n` and introduce `A` in all positions. As we have pre-calculated the sequences before `(dp[i - 1])` and after `(dp[n - i])`:\n\nFor one `i` this means: `dp[i - 1] * dp[n - i]`. \nWe then just iterate through all `i` and add to our final total.\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkRecord(self, n: int) -> int:\n self.dp = defaultdict(int)\n\n self.dp[0] = 1\n self.dp[1] = 2\n self.dp[2] = 4\n self.dp[3] = 7\n\n self.helper(n)\n total = self.dp[n]\n\n for i in range(1, n + 1):\n total += self.dp[i - 1] * self.dp[n - i] \n\n return total % ((10 ** 9) + 7)\n\n def helper(self, i):\n if i < 0:\n return 0\n if i in self.dp:\n return self.dp[i]\n\n self.dp[i] = (2 * self.helper(i - 1) - self.helper(i - 4)) % ((10 ** 9) + 7)\n \n return self.dp[i]\n```
1
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. Any student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Given an integer `n`, return _the **number** of possible attendance records of length_ `n` _that make a student eligible for an attendance award. The answer may be very large, so return it **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 2 **Output:** 8 **Explanation:** There are 8 records with length 2 that are eligible for an award: "PP ", "AP ", "PA ", "LP ", "PL ", "AL ", "LA ", "LL " Only "AA " is not eligible because there are 2 absences (there need to be fewer than 2). **Example 2:** **Input:** n = 1 **Output:** 3 **Example 3:** **Input:** n = 10101 **Output:** 183236316 **Constraints:** * `1 <= n <= 105`
null
552: Solution with step by step explanation
student-attendance-record-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize the modulo value kMod to 10**9 + 7.\n2. Create a 2D list dp of size 2 x 3 filled with zeros, where dp[i][j] represents the number of valid records with i A\'s and the latest j characters being L\'s.\n3. Set dp[0][0] = 1 to represent the empty record.\n4. Iterate n times using a for loop, where n is the length of the record.\n5. For each iteration:\n - Store the current values of dp[0][0], dp[0][1], dp[0][2], dp[1][0], dp[1][1], and dp[1][2] in variables p0, p1, p2, q0, q1, and q2, respectively.\n - Update dp[0][0] by adding the previous values of dp[0][0], dp[0][1], and dp[0][2], and taking the result modulo kMod. This represents appending a "P" to the record.\n - Update dp[0][1] by setting it to the previous value of dp[0][0]. This represents appending an "L" to the record.\n - Update dp[0][2] by setting it to the previous value of dp[0][1]. This also represents appending an "L" to the record.\n - Update dp[1][0] by adding the previous values of dp[0][0], dp[0][1], dp[0][2], dp[1][0], dp[1][1], and dp[1][2], and taking the result modulo kMod. This represents either appending an "A" or appending a "P" to the record.\n - Update dp[1][1] by setting it to the previous value of dp[1][0]. This represents appending an "L" to the record.\n - Update dp[1][2] by setting it to the previous value of dp[1][1]. This also represents appending an "L" to the record.\n6. Compute the sum of all elements in dp using the sum function, and take the result modulo kMod.\n7. Return the result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkRecord(self, n: int) -> int:\n kMod = 10**9 + 7\n dp = [[0] * 3 for _ in range(2)]\n dp[0][0] = 1\n\n for i in range(n):\n p0, p1, p2, q0, q1, q2 = dp[0][0], dp[0][1], dp[0][2], dp[1][0], dp[1][1], dp[1][2]\n \n # Append P\n dp[0][0] = (p0 + p1 + p2) % kMod\n\n # Append L\n dp[0][1] = p0\n\n # Append L\n dp[0][2] = p1\n\n # Append A or append P\n dp[1][0] = (p0 + p1 + p2 + q0 + q1 + q2) % kMod\n\n # Append L\n dp[1][1] = q0\n\n # Append L\n dp[1][2] = q1\n\n return sum(dp[0] + dp[1]) % kMod\n\n```
3
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. Any student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Given an integer `n`, return _the **number** of possible attendance records of length_ `n` _that make a student eligible for an attendance award. The answer may be very large, so return it **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 2 **Output:** 8 **Explanation:** There are 8 records with length 2 that are eligible for an award: "PP ", "AP ", "PA ", "LP ", "PL ", "AL ", "LA ", "LL " Only "AA " is not eligible because there are 2 absences (there need to be fewer than 2). **Example 2:** **Input:** n = 1 **Output:** 3 **Example 3:** **Input:** n = 10101 **Output:** 183236316 **Constraints:** * `1 <= n <= 105`
null
Python solution with explanation
student-attendance-record-ii
0
1
Here is a python solution with detailed expalanation:\n\n```\nclass Solution:\n def checkRecord(self, n: int) -> int:\n """\n Suppose dp[i] is the number of all the rewarded sequences without \'A\'\n having their length equals to i, then we have:\n 1. Number of sequence ends with \'P\': dp[i - 1]\n 2. Number of sequence ends with \'L\':\n 2.1 Number of sequence ends with \'PL\': dp[i - 2]\n 2.2 Number of sequence ends with \'LL\':\n 2.2.1 Number of sequence ends with \'PLL\': dp[i - 3]\n 2.2.2 Number of sequence ends with \'LLL\': 0 (not allowed)\n\n So dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3], 3 <= i <= n\n\n Then all the rewarding sequences with length n are divided into\n two cases as follows:\n 1. Number of sequences without \'A\': dp[n]\n 2. Number of sequence with A in the middle, since we could only \n have at most one A in the sequence to get it rewarded, \n suppose A is at the ith position, then we have:\n A[i] = dp[i] * dp[n - 1 - i]\n\n Then the number of such sequences is:\n sum(A[i] for i in range(n))\n\n Then our final result will be dp[n] + sum(A[i] for i in range(n)).\n\n Corner cases:\n 1. dp[0] = 1: which means the only case when the sequence is an\n empty string.\n 2. dp[1] = 2: \'L\', \'P\'\n 3. dp[2] = 4: \'LL\', \'LP\', \'PL\', \'PP\'\n """\n if not n:\n return 0\n\n if n == 1:\n return 3\n\n MOD = 10 ** 9 + 7\n dp = [1, 2, 4] + [0] * (n - 2)\n\n # Calculate sequences without \'A\'.\n for i in range(3, n + 1):\n dp[i] = (dp[i - 1] + dp[i - 2] + dp[i - 3]) % MOD\n\n # Calculate final result.\n rslt = dp[n] % MOD\n for i in range(n):\n rslt += (dp[i] * dp[n - 1 - i]) % MOD\n\n return rslt % MOD\n```
10
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. Any student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Given an integer `n`, return _the **number** of possible attendance records of length_ `n` _that make a student eligible for an attendance award. The answer may be very large, so return it **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 2 **Output:** 8 **Explanation:** There are 8 records with length 2 that are eligible for an award: "PP ", "AP ", "PA ", "LP ", "PL ", "AL ", "LA ", "LL " Only "AA " is not eligible because there are 2 absences (there need to be fewer than 2). **Example 2:** **Input:** n = 1 **Output:** 3 **Example 3:** **Input:** n = 10101 **Output:** 183236316 **Constraints:** * `1 <= n <= 105`
null
Solution in Python 3 (five lines) (with explanation)
student-attendance-record-ii
0
1
```\nclass Solution:\n def checkRecord(self, n: int) -> int:\n \tC, m = [1,1,0,1,0,0], 10**9 + 7\n \tfor i in range(n-1):\n \t\ta, b = sum(C[:3]) % m, sum(C[3:]) % m\n \t\tC = [a, C[0], C[1], a + b, C[3], C[4]]\n \treturn (sum(C) % m)\n\t\t\n```\n_Explanation_\n\nThe list C is structured as follows:\n\nC[0] = no A, ends in no L\nC[1] = no A, ends in 1 L\nC[2] = no A, ends in 2 Ls\nC[3] = 1 A, ends in no L\nC[4] = 1 A, ends in 1 L\nC[5] = 1 A, ends in 2 Ls\n\nThe program starts by initializing C to the case where n = 1 (A or P or L). Given the n = 1 scenario, the only things that can happen on day 2 is A or P or L, leading to new values for each of the six disjoint categories in C. It\'s very important that the six categories outlined in the structure of C above do not overlap and also cover all possible cases. Given the set of all possible attendance records for a specific value of n (i.e. list C), it is possible to predict what C will look like for n + 1 and thus the recursive iteration can be established. At the end of the program, we simply sum all of the values in C to get the total number of possibilities. The arithmetic is kept mod m throughout to keep the numbers as small as possible and speed up the calculations.\n```\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com
16
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. Any student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Given an integer `n`, return _the **number** of possible attendance records of length_ `n` _that make a student eligible for an attendance award. The answer may be very large, so return it **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 2 **Output:** 8 **Explanation:** There are 8 records with length 2 that are eligible for an award: "PP ", "AP ", "PA ", "LP ", "PL ", "AL ", "LA ", "LL " Only "AA " is not eligible because there are 2 absences (there need to be fewer than 2). **Example 2:** **Input:** n = 1 **Output:** 3 **Example 3:** **Input:** n = 10101 **Output:** 183236316 **Constraints:** * `1 <= n <= 105`
null
Solution
optimal-division
1
1
```C++ []\nclass Solution {\n public:\n string optimalDivision(vector<int>& nums) {\n string ans = to_string(nums[0]);\n\n if (nums.size() == 1)\n return ans;\n if (nums.size() == 2)\n return ans + "/" + to_string(nums[1]);\n\n ans += "/(" + to_string(nums[1]);\n for (int i = 2; i < nums.size(); ++i)\n ans += "/" + to_string(nums[i]);\n ans += ")";\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def optimalDivision(self, nums: List[int]) -> str:\n \n if len(nums) == 1:\n return str(nums[0])\n elif len(nums) == 2:\n return str(nums[0]) + "/" + str(nums[1])\n else:\n return str(nums[0]) + "/(" + "/".join([str(num) for num in nums[1:]]) + ")"\n```\n\n```Java []\nclass Solution {\n public String optimalDivision(int[] nums) {\n int n = nums.length;\n StringBuilder sb = new StringBuilder().append(nums[0]);\n\n if (n == 1) return sb.toString();\n if (n == 2) return sb.append("/").append(nums[1]).toString();\n sb.append("/(");\n for (int i = 1; i < n; i++) \n sb.append(nums[i]).append("/");\n \n sb.setCharAt(sb.length()-1, \')\');\n return sb.toString();\n }\n}\n```\n
2
You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. * For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`. However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return _the corresponding expression that has the maximum value in string format_. **Note:** your expression should not contain redundant parenthesis. **Example 1:** **Input:** nums = \[1000,100,10,2\] **Output:** "1000/(100/10/2) " **Explanation:** 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/(**(**100/10**)**/2) " are redundant since they do not influence the operation priority. So you should return "1000/(100/10/2) ". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 **Example 2:** **Input:** nums = \[2,3,4\] **Output:** "2/(3/4) " **Explanation:** (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 **Constraints:** * `1 <= nums.length <= 10` * `2 <= nums[i] <= 1000` * There is only one optimal division for the given input.
null
553: Solution with step by step explanation
optimal-division
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. If the length of the given array "nums" is 1, return the only number in the string format.\n2. If the length of the given array "nums" is 2, return the division of the first and second number in the string format.\n3. If the length of the given array "nums" is greater than 2, convert all the numbers in "nums" into string format and join them using a forward slash (\'/\') separator.\n4. Place the first number in "nums" outside of the parenthesis and enclose the remaining numbers inside the parenthesis with forward slashes as the separator.\n5. Return the string with the expression that has the maximum value after the evaluation.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def optimalDivision(self, nums: List[int]) -> str:\n if len(nums) == 1:\n return str(nums[0])\n elif len(nums) == 2:\n return str(nums[0]) + \'/\' + str(nums[1])\n else:\n nums_str = list(map(str, nums))\n return str(nums[0]) + \'/(\' + \'/\'.join(nums_str[1:]) + \')\'\n\n```
2
You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. * For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`. However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return _the corresponding expression that has the maximum value in string format_. **Note:** your expression should not contain redundant parenthesis. **Example 1:** **Input:** nums = \[1000,100,10,2\] **Output:** "1000/(100/10/2) " **Explanation:** 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/(**(**100/10**)**/2) " are redundant since they do not influence the operation priority. So you should return "1000/(100/10/2) ". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 **Example 2:** **Input:** nums = \[2,3,4\] **Output:** "2/(3/4) " **Explanation:** (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 **Constraints:** * `1 <= nums.length <= 10` * `2 <= nums[i] <= 1000` * There is only one optimal division for the given input.
null
Python 3 Solution, Runtime beats 94%
optimal-division
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen len(nums)>=2, the first num in nums is dividend, and the rest of nums together form the divisor. In order to maximun the result, our strategy should be minimun the divisor.\n! That is a simple but not decent approach (from my perspective)\n![image.png](https://assets.leetcode.com/users/images/cac7a556-af40-4c8d-aca1-298f10aabeb2_1700505391.100823.png)\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(n)$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def optimalDivision(self, nums: List[int]) -> str:\n if len(nums)==1:\n return str(nums[0])\n if len(nums)==2:\n return str(nums[0])+"/"+str(nums[1])\n res=str(nums[0])+"/("\n for num in nums[1:-1]:\n res+=str(num)+"/"\n return res+str(nums[-1])+")"\n```
0
You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. * For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`. However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return _the corresponding expression that has the maximum value in string format_. **Note:** your expression should not contain redundant parenthesis. **Example 1:** **Input:** nums = \[1000,100,10,2\] **Output:** "1000/(100/10/2) " **Explanation:** 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/(**(**100/10**)**/2) " are redundant since they do not influence the operation priority. So you should return "1000/(100/10/2) ". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 **Example 2:** **Input:** nums = \[2,3,4\] **Output:** "2/(3/4) " **Explanation:** (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 **Constraints:** * `1 <= nums.length <= 10` * `2 <= nums[i] <= 1000` * There is only one optimal division for the given input.
null
PYTHON EASY SOLUTION | Faster than 75% 📌🔥
optimal-division
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def optimalDivision(self, nums: List[int]) -> str:\n ans = str(nums[0])\n\n if len(nums) == 1:\n return ans\n if len(nums) == 2:\n return ans + \'/\' + str(nums[1])\n\n ans += \'/(\' + str(nums[1])\n for i in range(2, len(nums)):\n ans += \'/\' + str(nums[i])\n ans += \')\'\n return ans\n\n```
0
You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. * For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`. However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return _the corresponding expression that has the maximum value in string format_. **Note:** your expression should not contain redundant parenthesis. **Example 1:** **Input:** nums = \[1000,100,10,2\] **Output:** "1000/(100/10/2) " **Explanation:** 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/(**(**100/10**)**/2) " are redundant since they do not influence the operation priority. So you should return "1000/(100/10/2) ". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 **Example 2:** **Input:** nums = \[2,3,4\] **Output:** "2/(3/4) " **Explanation:** (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 **Constraints:** * `1 <= nums.length <= 10` * `2 <= nums[i] <= 1000` * There is only one optimal division for the given input.
null
Easy string manipulation solution.
optimal-division
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def optimalDivision(self, nums: List[int]) -> str:\n #mjhearn.com borosilicate oct 25, 2023\n if(len(nums)>2):\n out=\'\'+str(nums[0])+\'/(\'\n for j in nums[1:]:\n out+=str(j)+\'/\'\n out=out[:len(out)-1]\n out+=\')\'\n elif(len(nums)==2):\n out=\'\'+str(nums[0])+\'/\'+str(nums[1])\n else:\n return f\'{nums[0]}\'\n return out\n\n```
0
You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. * For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`. However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return _the corresponding expression that has the maximum value in string format_. **Note:** your expression should not contain redundant parenthesis. **Example 1:** **Input:** nums = \[1000,100,10,2\] **Output:** "1000/(100/10/2) " **Explanation:** 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/(**(**100/10**)**/2) " are redundant since they do not influence the operation priority. So you should return "1000/(100/10/2) ". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 **Example 2:** **Input:** nums = \[2,3,4\] **Output:** "2/(3/4) " **Explanation:** (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 **Constraints:** * `1 <= nums.length <= 10` * `2 <= nums[i] <= 1000` * There is only one optimal division for the given input.
null
Python3 O(n)
optimal-division
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def optimalDivision(self, nums: List[int]) -> str:\n n = len(nums)\n if n == 0:\n return 0\n if n == 1:\n return str(nums[0])\n if n == 2:\n return str(nums[0]) + "/" + str(nums[1])\n \n nums = map(str, nums)\n fnums=""\n for i,x in enumerate(nums):\n if i == 0:\n fnums += x+"/("\n elif i == n - 1:\n fnums += x+")"\n return fnums\n else:\n fnums+=x+"/"\n return -1\n```
0
You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. * For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`. However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return _the corresponding expression that has the maximum value in string format_. **Note:** your expression should not contain redundant parenthesis. **Example 1:** **Input:** nums = \[1000,100,10,2\] **Output:** "1000/(100/10/2) " **Explanation:** 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/(**(**100/10**)**/2) " are redundant since they do not influence the operation priority. So you should return "1000/(100/10/2) ". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 **Example 2:** **Input:** nums = \[2,3,4\] **Output:** "2/(3/4) " **Explanation:** (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 **Constraints:** * `1 <= nums.length <= 10` * `2 <= nums[i] <= 1000` * There is only one optimal division for the given input.
null
Clear Python DP Solution with Faster than 50%
optimal-division
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSplit array to `Left` and `Right` parts, and then we can get max value of the whole array by `Left.max_val/Right.min_val` and the corresponding string by `"f{Left.max_str/Right.min_str}"`(There requires some ammendments on the min_str while building the longer string, but you get the idea)\n\ndp[i][j] contains the MaxMinInfo for string between nums[i:j+1], build this info from short slices to the full nums array.\n\nThere shold be approaches to optimze my code but the idea is quite straight forward, feel free to add more comment.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDP\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^3)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n# Code\n```\nclass MaxMinInfo:\n def __init__(self, max_val=float("-inf"), min_val=float("inf"), max_str="", min_str=""):\n self.max_val = max_val\n self.max_str = max_str\n self.min_val = min_val\n self.min_str = min_str\n def setVal(self, val, string):\n self.max_val = val\n self.min_val = val\n self.max_str = string\n self.min_str = string\n def updateMax(self, val, string):\n if val > self.max_val:\n self.max_val = val\n self.max_str = string\n def updateMin(self, val, string):\n if val < self.min_val:\n self.min_val = val\n self.min_str = string\n\ndef getString(string, dist):\n if dist == 0:\n return string\n else:\n return f"({string})"\n \nclass Solution:\n def optimalDivision(self, nums: List[int]) -> str:\n n = len(nums)\n ans = ""\n cur_max = -1\n dp = [[MaxMinInfo() for _ in range(n)] for _ in range(n)]\n #Initialzation\n for i in range(len(nums)):\n dp[i][i].setVal(nums[i], f"{nums[i]}")\n for i in range(len(nums) - 1):\n dp[i][i+1].setVal(nums[i] / nums[i + 1], f"{nums[i]}/{nums[i + 1]}")\n #Bottom Up\n for length in range(2, len(nums)):\n for i in range(len(nums) - length):\n j = i + length\n for mid in range(i, j):\n dp[i][j].updateMax(dp[i][mid].max_val / dp[mid + 1][j].min_val, f"{dp[i][mid].max_str}/{getString(dp[mid + 1][j].min_str, mid + 1 -j)}")\n dp[i][j].updateMin(dp[i][mid].min_val / dp[mid + 1][j].max_val, f"{dp[i][mid].min_str}/{getString(dp[mid + 1][j].max_str, mid + 1 -j)}")\n\n return dp[0][-1].max_str\n\n```
0
You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. * For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`. However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return _the corresponding expression that has the maximum value in string format_. **Note:** your expression should not contain redundant parenthesis. **Example 1:** **Input:** nums = \[1000,100,10,2\] **Output:** "1000/(100/10/2) " **Explanation:** 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/(**(**100/10**)**/2) " are redundant since they do not influence the operation priority. So you should return "1000/(100/10/2) ". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 **Example 2:** **Input:** nums = \[2,3,4\] **Output:** "2/(3/4) " **Explanation:** (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 **Constraints:** * `1 <= nums.length <= 10` * `2 <= nums[i] <= 1000` * There is only one optimal division for the given input.
null
Python Dictionary With Explanation
brick-wall
0
1
# Intuition\nYou have to find the best coloumn basically through which we can draw a line so we cross the least number of walls.\nSo why not we store all the number of bricks which end at that particular coloumn.\n\n`Why? Because if we choose a coloumn where max brick ends then we have to cross the least number of bricks.`\n\nSo Make a dict to store all the number of bricks ending at particular coloumn and then choose the max brick ending and subtract it with n.\n\n`Why? Becuase n is the number of rows so it will denote the total number of bricks it have to cross`\n# Code\n```\nclass Solution:\n def leastBricks(self, wall: List[List[int]]) -> int:\n n = len(wall)\n m = sum(wall[0])\n col0 = defaultdict(int)\n for i in range(n):\n prev = 0\n for j in range(len(wall[i])):\n col0[prev + wall[i][j]] += 1\n prev += wall[i][j] # update the ending of particular brick for each row \n col0[m] = 0\n bricks = max(v for v in col0.values())\n return n - bricks\n \n```
2
There is a rectangular brick wall in front of you with `n` rows of bricks. The `ith` row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. Given the 2D array `wall` that contains the information about the wall, return _the minimum number of crossed bricks after drawing such a vertical line_. **Example 1:** **Input:** wall = \[\[1,2,2,1\],\[3,1,2\],\[1,3,2\],\[2,4\],\[3,1,2\],\[1,3,1,1\]\] **Output:** 2 **Example 2:** **Input:** wall = \[\[1\],\[1\],\[1\]\] **Output:** 3 **Constraints:** * `n == wall.length` * `1 <= n <= 104` * `1 <= wall[i].length <= 104` * `1 <= sum(wall[i].length) <= 2 * 104` * `sum(wall[i])` is the same for each row `i`. * `1 <= wall[i][j] <= 231 - 1`
null