id
int64
1
3.71k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
498
Diagonal Traverse
Medium
<p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0498.Diagonal%20Traverse/images/diag1-grid.jpg" style="width: 334px; height: 334px;" /> <pre> <strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,4,7,5,3,6,8,9] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[1,2],[3,4]] <strong>Output:</strong> [1,2,3,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>5</sup> &lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Matrix; Simulation
Python
class Solution: def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]: m, n = len(mat), len(mat[0]) ans = [] for k in range(m + n - 1): t = [] i = 0 if k < n else k - n + 1 j = k if k < n else n - 1 while i < m and j >= 0: t.append(mat[i][j]) i += 1 j -= 1 if k % 2 == 0: t = t[::-1] ans.extend(t) return ans
498
Diagonal Traverse
Medium
<p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0498.Diagonal%20Traverse/images/diag1-grid.jpg" style="width: 334px; height: 334px;" /> <pre> <strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,4,7,5,3,6,8,9] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[1,2],[3,4]] <strong>Output:</strong> [1,2,3,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>5</sup> &lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Matrix; Simulation
Rust
impl Solution { pub fn find_diagonal_order(mat: Vec<Vec<i32>>) -> Vec<i32> { let m = mat.len(); let n = mat[0].len(); let mut ans = Vec::with_capacity(m * n); for k in 0..(m + n - 1) { let mut t = Vec::new(); let (mut i, mut j) = if k < n { (0, k) } else { (k - n + 1, n - 1) }; while i < m && j < n { t.push(mat[i][j]); i += 1; if j == 0 { break; } j -= 1; } if k % 2 == 0 { t.reverse(); } ans.extend(t); } ans } }
498
Diagonal Traverse
Medium
<p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0498.Diagonal%20Traverse/images/diag1-grid.jpg" style="width: 334px; height: 334px;" /> <pre> <strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]] <strong>Output:</strong> [1,2,4,7,5,3,6,8,9] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[1,2],[3,4]] <strong>Output:</strong> [1,2,3,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>5</sup> &lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Matrix; Simulation
TypeScript
function findDiagonalOrder(mat: number[][]): number[] { const m = mat.length; const n = mat[0].length; const ans: number[] = []; for (let k = 0; k < m + n - 1; k++) { const t: number[] = []; let i = k < n ? 0 : k - n + 1; let j = k < n ? k : n - 1; while (i < m && j >= 0) { t.push(mat[i][j]); i++; j--; } if (k % 2 === 0) { t.reverse(); } ans.push(...t); } return ans; }
499
The Maze III
Hard
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won&#39;t stop rolling until hitting a wall. When the ball stops, it could choose the next direction (must be different from last chosen direction). There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole.</p> <p>Given the <code>m x n</code> <code>maze</code>, the ball&#39;s position <code>ball</code> and the hole&#39;s position <code>hole</code>, where <code>ball = [ball<sub>row</sub>, ball<sub>col</sub>]</code> and <code>hole = [hole<sub>row</sub>, hole<sub>col</sub>]</code>, return <em>a string </em><code>instructions</code><em> of all the instructions that the ball should follow to drop in the hole with the <strong>shortest distance</strong> possible</em>. If there are multiple valid instructions, return the <strong>lexicographically minimum</strong> one. If the ball can&#39;t drop in the hole, return <code>&quot;impossible&quot;</code>.</p> <p>If there is a way for the ball to drop in the hole, the answer <code>instructions</code> should contain the characters <code>&#39;u&#39;</code> (i.e., up), <code>&#39;d&#39;</code> (i.e., down), <code>&#39;l&#39;</code> (i.e., left), and <code>&#39;r&#39;</code> (i.e., right).</p> <p>The <strong>distance</strong> is the number of <strong>empty spaces</strong> traveled by the ball from the start position (excluded) to the destination (included).</p> <p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0499.The%20Maze%20III/images/maze3-1-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [0,1] <strong>Output:</strong> &quot;lul&quot; <strong>Explanation:</strong> There are two shortest ways for the ball to drop into the hole. The first way is left -&gt; up -&gt; left, represented by &quot;lul&quot;. The second way is up -&gt; left, represented by &#39;ul&#39;. Both ways have shortest distance 6, but the first way is lexicographically smaller because &#39;l&#39; &lt; &#39;u&#39;. So the output is &quot;lul&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0499.The%20Maze%20III/images/maze3-2-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [3,0] <strong>Output:</strong> &quot;impossible&quot; <strong>Explanation:</strong> The ball cannot reach the hole. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0,0,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]], ball = [0,4], hole = [3,5] <strong>Output:</strong> &quot;dldr&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == maze.length</code></li> <li><code>n == maze[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>ball.length == 2</code></li> <li><code>hole.length == 2</code></li> <li><code>0 &lt;= ball<sub>row</sub>, hole<sub>row</sub> &lt;= m</code></li> <li><code>0 &lt;= ball<sub>col</sub>, hole<sub>col</sub> &lt;= n</code></li> <li>Both the ball and the hole exist in an empty space, and they will not be in the same position initially.</li> <li>The maze contains <strong>at least 2 empty spaces</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Array; String; Matrix; Shortest Path; Heap (Priority Queue)
C++
class Solution { public: string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) { int m = maze.size(); int n = maze[0].size(); int r = ball[0], c = ball[1]; int rh = hole[0], ch = hole[1]; queue<pair<int, int>> q; q.push({r, c}); vector<vector<int>> dist(m, vector<int>(n, INT_MAX)); dist[r][c] = 0; vector<vector<string>> path(m, vector<string>(n, "")); vector<vector<int>> dirs = {{-1, 0, 'u'}, {1, 0, 'd'}, {0, -1, 'l'}, {0, 1, 'r'}}; while (!q.empty()) { auto p = q.front(); q.pop(); int i = p.first, j = p.second; for (auto& dir : dirs) { int a = dir[0], b = dir[1]; char d = (char) dir[2]; int x = i, y = j; int step = dist[i][j]; while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0 && (x != rh || y != ch)) { x += a; y += b; ++step; } if (dist[x][y] > step || (dist[x][y] == step && (path[i][j] + d < path[x][y]))) { dist[x][y] = step; path[x][y] = path[i][j] + d; if (x != rh || y != ch) q.push({x, y}); } } } return path[rh][ch] == "" ? "impossible" : path[rh][ch]; } };
499
The Maze III
Hard
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won&#39;t stop rolling until hitting a wall. When the ball stops, it could choose the next direction (must be different from last chosen direction). There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole.</p> <p>Given the <code>m x n</code> <code>maze</code>, the ball&#39;s position <code>ball</code> and the hole&#39;s position <code>hole</code>, where <code>ball = [ball<sub>row</sub>, ball<sub>col</sub>]</code> and <code>hole = [hole<sub>row</sub>, hole<sub>col</sub>]</code>, return <em>a string </em><code>instructions</code><em> of all the instructions that the ball should follow to drop in the hole with the <strong>shortest distance</strong> possible</em>. If there are multiple valid instructions, return the <strong>lexicographically minimum</strong> one. If the ball can&#39;t drop in the hole, return <code>&quot;impossible&quot;</code>.</p> <p>If there is a way for the ball to drop in the hole, the answer <code>instructions</code> should contain the characters <code>&#39;u&#39;</code> (i.e., up), <code>&#39;d&#39;</code> (i.e., down), <code>&#39;l&#39;</code> (i.e., left), and <code>&#39;r&#39;</code> (i.e., right).</p> <p>The <strong>distance</strong> is the number of <strong>empty spaces</strong> traveled by the ball from the start position (excluded) to the destination (included).</p> <p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0499.The%20Maze%20III/images/maze3-1-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [0,1] <strong>Output:</strong> &quot;lul&quot; <strong>Explanation:</strong> There are two shortest ways for the ball to drop into the hole. The first way is left -&gt; up -&gt; left, represented by &quot;lul&quot;. The second way is up -&gt; left, represented by &#39;ul&#39;. Both ways have shortest distance 6, but the first way is lexicographically smaller because &#39;l&#39; &lt; &#39;u&#39;. So the output is &quot;lul&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0499.The%20Maze%20III/images/maze3-2-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [3,0] <strong>Output:</strong> &quot;impossible&quot; <strong>Explanation:</strong> The ball cannot reach the hole. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0,0,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]], ball = [0,4], hole = [3,5] <strong>Output:</strong> &quot;dldr&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == maze.length</code></li> <li><code>n == maze[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>ball.length == 2</code></li> <li><code>hole.length == 2</code></li> <li><code>0 &lt;= ball<sub>row</sub>, hole<sub>row</sub> &lt;= m</code></li> <li><code>0 &lt;= ball<sub>col</sub>, hole<sub>col</sub> &lt;= n</code></li> <li>Both the ball and the hole exist in an empty space, and they will not be in the same position initially.</li> <li>The maze contains <strong>at least 2 empty spaces</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Array; String; Matrix; Shortest Path; Heap (Priority Queue)
Go
import "math" func findShortestWay(maze [][]int, ball []int, hole []int) string { m, n := len(maze), len(maze[0]) r, c := ball[0], ball[1] rh, ch := hole[0], hole[1] q := [][]int{[]int{r, c}} dist := make([][]int, m) path := make([][]string, m) for i := range dist { dist[i] = make([]int, n) path[i] = make([]string, n) for j := range dist[i] { dist[i][j] = math.MaxInt32 path[i][j] = "" } } dist[r][c] = 0 dirs := map[string][]int{"u": {-1, 0}, "d": {1, 0}, "l": {0, -1}, "r": {0, 1}} for len(q) > 0 { p := q[0] q = q[1:] i, j := p[0], p[1] for d, dir := range dirs { a, b := dir[0], dir[1] x, y := i, j step := dist[i][j] for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 && (x != rh || y != ch) { x += a y += b step++ } if dist[x][y] > step || (dist[x][y] == step && (path[i][j]+d) < path[x][y]) { dist[x][y] = step path[x][y] = path[i][j] + d if x != rh || y != ch { q = append(q, []int{x, y}) } } } } if path[rh][ch] == "" { return "impossible" } return path[rh][ch] }
499
The Maze III
Hard
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won&#39;t stop rolling until hitting a wall. When the ball stops, it could choose the next direction (must be different from last chosen direction). There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole.</p> <p>Given the <code>m x n</code> <code>maze</code>, the ball&#39;s position <code>ball</code> and the hole&#39;s position <code>hole</code>, where <code>ball = [ball<sub>row</sub>, ball<sub>col</sub>]</code> and <code>hole = [hole<sub>row</sub>, hole<sub>col</sub>]</code>, return <em>a string </em><code>instructions</code><em> of all the instructions that the ball should follow to drop in the hole with the <strong>shortest distance</strong> possible</em>. If there are multiple valid instructions, return the <strong>lexicographically minimum</strong> one. If the ball can&#39;t drop in the hole, return <code>&quot;impossible&quot;</code>.</p> <p>If there is a way for the ball to drop in the hole, the answer <code>instructions</code> should contain the characters <code>&#39;u&#39;</code> (i.e., up), <code>&#39;d&#39;</code> (i.e., down), <code>&#39;l&#39;</code> (i.e., left), and <code>&#39;r&#39;</code> (i.e., right).</p> <p>The <strong>distance</strong> is the number of <strong>empty spaces</strong> traveled by the ball from the start position (excluded) to the destination (included).</p> <p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0499.The%20Maze%20III/images/maze3-1-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [0,1] <strong>Output:</strong> &quot;lul&quot; <strong>Explanation:</strong> There are two shortest ways for the ball to drop into the hole. The first way is left -&gt; up -&gt; left, represented by &quot;lul&quot;. The second way is up -&gt; left, represented by &#39;ul&#39;. Both ways have shortest distance 6, but the first way is lexicographically smaller because &#39;l&#39; &lt; &#39;u&#39;. So the output is &quot;lul&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0499.The%20Maze%20III/images/maze3-2-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [3,0] <strong>Output:</strong> &quot;impossible&quot; <strong>Explanation:</strong> The ball cannot reach the hole. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0,0,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]], ball = [0,4], hole = [3,5] <strong>Output:</strong> &quot;dldr&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == maze.length</code></li> <li><code>n == maze[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>ball.length == 2</code></li> <li><code>hole.length == 2</code></li> <li><code>0 &lt;= ball<sub>row</sub>, hole<sub>row</sub> &lt;= m</code></li> <li><code>0 &lt;= ball<sub>col</sub>, hole<sub>col</sub> &lt;= n</code></li> <li>Both the ball and the hole exist in an empty space, and they will not be in the same position initially.</li> <li>The maze contains <strong>at least 2 empty spaces</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Array; String; Matrix; Shortest Path; Heap (Priority Queue)
Java
class Solution { public String findShortestWay(int[][] maze, int[] ball, int[] hole) { int m = maze.length; int n = maze[0].length; int r = ball[0], c = ball[1]; int rh = hole[0], ch = hole[1]; Deque<int[]> q = new LinkedList<>(); q.offer(new int[] {r, c}); int[][] dist = new int[m][n]; for (int i = 0; i < m; ++i) { Arrays.fill(dist[i], Integer.MAX_VALUE); } dist[r][c] = 0; String[][] path = new String[m][n]; path[r][c] = ""; int[][] dirs = {{-1, 0, 'u'}, {1, 0, 'd'}, {0, -1, 'l'}, {0, 1, 'r'}}; while (!q.isEmpty()) { int[] p = q.poll(); int i = p[0], j = p[1]; for (int[] dir : dirs) { int a = dir[0], b = dir[1]; String d = String.valueOf((char) (dir[2])); int x = i, y = j; int step = dist[i][j]; while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0 && (x != rh || y != ch)) { x += a; y += b; ++step; } if (dist[x][y] > step || (dist[x][y] == step && (path[i][j] + d).compareTo(path[x][y]) < 0)) { dist[x][y] = step; path[x][y] = path[i][j] + d; if (x != rh || y != ch) { q.offer(new int[] {x, y}); } } } } return path[rh][ch] == null ? "impossible" : path[rh][ch]; } }
499
The Maze III
Hard
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won&#39;t stop rolling until hitting a wall. When the ball stops, it could choose the next direction (must be different from last chosen direction). There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole.</p> <p>Given the <code>m x n</code> <code>maze</code>, the ball&#39;s position <code>ball</code> and the hole&#39;s position <code>hole</code>, where <code>ball = [ball<sub>row</sub>, ball<sub>col</sub>]</code> and <code>hole = [hole<sub>row</sub>, hole<sub>col</sub>]</code>, return <em>a string </em><code>instructions</code><em> of all the instructions that the ball should follow to drop in the hole with the <strong>shortest distance</strong> possible</em>. If there are multiple valid instructions, return the <strong>lexicographically minimum</strong> one. If the ball can&#39;t drop in the hole, return <code>&quot;impossible&quot;</code>.</p> <p>If there is a way for the ball to drop in the hole, the answer <code>instructions</code> should contain the characters <code>&#39;u&#39;</code> (i.e., up), <code>&#39;d&#39;</code> (i.e., down), <code>&#39;l&#39;</code> (i.e., left), and <code>&#39;r&#39;</code> (i.e., right).</p> <p>The <strong>distance</strong> is the number of <strong>empty spaces</strong> traveled by the ball from the start position (excluded) to the destination (included).</p> <p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0499.The%20Maze%20III/images/maze3-1-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [0,1] <strong>Output:</strong> &quot;lul&quot; <strong>Explanation:</strong> There are two shortest ways for the ball to drop into the hole. The first way is left -&gt; up -&gt; left, represented by &quot;lul&quot;. The second way is up -&gt; left, represented by &#39;ul&#39;. Both ways have shortest distance 6, but the first way is lexicographically smaller because &#39;l&#39; &lt; &#39;u&#39;. So the output is &quot;lul&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0499.The%20Maze%20III/images/maze3-2-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [3,0] <strong>Output:</strong> &quot;impossible&quot; <strong>Explanation:</strong> The ball cannot reach the hole. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0,0,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]], ball = [0,4], hole = [3,5] <strong>Output:</strong> &quot;dldr&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == maze.length</code></li> <li><code>n == maze[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>ball.length == 2</code></li> <li><code>hole.length == 2</code></li> <li><code>0 &lt;= ball<sub>row</sub>, hole<sub>row</sub> &lt;= m</code></li> <li><code>0 &lt;= ball<sub>col</sub>, hole<sub>col</sub> &lt;= n</code></li> <li>Both the ball and the hole exist in an empty space, and they will not be in the same position initially.</li> <li>The maze contains <strong>at least 2 empty spaces</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Array; String; Matrix; Shortest Path; Heap (Priority Queue)
Python
class Solution: def findShortestWay( self, maze: List[List[int]], ball: List[int], hole: List[int] ) -> str: m, n = len(maze), len(maze[0]) r, c = ball rh, ch = hole q = deque([(r, c)]) dist = [[inf] * n for _ in range(m)] dist[r][c] = 0 path = [[None] * n for _ in range(m)] path[r][c] = '' while q: i, j = q.popleft() for a, b, d in [(-1, 0, 'u'), (1, 0, 'd'), (0, -1, 'l'), (0, 1, 'r')]: x, y, step = i, j, dist[i][j] while ( 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0 and (x != rh or y != ch) ): x, y = x + a, y + b step += 1 if dist[x][y] > step or ( dist[x][y] == step and path[i][j] + d < path[x][y] ): dist[x][y] = step path[x][y] = path[i][j] + d if x != rh or y != ch: q.append((x, y)) return path[rh][ch] or 'impossible'
500
Keyboard Row
Easy
<p>Given an array of strings <code>words</code>, return <em>the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below</em>.</p> <p><strong>Note</strong> that the strings are <strong>case-insensitive</strong>, both lowercased and uppercased of the same letter are treated as if they are at the same row.</p> <p>In the <strong>American keyboard</strong>:</p> <ul> <li>the first row consists of the characters <code>&quot;qwertyuiop&quot;</code>,</li> <li>the second row consists of the characters <code>&quot;asdfghjkl&quot;</code>, and</li> <li>the third row consists of the characters <code>&quot;zxcvbnm&quot;</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0500.Keyboard%20Row/images/keyboard.png" style="width: 800px; max-width: 600px; height: 267px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;Hello&quot;,&quot;Alaska&quot;,&quot;Dad&quot;,&quot;Peace&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;Alaska&quot;,&quot;Dad&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>Both <code>&quot;a&quot;</code> and <code>&quot;A&quot;</code> are in the 2nd row of the American keyboard due to case insensitivity.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;omk&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 20</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists of English letters (both lowercase and uppercase).&nbsp;</li> </ul>
Array; Hash Table; String
C++
class Solution { public: vector<string> findWords(vector<string>& words) { string s = "12210111011122000010020202"; vector<string> ans; for (auto& w : words) { char x = s[tolower(w[0]) - 'a']; bool ok = true; for (char& c : w) { if (s[tolower(c) - 'a'] != x) { ok = false; break; } } if (ok) { ans.emplace_back(w); } } return ans; } };
500
Keyboard Row
Easy
<p>Given an array of strings <code>words</code>, return <em>the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below</em>.</p> <p><strong>Note</strong> that the strings are <strong>case-insensitive</strong>, both lowercased and uppercased of the same letter are treated as if they are at the same row.</p> <p>In the <strong>American keyboard</strong>:</p> <ul> <li>the first row consists of the characters <code>&quot;qwertyuiop&quot;</code>,</li> <li>the second row consists of the characters <code>&quot;asdfghjkl&quot;</code>, and</li> <li>the third row consists of the characters <code>&quot;zxcvbnm&quot;</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0500.Keyboard%20Row/images/keyboard.png" style="width: 800px; max-width: 600px; height: 267px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;Hello&quot;,&quot;Alaska&quot;,&quot;Dad&quot;,&quot;Peace&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;Alaska&quot;,&quot;Dad&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>Both <code>&quot;a&quot;</code> and <code>&quot;A&quot;</code> are in the 2nd row of the American keyboard due to case insensitivity.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;omk&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 20</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists of English letters (both lowercase and uppercase).&nbsp;</li> </ul>
Array; Hash Table; String
C#
public class Solution { public string[] FindWords(string[] words) { string s = "12210111011122000010020202"; IList<string> ans = new List<string>(); foreach (string w in words) { char x = s[char.ToLower(w[0]) - 'a']; bool ok = true; for (int i = 1; i < w.Length; ++i) { if (s[char.ToLower(w[i]) - 'a'] != x) { ok = false; break; } } if (ok) { ans.Add(w); } } return ans.ToArray(); } }
500
Keyboard Row
Easy
<p>Given an array of strings <code>words</code>, return <em>the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below</em>.</p> <p><strong>Note</strong> that the strings are <strong>case-insensitive</strong>, both lowercased and uppercased of the same letter are treated as if they are at the same row.</p> <p>In the <strong>American keyboard</strong>:</p> <ul> <li>the first row consists of the characters <code>&quot;qwertyuiop&quot;</code>,</li> <li>the second row consists of the characters <code>&quot;asdfghjkl&quot;</code>, and</li> <li>the third row consists of the characters <code>&quot;zxcvbnm&quot;</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0500.Keyboard%20Row/images/keyboard.png" style="width: 800px; max-width: 600px; height: 267px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;Hello&quot;,&quot;Alaska&quot;,&quot;Dad&quot;,&quot;Peace&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;Alaska&quot;,&quot;Dad&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>Both <code>&quot;a&quot;</code> and <code>&quot;A&quot;</code> are in the 2nd row of the American keyboard due to case insensitivity.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;omk&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 20</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists of English letters (both lowercase and uppercase).&nbsp;</li> </ul>
Array; Hash Table; String
Go
func findWords(words []string) (ans []string) { s := "12210111011122000010020202" for _, w := range words { x := s[unicode.ToLower(rune(w[0]))-'a'] ok := true for _, c := range w[1:] { if s[unicode.ToLower(c)-'a'] != x { ok = false break } } if ok { ans = append(ans, w) } } return }
500
Keyboard Row
Easy
<p>Given an array of strings <code>words</code>, return <em>the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below</em>.</p> <p><strong>Note</strong> that the strings are <strong>case-insensitive</strong>, both lowercased and uppercased of the same letter are treated as if they are at the same row.</p> <p>In the <strong>American keyboard</strong>:</p> <ul> <li>the first row consists of the characters <code>&quot;qwertyuiop&quot;</code>,</li> <li>the second row consists of the characters <code>&quot;asdfghjkl&quot;</code>, and</li> <li>the third row consists of the characters <code>&quot;zxcvbnm&quot;</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0500.Keyboard%20Row/images/keyboard.png" style="width: 800px; max-width: 600px; height: 267px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;Hello&quot;,&quot;Alaska&quot;,&quot;Dad&quot;,&quot;Peace&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;Alaska&quot;,&quot;Dad&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>Both <code>&quot;a&quot;</code> and <code>&quot;A&quot;</code> are in the 2nd row of the American keyboard due to case insensitivity.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;omk&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 20</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists of English letters (both lowercase and uppercase).&nbsp;</li> </ul>
Array; Hash Table; String
Java
class Solution { public String[] findWords(String[] words) { String s = "12210111011122000010020202"; List<String> ans = new ArrayList<>(); for (var w : words) { String t = w.toLowerCase(); char x = s.charAt(t.charAt(0) - 'a'); boolean ok = true; for (char c : t.toCharArray()) { if (s.charAt(c - 'a') != x) { ok = false; break; } } if (ok) { ans.add(w); } } return ans.toArray(new String[0]); } }
500
Keyboard Row
Easy
<p>Given an array of strings <code>words</code>, return <em>the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below</em>.</p> <p><strong>Note</strong> that the strings are <strong>case-insensitive</strong>, both lowercased and uppercased of the same letter are treated as if they are at the same row.</p> <p>In the <strong>American keyboard</strong>:</p> <ul> <li>the first row consists of the characters <code>&quot;qwertyuiop&quot;</code>,</li> <li>the second row consists of the characters <code>&quot;asdfghjkl&quot;</code>, and</li> <li>the third row consists of the characters <code>&quot;zxcvbnm&quot;</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0500.Keyboard%20Row/images/keyboard.png" style="width: 800px; max-width: 600px; height: 267px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;Hello&quot;,&quot;Alaska&quot;,&quot;Dad&quot;,&quot;Peace&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;Alaska&quot;,&quot;Dad&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>Both <code>&quot;a&quot;</code> and <code>&quot;A&quot;</code> are in the 2nd row of the American keyboard due to case insensitivity.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;omk&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 20</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists of English letters (both lowercase and uppercase).&nbsp;</li> </ul>
Array; Hash Table; String
Python
class Solution: def findWords(self, words: List[str]) -> List[str]: s1 = set('qwertyuiop') s2 = set('asdfghjkl') s3 = set('zxcvbnm') ans = [] for w in words: s = set(w.lower()) if s <= s1 or s <= s2 or s <= s3: ans.append(w) return ans
500
Keyboard Row
Easy
<p>Given an array of strings <code>words</code>, return <em>the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below</em>.</p> <p><strong>Note</strong> that the strings are <strong>case-insensitive</strong>, both lowercased and uppercased of the same letter are treated as if they are at the same row.</p> <p>In the <strong>American keyboard</strong>:</p> <ul> <li>the first row consists of the characters <code>&quot;qwertyuiop&quot;</code>,</li> <li>the second row consists of the characters <code>&quot;asdfghjkl&quot;</code>, and</li> <li>the third row consists of the characters <code>&quot;zxcvbnm&quot;</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0500.Keyboard%20Row/images/keyboard.png" style="width: 800px; max-width: 600px; height: 267px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;Hello&quot;,&quot;Alaska&quot;,&quot;Dad&quot;,&quot;Peace&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;Alaska&quot;,&quot;Dad&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>Both <code>&quot;a&quot;</code> and <code>&quot;A&quot;</code> are in the 2nd row of the American keyboard due to case insensitivity.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;omk&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;adsdf&quot;,&quot;sfd&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 20</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists of English letters (both lowercase and uppercase).&nbsp;</li> </ul>
Array; Hash Table; String
TypeScript
function findWords(words: string[]): string[] { const s = '12210111011122000010020202'; const ans: string[] = []; for (const w of words) { const t = w.toLowerCase(); const x = s[t.charCodeAt(0) - 'a'.charCodeAt(0)]; let ok = true; for (const c of t) { if (s[c.charCodeAt(0) - 'a'.charCodeAt(0)] !== x) { ok = false; break; } } if (ok) { ans.push(w); } } return ans; }
501
Find Mode in Binary Search Tree
Easy
<p>Given the <code>root</code> of a binary search tree (BST) with duplicates, return <em>all the <a href="https://en.wikipedia.org/wiki/Mode_(statistics)" target="_blank">mode(s)</a> (i.e., the most frequently occurred element) in it</em>.</p> <p>If the tree has more than one mode, return them in <strong>any order</strong>.</p> <p>Assume a BST is defined as follows:</p> <ul> <li>The left subtree of a node contains only nodes with keys <strong>less than or equal to</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than or equal to</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0501.Find%20Mode%20in%20Binary%20Search%20Tree/images/mode-tree.jpg" style="width: 142px; height: 222px;" /> <pre> <strong>Input:</strong> root = [1,null,2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Tree; Depth-First Search; Binary Search Tree; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* prev; int mx, cnt; vector<int> ans; vector<int> findMode(TreeNode* root) { dfs(root); return ans; } void dfs(TreeNode* root) { if (!root) return; dfs(root->left); cnt = prev != nullptr && prev->val == root->val ? cnt + 1 : 1; if (cnt > mx) { ans.clear(); ans.push_back(root->val); mx = cnt; } else if (cnt == mx) ans.push_back(root->val); prev = root; dfs(root->right); } };
501
Find Mode in Binary Search Tree
Easy
<p>Given the <code>root</code> of a binary search tree (BST) with duplicates, return <em>all the <a href="https://en.wikipedia.org/wiki/Mode_(statistics)" target="_blank">mode(s)</a> (i.e., the most frequently occurred element) in it</em>.</p> <p>If the tree has more than one mode, return them in <strong>any order</strong>.</p> <p>Assume a BST is defined as follows:</p> <ul> <li>The left subtree of a node contains only nodes with keys <strong>less than or equal to</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than or equal to</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0501.Find%20Mode%20in%20Binary%20Search%20Tree/images/mode-tree.jpg" style="width: 142px; height: 222px;" /> <pre> <strong>Input:</strong> root = [1,null,2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Tree; Depth-First Search; Binary Search Tree; Binary Tree
C#
public class Solution { private int mx; private int cnt; private TreeNode prev; private List<int> res; public int[] FindMode(TreeNode root) { res = new List<int>(); Dfs(root); int[] ans = new int[res.Count]; for (int i = 0; i < res.Count; ++i) { ans[i] = res[i]; } return ans; } private void Dfs(TreeNode root) { if (root == null) { return; } Dfs(root.left); cnt = prev != null && prev.val == root.val ? cnt + 1 : 1; if (cnt > mx) { res = new List<int>(new int[] { root.val }); mx = cnt; } else if (cnt == mx) { res.Add(root.val); } prev = root; Dfs(root.right); } }
501
Find Mode in Binary Search Tree
Easy
<p>Given the <code>root</code> of a binary search tree (BST) with duplicates, return <em>all the <a href="https://en.wikipedia.org/wiki/Mode_(statistics)" target="_blank">mode(s)</a> (i.e., the most frequently occurred element) in it</em>.</p> <p>If the tree has more than one mode, return them in <strong>any order</strong>.</p> <p>Assume a BST is defined as follows:</p> <ul> <li>The left subtree of a node contains only nodes with keys <strong>less than or equal to</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than or equal to</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0501.Find%20Mode%20in%20Binary%20Search%20Tree/images/mode-tree.jpg" style="width: 142px; height: 222px;" /> <pre> <strong>Input:</strong> root = [1,null,2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findMode(root *TreeNode) []int { mx, cnt := 0, 0 var prev *TreeNode var ans []int var dfs func(root *TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) if prev != nil && prev.Val == root.Val { cnt++ } else { cnt = 1 } if cnt > mx { ans = []int{root.Val} mx = cnt } else if cnt == mx { ans = append(ans, root.Val) } prev = root dfs(root.Right) } dfs(root) return ans }
501
Find Mode in Binary Search Tree
Easy
<p>Given the <code>root</code> of a binary search tree (BST) with duplicates, return <em>all the <a href="https://en.wikipedia.org/wiki/Mode_(statistics)" target="_blank">mode(s)</a> (i.e., the most frequently occurred element) in it</em>.</p> <p>If the tree has more than one mode, return them in <strong>any order</strong>.</p> <p>Assume a BST is defined as follows:</p> <ul> <li>The left subtree of a node contains only nodes with keys <strong>less than or equal to</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than or equal to</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0501.Find%20Mode%20in%20Binary%20Search%20Tree/images/mode-tree.jpg" style="width: 142px; height: 222px;" /> <pre> <strong>Input:</strong> root = [1,null,2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int mx; private int cnt; private TreeNode prev; private List<Integer> res; public int[] findMode(TreeNode root) { res = new ArrayList<>(); dfs(root); int[] ans = new int[res.size()]; for (int i = 0; i < res.size(); ++i) { ans[i] = res.get(i); } return ans; } private void dfs(TreeNode root) { if (root == null) { return; } dfs(root.left); cnt = prev != null && prev.val == root.val ? cnt + 1 : 1; if (cnt > mx) { res = new ArrayList<>(Arrays.asList(root.val)); mx = cnt; } else if (cnt == mx) { res.add(root.val); } prev = root; dfs(root.right); } }
501
Find Mode in Binary Search Tree
Easy
<p>Given the <code>root</code> of a binary search tree (BST) with duplicates, return <em>all the <a href="https://en.wikipedia.org/wiki/Mode_(statistics)" target="_blank">mode(s)</a> (i.e., the most frequently occurred element) in it</em>.</p> <p>If the tree has more than one mode, return them in <strong>any order</strong>.</p> <p>Assume a BST is defined as follows:</p> <ul> <li>The left subtree of a node contains only nodes with keys <strong>less than or equal to</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than or equal to</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0501.Find%20Mode%20in%20Binary%20Search%20Tree/images/mode-tree.jpg" style="width: 142px; height: 222px;" /> <pre> <strong>Input:</strong> root = [1,null,2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findMode(self, root: TreeNode) -> List[int]: def dfs(root): if root is None: return nonlocal mx, prev, ans, cnt dfs(root.left) cnt = cnt + 1 if prev == root.val else 1 if cnt > mx: ans = [root.val] mx = cnt elif cnt == mx: ans.append(root.val) prev = root.val dfs(root.right) prev = None mx = cnt = 0 ans = [] dfs(root) return ans
502
IPO
Hard
<p>Suppose LeetCode will start its <strong>IPO</strong> soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the <strong>IPO</strong>. Since it has limited resources, it can only finish at most <code>k</code> distinct projects before the <strong>IPO</strong>. Help LeetCode design the best way to maximize its total capital after finishing at most <code>k</code> distinct projects.</p> <p>You are given <code>n</code> projects where the <code>i<sup>th</sup></code> project has a pure profit <code>profits[i]</code> and a minimum capital of <code>capital[i]</code> is needed to start it.</p> <p>Initially, you have <code>w</code> capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.</p> <p>Pick a list of <strong>at most</strong> <code>k</code> distinct projects from given projects to <strong>maximize your final capital</strong>, and return <em>the final maximized capital</em>.</p> <p>The answer is guaranteed to fit in a 32-bit signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] <strong>Output:</strong> 6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= w &lt;= 10<sup>9</sup></code></li> <li><code>n == profits.length</code></li> <li><code>n == capital.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= profits[i] &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= capital[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
C++
using pii = pair<int, int>; class Solution { public: int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) { priority_queue<pii, vector<pii>, greater<pii>> q1; int n = profits.size(); for (int i = 0; i < n; ++i) { q1.push({capital[i], profits[i]}); } priority_queue<int> q2; while (k--) { while (!q1.empty() && q1.top().first <= w) { q2.push(q1.top().second); q1.pop(); } if (q2.empty()) { break; } w += q2.top(); q2.pop(); } return w; } };
502
IPO
Hard
<p>Suppose LeetCode will start its <strong>IPO</strong> soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the <strong>IPO</strong>. Since it has limited resources, it can only finish at most <code>k</code> distinct projects before the <strong>IPO</strong>. Help LeetCode design the best way to maximize its total capital after finishing at most <code>k</code> distinct projects.</p> <p>You are given <code>n</code> projects where the <code>i<sup>th</sup></code> project has a pure profit <code>profits[i]</code> and a minimum capital of <code>capital[i]</code> is needed to start it.</p> <p>Initially, you have <code>w</code> capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.</p> <p>Pick a list of <strong>at most</strong> <code>k</code> distinct projects from given projects to <strong>maximize your final capital</strong>, and return <em>the final maximized capital</em>.</p> <p>The answer is guaranteed to fit in a 32-bit signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] <strong>Output:</strong> 6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= w &lt;= 10<sup>9</sup></code></li> <li><code>n == profits.length</code></li> <li><code>n == capital.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= profits[i] &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= capital[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Go
func findMaximizedCapital(k int, w int, profits []int, capital []int) int { q1 := hp2{} for i, c := range capital { heap.Push(&q1, pair{c, profits[i]}) } q2 := hp{} for k > 0 { for len(q1) > 0 && q1[0].c <= w { heap.Push(&q2, heap.Pop(&q1).(pair).p) } if q2.Len() == 0 { break } w += heap.Pop(&q2).(int) k-- } return w } type hp struct{ sort.IntSlice } func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { a := h.IntSlice v := a[len(a)-1] h.IntSlice = a[:len(a)-1] return v } type pair struct{ c, p int } type hp2 []pair func (h hp2) Len() int { return len(h) } func (h hp2) Less(i, j int) bool { return h[i].c < h[j].c } func (h hp2) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *hp2) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp2) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
502
IPO
Hard
<p>Suppose LeetCode will start its <strong>IPO</strong> soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the <strong>IPO</strong>. Since it has limited resources, it can only finish at most <code>k</code> distinct projects before the <strong>IPO</strong>. Help LeetCode design the best way to maximize its total capital after finishing at most <code>k</code> distinct projects.</p> <p>You are given <code>n</code> projects where the <code>i<sup>th</sup></code> project has a pure profit <code>profits[i]</code> and a minimum capital of <code>capital[i]</code> is needed to start it.</p> <p>Initially, you have <code>w</code> capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.</p> <p>Pick a list of <strong>at most</strong> <code>k</code> distinct projects from given projects to <strong>maximize your final capital</strong>, and return <em>the final maximized capital</em>.</p> <p>The answer is guaranteed to fit in a 32-bit signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] <strong>Output:</strong> 6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= w &lt;= 10<sup>9</sup></code></li> <li><code>n == profits.length</code></li> <li><code>n == capital.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= profits[i] &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= capital[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Java
class Solution { public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) { int n = capital.length; PriorityQueue<int[]> q1 = new PriorityQueue<>((a, b) -> a[0] - b[0]); for (int i = 0; i < n; ++i) { q1.offer(new int[] {capital[i], profits[i]}); } PriorityQueue<Integer> q2 = new PriorityQueue<>((a, b) -> b - a); while (k-- > 0) { while (!q1.isEmpty() && q1.peek()[0] <= w) { q2.offer(q1.poll()[1]); } if (q2.isEmpty()) { break; } w += q2.poll(); } return w; } }
502
IPO
Hard
<p>Suppose LeetCode will start its <strong>IPO</strong> soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the <strong>IPO</strong>. Since it has limited resources, it can only finish at most <code>k</code> distinct projects before the <strong>IPO</strong>. Help LeetCode design the best way to maximize its total capital after finishing at most <code>k</code> distinct projects.</p> <p>You are given <code>n</code> projects where the <code>i<sup>th</sup></code> project has a pure profit <code>profits[i]</code> and a minimum capital of <code>capital[i]</code> is needed to start it.</p> <p>Initially, you have <code>w</code> capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.</p> <p>Pick a list of <strong>at most</strong> <code>k</code> distinct projects from given projects to <strong>maximize your final capital</strong>, and return <em>the final maximized capital</em>.</p> <p>The answer is guaranteed to fit in a 32-bit signed integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] <strong>Output:</strong> 6 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= w &lt;= 10<sup>9</sup></code></li> <li><code>n == profits.length</code></li> <li><code>n == capital.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= profits[i] &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= capital[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Python
class Solution: def findMaximizedCapital( self, k: int, w: int, profits: List[int], capital: List[int] ) -> int: h1 = [(c, p) for c, p in zip(capital, profits)] heapify(h1) h2 = [] while k: while h1 and h1[0][0] <= w: heappush(h2, -heappop(h1)[1]) if not h2: break w -= heappop(h2) k -= 1 return w
503
Next Greater Element II
Medium
<p>Given a circular integer array <code>nums</code> (i.e., the next element of <code>nums[nums.length - 1]</code> is <code>nums[0]</code>), return <em>the <strong>next greater number</strong> for every element in</em> <code>nums</code>.</p> <p>The <strong>next greater number</strong> of a number <code>x</code> is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn&#39;t exist, return <code>-1</code> for this number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1] <strong>Output:</strong> [2,-1,2] Explanation: The first 1&#39;s next greater number is 2; The number 2 can&#39;t find next greater number. The second 1&#39;s next greater number needs to search circularly, which is also 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,3] <strong>Output:</strong> [2,3,4,-1,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
C++
class Solution { public: vector<int> nextGreaterElements(vector<int>& nums) { int n = nums.size(); vector<int> ans(n, -1); stack<int> stk; for (int i = n * 2 - 1; ~i; --i) { int j = i % n; while (stk.size() && stk.top() <= nums[j]) { stk.pop(); } if (stk.size()) { ans[j] = stk.top(); } stk.push(nums[j]); } return ans; } };
503
Next Greater Element II
Medium
<p>Given a circular integer array <code>nums</code> (i.e., the next element of <code>nums[nums.length - 1]</code> is <code>nums[0]</code>), return <em>the <strong>next greater number</strong> for every element in</em> <code>nums</code>.</p> <p>The <strong>next greater number</strong> of a number <code>x</code> is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn&#39;t exist, return <code>-1</code> for this number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1] <strong>Output:</strong> [2,-1,2] Explanation: The first 1&#39;s next greater number is 2; The number 2 can&#39;t find next greater number. The second 1&#39;s next greater number needs to search circularly, which is also 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,3] <strong>Output:</strong> [2,3,4,-1,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Go
func nextGreaterElements(nums []int) []int { n := len(nums) ans := make([]int, n) for i := range ans { ans[i] = -1 } stk := []int{} for i := n*2 - 1; i >= 0; i-- { j := i % n for len(stk) > 0 && stk[len(stk)-1] <= nums[j] { stk = stk[:len(stk)-1] } if len(stk) > 0 { ans[j] = stk[len(stk)-1] } stk = append(stk, nums[j]) } return ans }
503
Next Greater Element II
Medium
<p>Given a circular integer array <code>nums</code> (i.e., the next element of <code>nums[nums.length - 1]</code> is <code>nums[0]</code>), return <em>the <strong>next greater number</strong> for every element in</em> <code>nums</code>.</p> <p>The <strong>next greater number</strong> of a number <code>x</code> is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn&#39;t exist, return <code>-1</code> for this number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1] <strong>Output:</strong> [2,-1,2] Explanation: The first 1&#39;s next greater number is 2; The number 2 can&#39;t find next greater number. The second 1&#39;s next greater number needs to search circularly, which is also 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,3] <strong>Output:</strong> [2,3,4,-1,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Java
class Solution { public int[] nextGreaterElements(int[] nums) { int n = nums.length; int[] ans = new int[n]; Arrays.fill(ans, -1); Deque<Integer> stk = new ArrayDeque<>(); for (int i = n * 2 - 1; i >= 0; --i) { int j = i % n; while (!stk.isEmpty() && stk.peek() <= nums[j]) { stk.pop(); } if (!stk.isEmpty()) { ans[j] = stk.peek(); } stk.push(nums[j]); } return ans; } }
503
Next Greater Element II
Medium
<p>Given a circular integer array <code>nums</code> (i.e., the next element of <code>nums[nums.length - 1]</code> is <code>nums[0]</code>), return <em>the <strong>next greater number</strong> for every element in</em> <code>nums</code>.</p> <p>The <strong>next greater number</strong> of a number <code>x</code> is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn&#39;t exist, return <code>-1</code> for this number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1] <strong>Output:</strong> [2,-1,2] Explanation: The first 1&#39;s next greater number is 2; The number 2 can&#39;t find next greater number. The second 1&#39;s next greater number needs to search circularly, which is also 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,3] <strong>Output:</strong> [2,3,4,-1,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
JavaScript
/** * @param {number[]} nums * @return {number[]} */ var nextGreaterElements = function (nums) { const n = nums.length; const stk = []; const ans = Array(n).fill(-1); for (let i = n * 2 - 1; ~i; --i) { const j = i % n; while (stk.length && stk.at(-1) <= nums[j]) { stk.pop(); } if (stk.length) { ans[j] = stk.at(-1); } stk.push(nums[j]); } return ans; };
503
Next Greater Element II
Medium
<p>Given a circular integer array <code>nums</code> (i.e., the next element of <code>nums[nums.length - 1]</code> is <code>nums[0]</code>), return <em>the <strong>next greater number</strong> for every element in</em> <code>nums</code>.</p> <p>The <strong>next greater number</strong> of a number <code>x</code> is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn&#39;t exist, return <code>-1</code> for this number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1] <strong>Output:</strong> [2,-1,2] Explanation: The first 1&#39;s next greater number is 2; The number 2 can&#39;t find next greater number. The second 1&#39;s next greater number needs to search circularly, which is also 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,3] <strong>Output:</strong> [2,3,4,-1,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Python
class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: n = len(nums) ans = [-1] * n stk = [] for i in range(n * 2 - 1, -1, -1): i %= n while stk and stk[-1] <= nums[i]: stk.pop() if stk: ans[i] = stk[-1] stk.append(nums[i]) return ans
503
Next Greater Element II
Medium
<p>Given a circular integer array <code>nums</code> (i.e., the next element of <code>nums[nums.length - 1]</code> is <code>nums[0]</code>), return <em>the <strong>next greater number</strong> for every element in</em> <code>nums</code>.</p> <p>The <strong>next greater number</strong> of a number <code>x</code> is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn&#39;t exist, return <code>-1</code> for this number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1] <strong>Output:</strong> [2,-1,2] Explanation: The first 1&#39;s next greater number is 2; The number 2 can&#39;t find next greater number. The second 1&#39;s next greater number needs to search circularly, which is also 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,3] <strong>Output:</strong> [2,3,4,-1,4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
TypeScript
function nextGreaterElements(nums: number[]): number[] { const n = nums.length; const stk: number[] = []; const ans: number[] = Array(n).fill(-1); for (let i = n * 2 - 1; ~i; --i) { const j = i % n; while (stk.length && stk.at(-1)! <= nums[j]) { stk.pop(); } if (stk.length) { ans[j] = stk.at(-1)!; } stk.push(nums[j]); } return ans; }
504
Base 7
Easy
<p>Given an integer <code>num</code>, return <em>a string of its <strong>base 7</strong> representation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 100 <strong>Output:</strong> "202" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = -7 <strong>Output:</strong> "-10" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>7</sup> &lt;= num &lt;= 10<sup>7</sup></code></li> </ul>
Math; String
C++
class Solution { public: string convertToBase7(int num) { if (num == 0) return "0"; if (num < 0) return "-" + convertToBase7(-num); string ans = ""; while (num) { ans = to_string(num % 7) + ans; num /= 7; } return ans; } };
504
Base 7
Easy
<p>Given an integer <code>num</code>, return <em>a string of its <strong>base 7</strong> representation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 100 <strong>Output:</strong> "202" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = -7 <strong>Output:</strong> "-10" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>7</sup> &lt;= num &lt;= 10<sup>7</sup></code></li> </ul>
Math; String
Go
func convertToBase7(num int) string { if num == 0 { return "0" } if num < 0 { return "-" + convertToBase7(-num) } ans := []byte{} for num != 0 { ans = append([]byte{'0' + byte(num%7)}, ans...) num /= 7 } return string(ans) }
504
Base 7
Easy
<p>Given an integer <code>num</code>, return <em>a string of its <strong>base 7</strong> representation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 100 <strong>Output:</strong> "202" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = -7 <strong>Output:</strong> "-10" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>7</sup> &lt;= num &lt;= 10<sup>7</sup></code></li> </ul>
Math; String
Java
class Solution { public String convertToBase7(int num) { if (num == 0) { return "0"; } if (num < 0) { return "-" + convertToBase7(-num); } StringBuilder sb = new StringBuilder(); while (num != 0) { sb.append(num % 7); num /= 7; } return sb.reverse().toString(); } }
504
Base 7
Easy
<p>Given an integer <code>num</code>, return <em>a string of its <strong>base 7</strong> representation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 100 <strong>Output:</strong> "202" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = -7 <strong>Output:</strong> "-10" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>7</sup> &lt;= num &lt;= 10<sup>7</sup></code></li> </ul>
Math; String
Python
class Solution: def convertToBase7(self, num: int) -> str: if num == 0: return '0' if num < 0: return '-' + self.convertToBase7(-num) ans = [] while num: ans.append(str(num % 7)) num //= 7 return ''.join(ans[::-1])
504
Base 7
Easy
<p>Given an integer <code>num</code>, return <em>a string of its <strong>base 7</strong> representation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 100 <strong>Output:</strong> "202" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = -7 <strong>Output:</strong> "-10" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>7</sup> &lt;= num &lt;= 10<sup>7</sup></code></li> </ul>
Math; String
Rust
impl Solution { pub fn convert_to_base7(mut num: i32) -> String { if num == 0 { return String::from("0"); } let mut res = String::new(); let is_minus = num < 0; if is_minus { num = -num; } while num != 0 { res.push_str((num % 7).to_string().as_str()); num /= 7; } if is_minus { res.push('-'); } res.chars().rev().collect() } }
504
Base 7
Easy
<p>Given an integer <code>num</code>, return <em>a string of its <strong>base 7</strong> representation</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num = 100 <strong>Output:</strong> "202" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num = -7 <strong>Output:</strong> "-10" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>7</sup> &lt;= num &lt;= 10<sup>7</sup></code></li> </ul>
Math; String
TypeScript
function convertToBase7(num: number): string { if (num == 0) { return '0'; } let res = ''; const isMinus = num < 0; if (isMinus) { num = -num; } while (num != 0) { const r = num % 7; res = r + res; num = (num - r) / 7; } return isMinus ? '-' + res : res; }
505
The Maze II
Medium
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won&#39;t stop rolling until hitting a wall. When the ball stops, it could choose the next direction.</p> <p>Given the <code>m x n</code> <code>maze</code>, the ball&#39;s <code>start</code> position and the <code>destination</code>, where <code>start = [start<sub>row</sub>, start<sub>col</sub>]</code> and <code>destination = [destination<sub>row</sub>, destination<sub>col</sub>]</code>, return <em>the shortest <strong>distance</strong> for the ball to stop at the destination</em>. If the ball cannot stop at <code>destination</code>, return <code>-1</code>.</p> <p>The <strong>distance</strong> is the number of <strong>empty spaces</strong> traveled by the ball from the start position (excluded) to the destination (included).</p> <p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0505.The%20Maze%20II/images/maze1-1-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4] <strong>Output:</strong> 12 <strong>Explanation:</strong> One possible way is : left -&gt; down -&gt; left -&gt; down -&gt; right -&gt; down -&gt; right. The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0505.The%20Maze%20II/images/maze1-2-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1] <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == maze.length</code></li> <li><code>n == maze[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>start.length == 2</code></li> <li><code>destination.length == 2</code></li> <li><code>0 &lt;= start<sub>row</sub>, destination<sub>row</sub> &lt; m</code></li> <li><code>0 &lt;= start<sub>col</sub>, destination<sub>col</sub> &lt; n</code></li> <li>Both the ball and the destination exist in an empty space, and they will not be in the same position initially.</li> <li>The maze contains <strong>at least 2 empty spaces</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
C++
class Solution { public: int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) { int m = maze.size(), n = maze[0].size(); int dist[m][n]; memset(dist, 0x3f, sizeof(dist)); int si = start[0], sj = start[1]; int di = destination[0], dj = destination[1]; dist[si][sj] = 0; queue<pair<int, int>> q; q.emplace(si, sj); int dirs[5] = {-1, 0, 1, 0, -1}; while (!q.empty()) { auto [i, j] = q.front(); q.pop(); for (int d = 0; d < 4; ++d) { int x = i, y = j, k = dist[i][j]; int a = dirs[d], b = dirs[d + 1]; while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { x += a; y += b; ++k; } if (k < dist[x][y]) { dist[x][y] = k; q.emplace(x, y); } } } return dist[di][dj] == 0x3f3f3f3f ? -1 : dist[di][dj]; } };
505
The Maze II
Medium
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won&#39;t stop rolling until hitting a wall. When the ball stops, it could choose the next direction.</p> <p>Given the <code>m x n</code> <code>maze</code>, the ball&#39;s <code>start</code> position and the <code>destination</code>, where <code>start = [start<sub>row</sub>, start<sub>col</sub>]</code> and <code>destination = [destination<sub>row</sub>, destination<sub>col</sub>]</code>, return <em>the shortest <strong>distance</strong> for the ball to stop at the destination</em>. If the ball cannot stop at <code>destination</code>, return <code>-1</code>.</p> <p>The <strong>distance</strong> is the number of <strong>empty spaces</strong> traveled by the ball from the start position (excluded) to the destination (included).</p> <p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0505.The%20Maze%20II/images/maze1-1-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4] <strong>Output:</strong> 12 <strong>Explanation:</strong> One possible way is : left -&gt; down -&gt; left -&gt; down -&gt; right -&gt; down -&gt; right. The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0505.The%20Maze%20II/images/maze1-2-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1] <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == maze.length</code></li> <li><code>n == maze[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>start.length == 2</code></li> <li><code>destination.length == 2</code></li> <li><code>0 &lt;= start<sub>row</sub>, destination<sub>row</sub> &lt; m</code></li> <li><code>0 &lt;= start<sub>col</sub>, destination<sub>col</sub> &lt; n</code></li> <li>Both the ball and the destination exist in an empty space, and they will not be in the same position initially.</li> <li>The maze contains <strong>at least 2 empty spaces</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Go
func shortestDistance(maze [][]int, start []int, destination []int) int { m, n := len(maze), len(maze[0]) dist := make([][]int, m) const inf = 1 << 30 for i := range dist { dist[i] = make([]int, n) for j := range dist[i] { dist[i][j] = inf } } dist[start[0]][start[1]] = 0 q := [][]int{start} dirs := [5]int{-1, 0, 1, 0, -1} for len(q) > 0 { p := q[0] q = q[1:] i, j := p[0], p[1] for d := 0; d < 4; d++ { x, y, k := i, j, dist[i][j] a, b := dirs[d], dirs[d+1] for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 { x, y, k = x+a, y+b, k+1 } if k < dist[x][y] { dist[x][y] = k q = append(q, []int{x, y}) } } } di, dj := destination[0], destination[1] if dist[di][dj] == inf { return -1 } return dist[di][dj] }
505
The Maze II
Medium
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won&#39;t stop rolling until hitting a wall. When the ball stops, it could choose the next direction.</p> <p>Given the <code>m x n</code> <code>maze</code>, the ball&#39;s <code>start</code> position and the <code>destination</code>, where <code>start = [start<sub>row</sub>, start<sub>col</sub>]</code> and <code>destination = [destination<sub>row</sub>, destination<sub>col</sub>]</code>, return <em>the shortest <strong>distance</strong> for the ball to stop at the destination</em>. If the ball cannot stop at <code>destination</code>, return <code>-1</code>.</p> <p>The <strong>distance</strong> is the number of <strong>empty spaces</strong> traveled by the ball from the start position (excluded) to the destination (included).</p> <p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0505.The%20Maze%20II/images/maze1-1-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4] <strong>Output:</strong> 12 <strong>Explanation:</strong> One possible way is : left -&gt; down -&gt; left -&gt; down -&gt; right -&gt; down -&gt; right. The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0505.The%20Maze%20II/images/maze1-2-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1] <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == maze.length</code></li> <li><code>n == maze[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>start.length == 2</code></li> <li><code>destination.length == 2</code></li> <li><code>0 &lt;= start<sub>row</sub>, destination<sub>row</sub> &lt; m</code></li> <li><code>0 &lt;= start<sub>col</sub>, destination<sub>col</sub> &lt; n</code></li> <li>Both the ball and the destination exist in an empty space, and they will not be in the same position initially.</li> <li>The maze contains <strong>at least 2 empty spaces</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Java
class Solution { public int shortestDistance(int[][] maze, int[] start, int[] destination) { int m = maze.length, n = maze[0].length; final int inf = 1 << 30; int[][] dist = new int[m][n]; for (var row : dist) { Arrays.fill(row, inf); } int si = start[0], sj = start[1]; int di = destination[0], dj = destination[1]; dist[si][sj] = 0; Deque<int[]> q = new ArrayDeque<>(); q.offer(new int[] {si, sj}); int[] dirs = {-1, 0, 1, 0, -1}; while (!q.isEmpty()) { var p = q.poll(); int i = p[0], j = p[1]; for (int d = 0; d < 4; ++d) { int x = i, y = j, k = dist[i][j]; int a = dirs[d], b = dirs[d + 1]; while ( x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { x += a; y += b; ++k; } if (k < dist[x][y]) { dist[x][y] = k; q.offer(new int[] {x, y}); } } } return dist[di][dj] == inf ? -1 : dist[di][dj]; } }
505
The Maze II
Medium
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won&#39;t stop rolling until hitting a wall. When the ball stops, it could choose the next direction.</p> <p>Given the <code>m x n</code> <code>maze</code>, the ball&#39;s <code>start</code> position and the <code>destination</code>, where <code>start = [start<sub>row</sub>, start<sub>col</sub>]</code> and <code>destination = [destination<sub>row</sub>, destination<sub>col</sub>]</code>, return <em>the shortest <strong>distance</strong> for the ball to stop at the destination</em>. If the ball cannot stop at <code>destination</code>, return <code>-1</code>.</p> <p>The <strong>distance</strong> is the number of <strong>empty spaces</strong> traveled by the ball from the start position (excluded) to the destination (included).</p> <p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0505.The%20Maze%20II/images/maze1-1-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4] <strong>Output:</strong> 12 <strong>Explanation:</strong> One possible way is : left -&gt; down -&gt; left -&gt; down -&gt; right -&gt; down -&gt; right. The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0505.The%20Maze%20II/images/maze1-2-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1] <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == maze.length</code></li> <li><code>n == maze[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>start.length == 2</code></li> <li><code>destination.length == 2</code></li> <li><code>0 &lt;= start<sub>row</sub>, destination<sub>row</sub> &lt; m</code></li> <li><code>0 &lt;= start<sub>col</sub>, destination<sub>col</sub> &lt; n</code></li> <li>Both the ball and the destination exist in an empty space, and they will not be in the same position initially.</li> <li>The maze contains <strong>at least 2 empty spaces</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Python
class Solution: def shortestDistance( self, maze: List[List[int]], start: List[int], destination: List[int] ) -> int: m, n = len(maze), len(maze[0]) dirs = (-1, 0, 1, 0, -1) si, sj = start di, dj = destination q = deque([(si, sj)]) dist = [[inf] * n for _ in range(m)] dist[si][sj] = 0 while q: i, j = q.popleft() for a, b in pairwise(dirs): x, y, k = i, j, dist[i][j] while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0: x, y, k = x + a, y + b, k + 1 if k < dist[x][y]: dist[x][y] = k q.append((x, y)) return -1 if dist[di][dj] == inf else dist[di][dj]
505
The Maze II
Medium
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won&#39;t stop rolling until hitting a wall. When the ball stops, it could choose the next direction.</p> <p>Given the <code>m x n</code> <code>maze</code>, the ball&#39;s <code>start</code> position and the <code>destination</code>, where <code>start = [start<sub>row</sub>, start<sub>col</sub>]</code> and <code>destination = [destination<sub>row</sub>, destination<sub>col</sub>]</code>, return <em>the shortest <strong>distance</strong> for the ball to stop at the destination</em>. If the ball cannot stop at <code>destination</code>, return <code>-1</code>.</p> <p>The <strong>distance</strong> is the number of <strong>empty spaces</strong> traveled by the ball from the start position (excluded) to the destination (included).</p> <p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0505.The%20Maze%20II/images/maze1-1-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4] <strong>Output:</strong> 12 <strong>Explanation:</strong> One possible way is : left -&gt; down -&gt; left -&gt; down -&gt; right -&gt; down -&gt; right. The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0505.The%20Maze%20II/images/maze1-2-grid.jpg" style="width: 573px; height: 573px;" /> <pre> <strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1] <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == maze.length</code></li> <li><code>n == maze[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>start.length == 2</code></li> <li><code>destination.length == 2</code></li> <li><code>0 &lt;= start<sub>row</sub>, destination<sub>row</sub> &lt; m</code></li> <li><code>0 &lt;= start<sub>col</sub>, destination<sub>col</sub> &lt; n</code></li> <li>Both the ball and the destination exist in an empty space, and they will not be in the same position initially.</li> <li>The maze contains <strong>at least 2 empty spaces</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
TypeScript
function shortestDistance(maze: number[][], start: number[], destination: number[]): number { const m = maze.length; const n = maze[0].length; const dist: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => Infinity), ); const [si, sj] = start; const [di, dj] = destination; dist[si][sj] = 0; const q: number[][] = [[si, sj]]; const dirs = [-1, 0, 1, 0, -1]; while (q.length) { const [i, j] = q.shift()!; for (let d = 0; d < 4; ++d) { let [x, y, k] = [i, j, dist[i][j]]; const [a, b] = [dirs[d], dirs[d + 1]]; while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] === 0) { x += a; y += b; ++k; } if (k < dist[x][y]) { dist[x][y] = k; q.push([x, y]); } } } return dist[di][dj] === Infinity ? -1 : dist[di][dj]; }
506
Relative Ranks
Easy
<p>You are given an integer array <code>score</code> of size <code>n</code>, where <code>score[i]</code> is the score of the <code>i<sup>th</sup></code> athlete in a competition. All the scores are guaranteed to be <strong>unique</strong>.</p> <p>The athletes are <strong>placed</strong> based on their scores, where the <code>1<sup>st</sup></code> place athlete has the highest score, the <code>2<sup>nd</sup></code> place athlete has the <code>2<sup>nd</sup></code> highest score, and so on. The placement of each athlete determines their rank:</p> <ul> <li>The <code>1<sup>st</sup></code> place athlete&#39;s rank is <code>&quot;Gold Medal&quot;</code>.</li> <li>The <code>2<sup>nd</sup></code> place athlete&#39;s rank is <code>&quot;Silver Medal&quot;</code>.</li> <li>The <code>3<sup>rd</sup></code> place athlete&#39;s rank is <code>&quot;Bronze Medal&quot;</code>.</li> <li>For the <code>4<sup>th</sup></code> place to the <code>n<sup>th</sup></code> place athlete, their rank is their placement number (i.e., the <code>x<sup>th</sup></code> place athlete&#39;s rank is <code>&quot;x&quot;</code>).</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>rank</strong> of the <code>i<sup>th</sup></code> athlete.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> score = [5,4,3,2,1] <strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;Silver Medal&quot;,&quot;Bronze Medal&quot;,&quot;4&quot;,&quot;5&quot;] <strong>Explanation:</strong> The placements are [1<sup>st</sup>, 2<sup>nd</sup>, 3<sup>rd</sup>, 4<sup>th</sup>, 5<sup>th</sup>].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> score = [10,3,8,9,4] <strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;5&quot;,&quot;Bronze Medal&quot;,&quot;Silver Medal&quot;,&quot;4&quot;] <strong>Explanation:</strong> The placements are [1<sup>st</sup>, 5<sup>th</sup>, 3<sup>rd</sup>, 2<sup>nd</sup>, 4<sup>th</sup>]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == score.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= score[i] &lt;= 10<sup>6</sup></code></li> <li>All the values in <code>score</code> are <strong>unique</strong>.</li> </ul>
Array; Sorting; Heap (Priority Queue)
C++
class Solution { public: vector<string> findRelativeRanks(vector<int>& score) { int n = score.size(); vector<int> idx(n); iota(idx.begin(), idx.end(), 0); sort(idx.begin(), idx.end(), [&score](int a, int b) { return score[a] > score[b]; }); vector<string> ans(n); vector<string> top3 = {"Gold Medal", "Silver Medal", "Bronze Medal"}; for (int i = 0; i < n; ++i) { ans[idx[i]] = i < 3 ? top3[i] : to_string(i + 1); } return ans; } };
506
Relative Ranks
Easy
<p>You are given an integer array <code>score</code> of size <code>n</code>, where <code>score[i]</code> is the score of the <code>i<sup>th</sup></code> athlete in a competition. All the scores are guaranteed to be <strong>unique</strong>.</p> <p>The athletes are <strong>placed</strong> based on their scores, where the <code>1<sup>st</sup></code> place athlete has the highest score, the <code>2<sup>nd</sup></code> place athlete has the <code>2<sup>nd</sup></code> highest score, and so on. The placement of each athlete determines their rank:</p> <ul> <li>The <code>1<sup>st</sup></code> place athlete&#39;s rank is <code>&quot;Gold Medal&quot;</code>.</li> <li>The <code>2<sup>nd</sup></code> place athlete&#39;s rank is <code>&quot;Silver Medal&quot;</code>.</li> <li>The <code>3<sup>rd</sup></code> place athlete&#39;s rank is <code>&quot;Bronze Medal&quot;</code>.</li> <li>For the <code>4<sup>th</sup></code> place to the <code>n<sup>th</sup></code> place athlete, their rank is their placement number (i.e., the <code>x<sup>th</sup></code> place athlete&#39;s rank is <code>&quot;x&quot;</code>).</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>rank</strong> of the <code>i<sup>th</sup></code> athlete.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> score = [5,4,3,2,1] <strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;Silver Medal&quot;,&quot;Bronze Medal&quot;,&quot;4&quot;,&quot;5&quot;] <strong>Explanation:</strong> The placements are [1<sup>st</sup>, 2<sup>nd</sup>, 3<sup>rd</sup>, 4<sup>th</sup>, 5<sup>th</sup>].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> score = [10,3,8,9,4] <strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;5&quot;,&quot;Bronze Medal&quot;,&quot;Silver Medal&quot;,&quot;4&quot;] <strong>Explanation:</strong> The placements are [1<sup>st</sup>, 5<sup>th</sup>, 3<sup>rd</sup>, 2<sup>nd</sup>, 4<sup>th</sup>]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == score.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= score[i] &lt;= 10<sup>6</sup></code></li> <li>All the values in <code>score</code> are <strong>unique</strong>.</li> </ul>
Array; Sorting; Heap (Priority Queue)
Go
func findRelativeRanks(score []int) []string { n := len(score) idx := make([][]int, n) for i := 0; i < n; i++ { idx[i] = []int{score[i], i} } sort.Slice(idx, func(i1, i2 int) bool { return idx[i1][0] > idx[i2][0] }) ans := make([]string, n) top3 := []string{"Gold Medal", "Silver Medal", "Bronze Medal"} for i := 0; i < n; i++ { if i < 3 { ans[idx[i][1]] = top3[i] } else { ans[idx[i][1]] = strconv.Itoa(i + 1) } } return ans }
506
Relative Ranks
Easy
<p>You are given an integer array <code>score</code> of size <code>n</code>, where <code>score[i]</code> is the score of the <code>i<sup>th</sup></code> athlete in a competition. All the scores are guaranteed to be <strong>unique</strong>.</p> <p>The athletes are <strong>placed</strong> based on their scores, where the <code>1<sup>st</sup></code> place athlete has the highest score, the <code>2<sup>nd</sup></code> place athlete has the <code>2<sup>nd</sup></code> highest score, and so on. The placement of each athlete determines their rank:</p> <ul> <li>The <code>1<sup>st</sup></code> place athlete&#39;s rank is <code>&quot;Gold Medal&quot;</code>.</li> <li>The <code>2<sup>nd</sup></code> place athlete&#39;s rank is <code>&quot;Silver Medal&quot;</code>.</li> <li>The <code>3<sup>rd</sup></code> place athlete&#39;s rank is <code>&quot;Bronze Medal&quot;</code>.</li> <li>For the <code>4<sup>th</sup></code> place to the <code>n<sup>th</sup></code> place athlete, their rank is their placement number (i.e., the <code>x<sup>th</sup></code> place athlete&#39;s rank is <code>&quot;x&quot;</code>).</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>rank</strong> of the <code>i<sup>th</sup></code> athlete.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> score = [5,4,3,2,1] <strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;Silver Medal&quot;,&quot;Bronze Medal&quot;,&quot;4&quot;,&quot;5&quot;] <strong>Explanation:</strong> The placements are [1<sup>st</sup>, 2<sup>nd</sup>, 3<sup>rd</sup>, 4<sup>th</sup>, 5<sup>th</sup>].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> score = [10,3,8,9,4] <strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;5&quot;,&quot;Bronze Medal&quot;,&quot;Silver Medal&quot;,&quot;4&quot;] <strong>Explanation:</strong> The placements are [1<sup>st</sup>, 5<sup>th</sup>, 3<sup>rd</sup>, 2<sup>nd</sup>, 4<sup>th</sup>]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == score.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= score[i] &lt;= 10<sup>6</sup></code></li> <li>All the values in <code>score</code> are <strong>unique</strong>.</li> </ul>
Array; Sorting; Heap (Priority Queue)
Java
class Solution { public String[] findRelativeRanks(int[] score) { int n = score.length; Integer[] idx = new Integer[n]; Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i1, i2) -> score[i2] - score[i1]); String[] ans = new String[n]; String[] top3 = new String[] {"Gold Medal", "Silver Medal", "Bronze Medal"}; for (int i = 0; i < n; ++i) { ans[idx[i]] = i < 3 ? top3[i] : String.valueOf(i + 1); } return ans; } }
506
Relative Ranks
Easy
<p>You are given an integer array <code>score</code> of size <code>n</code>, where <code>score[i]</code> is the score of the <code>i<sup>th</sup></code> athlete in a competition. All the scores are guaranteed to be <strong>unique</strong>.</p> <p>The athletes are <strong>placed</strong> based on their scores, where the <code>1<sup>st</sup></code> place athlete has the highest score, the <code>2<sup>nd</sup></code> place athlete has the <code>2<sup>nd</sup></code> highest score, and so on. The placement of each athlete determines their rank:</p> <ul> <li>The <code>1<sup>st</sup></code> place athlete&#39;s rank is <code>&quot;Gold Medal&quot;</code>.</li> <li>The <code>2<sup>nd</sup></code> place athlete&#39;s rank is <code>&quot;Silver Medal&quot;</code>.</li> <li>The <code>3<sup>rd</sup></code> place athlete&#39;s rank is <code>&quot;Bronze Medal&quot;</code>.</li> <li>For the <code>4<sup>th</sup></code> place to the <code>n<sup>th</sup></code> place athlete, their rank is their placement number (i.e., the <code>x<sup>th</sup></code> place athlete&#39;s rank is <code>&quot;x&quot;</code>).</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>rank</strong> of the <code>i<sup>th</sup></code> athlete.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> score = [5,4,3,2,1] <strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;Silver Medal&quot;,&quot;Bronze Medal&quot;,&quot;4&quot;,&quot;5&quot;] <strong>Explanation:</strong> The placements are [1<sup>st</sup>, 2<sup>nd</sup>, 3<sup>rd</sup>, 4<sup>th</sup>, 5<sup>th</sup>].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> score = [10,3,8,9,4] <strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;5&quot;,&quot;Bronze Medal&quot;,&quot;Silver Medal&quot;,&quot;4&quot;] <strong>Explanation:</strong> The placements are [1<sup>st</sup>, 5<sup>th</sup>, 3<sup>rd</sup>, 2<sup>nd</sup>, 4<sup>th</sup>]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == score.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= score[i] &lt;= 10<sup>6</sup></code></li> <li>All the values in <code>score</code> are <strong>unique</strong>.</li> </ul>
Array; Sorting; Heap (Priority Queue)
Python
class Solution: def findRelativeRanks(self, score: List[int]) -> List[str]: n = len(score) idx = list(range(n)) idx.sort(key=lambda x: -score[x]) top3 = ["Gold Medal", "Silver Medal", "Bronze Medal"] ans = [None] * n for i, j in enumerate(idx): ans[j] = top3[i] if i < 3 else str(i + 1) return ans
506
Relative Ranks
Easy
<p>You are given an integer array <code>score</code> of size <code>n</code>, where <code>score[i]</code> is the score of the <code>i<sup>th</sup></code> athlete in a competition. All the scores are guaranteed to be <strong>unique</strong>.</p> <p>The athletes are <strong>placed</strong> based on their scores, where the <code>1<sup>st</sup></code> place athlete has the highest score, the <code>2<sup>nd</sup></code> place athlete has the <code>2<sup>nd</sup></code> highest score, and so on. The placement of each athlete determines their rank:</p> <ul> <li>The <code>1<sup>st</sup></code> place athlete&#39;s rank is <code>&quot;Gold Medal&quot;</code>.</li> <li>The <code>2<sup>nd</sup></code> place athlete&#39;s rank is <code>&quot;Silver Medal&quot;</code>.</li> <li>The <code>3<sup>rd</sup></code> place athlete&#39;s rank is <code>&quot;Bronze Medal&quot;</code>.</li> <li>For the <code>4<sup>th</sup></code> place to the <code>n<sup>th</sup></code> place athlete, their rank is their placement number (i.e., the <code>x<sup>th</sup></code> place athlete&#39;s rank is <code>&quot;x&quot;</code>).</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>rank</strong> of the <code>i<sup>th</sup></code> athlete.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> score = [5,4,3,2,1] <strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;Silver Medal&quot;,&quot;Bronze Medal&quot;,&quot;4&quot;,&quot;5&quot;] <strong>Explanation:</strong> The placements are [1<sup>st</sup>, 2<sup>nd</sup>, 3<sup>rd</sup>, 4<sup>th</sup>, 5<sup>th</sup>].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> score = [10,3,8,9,4] <strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;5&quot;,&quot;Bronze Medal&quot;,&quot;Silver Medal&quot;,&quot;4&quot;] <strong>Explanation:</strong> The placements are [1<sup>st</sup>, 5<sup>th</sup>, 3<sup>rd</sup>, 2<sup>nd</sup>, 4<sup>th</sup>]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == score.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= score[i] &lt;= 10<sup>6</sup></code></li> <li>All the values in <code>score</code> are <strong>unique</strong>.</li> </ul>
Array; Sorting; Heap (Priority Queue)
TypeScript
function findRelativeRanks(score: number[]): string[] { const n = score.length; const idx = Array.from({ length: n }, (_, i) => i); idx.sort((a, b) => score[b] - score[a]); const top3 = ['Gold Medal', 'Silver Medal', 'Bronze Medal']; const ans: string[] = Array(n); for (let i = 0; i < n; i++) { if (i < 3) { ans[idx[i]] = top3[i]; } else { ans[idx[i]] = (i + 1).toString(); } } return ans; }
507
Perfect Number
Easy
<p>A <a href="https://en.wikipedia.org/wiki/Perfect_number" target="_blank"><strong>perfect number</strong></a> is a <strong>positive integer</strong> that is equal to the sum of its <strong>positive divisors</strong>, excluding the number itself. A <strong>divisor</strong> of an integer <code>x</code> is an integer that can divide <code>x</code> evenly.</p> <p>Given an integer <code>n</code>, return <code>true</code><em> if </em><code>n</code><em> is a perfect number, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 28 <strong>Output:</strong> true <strong>Explanation:</strong> 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 7 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Math
C++
class Solution { public: bool checkPerfectNumber(int num) { if (num == 1) { return false; } int s = 1; for (int i = 2; i <= num / i; ++i) { if (num % i == 0) { s += i; if (i != num / i) { s += num / i; } } } return s == num; } };
507
Perfect Number
Easy
<p>A <a href="https://en.wikipedia.org/wiki/Perfect_number" target="_blank"><strong>perfect number</strong></a> is a <strong>positive integer</strong> that is equal to the sum of its <strong>positive divisors</strong>, excluding the number itself. A <strong>divisor</strong> of an integer <code>x</code> is an integer that can divide <code>x</code> evenly.</p> <p>Given an integer <code>n</code>, return <code>true</code><em> if </em><code>n</code><em> is a perfect number, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 28 <strong>Output:</strong> true <strong>Explanation:</strong> 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 7 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Math
Go
func checkPerfectNumber(num int) bool { if num == 1 { return false } s := 1 for i := 2; i <= num/i; i++ { if num%i == 0 { s += i if j := num / i; i != j { s += j } } } return s == num }
507
Perfect Number
Easy
<p>A <a href="https://en.wikipedia.org/wiki/Perfect_number" target="_blank"><strong>perfect number</strong></a> is a <strong>positive integer</strong> that is equal to the sum of its <strong>positive divisors</strong>, excluding the number itself. A <strong>divisor</strong> of an integer <code>x</code> is an integer that can divide <code>x</code> evenly.</p> <p>Given an integer <code>n</code>, return <code>true</code><em> if </em><code>n</code><em> is a perfect number, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 28 <strong>Output:</strong> true <strong>Explanation:</strong> 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 7 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Math
Java
class Solution { public boolean checkPerfectNumber(int num) { if (num == 1) { return false; } int s = 1; for (int i = 2; i <= num / i; ++i) { if (num % i == 0) { s += i; if (i != num / i) { s += num / i; } } } return s == num; } }
507
Perfect Number
Easy
<p>A <a href="https://en.wikipedia.org/wiki/Perfect_number" target="_blank"><strong>perfect number</strong></a> is a <strong>positive integer</strong> that is equal to the sum of its <strong>positive divisors</strong>, excluding the number itself. A <strong>divisor</strong> of an integer <code>x</code> is an integer that can divide <code>x</code> evenly.</p> <p>Given an integer <code>n</code>, return <code>true</code><em> if </em><code>n</code><em> is a perfect number, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 28 <strong>Output:</strong> true <strong>Explanation:</strong> 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 7 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Math
Python
class Solution: def checkPerfectNumber(self, num: int) -> bool: if num == 1: return False s, i = 1, 2 while i <= num // i: if num % i == 0: s += i if i != num // i: s += num // i i += 1 return s == num
507
Perfect Number
Easy
<p>A <a href="https://en.wikipedia.org/wiki/Perfect_number" target="_blank"><strong>perfect number</strong></a> is a <strong>positive integer</strong> that is equal to the sum of its <strong>positive divisors</strong>, excluding the number itself. A <strong>divisor</strong> of an integer <code>x</code> is an integer that can divide <code>x</code> evenly.</p> <p>Given an integer <code>n</code>, return <code>true</code><em> if </em><code>n</code><em> is a perfect number, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 28 <strong>Output:</strong> true <strong>Explanation:</strong> 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 7 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Math
TypeScript
function checkPerfectNumber(num: number): boolean { if (num <= 1) { return false; } let s = 1; for (let i = 2; i <= num / i; ++i) { if (num % i === 0) { s += i; if (i * i !== num) { s += num / i; } } } return s === num; }
508
Most Frequent Subtree Sum
Medium
<p>Given the <code>root</code> of a binary tree, return the most frequent <strong>subtree sum</strong>. If there is a tie, return all the values with the highest frequency in any order.</p> <p>The <strong>subtree sum</strong> of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq1-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-3] <strong>Output:</strong> [2,-3,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq2-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-5] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Hash Table; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> findFrequentTreeSum(TreeNode* root) { unordered_map<int, int> cnt; int mx = 0; function<int(TreeNode*)> dfs = [&](TreeNode* root) -> int { if (!root) { return 0; } int s = root->val + dfs(root->left) + dfs(root->right); mx = max(mx, ++cnt[s]); return s; }; dfs(root); vector<int> ans; for (const auto& [k, v] : cnt) { if (v == mx) { ans.push_back(k); } } return ans; } };
508
Most Frequent Subtree Sum
Medium
<p>Given the <code>root</code> of a binary tree, return the most frequent <strong>subtree sum</strong>. If there is a tie, return all the values with the highest frequency in any order.</p> <p>The <strong>subtree sum</strong> of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq1-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-3] <strong>Output:</strong> [2,-3,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq2-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-5] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Hash Table; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findFrequentTreeSum(root *TreeNode) (ans []int) { cnt := map[int]int{} var mx int var dfs func(*TreeNode) int dfs = func(root *TreeNode) int { if root == nil { return 0 } s := root.Val + dfs(root.Left) + dfs(root.Right) cnt[s]++ mx = max(mx, cnt[s]) return s } dfs(root) for k, v := range cnt { if v == mx { ans = append(ans, k) } } return }
508
Most Frequent Subtree Sum
Medium
<p>Given the <code>root</code> of a binary tree, return the most frequent <strong>subtree sum</strong>. If there is a tie, return all the values with the highest frequency in any order.</p> <p>The <strong>subtree sum</strong> of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq1-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-3] <strong>Output:</strong> [2,-3,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq2-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-5] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Hash Table; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private Map<Integer, Integer> cnt = new HashMap<>(); private int mx; public int[] findFrequentTreeSum(TreeNode root) { dfs(root); List<Integer> ans = new ArrayList<>(); for (var e : cnt.entrySet()) { if (e.getValue() == mx) { ans.add(e.getKey()); } } return ans.stream().mapToInt(i -> i).toArray(); } private int dfs(TreeNode root) { if (root == null) { return 0; } int s = root.val + dfs(root.left) + dfs(root.right); mx = Math.max(mx, cnt.merge(s, 1, Integer::sum)); return s; } }
508
Most Frequent Subtree Sum
Medium
<p>Given the <code>root</code> of a binary tree, return the most frequent <strong>subtree sum</strong>. If there is a tie, return all the values with the highest frequency in any order.</p> <p>The <strong>subtree sum</strong> of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq1-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-3] <strong>Output:</strong> [2,-3,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq2-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-5] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Hash Table; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]: def dfs(root: Optional[TreeNode]) -> int: if root is None: return 0 l, r = dfs(root.left), dfs(root.right) s = l + r + root.val cnt[s] += 1 return s cnt = Counter() dfs(root) mx = max(cnt.values()) return [k for k, v in cnt.items() if v == mx]
508
Most Frequent Subtree Sum
Medium
<p>Given the <code>root</code> of a binary tree, return the most frequent <strong>subtree sum</strong>. If there is a tie, return all the values with the highest frequency in any order.</p> <p>The <strong>subtree sum</strong> of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq1-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-3] <strong>Output:</strong> [2,-3,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq2-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-5] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Hash Table; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; impl Solution { pub fn find_frequent_tree_sum(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> { fn dfs(root: Option<Rc<RefCell<TreeNode>>>, cnt: &mut HashMap<i32, i32>) -> i32 { if let Some(node) = root { let l = dfs(node.borrow().left.clone(), cnt); let r = dfs(node.borrow().right.clone(), cnt); let s = l + r + node.borrow().val; *cnt.entry(s).or_insert(0) += 1; s } else { 0 } } let mut cnt = HashMap::new(); dfs(root, &mut cnt); let mx = cnt.values().cloned().max().unwrap_or(0); cnt.into_iter() .filter(|&(_, v)| v == mx) .map(|(k, _)| k) .collect() } }
508
Most Frequent Subtree Sum
Medium
<p>Given the <code>root</code> of a binary tree, return the most frequent <strong>subtree sum</strong>. If there is a tie, return all the values with the highest frequency in any order.</p> <p>The <strong>subtree sum</strong> of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq1-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-3] <strong>Output:</strong> [2,-3,4] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/images/freq2-tree.jpg" style="width: 207px; height: 183px;" /> <pre> <strong>Input:</strong> root = [5,2,-5] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Depth-First Search; Hash Table; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function findFrequentTreeSum(root: TreeNode | null): number[] { const cnt = new Map<number, number>(); let mx = 0; const dfs = (root: TreeNode | null): number => { if (!root) { return 0; } const { val, left, right } = root; const s = val + dfs(left) + dfs(right); cnt.set(s, (cnt.get(s) ?? 0) + 1); mx = Math.max(mx, cnt.get(s)!); return s; }; dfs(root); return Array.from(cnt.entries()) .filter(([_, c]) => c === mx) .map(([s, _]) => s); }
509
Fibonacci Number
Easy
<p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p> <pre> F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n &gt; 1. </pre> <p>Given <code>n</code>, calculate <code>F(n)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 30</code></li> </ul>
Recursion; Memoization; Math; Dynamic Programming
C++
class Solution { public: int fib(int n) { int a = 0, b = 1; while (n--) { int c = a + b; a = b; b = c; } return a; } };
509
Fibonacci Number
Easy
<p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p> <pre> F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n &gt; 1. </pre> <p>Given <code>n</code>, calculate <code>F(n)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 30</code></li> </ul>
Recursion; Memoization; Math; Dynamic Programming
Go
func fib(n int) int { a, b := 0, 1 for i := 0; i < n; i++ { a, b = b, a+b } return a }
509
Fibonacci Number
Easy
<p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p> <pre> F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n &gt; 1. </pre> <p>Given <code>n</code>, calculate <code>F(n)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 30</code></li> </ul>
Recursion; Memoization; Math; Dynamic Programming
Java
class Solution { public int fib(int n) { int a = 0, b = 1; while (n-- > 0) { int c = a + b; a = b; b = c; } return a; } }
509
Fibonacci Number
Easy
<p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p> <pre> F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n &gt; 1. </pre> <p>Given <code>n</code>, calculate <code>F(n)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 30</code></li> </ul>
Recursion; Memoization; Math; Dynamic Programming
JavaScript
/** * @param {number} n * @return {number} */ var fib = function (n) { let [a, b] = [0, 1]; while (n--) { [a, b] = [b, a + b]; } return a; };
509
Fibonacci Number
Easy
<p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p> <pre> F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n &gt; 1. </pre> <p>Given <code>n</code>, calculate <code>F(n)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 30</code></li> </ul>
Recursion; Memoization; Math; Dynamic Programming
PHP
class Solution { /** * @param Integer $n * @return Integer */ function fib($n) { $a = 0; $b = 1; for ($i = 0; $i < $n; $i++) { $temp = $a; $a = $b; $b = $temp + $b; } return $a; } }
509
Fibonacci Number
Easy
<p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p> <pre> F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n &gt; 1. </pre> <p>Given <code>n</code>, calculate <code>F(n)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 30</code></li> </ul>
Recursion; Memoization; Math; Dynamic Programming
Python
class Solution: def fib(self, n: int) -> int: a, b = 0, 1 for _ in range(n): a, b = b, a + b return a
509
Fibonacci Number
Easy
<p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p> <pre> F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n &gt; 1. </pre> <p>Given <code>n</code>, calculate <code>F(n)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 30</code></li> </ul>
Recursion; Memoization; Math; Dynamic Programming
Rust
impl Solution { pub fn fib(n: i32) -> i32 { let mut a = 0; let mut b = 1; for _ in 0..n { let t = b; b = a + b; a = t; } a } }
509
Fibonacci Number
Easy
<p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p> <pre> F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n &gt; 1. </pre> <p>Given <code>n</code>, calculate <code>F(n)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 30</code></li> </ul>
Recursion; Memoization; Math; Dynamic Programming
TypeScript
function fib(n: number): number { let [a, b] = [0, 1]; while (n--) { [a, b] = [b, a + b]; } return a; }
510
Inorder Successor in BST II
Medium
<p>Given a <code>node</code> in a binary search tree, return <em>the in-order successor of that node in the BST</em>. If that node has no in-order successor, return <code>null</code>.</p> <p>The successor of a <code>node</code> is the node with the smallest key greater than <code>node.val</code>.</p> <p>You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for <code>Node</code>:</p> <pre> class Node { public int val; public Node left; public Node right; public Node parent; } </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> tree = [2,1,3], node = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both the node and the return value is of Node type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> tree = [5,3,6,2,4,null,null,1], node = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it without looking up any of the node&#39;s values?</p>
Tree; Binary Search Tree; Binary Tree
C++
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* parent; }; */ class Solution { public: Node* inorderSuccessor(Node* node) { if (node->right) { node = node->right; while (node->left) { node = node->left; } return node; } while (node->parent && node->parent->right == node) { node = node->parent; } return node->parent; } };
510
Inorder Successor in BST II
Medium
<p>Given a <code>node</code> in a binary search tree, return <em>the in-order successor of that node in the BST</em>. If that node has no in-order successor, return <code>null</code>.</p> <p>The successor of a <code>node</code> is the node with the smallest key greater than <code>node.val</code>.</p> <p>You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for <code>Node</code>:</p> <pre> class Node { public int val; public Node left; public Node right; public Node parent; } </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> tree = [2,1,3], node = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both the node and the return value is of Node type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> tree = [5,3,6,2,4,null,null,1], node = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it without looking up any of the node&#39;s values?</p>
Tree; Binary Search Tree; Binary Tree
Go
/** * Definition for Node. * type Node struct { * Val int * Left *Node * Right *Node * Parent *Node * } */ func inorderSuccessor(node *Node) *Node { if node.Right != nil { node = node.Right for node.Left != nil { node = node.Left } return node } for node.Parent != nil && node == node.Parent.Right { node = node.Parent } return node.Parent }
510
Inorder Successor in BST II
Medium
<p>Given a <code>node</code> in a binary search tree, return <em>the in-order successor of that node in the BST</em>. If that node has no in-order successor, return <code>null</code>.</p> <p>The successor of a <code>node</code> is the node with the smallest key greater than <code>node.val</code>.</p> <p>You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for <code>Node</code>:</p> <pre> class Node { public int val; public Node left; public Node right; public Node parent; } </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> tree = [2,1,3], node = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both the node and the return value is of Node type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> tree = [5,3,6,2,4,null,null,1], node = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it without looking up any of the node&#39;s values?</p>
Tree; Binary Search Tree; Binary Tree
Java
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node parent; }; */ class Solution { public Node inorderSuccessor(Node node) { if (node.right != null) { node = node.right; while (node.left != null) { node = node.left; } return node; } while (node.parent != null && node.parent.right == node) { node = node.parent; } return node.parent; } }
510
Inorder Successor in BST II
Medium
<p>Given a <code>node</code> in a binary search tree, return <em>the in-order successor of that node in the BST</em>. If that node has no in-order successor, return <code>null</code>.</p> <p>The successor of a <code>node</code> is the node with the smallest key greater than <code>node.val</code>.</p> <p>You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for <code>Node</code>:</p> <pre> class Node { public int val; public Node left; public Node right; public Node parent; } </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> tree = [2,1,3], node = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both the node and the return value is of Node type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> tree = [5,3,6,2,4,null,null,1], node = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it without looking up any of the node&#39;s values?</p>
Tree; Binary Search Tree; Binary Tree
JavaScript
/** * // Definition for a Node. * function Node(val) { * this.val = val; * this.left = null; * this.right = null; * this.parent = null; * }; */ /** * @param {Node} node * @return {Node} */ var inorderSuccessor = function (node) { if (node.right) { node = node.right; while (node.left) { node = node.left; } return node; } while (node.parent && node === node.parent.right) { node = node.parent; } return node.parent; };
510
Inorder Successor in BST II
Medium
<p>Given a <code>node</code> in a binary search tree, return <em>the in-order successor of that node in the BST</em>. If that node has no in-order successor, return <code>null</code>.</p> <p>The successor of a <code>node</code> is the node with the smallest key greater than <code>node.val</code>.</p> <p>You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for <code>Node</code>:</p> <pre> class Node { public int val; public Node left; public Node right; public Node parent; } </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> tree = [2,1,3], node = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both the node and the return value is of Node type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> tree = [5,3,6,2,4,null,null,1], node = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it without looking up any of the node&#39;s values?</p>
Tree; Binary Search Tree; Binary Tree
Python
""" # Definition for a Node. class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None """ class Solution: def inorderSuccessor(self, node: "Node") -> "Optional[Node]": if node.right: node = node.right while node.left: node = node.left return node while node.parent and node.parent.right is node: node = node.parent return node.parent
510
Inorder Successor in BST II
Medium
<p>Given a <code>node</code> in a binary search tree, return <em>the in-order successor of that node in the BST</em>. If that node has no in-order successor, return <code>null</code>.</p> <p>The successor of a <code>node</code> is the node with the smallest key greater than <code>node.val</code>.</p> <p>You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for <code>Node</code>:</p> <pre> class Node { public int val; public Node left; public Node right; public Node parent; } </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> tree = [2,1,3], node = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both the node and the return value is of Node type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> tree = [5,3,6,2,4,null,null,1], node = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it without looking up any of the node&#39;s values?</p>
Tree; Binary Search Tree; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class Node { * val: number * left: Node | null * right: Node | null * parent: Node | null * constructor(val?: number, left?: Node | null, right?: Node | null, parent?: Node | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * this.parent = (parent===undefined ? null : parent) * } * } */ function inorderSuccessor(node: Node | null): Node | null { if (node.right) { node = node.right; while (node.left) { node = node.left; } return node; } while (node.parent && node === node.parent.right) { node = node.parent; } return node.parent; }
511
Game Play Analysis I
Easy
<p>Table: <code>Activity</code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | player_id | int | | device_id | int | | event_date | date | | games_played | int | +--------------+---------+ (player_id, event_date) is the primary key (combination of columns with unique values) of this table. This table shows the activity of players of some games. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device. </pre> <p>&nbsp;</p> <p>Write a solution to find the <strong>first login date</strong> for each player.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Activity table: +-----------+-----------+------------+--------------+ | player_id | device_id | event_date | games_played | +-----------+-----------+------------+--------------+ | 1 | 2 | 2016-03-01 | 5 | | 1 | 2 | 2016-05-02 | 6 | | 2 | 3 | 2017-06-25 | 1 | | 3 | 1 | 2016-03-02 | 0 | | 3 | 4 | 2018-07-03 | 5 | +-----------+-----------+------------+--------------+ <strong>Output:</strong> +-----------+-------------+ | player_id | first_login | +-----------+-------------+ | 1 | 2016-03-01 | | 2 | 2017-06-25 | | 3 | 2016-03-02 | +-----------+-------------+ </pre>
Database
Python
import pandas as pd def game_analysis(activity: pd.DataFrame) -> pd.DataFrame: return ( activity.groupby("player_id") .agg(first_login=("event_date", "min")) .reset_index() )
511
Game Play Analysis I
Easy
<p>Table: <code>Activity</code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | player_id | int | | device_id | int | | event_date | date | | games_played | int | +--------------+---------+ (player_id, event_date) is the primary key (combination of columns with unique values) of this table. This table shows the activity of players of some games. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device. </pre> <p>&nbsp;</p> <p>Write a solution to find the <strong>first login date</strong> for each player.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Activity table: +-----------+-----------+------------+--------------+ | player_id | device_id | event_date | games_played | +-----------+-----------+------------+--------------+ | 1 | 2 | 2016-03-01 | 5 | | 1 | 2 | 2016-05-02 | 6 | | 2 | 3 | 2017-06-25 | 1 | | 3 | 1 | 2016-03-02 | 0 | | 3 | 4 | 2018-07-03 | 5 | +-----------+-----------+------------+--------------+ <strong>Output:</strong> +-----------+-------------+ | player_id | first_login | +-----------+-------------+ | 1 | 2016-03-01 | | 2 | 2017-06-25 | | 3 | 2016-03-02 | +-----------+-------------+ </pre>
Database
SQL
# Write your MySQL query statement below SELECT player_id, MIN(event_date) AS first_login FROM Activity GROUP BY 1;
512
Game Play Analysis II
Easy
<p>Table: <code>Activity</code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | player_id | int | | device_id | int | | event_date | date | | games_played | int | +--------------+---------+ (player_id, event_date) is the primary key (combination of columns with unique values) of this table. This table shows the activity of players of some games. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device. </pre> <p>&nbsp;</p> <p>Write a solution to report the <strong>device</strong> that is first logged in for each player.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Activity table: +-----------+-----------+------------+--------------+ | player_id | device_id | event_date | games_played | +-----------+-----------+------------+--------------+ | 1 | 2 | 2016-03-01 | 5 | | 1 | 2 | 2016-05-02 | 6 | | 2 | 3 | 2017-06-25 | 1 | | 3 | 1 | 2016-03-02 | 0 | | 3 | 4 | 2018-07-03 | 5 | +-----------+-----------+------------+--------------+ <strong>Output:</strong> +-----------+-----------+ | player_id | device_id | +-----------+-----------+ | 1 | 2 | | 2 | 3 | | 3 | 1 | +-----------+-----------+ </pre>
Database
SQL
# Write your MySQL query statement below SELECT player_id, device_id FROM Activity WHERE (player_id, event_date) IN ( SELECT player_id, MIN(event_date) AS event_date FROM Activity GROUP BY 1 );
513
Find Bottom Left Tree Value
Medium
<p>Given the <code>root</code> of a binary tree, return the leftmost value in the last row of the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree2.jpg" style="width: 432px; height: 421px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,5,6,null,null,7] <strong>Output:</strong> 7 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int findBottomLeftValue(TreeNode* root) { queue<TreeNode*> q{{root}}; int ans = 0; while (!q.empty()) { ans = q.front()->val; for (int i = q.size(); i; --i) { TreeNode* node = q.front(); q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } } return ans; } };
513
Find Bottom Left Tree Value
Medium
<p>Given the <code>root</code> of a binary tree, return the leftmost value in the last row of the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree2.jpg" style="width: 432px; height: 421px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,5,6,null,null,7] <strong>Output:</strong> 7 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findBottomLeftValue(root *TreeNode) int { q := []*TreeNode{root} ans := 0 for len(q) > 0 { ans = q[0].Val for i := len(q); i > 0; i-- { node := q[0] q = q[1:] if node.Left != nil { q = append(q, node.Left) } if node.Right != nil { q = append(q, node.Right) } } } return ans }
513
Find Bottom Left Tree Value
Medium
<p>Given the <code>root</code> of a binary tree, return the leftmost value in the last row of the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree2.jpg" style="width: 432px; height: 421px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,5,6,null,null,7] <strong>Output:</strong> 7 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int findBottomLeftValue(TreeNode root) { Queue<TreeNode> q = new ArrayDeque<>(); q.offer(root); int ans = 0; while (!q.isEmpty()) { ans = q.peek().val; for (int i = q.size(); i > 0; --i) { TreeNode node = q.poll(); if (node.left != null) { q.offer(node.left); } if (node.right != null) { q.offer(node.right); } } } return ans; } }
513
Find Bottom Left Tree Value
Medium
<p>Given the <code>root</code> of a binary tree, return the leftmost value in the last row of the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree2.jpg" style="width: 432px; height: 421px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,5,6,null,null,7] <strong>Output:</strong> 7 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: q = deque([root]) ans = 0 while q: ans = q[0].val for _ in range(len(q)): node = q.popleft() if node.left: q.append(node.left) if node.right: q.append(node.right) return ans
513
Find Bottom Left Tree Value
Medium
<p>Given the <code>root</code> of a binary tree, return the leftmost value in the last row of the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree2.jpg" style="width: 432px; height: 421px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,5,6,null,null,7] <strong>Output:</strong> 7 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; impl Solution { pub fn find_bottom_left_value(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { let mut queue = VecDeque::new(); queue.push_back(root); let mut res = 0; while !queue.is_empty() { res = queue.front().unwrap().as_ref().unwrap().borrow_mut().val; for _ in 0..queue.len() { let node = queue.pop_front().unwrap(); let mut node = node.as_ref().unwrap().borrow_mut(); if node.left.is_some() { queue.push_back(node.left.take()); } if node.right.is_some() { queue.push_back(node.right.take()); } } } res } }
513
Find Bottom Left Tree Value
Medium
<p>Given the <code>root</code> of a binary tree, return the leftmost value in the last row of the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/images/tree2.jpg" style="width: 432px; height: 421px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,null,5,6,null,null,7] <strong>Output:</strong> 7 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function findBottomLeftValue(root: TreeNode | null): number { let ans = 0; const q = [root]; while (q.length) { ans = q[0].val; for (let i = q.length; i; --i) { const node = q.shift(); if (node.left) { q.push(node.left); } if (node.right) { q.push(node.right); } } } return ans; }
514
Freedom Trail
Hard
<p>In the video game Fallout 4, the quest <strong>&quot;Road to Freedom&quot;</strong> requires players to reach a metal dial called the <strong>&quot;Freedom Trail Ring&quot;</strong> and use the dial to spell a specific keyword to open the door.</p> <p>Given a string <code>ring</code> that represents the code engraved on the outer ring and another string <code>key</code> that represents the keyword that needs to be spelled, return <em>the minimum number of steps to spell all the characters in the keyword</em>.</p> <p>Initially, the first character of the ring is aligned at the <code>&quot;12:00&quot;</code> direction. You should spell all the characters in <code>key</code> one by one by rotating <code>ring</code> clockwise or anticlockwise to make each character of the string key aligned at the <code>&quot;12:00&quot;</code> direction and then by pressing the center button.</p> <p>At the stage of rotating the ring to spell the key character <code>key[i]</code>:</p> <ol> <li>You can rotate the ring clockwise or anticlockwise by one place, which counts as <strong>one step</strong>. The final purpose of the rotation is to align one of <code>ring</code>&#39;s characters at the <code>&quot;12:00&quot;</code> direction, where this character must equal <code>key[i]</code>.</li> <li>If the character <code>key[i]</code> has been aligned at the <code>&quot;12:00&quot;</code> direction, press the center button to spell, which also counts as <strong>one step</strong>. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0514.Freedom%20Trail/images/ring.jpg" style="width: 450px; height: 450px;" /> <pre> <strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;gd&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> For the first key character &#39;g&#39;, since it is already in place, we just need 1 step to spell this character. For the second key character &#39;d&#39;, we need to rotate the ring &quot;godding&quot; anticlockwise by two steps to make it become &quot;ddinggo&quot;. Also, we need 1 more step for spelling. So the final output is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;godding&quot; <strong>Output:</strong> 13 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ring.length, key.length &lt;= 100</code></li> <li><code>ring</code> and <code>key</code> consist of only lower case English letters.</li> <li>It is guaranteed that <code>key</code> could always be spelled by rotating <code>ring</code>.</li> </ul>
Depth-First Search; Breadth-First Search; String; Dynamic Programming
C++
class Solution { public: int findRotateSteps(string ring, string key) { int m = key.size(), n = ring.size(); vector<int> pos[26]; for (int j = 0; j < n; ++j) { pos[ring[j] - 'a'].push_back(j); } int f[m][n]; memset(f, 0x3f, sizeof(f)); for (int j : pos[key[0] - 'a']) { f[0][j] = min(j, n - j) + 1; } for (int i = 1; i < m; ++i) { for (int j : pos[key[i] - 'a']) { for (int k : pos[key[i - 1] - 'a']) { f[i][j] = min(f[i][j], f[i - 1][k] + min(abs(j - k), n - abs(j - k)) + 1); } } } int ans = 1 << 30; for (int j : pos[key[m - 1] - 'a']) { ans = min(ans, f[m - 1][j]); } return ans; } };
514
Freedom Trail
Hard
<p>In the video game Fallout 4, the quest <strong>&quot;Road to Freedom&quot;</strong> requires players to reach a metal dial called the <strong>&quot;Freedom Trail Ring&quot;</strong> and use the dial to spell a specific keyword to open the door.</p> <p>Given a string <code>ring</code> that represents the code engraved on the outer ring and another string <code>key</code> that represents the keyword that needs to be spelled, return <em>the minimum number of steps to spell all the characters in the keyword</em>.</p> <p>Initially, the first character of the ring is aligned at the <code>&quot;12:00&quot;</code> direction. You should spell all the characters in <code>key</code> one by one by rotating <code>ring</code> clockwise or anticlockwise to make each character of the string key aligned at the <code>&quot;12:00&quot;</code> direction and then by pressing the center button.</p> <p>At the stage of rotating the ring to spell the key character <code>key[i]</code>:</p> <ol> <li>You can rotate the ring clockwise or anticlockwise by one place, which counts as <strong>one step</strong>. The final purpose of the rotation is to align one of <code>ring</code>&#39;s characters at the <code>&quot;12:00&quot;</code> direction, where this character must equal <code>key[i]</code>.</li> <li>If the character <code>key[i]</code> has been aligned at the <code>&quot;12:00&quot;</code> direction, press the center button to spell, which also counts as <strong>one step</strong>. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0514.Freedom%20Trail/images/ring.jpg" style="width: 450px; height: 450px;" /> <pre> <strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;gd&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> For the first key character &#39;g&#39;, since it is already in place, we just need 1 step to spell this character. For the second key character &#39;d&#39;, we need to rotate the ring &quot;godding&quot; anticlockwise by two steps to make it become &quot;ddinggo&quot;. Also, we need 1 more step for spelling. So the final output is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;godding&quot; <strong>Output:</strong> 13 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ring.length, key.length &lt;= 100</code></li> <li><code>ring</code> and <code>key</code> consist of only lower case English letters.</li> <li>It is guaranteed that <code>key</code> could always be spelled by rotating <code>ring</code>.</li> </ul>
Depth-First Search; Breadth-First Search; String; Dynamic Programming
Go
func findRotateSteps(ring string, key string) int { m, n := len(key), len(ring) pos := [26][]int{} for j, c := range ring { pos[c-'a'] = append(pos[c-'a'], j) } f := make([][]int, m) for i := range f { f[i] = make([]int, n) for j := range f[i] { f[i][j] = 1 << 30 } } for _, j := range pos[key[0]-'a'] { f[0][j] = min(j, n-j) + 1 } for i := 1; i < m; i++ { for _, j := range pos[key[i]-'a'] { for _, k := range pos[key[i-1]-'a'] { f[i][j] = min(f[i][j], f[i-1][k]+min(abs(j-k), n-abs(j-k))+1) } } } ans := 1 << 30 for _, j := range pos[key[m-1]-'a'] { ans = min(ans, f[m-1][j]) } return ans } func abs(x int) int { if x < 0 { return -x } return x }
514
Freedom Trail
Hard
<p>In the video game Fallout 4, the quest <strong>&quot;Road to Freedom&quot;</strong> requires players to reach a metal dial called the <strong>&quot;Freedom Trail Ring&quot;</strong> and use the dial to spell a specific keyword to open the door.</p> <p>Given a string <code>ring</code> that represents the code engraved on the outer ring and another string <code>key</code> that represents the keyword that needs to be spelled, return <em>the minimum number of steps to spell all the characters in the keyword</em>.</p> <p>Initially, the first character of the ring is aligned at the <code>&quot;12:00&quot;</code> direction. You should spell all the characters in <code>key</code> one by one by rotating <code>ring</code> clockwise or anticlockwise to make each character of the string key aligned at the <code>&quot;12:00&quot;</code> direction and then by pressing the center button.</p> <p>At the stage of rotating the ring to spell the key character <code>key[i]</code>:</p> <ol> <li>You can rotate the ring clockwise or anticlockwise by one place, which counts as <strong>one step</strong>. The final purpose of the rotation is to align one of <code>ring</code>&#39;s characters at the <code>&quot;12:00&quot;</code> direction, where this character must equal <code>key[i]</code>.</li> <li>If the character <code>key[i]</code> has been aligned at the <code>&quot;12:00&quot;</code> direction, press the center button to spell, which also counts as <strong>one step</strong>. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0514.Freedom%20Trail/images/ring.jpg" style="width: 450px; height: 450px;" /> <pre> <strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;gd&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> For the first key character &#39;g&#39;, since it is already in place, we just need 1 step to spell this character. For the second key character &#39;d&#39;, we need to rotate the ring &quot;godding&quot; anticlockwise by two steps to make it become &quot;ddinggo&quot;. Also, we need 1 more step for spelling. So the final output is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;godding&quot; <strong>Output:</strong> 13 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ring.length, key.length &lt;= 100</code></li> <li><code>ring</code> and <code>key</code> consist of only lower case English letters.</li> <li>It is guaranteed that <code>key</code> could always be spelled by rotating <code>ring</code>.</li> </ul>
Depth-First Search; Breadth-First Search; String; Dynamic Programming
Java
class Solution { public int findRotateSteps(String ring, String key) { int m = key.length(), n = ring.length(); List<Integer>[] pos = new List[26]; Arrays.setAll(pos, k -> new ArrayList<>()); for (int i = 0; i < n; ++i) { int j = ring.charAt(i) - 'a'; pos[j].add(i); } int[][] f = new int[m][n]; for (var g : f) { Arrays.fill(g, 1 << 30); } for (int j : pos[key.charAt(0) - 'a']) { f[0][j] = Math.min(j, n - j) + 1; } for (int i = 1; i < m; ++i) { for (int j : pos[key.charAt(i) - 'a']) { for (int k : pos[key.charAt(i - 1) - 'a']) { f[i][j] = Math.min( f[i][j], f[i - 1][k] + Math.min(Math.abs(j - k), n - Math.abs(j - k)) + 1); } } } int ans = 1 << 30; for (int j : pos[key.charAt(m - 1) - 'a']) { ans = Math.min(ans, f[m - 1][j]); } return ans; } }
514
Freedom Trail
Hard
<p>In the video game Fallout 4, the quest <strong>&quot;Road to Freedom&quot;</strong> requires players to reach a metal dial called the <strong>&quot;Freedom Trail Ring&quot;</strong> and use the dial to spell a specific keyword to open the door.</p> <p>Given a string <code>ring</code> that represents the code engraved on the outer ring and another string <code>key</code> that represents the keyword that needs to be spelled, return <em>the minimum number of steps to spell all the characters in the keyword</em>.</p> <p>Initially, the first character of the ring is aligned at the <code>&quot;12:00&quot;</code> direction. You should spell all the characters in <code>key</code> one by one by rotating <code>ring</code> clockwise or anticlockwise to make each character of the string key aligned at the <code>&quot;12:00&quot;</code> direction and then by pressing the center button.</p> <p>At the stage of rotating the ring to spell the key character <code>key[i]</code>:</p> <ol> <li>You can rotate the ring clockwise or anticlockwise by one place, which counts as <strong>one step</strong>. The final purpose of the rotation is to align one of <code>ring</code>&#39;s characters at the <code>&quot;12:00&quot;</code> direction, where this character must equal <code>key[i]</code>.</li> <li>If the character <code>key[i]</code> has been aligned at the <code>&quot;12:00&quot;</code> direction, press the center button to spell, which also counts as <strong>one step</strong>. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0514.Freedom%20Trail/images/ring.jpg" style="width: 450px; height: 450px;" /> <pre> <strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;gd&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> For the first key character &#39;g&#39;, since it is already in place, we just need 1 step to spell this character. For the second key character &#39;d&#39;, we need to rotate the ring &quot;godding&quot; anticlockwise by two steps to make it become &quot;ddinggo&quot;. Also, we need 1 more step for spelling. So the final output is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;godding&quot; <strong>Output:</strong> 13 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ring.length, key.length &lt;= 100</code></li> <li><code>ring</code> and <code>key</code> consist of only lower case English letters.</li> <li>It is guaranteed that <code>key</code> could always be spelled by rotating <code>ring</code>.</li> </ul>
Depth-First Search; Breadth-First Search; String; Dynamic Programming
Python
class Solution: def findRotateSteps(self, ring: str, key: str) -> int: m, n = len(key), len(ring) pos = defaultdict(list) for i, c in enumerate(ring): pos[c].append(i) f = [[inf] * n for _ in range(m)] for j in pos[key[0]]: f[0][j] = min(j, n - j) + 1 for i in range(1, m): for j in pos[key[i]]: for k in pos[key[i - 1]]: f[i][j] = min( f[i][j], f[i - 1][k] + min(abs(j - k), n - abs(j - k)) + 1 ) return min(f[-1][j] for j in pos[key[-1]])
514
Freedom Trail
Hard
<p>In the video game Fallout 4, the quest <strong>&quot;Road to Freedom&quot;</strong> requires players to reach a metal dial called the <strong>&quot;Freedom Trail Ring&quot;</strong> and use the dial to spell a specific keyword to open the door.</p> <p>Given a string <code>ring</code> that represents the code engraved on the outer ring and another string <code>key</code> that represents the keyword that needs to be spelled, return <em>the minimum number of steps to spell all the characters in the keyword</em>.</p> <p>Initially, the first character of the ring is aligned at the <code>&quot;12:00&quot;</code> direction. You should spell all the characters in <code>key</code> one by one by rotating <code>ring</code> clockwise or anticlockwise to make each character of the string key aligned at the <code>&quot;12:00&quot;</code> direction and then by pressing the center button.</p> <p>At the stage of rotating the ring to spell the key character <code>key[i]</code>:</p> <ol> <li>You can rotate the ring clockwise or anticlockwise by one place, which counts as <strong>one step</strong>. The final purpose of the rotation is to align one of <code>ring</code>&#39;s characters at the <code>&quot;12:00&quot;</code> direction, where this character must equal <code>key[i]</code>.</li> <li>If the character <code>key[i]</code> has been aligned at the <code>&quot;12:00&quot;</code> direction, press the center button to spell, which also counts as <strong>one step</strong>. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0514.Freedom%20Trail/images/ring.jpg" style="width: 450px; height: 450px;" /> <pre> <strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;gd&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> For the first key character &#39;g&#39;, since it is already in place, we just need 1 step to spell this character. For the second key character &#39;d&#39;, we need to rotate the ring &quot;godding&quot; anticlockwise by two steps to make it become &quot;ddinggo&quot;. Also, we need 1 more step for spelling. So the final output is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;godding&quot; <strong>Output:</strong> 13 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ring.length, key.length &lt;= 100</code></li> <li><code>ring</code> and <code>key</code> consist of only lower case English letters.</li> <li>It is guaranteed that <code>key</code> could always be spelled by rotating <code>ring</code>.</li> </ul>
Depth-First Search; Breadth-First Search; String; Dynamic Programming
TypeScript
function findRotateSteps(ring: string, key: string): number { const m: number = key.length; const n: number = ring.length; const pos: number[][] = Array.from({ length: 26 }, () => []); for (let i = 0; i < n; ++i) { const j: number = ring.charCodeAt(i) - 'a'.charCodeAt(0); pos[j].push(i); } const f: number[][] = Array.from({ length: m }, () => Array(n).fill(1 << 30)); for (const j of pos[key.charCodeAt(0) - 'a'.charCodeAt(0)]) { f[0][j] = Math.min(j, n - j) + 1; } for (let i = 1; i < m; ++i) { for (const j of pos[key.charCodeAt(i) - 'a'.charCodeAt(0)]) { for (const k of pos[key.charCodeAt(i - 1) - 'a'.charCodeAt(0)]) { f[i][j] = Math.min( f[i][j], f[i - 1][k] + Math.min(Math.abs(j - k), n - Math.abs(j - k)) + 1, ); } } } let ans: number = 1 << 30; for (const j of pos[key.charCodeAt(m - 1) - 'a'.charCodeAt(0)]) { ans = Math.min(ans, f[m - 1][j]); } return ans; }
515
Find Largest Value in Each Tree Row
Medium
<p>Given the <code>root</code> of a binary tree, return <em>an array of the largest value in each row</em> of the tree <strong>(0-indexed)</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0515.Find%20Largest%20Value%20in%20Each%20Tree%20Row/images/largest_e1.jpg" style="width: 300px; height: 172px;" /> <pre> <strong>Input:</strong> root = [1,3,2,5,3,null,9] <strong>Output:</strong> [1,3,9] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> [1,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree will be in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> largestValues(TreeNode* root) { vector<int> ans; if (!root) { return ans; } queue<TreeNode*> q{{root}}; while (q.size()) { int x = INT_MIN; for (int i = q.size(); i; --i) { TreeNode* node = q.front(); q.pop(); x = max(x, node->val); if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } ans.push_back(x); } return ans; } };
515
Find Largest Value in Each Tree Row
Medium
<p>Given the <code>root</code> of a binary tree, return <em>an array of the largest value in each row</em> of the tree <strong>(0-indexed)</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0515.Find%20Largest%20Value%20in%20Each%20Tree%20Row/images/largest_e1.jpg" style="width: 300px; height: 172px;" /> <pre> <strong>Input:</strong> root = [1,3,2,5,3,null,9] <strong>Output:</strong> [1,3,9] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> [1,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree will be in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func largestValues(root *TreeNode) (ans []int) { if root == nil { return } q := []*TreeNode{root} for len(q) > 0 { x := q[0].Val for i := len(q); i > 0; i-- { node := q[0] q = q[1:] x = max(x, node.Val) if node.Left != nil { q = append(q, node.Left) } if node.Right != nil { q = append(q, node.Right) } } ans = append(ans, x) } return }
515
Find Largest Value in Each Tree Row
Medium
<p>Given the <code>root</code> of a binary tree, return <em>an array of the largest value in each row</em> of the tree <strong>(0-indexed)</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0515.Find%20Largest%20Value%20in%20Each%20Tree%20Row/images/largest_e1.jpg" style="width: 300px; height: 172px;" /> <pre> <strong>Input:</strong> root = [1,3,2,5,3,null,9] <strong>Output:</strong> [1,3,9] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> [1,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree will be in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Integer> largestValues(TreeNode root) { List<Integer> ans = new ArrayList<>(); if (root == null) { return ans; } Deque<TreeNode> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { int t = q.peek().val; for (int i = q.size(); i > 0; --i) { TreeNode node = q.poll(); t = Math.max(t, node.val); if (node.left != null) { q.offer(node.left); } if (node.right != null) { q.offer(node.right); } } ans.add(t); } return ans; } }
515
Find Largest Value in Each Tree Row
Medium
<p>Given the <code>root</code> of a binary tree, return <em>an array of the largest value in each row</em> of the tree <strong>(0-indexed)</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0515.Find%20Largest%20Value%20in%20Each%20Tree%20Row/images/largest_e1.jpg" style="width: 300px; height: 172px;" /> <pre> <strong>Input:</strong> root = [1,3,2,5,3,null,9] <strong>Output:</strong> [1,3,9] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> [1,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree will be in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestValues(self, root: Optional[TreeNode]) -> List[int]: ans = [] if root is None: return ans q = deque([root]) while q: x = -inf for _ in range(len(q)): node = q.popleft() x = max(x, node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) ans.append(x) return ans
515
Find Largest Value in Each Tree Row
Medium
<p>Given the <code>root</code> of a binary tree, return <em>an array of the largest value in each row</em> of the tree <strong>(0-indexed)</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0515.Find%20Largest%20Value%20in%20Each%20Tree%20Row/images/largest_e1.jpg" style="width: 300px; height: 172px;" /> <pre> <strong>Input:</strong> root = [1,3,2,5,3,null,9] <strong>Output:</strong> [1,3,9] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> [1,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree will be in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; impl Solution { pub fn largest_values(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> { let mut ans = Vec::new(); let mut q = VecDeque::new(); if root.is_some() { q.push_back(root.clone()); } while !q.is_empty() { let mut x = i32::MIN; for _ in 0..q.len() { let node = q.pop_front().unwrap(); let node = node.as_ref().unwrap().borrow(); x = x.max(node.val); if node.left.is_some() { q.push_back(node.left.clone()); } if node.right.is_some() { q.push_back(node.right.clone()); } } ans.push(x); } ans } }
515
Find Largest Value in Each Tree Row
Medium
<p>Given the <code>root</code> of a binary tree, return <em>an array of the largest value in each row</em> of the tree <strong>(0-indexed)</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0515.Find%20Largest%20Value%20in%20Each%20Tree%20Row/images/largest_e1.jpg" style="width: 300px; height: 172px;" /> <pre> <strong>Input:</strong> root = [1,3,2,5,3,null,9] <strong>Output:</strong> [1,3,9] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3] <strong>Output:</strong> [1,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree will be in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function largestValues(root: TreeNode | null): number[] { const ans: number[] = []; if (!root) { return ans; } const q: TreeNode[] = [root]; while (q.length) { const nq: TreeNode[] = []; let x = -Infinity; for (const { val, left, right } of q) { x = Math.max(x, val); if (left) { nq.push(left); } if (right) { nq.push(right); } } ans.push(x); q.length = 0; q.push(...nq); } return ans; }
516
Longest Palindromic Subsequence
Medium
<p>Given a string <code>s</code>, find <em>the longest palindromic <strong>subsequence</strong>&#39;s length in</em> <code>s</code>.</p> <p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbab&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bbbb&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bb&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String; Dynamic Programming
C++
class Solution { public: int longestPalindromeSubseq(string s) { int n = s.size(); int f[n][n]; memset(f, 0, sizeof(f)); for (int i = 0; i < n; ++i) { f[i][i] = 1; } for (int i = n - 1; ~i; --i) { for (int j = i + 1; j < n; ++j) { if (s[i] == s[j]) { f[i][j] = f[i + 1][j - 1] + 2; } else { f[i][j] = max(f[i + 1][j], f[i][j - 1]); } } } return f[0][n - 1]; } };
516
Longest Palindromic Subsequence
Medium
<p>Given a string <code>s</code>, find <em>the longest palindromic <strong>subsequence</strong>&#39;s length in</em> <code>s</code>.</p> <p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbab&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bbbb&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bb&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String; Dynamic Programming
Go
func longestPalindromeSubseq(s string) int { n := len(s) f := make([][]int, n) for i := range f { f[i] = make([]int, n) f[i][i] = 1 } for i := n - 2; i >= 0; i-- { for j := i + 1; j < n; j++ { if s[i] == s[j] { f[i][j] = f[i+1][j-1] + 2 } else { f[i][j] = max(f[i+1][j], f[i][j-1]) } } } return f[0][n-1] }
516
Longest Palindromic Subsequence
Medium
<p>Given a string <code>s</code>, find <em>the longest palindromic <strong>subsequence</strong>&#39;s length in</em> <code>s</code>.</p> <p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbab&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bbbb&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bb&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String; Dynamic Programming
Java
class Solution { public int longestPalindromeSubseq(String s) { int n = s.length(); int[][] f = new int[n][n]; for (int i = 0; i < n; ++i) { f[i][i] = 1; } for (int i = n - 1; i >= 0; --i) { for (int j = i + 1; j < n; ++j) { if (s.charAt(i) == s.charAt(j)) { f[i][j] = f[i + 1][j - 1] + 2; } else { f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]); } } } return f[0][n - 1]; } }
516
Longest Palindromic Subsequence
Medium
<p>Given a string <code>s</code>, find <em>the longest palindromic <strong>subsequence</strong>&#39;s length in</em> <code>s</code>.</p> <p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbab&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bbbb&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bb&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String; Dynamic Programming
Python
class Solution: def longestPalindromeSubseq(self, s: str) -> int: n = len(s) dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for j in range(1, n): for i in range(j - 1, -1, -1): if s[i] == s[j]: dp[i][j] = dp[i + 1][j - 1] + 2 else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) return dp[0][-1]
516
Longest Palindromic Subsequence
Medium
<p>Given a string <code>s</code>, find <em>the longest palindromic <strong>subsequence</strong>&#39;s length in</em> <code>s</code>.</p> <p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbab&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bbbb&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bb&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String; Dynamic Programming
TypeScript
function longestPalindromeSubseq(s: string): number { const n = s.length; const f: number[][] = Array.from({ length: n }, () => Array(n).fill(0)); for (let i = 0; i < n; ++i) { f[i][i] = 1; } for (let i = n - 2; ~i; --i) { for (let j = i + 1; j < n; ++j) { if (s[i] === s[j]) { f[i][j] = f[i + 1][j - 1] + 2; } else { f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]); } } } return f[0][n - 1]; }
517
Super Washing Machines
Hard
<p>You have <code>n</code> super washing machines on a line. Initially, each washing machine has some dresses or is empty.</p> <p>For each move, you could choose any <code>m</code> (<code>1 &lt;= m &lt;= n</code>) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.</p> <p>Given an integer array <code>machines</code> representing the number of dresses in each washing machine from left to right on the line, return <em>the minimum number of moves to make all the washing machines have the same number of dresses</em>. If it is not possible to do it, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> machines = [1,0,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 1st move: 1 0 &lt;-- 5 =&gt; 1 1 4 2nd move: 1 &lt;-- 1 &lt;-- 4 =&gt; 2 1 3 3rd move: 2 1 &lt;-- 3 =&gt; 2 2 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> machines = [0,3,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1st move: 0 &lt;-- 3 0 =&gt; 1 2 0 2nd move: 1 2 --&gt; 0 =&gt; 1 1 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> machines = [0,2,0] <strong>Output:</strong> -1 <strong>Explanation:</strong> It&#39;s impossible to make all three washing machines have the same number of dresses. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == machines.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= machines[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array
C++
class Solution { public: int findMinMoves(vector<int>& machines) { int n = machines.size(); int s = accumulate(machines.begin(), machines.end(), 0); if (s % n) { return -1; } int k = s / n; s = 0; int ans = 0; for (int x : machines) { x -= k; s += x; ans = max({ans, abs(s), x}); } return ans; } };
517
Super Washing Machines
Hard
<p>You have <code>n</code> super washing machines on a line. Initially, each washing machine has some dresses or is empty.</p> <p>For each move, you could choose any <code>m</code> (<code>1 &lt;= m &lt;= n</code>) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.</p> <p>Given an integer array <code>machines</code> representing the number of dresses in each washing machine from left to right on the line, return <em>the minimum number of moves to make all the washing machines have the same number of dresses</em>. If it is not possible to do it, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> machines = [1,0,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 1st move: 1 0 &lt;-- 5 =&gt; 1 1 4 2nd move: 1 &lt;-- 1 &lt;-- 4 =&gt; 2 1 3 3rd move: 2 1 &lt;-- 3 =&gt; 2 2 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> machines = [0,3,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1st move: 0 &lt;-- 3 0 =&gt; 1 2 0 2nd move: 1 2 --&gt; 0 =&gt; 1 1 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> machines = [0,2,0] <strong>Output:</strong> -1 <strong>Explanation:</strong> It&#39;s impossible to make all three washing machines have the same number of dresses. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == machines.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= machines[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array
Go
func findMinMoves(machines []int) (ans int) { n := len(machines) s := 0 for _, x := range machines { s += x } if s%n != 0 { return -1 } k := s / n s = 0 for _, x := range machines { x -= k s += x ans = max(ans, max(abs(s), x)) } return } func abs(x int) int { if x < 0 { return -x } return x }
517
Super Washing Machines
Hard
<p>You have <code>n</code> super washing machines on a line. Initially, each washing machine has some dresses or is empty.</p> <p>For each move, you could choose any <code>m</code> (<code>1 &lt;= m &lt;= n</code>) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.</p> <p>Given an integer array <code>machines</code> representing the number of dresses in each washing machine from left to right on the line, return <em>the minimum number of moves to make all the washing machines have the same number of dresses</em>. If it is not possible to do it, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> machines = [1,0,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 1st move: 1 0 &lt;-- 5 =&gt; 1 1 4 2nd move: 1 &lt;-- 1 &lt;-- 4 =&gt; 2 1 3 3rd move: 2 1 &lt;-- 3 =&gt; 2 2 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> machines = [0,3,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1st move: 0 &lt;-- 3 0 =&gt; 1 2 0 2nd move: 1 2 --&gt; 0 =&gt; 1 1 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> machines = [0,2,0] <strong>Output:</strong> -1 <strong>Explanation:</strong> It&#39;s impossible to make all three washing machines have the same number of dresses. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == machines.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= machines[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array
Java
class Solution { public int findMinMoves(int[] machines) { int n = machines.length; int s = 0; for (int x : machines) { s += x; } if (s % n != 0) { return -1; } int k = s / n; s = 0; int ans = 0; for (int x : machines) { x -= k; s += x; ans = Math.max(ans, Math.max(Math.abs(s), x)); } return ans; } }
517
Super Washing Machines
Hard
<p>You have <code>n</code> super washing machines on a line. Initially, each washing machine has some dresses or is empty.</p> <p>For each move, you could choose any <code>m</code> (<code>1 &lt;= m &lt;= n</code>) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.</p> <p>Given an integer array <code>machines</code> representing the number of dresses in each washing machine from left to right on the line, return <em>the minimum number of moves to make all the washing machines have the same number of dresses</em>. If it is not possible to do it, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> machines = [1,0,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 1st move: 1 0 &lt;-- 5 =&gt; 1 1 4 2nd move: 1 &lt;-- 1 &lt;-- 4 =&gt; 2 1 3 3rd move: 2 1 &lt;-- 3 =&gt; 2 2 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> machines = [0,3,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1st move: 0 &lt;-- 3 0 =&gt; 1 2 0 2nd move: 1 2 --&gt; 0 =&gt; 1 1 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> machines = [0,2,0] <strong>Output:</strong> -1 <strong>Explanation:</strong> It&#39;s impossible to make all three washing machines have the same number of dresses. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == machines.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= machines[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array
Python
class Solution: def findMinMoves(self, machines: List[int]) -> int: n = len(machines) k, mod = divmod(sum(machines), n) if mod: return -1 ans = s = 0 for x in machines: x -= k s += x ans = max(ans, abs(s), x) return ans
517
Super Washing Machines
Hard
<p>You have <code>n</code> super washing machines on a line. Initially, each washing machine has some dresses or is empty.</p> <p>For each move, you could choose any <code>m</code> (<code>1 &lt;= m &lt;= n</code>) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.</p> <p>Given an integer array <code>machines</code> representing the number of dresses in each washing machine from left to right on the line, return <em>the minimum number of moves to make all the washing machines have the same number of dresses</em>. If it is not possible to do it, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> machines = [1,0,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> 1st move: 1 0 &lt;-- 5 =&gt; 1 1 4 2nd move: 1 &lt;-- 1 &lt;-- 4 =&gt; 2 1 3 3rd move: 2 1 &lt;-- 3 =&gt; 2 2 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> machines = [0,3,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1st move: 0 &lt;-- 3 0 =&gt; 1 2 0 2nd move: 1 2 --&gt; 0 =&gt; 1 1 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> machines = [0,2,0] <strong>Output:</strong> -1 <strong>Explanation:</strong> It&#39;s impossible to make all three washing machines have the same number of dresses. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == machines.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= machines[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array
TypeScript
function findMinMoves(machines: number[]): number { const n = machines.length; let s = machines.reduce((a, b) => a + b); if (s % n !== 0) { return -1; } const k = Math.floor(s / n); s = 0; let ans = 0; for (let x of machines) { x -= k; s += x; ans = Math.max(ans, Math.abs(s), x); } return ans; }
518
Coin Change II
Medium
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p> <p>Return <em>the number of combinations that make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>0</code>.</p> <p>You may assume that you have an infinite number of each kind of coin.</p> <p>The answer is <strong>guaranteed</strong> to fit into a signed <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> amount = 5, coins = [1,2,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> amount = 3, coins = [2] <strong>Output:</strong> 0 <strong>Explanation:</strong> the amount of 3 cannot be made up just with coins of 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> amount = 10, coins = [10] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= coins.length &lt;= 300</code></li> <li><code>1 &lt;= coins[i] &lt;= 5000</code></li> <li>All the values of <code>coins</code> are <strong>unique</strong>.</li> <li><code>0 &lt;= amount &lt;= 5000</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int change(int amount, vector<int>& coins) { int m = coins.size(), n = amount; unsigned f[m + 1][n + 1]; memset(f, 0, sizeof(f)); f[0][0] = 1; for (int i = 1; i <= m; ++i) { for (int j = 0; j <= n; ++j) { f[i][j] = f[i - 1][j]; if (j >= coins[i - 1]) { f[i][j] += f[i][j - coins[i - 1]]; } } } return f[m][n]; } };