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
417
Pacific Atlantic Water Flow
Medium
<p>There is an <code>m x n</code> rectangular island that borders both the <strong>Pacific Ocean</strong> and <strong>Atlantic Ocean</strong>. The <strong>Pacific Ocean</strong> touches the island&#39;s left and top edges, and the <strong>Atlantic Ocean</strong> touches the island&#39;s right and bottom edges.</p> <p>The island is partitioned into a grid of square cells. You are given an <code>m x n</code> integer matrix <code>heights</code> where <code>heights[r][c]</code> represents the <strong>height above sea level</strong> of the cell at coordinate <code>(r, c)</code>.</p> <p>The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell&#39;s height is <strong>less than or equal to</strong> the current cell&#39;s height. Water can flow from any cell adjacent to an ocean into the ocean.</p> <p>Return <em>a <strong>2D list</strong> of grid coordinates </em><code>result</code><em> where </em><code>result[i] = [r<sub>i</sub>, c<sub>i</sub>]</code><em> denotes that rain water can flow from cell </em><code>(r<sub>i</sub>, c<sub>i</sub>)</code><em> to <strong>both</strong> the Pacific and Atlantic oceans</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/0417.Pacific%20Atlantic%20Water%20Flow/images/waterflow-grid.jpg" style="width: 400px; height: 400px;" /> <pre> <strong>Input:</strong> heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] <strong>Output:</strong> [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] <strong>Explanation:</strong> The following cells can flow to the Pacific and Atlantic oceans, as shown below: [0,4]: [0,4] -&gt; Pacific Ocean &nbsp; [0,4] -&gt; Atlantic Ocean [1,3]: [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,3] -&gt; [1,4] -&gt; Atlantic Ocean [1,4]: [1,4] -&gt; [1,3] -&gt; [0,3] -&gt; Pacific Ocean &nbsp; [1,4] -&gt; Atlantic Ocean [2,2]: [2,2] -&gt; [1,2] -&gt; [0,2] -&gt; Pacific Ocean &nbsp; [2,2] -&gt; [2,3] -&gt; [2,4] -&gt; Atlantic Ocean [3,0]: [3,0] -&gt; Pacific Ocean &nbsp; [3,0] -&gt; [4,0] -&gt; Atlantic Ocean [3,1]: [3,1] -&gt; [3,0] -&gt; Pacific Ocean &nbsp; [3,1] -&gt; [4,1] -&gt; Atlantic Ocean [4,0]: [4,0] -&gt; Pacific Ocean [4,0] -&gt; Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heights = [[1]] <strong>Output:</strong> [[0,0]] <strong>Explanation:</strong> The water can flow from the only cell to the Pacific and Atlantic oceans. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == heights.length</code></li> <li><code>n == heights[r].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>0 &lt;= heights[r][c] &lt;= 10<sup>5</sup></code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
TypeScript
function pacificAtlantic(heights: number[][]): number[][] { const m = heights.length, n = heights[0].length; const vis1: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false)); const vis2: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false)); const q1: [number, number][] = []; const q2: [number, number][] = []; const dirs = [-1, 0, 1, 0, -1]; for (let i = 0; i < m; ++i) { q1.push([i, 0]); vis1[i][0] = true; q2.push([i, n - 1]); vis2[i][n - 1] = true; } for (let j = 0; j < n; ++j) { q1.push([0, j]); vis1[0][j] = true; q2.push([m - 1, j]); vis2[m - 1][j] = true; } const bfs = (q: [number, number][], vis: boolean[][]) => { while (q.length) { const [x, y] = q.shift()!; for (let k = 0; k < 4; ++k) { const nx = x + dirs[k], ny = y + dirs[k + 1]; if ( nx >= 0 && nx < m && ny >= 0 && ny < n && !vis[nx][ny] && heights[nx][ny] >= heights[x][y] ) { vis[nx][ny] = true; q.push([nx, ny]); } } } }; bfs(q1, vis1); bfs(q2, vis2); const ans: number[][] = []; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (vis1[i][j] && vis2[i][j]) { ans.push([i, j]); } } } return ans; }
418
Sentence Screen Fitting
Medium
<p>Given a&nbsp;<code>rows x cols</code> screen and a <code>sentence</code> represented as a list of strings, return <em>the number of&nbsp;times the given sentence can be fitted on the screen</em>.</p> <p>The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;hello&quot;,&quot;world&quot;], rows = 2, cols = 8 <strong>Output:</strong> 1 <strong>Explanation:</strong> hello--- world--- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;a&quot;, &quot;bcd&quot;, &quot;e&quot;], rows = 3, cols = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> a-bcd- e-a--- bcd-e- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;i&quot;,&quot;had&quot;,&quot;apple&quot;,&quot;pie&quot;], rows = 4, cols = 5 <strong>Output:</strong> 1 <strong>Explanation:</strong> i-had apple pie-i had-- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sentence.length &lt;= 100</code></li> <li><code>1 &lt;= sentence[i].length &lt;= 10</code></li> <li><code>sentence[i]</code> consists of lowercase English letters.</li> <li><code>1 &lt;= rows, cols &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Array; String; Dynamic Programming
C++
class Solution { public: int wordsTyping(vector<string>& sentence, int rows, int cols) { string s; for (auto& t : sentence) { s += t; s += " "; } int m = s.size(); int cur = 0; while (rows--) { cur += cols; if (s[cur % m] == ' ') { ++cur; } else { while (cur && s[(cur - 1) % m] != ' ') { --cur; } } } return cur / m; } };
418
Sentence Screen Fitting
Medium
<p>Given a&nbsp;<code>rows x cols</code> screen and a <code>sentence</code> represented as a list of strings, return <em>the number of&nbsp;times the given sentence can be fitted on the screen</em>.</p> <p>The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;hello&quot;,&quot;world&quot;], rows = 2, cols = 8 <strong>Output:</strong> 1 <strong>Explanation:</strong> hello--- world--- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;a&quot;, &quot;bcd&quot;, &quot;e&quot;], rows = 3, cols = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> a-bcd- e-a--- bcd-e- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;i&quot;,&quot;had&quot;,&quot;apple&quot;,&quot;pie&quot;], rows = 4, cols = 5 <strong>Output:</strong> 1 <strong>Explanation:</strong> i-had apple pie-i had-- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sentence.length &lt;= 100</code></li> <li><code>1 &lt;= sentence[i].length &lt;= 10</code></li> <li><code>sentence[i]</code> consists of lowercase English letters.</li> <li><code>1 &lt;= rows, cols &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Array; String; Dynamic Programming
Go
func wordsTyping(sentence []string, rows int, cols int) int { s := strings.Join(sentence, " ") + " " m := len(s) cur := 0 for i := 0; i < rows; i++ { cur += cols if s[cur%m] == ' ' { cur++ } else { for cur > 0 && s[(cur-1)%m] != ' ' { cur-- } } } return cur / m }
418
Sentence Screen Fitting
Medium
<p>Given a&nbsp;<code>rows x cols</code> screen and a <code>sentence</code> represented as a list of strings, return <em>the number of&nbsp;times the given sentence can be fitted on the screen</em>.</p> <p>The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;hello&quot;,&quot;world&quot;], rows = 2, cols = 8 <strong>Output:</strong> 1 <strong>Explanation:</strong> hello--- world--- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;a&quot;, &quot;bcd&quot;, &quot;e&quot;], rows = 3, cols = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> a-bcd- e-a--- bcd-e- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;i&quot;,&quot;had&quot;,&quot;apple&quot;,&quot;pie&quot;], rows = 4, cols = 5 <strong>Output:</strong> 1 <strong>Explanation:</strong> i-had apple pie-i had-- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sentence.length &lt;= 100</code></li> <li><code>1 &lt;= sentence[i].length &lt;= 10</code></li> <li><code>sentence[i]</code> consists of lowercase English letters.</li> <li><code>1 &lt;= rows, cols &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Array; String; Dynamic Programming
Java
class Solution { public int wordsTyping(String[] sentence, int rows, int cols) { String s = String.join(" ", sentence) + " "; int m = s.length(); int cur = 0; while (rows-- > 0) { cur += cols; if (s.charAt(cur % m) == ' ') { ++cur; } else { while (cur > 0 && s.charAt((cur - 1) % m) != ' ') { --cur; } } } return cur / m; } }
418
Sentence Screen Fitting
Medium
<p>Given a&nbsp;<code>rows x cols</code> screen and a <code>sentence</code> represented as a list of strings, return <em>the number of&nbsp;times the given sentence can be fitted on the screen</em>.</p> <p>The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;hello&quot;,&quot;world&quot;], rows = 2, cols = 8 <strong>Output:</strong> 1 <strong>Explanation:</strong> hello--- world--- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;a&quot;, &quot;bcd&quot;, &quot;e&quot;], rows = 3, cols = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> a-bcd- e-a--- bcd-e- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;i&quot;,&quot;had&quot;,&quot;apple&quot;,&quot;pie&quot;], rows = 4, cols = 5 <strong>Output:</strong> 1 <strong>Explanation:</strong> i-had apple pie-i had-- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sentence.length &lt;= 100</code></li> <li><code>1 &lt;= sentence[i].length &lt;= 10</code></li> <li><code>sentence[i]</code> consists of lowercase English letters.</li> <li><code>1 &lt;= rows, cols &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Array; String; Dynamic Programming
Python
class Solution: def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int: s = " ".join(sentence) + " " m = len(s) cur = 0 for _ in range(rows): cur += cols if s[cur % m] == " ": cur += 1 while cur and s[(cur - 1) % m] != " ": cur -= 1 return cur // m
418
Sentence Screen Fitting
Medium
<p>Given a&nbsp;<code>rows x cols</code> screen and a <code>sentence</code> represented as a list of strings, return <em>the number of&nbsp;times the given sentence can be fitted on the screen</em>.</p> <p>The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;hello&quot;,&quot;world&quot;], rows = 2, cols = 8 <strong>Output:</strong> 1 <strong>Explanation:</strong> hello--- world--- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;a&quot;, &quot;bcd&quot;, &quot;e&quot;], rows = 3, cols = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> a-bcd- e-a--- bcd-e- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> sentence = [&quot;i&quot;,&quot;had&quot;,&quot;apple&quot;,&quot;pie&quot;], rows = 4, cols = 5 <strong>Output:</strong> 1 <strong>Explanation:</strong> i-had apple pie-i had-- The character &#39;-&#39; signifies an empty space on the screen. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sentence.length &lt;= 100</code></li> <li><code>1 &lt;= sentence[i].length &lt;= 10</code></li> <li><code>sentence[i]</code> consists of lowercase English letters.</li> <li><code>1 &lt;= rows, cols &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Array; String; Dynamic Programming
TypeScript
function wordsTyping(sentence: string[], rows: number, cols: number): number { const s = sentence.join(' ') + ' '; let cur = 0; const m = s.length; for (let i = 0; i < rows; ++i) { cur += cols; if (s[cur % m] === ' ') { ++cur; } else { while (cur > 0 && s[(cur - 1) % m] !== ' ') { --cur; } } } return Math.floor(cur / m); }
419
Battleships in a Board
Medium
<p>Given an <code>m x n</code> matrix <code>board</code> where each cell is a battleship <code>&#39;X&#39;</code> or empty <code>&#39;.&#39;</code>, return <em>the number of the <strong>battleships</strong> on</em> <code>board</code>.</p> <p><strong>Battleships</strong> can only be placed horizontally or vertically on <code>board</code>. In other words, they can only be made of the shape <code>1 x k</code> (<code>1</code> row, <code>k</code> columns) or <code>k x 1</code> (<code>k</code> rows, <code>1</code> column), where <code>k</code> can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img height="333" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0419.Battleships%20in%20a%20Board/images/image.png" width="333" /> <pre> <strong>Input:</strong> board = [[&quot;X&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;.&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>board[i][j]</code> is either <code>&#39;.&#39;</code> or <code>&#39;X&#39;</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it in one-pass, using only <code>O(1)</code> extra memory and without modifying the values <code>board</code>?</p>
Depth-First Search; Array; Matrix
C++
class Solution { public: int countBattleships(vector<vector<char>>& board) { int m = board.size(), n = board[0].size(); int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (board[i][j] == '.') { continue; } if (i > 0 && board[i - 1][j] == 'X') { continue; } if (j > 0 && board[i][j - 1] == 'X') { continue; } ++ans; } } return ans; } };
419
Battleships in a Board
Medium
<p>Given an <code>m x n</code> matrix <code>board</code> where each cell is a battleship <code>&#39;X&#39;</code> or empty <code>&#39;.&#39;</code>, return <em>the number of the <strong>battleships</strong> on</em> <code>board</code>.</p> <p><strong>Battleships</strong> can only be placed horizontally or vertically on <code>board</code>. In other words, they can only be made of the shape <code>1 x k</code> (<code>1</code> row, <code>k</code> columns) or <code>k x 1</code> (<code>k</code> rows, <code>1</code> column), where <code>k</code> can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img height="333" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0419.Battleships%20in%20a%20Board/images/image.png" width="333" /> <pre> <strong>Input:</strong> board = [[&quot;X&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;.&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>board[i][j]</code> is either <code>&#39;.&#39;</code> or <code>&#39;X&#39;</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it in one-pass, using only <code>O(1)</code> extra memory and without modifying the values <code>board</code>?</p>
Depth-First Search; Array; Matrix
Go
func countBattleships(board [][]byte) (ans int) { for i, row := range board { for j, c := range row { if c == '.' { continue } if i > 0 && board[i-1][j] == 'X' { continue } if j > 0 && board[i][j-1] == 'X' { continue } ans++ } } return }
419
Battleships in a Board
Medium
<p>Given an <code>m x n</code> matrix <code>board</code> where each cell is a battleship <code>&#39;X&#39;</code> or empty <code>&#39;.&#39;</code>, return <em>the number of the <strong>battleships</strong> on</em> <code>board</code>.</p> <p><strong>Battleships</strong> can only be placed horizontally or vertically on <code>board</code>. In other words, they can only be made of the shape <code>1 x k</code> (<code>1</code> row, <code>k</code> columns) or <code>k x 1</code> (<code>k</code> rows, <code>1</code> column), where <code>k</code> can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img height="333" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0419.Battleships%20in%20a%20Board/images/image.png" width="333" /> <pre> <strong>Input:</strong> board = [[&quot;X&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;.&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>board[i][j]</code> is either <code>&#39;.&#39;</code> or <code>&#39;X&#39;</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it in one-pass, using only <code>O(1)</code> extra memory and without modifying the values <code>board</code>?</p>
Depth-First Search; Array; Matrix
Java
class Solution { public int countBattleships(char[][] board) { int m = board.length, n = board[0].length; int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (board[i][j] == '.') { continue; } if (i > 0 && board[i - 1][j] == 'X') { continue; } if (j > 0 && board[i][j - 1] == 'X') { continue; } ++ans; } } return ans; } }
419
Battleships in a Board
Medium
<p>Given an <code>m x n</code> matrix <code>board</code> where each cell is a battleship <code>&#39;X&#39;</code> or empty <code>&#39;.&#39;</code>, return <em>the number of the <strong>battleships</strong> on</em> <code>board</code>.</p> <p><strong>Battleships</strong> can only be placed horizontally or vertically on <code>board</code>. In other words, they can only be made of the shape <code>1 x k</code> (<code>1</code> row, <code>k</code> columns) or <code>k x 1</code> (<code>k</code> rows, <code>1</code> column), where <code>k</code> can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img height="333" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0419.Battleships%20in%20a%20Board/images/image.png" width="333" /> <pre> <strong>Input:</strong> board = [[&quot;X&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;.&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>board[i][j]</code> is either <code>&#39;.&#39;</code> or <code>&#39;X&#39;</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it in one-pass, using only <code>O(1)</code> extra memory and without modifying the values <code>board</code>?</p>
Depth-First Search; Array; Matrix
Python
class Solution: def countBattleships(self, board: List[List[str]]) -> int: m, n = len(board), len(board[0]) ans = 0 for i in range(m): for j in range(n): if board[i][j] == '.': continue if i > 0 and board[i - 1][j] == 'X': continue if j > 0 and board[i][j - 1] == 'X': continue ans += 1 return ans
419
Battleships in a Board
Medium
<p>Given an <code>m x n</code> matrix <code>board</code> where each cell is a battleship <code>&#39;X&#39;</code> or empty <code>&#39;.&#39;</code>, return <em>the number of the <strong>battleships</strong> on</em> <code>board</code>.</p> <p><strong>Battleships</strong> can only be placed horizontally or vertically on <code>board</code>. In other words, they can only be made of the shape <code>1 x k</code> (<code>1</code> row, <code>k</code> columns) or <code>k x 1</code> (<code>k</code> rows, <code>1</code> column), where <code>k</code> can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img height="333" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0419.Battleships%20in%20a%20Board/images/image.png" width="333" /> <pre> <strong>Input:</strong> board = [[&quot;X&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;.&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>board[i][j]</code> is either <code>&#39;.&#39;</code> or <code>&#39;X&#39;</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it in one-pass, using only <code>O(1)</code> extra memory and without modifying the values <code>board</code>?</p>
Depth-First Search; Array; Matrix
TypeScript
function countBattleships(board: string[][]): number { const m = board.length; const n = board[0].length; let ans = 0; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (board[i][j] === '.') { continue; } if (i && board[i - 1][j] === 'X') { continue; } if (j && board[i][j - 1] === 'X') { continue; } ++ans; } } return ans; }
420
Strong Password Checker
Hard
<p>A password is considered strong if the below conditions are all met:</p> <ul> <li>It has at least <code>6</code> characters and at most <code>20</code> characters.</li> <li>It contains at least <strong>one lowercase</strong> letter, at least <strong>one uppercase</strong> letter, and at least <strong>one digit</strong>.</li> <li>It does not contain three repeating characters in a row (i.e., <code>&quot;B<u><strong>aaa</strong></u>bb0&quot;</code> is weak, but <code>&quot;B<strong><u>aa</u></strong>b<u><strong>a</strong></u>0&quot;</code> is strong).</li> </ul> <p>Given a string <code>password</code>, return <em>the minimum number of steps required to make <code>password</code> strong. if <code>password</code> is already strong, return <code>0</code>.</em></p> <p>In one step, you can:</p> <ul> <li>Insert one character to <code>password</code>,</li> <li>Delete one character from <code>password</code>, or</li> <li>Replace one character of <code>password</code> with another character.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> password = "a" <strong>Output:</strong> 5 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> password = "aA1" <strong>Output:</strong> 3 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> password = "1337C0d3" <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= password.length &lt;= 50</code></li> <li><code>password</code> consists of letters, digits, dot&nbsp;<code>&#39;.&#39;</code> or exclamation mark <code>&#39;!&#39;</code>.</li> </ul>
Greedy; String; Heap (Priority Queue)
C++
class Solution { public: int strongPasswordChecker(string password) { int types = countTypes(password); int n = password.size(); if (n < 6) return max(6 - n, 3 - types); if (n <= 20) { int replace = 0, cnt = 0; char prev = '~'; for (char& curr : password) { if (curr == prev) ++cnt; else { replace += cnt / 3; cnt = 1; prev = curr; } } replace += cnt / 3; return max(replace, 3 - types); } int replace = 0, remove = n - 20; int remove2 = 0; int cnt = 0; char prev = '~'; for (char& curr : password) { if (curr == prev) ++cnt; else { if (remove > 0 && cnt >= 3) { if (cnt % 3 == 0) { --remove; --replace; } else if (cnt % 3 == 1) ++remove2; } replace += cnt / 3; cnt = 1; prev = curr; } } if (remove > 0 && cnt >= 3) { if (cnt % 3 == 0) { --remove; --replace; } else if (cnt % 3 == 1) ++remove2; } replace += cnt / 3; int use2 = min(min(replace, remove2), remove / 2); replace -= use2; remove -= use2 * 2; int use3 = min(replace, remove / 3); replace -= use3; remove -= use3 * 3; return (n - 20) + max(replace, 3 - types); } int countTypes(string& s) { int a = 0, b = 0, c = 0; for (char& ch : s) { if (islower(ch)) a = 1; else if (isupper(ch)) b = 1; else if (isdigit(ch)) c = 1; } return a + b + c; } };
420
Strong Password Checker
Hard
<p>A password is considered strong if the below conditions are all met:</p> <ul> <li>It has at least <code>6</code> characters and at most <code>20</code> characters.</li> <li>It contains at least <strong>one lowercase</strong> letter, at least <strong>one uppercase</strong> letter, and at least <strong>one digit</strong>.</li> <li>It does not contain three repeating characters in a row (i.e., <code>&quot;B<u><strong>aaa</strong></u>bb0&quot;</code> is weak, but <code>&quot;B<strong><u>aa</u></strong>b<u><strong>a</strong></u>0&quot;</code> is strong).</li> </ul> <p>Given a string <code>password</code>, return <em>the minimum number of steps required to make <code>password</code> strong. if <code>password</code> is already strong, return <code>0</code>.</em></p> <p>In one step, you can:</p> <ul> <li>Insert one character to <code>password</code>,</li> <li>Delete one character from <code>password</code>, or</li> <li>Replace one character of <code>password</code> with another character.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> password = "a" <strong>Output:</strong> 5 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> password = "aA1" <strong>Output:</strong> 3 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> password = "1337C0d3" <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= password.length &lt;= 50</code></li> <li><code>password</code> consists of letters, digits, dot&nbsp;<code>&#39;.&#39;</code> or exclamation mark <code>&#39;!&#39;</code>.</li> </ul>
Greedy; String; Heap (Priority Queue)
Java
class Solution { public int strongPasswordChecker(String password) { int types = countTypes(password); int n = password.length(); if (n < 6) { return Math.max(6 - n, 3 - types); } char[] chars = password.toCharArray(); if (n <= 20) { int replace = 0; int cnt = 0; char prev = '~'; for (char curr : chars) { if (curr == prev) { ++cnt; } else { replace += cnt / 3; cnt = 1; prev = curr; } } replace += cnt / 3; return Math.max(replace, 3 - types); } int replace = 0, remove = n - 20; int remove2 = 0; int cnt = 0; char prev = '~'; for (char curr : chars) { if (curr == prev) { ++cnt; } else { if (remove > 0 && cnt >= 3) { if (cnt % 3 == 0) { --remove; --replace; } else if (cnt % 3 == 1) { ++remove2; } } replace += cnt / 3; cnt = 1; prev = curr; } } if (remove > 0 && cnt >= 3) { if (cnt % 3 == 0) { --remove; --replace; } else if (cnt % 3 == 1) { ++remove2; } } replace += cnt / 3; int use2 = Math.min(Math.min(replace, remove2), remove / 2); replace -= use2; remove -= use2 * 2; int use3 = Math.min(replace, remove / 3); replace -= use3; remove -= use3 * 3; return (n - 20) + Math.max(replace, 3 - types); } private int countTypes(String s) { int a = 0, b = 0, c = 0; for (char ch : s.toCharArray()) { if (Character.isLowerCase(ch)) { a = 1; } else if (Character.isUpperCase(ch)) { b = 1; } else if (Character.isDigit(ch)) { c = 1; } } return a + b + c; } }
420
Strong Password Checker
Hard
<p>A password is considered strong if the below conditions are all met:</p> <ul> <li>It has at least <code>6</code> characters and at most <code>20</code> characters.</li> <li>It contains at least <strong>one lowercase</strong> letter, at least <strong>one uppercase</strong> letter, and at least <strong>one digit</strong>.</li> <li>It does not contain three repeating characters in a row (i.e., <code>&quot;B<u><strong>aaa</strong></u>bb0&quot;</code> is weak, but <code>&quot;B<strong><u>aa</u></strong>b<u><strong>a</strong></u>0&quot;</code> is strong).</li> </ul> <p>Given a string <code>password</code>, return <em>the minimum number of steps required to make <code>password</code> strong. if <code>password</code> is already strong, return <code>0</code>.</em></p> <p>In one step, you can:</p> <ul> <li>Insert one character to <code>password</code>,</li> <li>Delete one character from <code>password</code>, or</li> <li>Replace one character of <code>password</code> with another character.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> password = "a" <strong>Output:</strong> 5 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> password = "aA1" <strong>Output:</strong> 3 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> password = "1337C0d3" <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= password.length &lt;= 50</code></li> <li><code>password</code> consists of letters, digits, dot&nbsp;<code>&#39;.&#39;</code> or exclamation mark <code>&#39;!&#39;</code>.</li> </ul>
Greedy; String; Heap (Priority Queue)
Python
class Solution: def strongPasswordChecker(self, password: str) -> int: def countTypes(s): a = b = c = 0 for ch in s: if ch.islower(): a = 1 elif ch.isupper(): b = 1 elif ch.isdigit(): c = 1 return a + b + c types = countTypes(password) n = len(password) if n < 6: return max(6 - n, 3 - types) if n <= 20: replace = cnt = 0 prev = '~' for curr in password: if curr == prev: cnt += 1 else: replace += cnt // 3 cnt = 1 prev = curr replace += cnt // 3 return max(replace, 3 - types) replace = cnt = 0 remove, remove2 = n - 20, 0 prev = '~' for curr in password: if curr == prev: cnt += 1 else: if remove > 0 and cnt >= 3: if cnt % 3 == 0: remove -= 1 replace -= 1 elif cnt % 3 == 1: remove2 += 1 replace += cnt // 3 cnt = 1 prev = curr if remove > 0 and cnt >= 3: if cnt % 3 == 0: remove -= 1 replace -= 1 elif cnt % 3 == 1: remove2 += 1 replace += cnt // 3 use2 = min(replace, remove2, remove // 2) replace -= use2 remove -= use2 * 2 use3 = min(replace, remove // 3) replace -= use3 remove -= use3 * 3 return n - 20 + max(replace, 3 - types)
421
Maximum XOR of Two Numbers in an Array
Medium
<p>Given an integer array <code>nums</code>, return <em>the maximum result of </em><code>nums[i] XOR nums[j]</code>, where <code>0 &lt;= i &lt;= j &lt; n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,10,5,25,2,8] <strong>Output:</strong> 28 <strong>Explanation:</strong> The maximum result is 5 XOR 25 = 28. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [14,70,53,83,49,91,36,80,92,51,66,70] <strong>Output:</strong> 127 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation; Trie; Array; Hash Table
C++
class Trie { public: Trie* children[2]; Trie() : children{nullptr, nullptr} {} void insert(int x) { Trie* node = this; for (int i = 30; ~i; --i) { int v = x >> i & 1; if (!node->children[v]) { node->children[v] = new Trie(); } node = node->children[v]; } } int search(int x) { Trie* node = this; int ans = 0; for (int i = 30; ~i; --i) { int v = x >> i & 1; if (node->children[v ^ 1]) { ans |= 1 << i; node = node->children[v ^ 1]; } else { node = node->children[v]; } } return ans; } }; class Solution { public: int findMaximumXOR(vector<int>& nums) { Trie* trie = new Trie(); int ans = 0; for (int x : nums) { trie->insert(x); ans = max(ans, trie->search(x)); } return ans; } };
421
Maximum XOR of Two Numbers in an Array
Medium
<p>Given an integer array <code>nums</code>, return <em>the maximum result of </em><code>nums[i] XOR nums[j]</code>, where <code>0 &lt;= i &lt;= j &lt; n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,10,5,25,2,8] <strong>Output:</strong> 28 <strong>Explanation:</strong> The maximum result is 5 XOR 25 = 28. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [14,70,53,83,49,91,36,80,92,51,66,70] <strong>Output:</strong> 127 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation; Trie; Array; Hash Table
Go
type Trie struct { children [2]*Trie } func newTrie() *Trie { return &Trie{} } func (t *Trie) insert(x int) { node := t for i := 30; i >= 0; i-- { v := x >> i & 1 if node.children[v] == nil { node.children[v] = newTrie() } node = node.children[v] } } func (t *Trie) search(x int) int { node := t ans := 0 for i := 30; i >= 0; i-- { v := x >> i & 1 if node.children[v^1] != nil { ans |= 1 << i node = node.children[v^1] } else { node = node.children[v] } } return ans } func findMaximumXOR(nums []int) (ans int) { trie := newTrie() for _, x := range nums { trie.insert(x) ans = max(ans, trie.search(x)) } return ans }
421
Maximum XOR of Two Numbers in an Array
Medium
<p>Given an integer array <code>nums</code>, return <em>the maximum result of </em><code>nums[i] XOR nums[j]</code>, where <code>0 &lt;= i &lt;= j &lt; n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,10,5,25,2,8] <strong>Output:</strong> 28 <strong>Explanation:</strong> The maximum result is 5 XOR 25 = 28. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [14,70,53,83,49,91,36,80,92,51,66,70] <strong>Output:</strong> 127 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation; Trie; Array; Hash Table
Java
class Trie { private Trie[] children = new Trie[2]; public Trie() { } public void insert(int x) { Trie node = this; for (int i = 30; i >= 0; --i) { int v = x >> i & 1; if (node.children[v] == null) { node.children[v] = new Trie(); } node = node.children[v]; } } public int search(int x) { Trie node = this; int ans = 0; for (int i = 30; i >= 0; --i) { int v = x >> i & 1; if (node.children[v ^ 1] != null) { ans |= 1 << i; node = node.children[v ^ 1]; } else { node = node.children[v]; } } return ans; } } class Solution { public int findMaximumXOR(int[] nums) { Trie trie = new Trie(); int ans = 0; for (int x : nums) { trie.insert(x); ans = Math.max(ans, trie.search(x)); } return ans; } }
421
Maximum XOR of Two Numbers in an Array
Medium
<p>Given an integer array <code>nums</code>, return <em>the maximum result of </em><code>nums[i] XOR nums[j]</code>, where <code>0 &lt;= i &lt;= j &lt; n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,10,5,25,2,8] <strong>Output:</strong> 28 <strong>Explanation:</strong> The maximum result is 5 XOR 25 = 28. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [14,70,53,83,49,91,36,80,92,51,66,70] <strong>Output:</strong> 127 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation; Trie; Array; Hash Table
Python
class Trie: __slots__ = ("children",) def __init__(self): self.children: List[Trie | None] = [None, None] def insert(self, x: int): node = self for i in range(30, -1, -1): v = x >> i & 1 if node.children[v] is None: node.children[v] = Trie() node = node.children[v] def search(self, x: int) -> int: node = self ans = 0 for i in range(30, -1, -1): v = x >> i & 1 if node.children[v ^ 1]: ans |= 1 << i node = node.children[v ^ 1] else: node = node.children[v] return ans class Solution: def findMaximumXOR(self, nums: List[int]) -> int: trie = Trie() for x in nums: trie.insert(x) return max(trie.search(x) for x in nums)
421
Maximum XOR of Two Numbers in an Array
Medium
<p>Given an integer array <code>nums</code>, return <em>the maximum result of </em><code>nums[i] XOR nums[j]</code>, where <code>0 &lt;= i &lt;= j &lt; n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,10,5,25,2,8] <strong>Output:</strong> 28 <strong>Explanation:</strong> The maximum result is 5 XOR 25 = 28. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [14,70,53,83,49,91,36,80,92,51,66,70] <strong>Output:</strong> 127 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Bit Manipulation; Trie; Array; Hash Table
Rust
struct Trie { children: [Option<Box<Trie>>; 2], } impl Trie { fn new() -> Trie { Trie { children: [None, None], } } fn insert(&mut self, x: i32) { let mut node = self; for i in (0..=30).rev() { let v = ((x >> i) & 1) as usize; if node.children[v].is_none() { node.children[v] = Some(Box::new(Trie::new())); } node = node.children[v].as_mut().unwrap(); } } fn search(&self, x: i32) -> i32 { let mut node = self; let mut ans = 0; for i in (0..=30).rev() { let v = ((x >> i) & 1) as usize; if let Some(child) = &node.children[v ^ 1] { ans |= 1 << i; node = child.as_ref(); } else { node = node.children[v].as_ref().unwrap(); } } ans } } impl Solution { pub fn find_maximum_xor(nums: Vec<i32>) -> i32 { let mut trie = Trie::new(); let mut ans = 0; for &x in nums.iter() { trie.insert(x); ans = ans.max(trie.search(x)); } ans } }
422
Valid Word Square
Easy
<p>Given an array of strings <code>words</code>, return <code>true</code> <em>if it forms a valid <strong>word square</strong></em>.</p> <p>A sequence of strings forms a valid <strong>word square</strong> if the <code>k<sup>th</sup></code> row and column read the same string, where <code>0 &lt;= k &lt; max(numRows, numColumns)</code>.</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/0422.Valid%20Word%20Square/images/validsq1-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;bnrt&quot;,&quot;crmy&quot;,&quot;dtye&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> The 1<sup>st</sup> row and 1<sup>st</sup> column both read &quot;abcd&quot;. The 2<sup>nd</sup> row and 2<sup>nd</sup> column both read &quot;bnrt&quot;. The 3<sup>rd</sup> row and 3<sup>rd</sup> column both read &quot;crmy&quot;. The 4<sup>th</sup> row and 4<sup>th</sup> column both read &quot;dtye&quot;. Therefore, it is a valid word square. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0422.Valid%20Word%20Square/images/validsq2-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;bnrt&quot;,&quot;crm&quot;,&quot;dt&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> The 1<sup>st</sup> row and 1<sup>st</sup> column both read &quot;abcd&quot;. The 2<sup>nd</sup> row and 2<sup>nd</sup> column both read &quot;bnrt&quot;. The 3<sup>rd</sup> row and 3<sup>rd</sup> column both read &quot;crm&quot;. The 4<sup>th</sup> row and 4<sup>th</sup> column both read &quot;dt&quot;. Therefore, it is a valid word square. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0422.Valid%20Word%20Square/images/validsq3-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;ball&quot;,&quot;area&quot;,&quot;read&quot;,&quot;lady&quot;] <strong>Output:</strong> false <strong>Explanation:</strong> The 3<sup>rd</sup> row reads &quot;read&quot; while the 3<sup>rd</sup> column reads &quot;lead&quot;. Therefore, it is NOT a valid word square. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 500</code></li> <li><code>1 &lt;= words[i].length &lt;= 500</code></li> <li><code>words[i]</code> consists of only lowercase English letters.</li> </ul>
Array; Matrix
C++
class Solution { public: bool validWordSquare(vector<string>& words) { int m = words.size(); for (int i = 0; i < m; ++i) { int n = words[i].size(); for (int j = 0; j < n; ++j) { if (j >= m || i >= words[j].size() || words[i][j] != words[j][i]) { return false; } } } return true; } };
422
Valid Word Square
Easy
<p>Given an array of strings <code>words</code>, return <code>true</code> <em>if it forms a valid <strong>word square</strong></em>.</p> <p>A sequence of strings forms a valid <strong>word square</strong> if the <code>k<sup>th</sup></code> row and column read the same string, where <code>0 &lt;= k &lt; max(numRows, numColumns)</code>.</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/0422.Valid%20Word%20Square/images/validsq1-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;bnrt&quot;,&quot;crmy&quot;,&quot;dtye&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> The 1<sup>st</sup> row and 1<sup>st</sup> column both read &quot;abcd&quot;. The 2<sup>nd</sup> row and 2<sup>nd</sup> column both read &quot;bnrt&quot;. The 3<sup>rd</sup> row and 3<sup>rd</sup> column both read &quot;crmy&quot;. The 4<sup>th</sup> row and 4<sup>th</sup> column both read &quot;dtye&quot;. Therefore, it is a valid word square. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0422.Valid%20Word%20Square/images/validsq2-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;bnrt&quot;,&quot;crm&quot;,&quot;dt&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> The 1<sup>st</sup> row and 1<sup>st</sup> column both read &quot;abcd&quot;. The 2<sup>nd</sup> row and 2<sup>nd</sup> column both read &quot;bnrt&quot;. The 3<sup>rd</sup> row and 3<sup>rd</sup> column both read &quot;crm&quot;. The 4<sup>th</sup> row and 4<sup>th</sup> column both read &quot;dt&quot;. Therefore, it is a valid word square. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0422.Valid%20Word%20Square/images/validsq3-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;ball&quot;,&quot;area&quot;,&quot;read&quot;,&quot;lady&quot;] <strong>Output:</strong> false <strong>Explanation:</strong> The 3<sup>rd</sup> row reads &quot;read&quot; while the 3<sup>rd</sup> column reads &quot;lead&quot;. Therefore, it is NOT a valid word square. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 500</code></li> <li><code>1 &lt;= words[i].length &lt;= 500</code></li> <li><code>words[i]</code> consists of only lowercase English letters.</li> </ul>
Array; Matrix
Go
func validWordSquare(words []string) bool { m := len(words) for i, w := range words { for j := range w { if j >= m || i >= len(words[j]) || w[j] != words[j][i] { return false } } } return true }
422
Valid Word Square
Easy
<p>Given an array of strings <code>words</code>, return <code>true</code> <em>if it forms a valid <strong>word square</strong></em>.</p> <p>A sequence of strings forms a valid <strong>word square</strong> if the <code>k<sup>th</sup></code> row and column read the same string, where <code>0 &lt;= k &lt; max(numRows, numColumns)</code>.</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/0422.Valid%20Word%20Square/images/validsq1-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;bnrt&quot;,&quot;crmy&quot;,&quot;dtye&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> The 1<sup>st</sup> row and 1<sup>st</sup> column both read &quot;abcd&quot;. The 2<sup>nd</sup> row and 2<sup>nd</sup> column both read &quot;bnrt&quot;. The 3<sup>rd</sup> row and 3<sup>rd</sup> column both read &quot;crmy&quot;. The 4<sup>th</sup> row and 4<sup>th</sup> column both read &quot;dtye&quot;. Therefore, it is a valid word square. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0422.Valid%20Word%20Square/images/validsq2-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;bnrt&quot;,&quot;crm&quot;,&quot;dt&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> The 1<sup>st</sup> row and 1<sup>st</sup> column both read &quot;abcd&quot;. The 2<sup>nd</sup> row and 2<sup>nd</sup> column both read &quot;bnrt&quot;. The 3<sup>rd</sup> row and 3<sup>rd</sup> column both read &quot;crm&quot;. The 4<sup>th</sup> row and 4<sup>th</sup> column both read &quot;dt&quot;. Therefore, it is a valid word square. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0422.Valid%20Word%20Square/images/validsq3-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;ball&quot;,&quot;area&quot;,&quot;read&quot;,&quot;lady&quot;] <strong>Output:</strong> false <strong>Explanation:</strong> The 3<sup>rd</sup> row reads &quot;read&quot; while the 3<sup>rd</sup> column reads &quot;lead&quot;. Therefore, it is NOT a valid word square. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 500</code></li> <li><code>1 &lt;= words[i].length &lt;= 500</code></li> <li><code>words[i]</code> consists of only lowercase English letters.</li> </ul>
Array; Matrix
Java
class Solution { public boolean validWordSquare(List<String> words) { int m = words.size(); for (int i = 0; i < m; ++i) { int n = words.get(i).length(); for (int j = 0; j < n; ++j) { if (j >= m || i >= words.get(j).length()) { return false; } if (words.get(i).charAt(j) != words.get(j).charAt(i)) { return false; } } } return true; } }
422
Valid Word Square
Easy
<p>Given an array of strings <code>words</code>, return <code>true</code> <em>if it forms a valid <strong>word square</strong></em>.</p> <p>A sequence of strings forms a valid <strong>word square</strong> if the <code>k<sup>th</sup></code> row and column read the same string, where <code>0 &lt;= k &lt; max(numRows, numColumns)</code>.</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/0422.Valid%20Word%20Square/images/validsq1-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;bnrt&quot;,&quot;crmy&quot;,&quot;dtye&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> The 1<sup>st</sup> row and 1<sup>st</sup> column both read &quot;abcd&quot;. The 2<sup>nd</sup> row and 2<sup>nd</sup> column both read &quot;bnrt&quot;. The 3<sup>rd</sup> row and 3<sup>rd</sup> column both read &quot;crmy&quot;. The 4<sup>th</sup> row and 4<sup>th</sup> column both read &quot;dtye&quot;. Therefore, it is a valid word square. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0422.Valid%20Word%20Square/images/validsq2-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;bnrt&quot;,&quot;crm&quot;,&quot;dt&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> The 1<sup>st</sup> row and 1<sup>st</sup> column both read &quot;abcd&quot;. The 2<sup>nd</sup> row and 2<sup>nd</sup> column both read &quot;bnrt&quot;. The 3<sup>rd</sup> row and 3<sup>rd</sup> column both read &quot;crm&quot;. The 4<sup>th</sup> row and 4<sup>th</sup> column both read &quot;dt&quot;. Therefore, it is a valid word square. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0422.Valid%20Word%20Square/images/validsq3-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;ball&quot;,&quot;area&quot;,&quot;read&quot;,&quot;lady&quot;] <strong>Output:</strong> false <strong>Explanation:</strong> The 3<sup>rd</sup> row reads &quot;read&quot; while the 3<sup>rd</sup> column reads &quot;lead&quot;. Therefore, it is NOT a valid word square. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 500</code></li> <li><code>1 &lt;= words[i].length &lt;= 500</code></li> <li><code>words[i]</code> consists of only lowercase English letters.</li> </ul>
Array; Matrix
Python
class Solution: def validWordSquare(self, words: List[str]) -> bool: m = len(words) for i, w in enumerate(words): for j, c in enumerate(w): if j >= m or i >= len(words[j]) or c != words[j][i]: return False return True
422
Valid Word Square
Easy
<p>Given an array of strings <code>words</code>, return <code>true</code> <em>if it forms a valid <strong>word square</strong></em>.</p> <p>A sequence of strings forms a valid <strong>word square</strong> if the <code>k<sup>th</sup></code> row and column read the same string, where <code>0 &lt;= k &lt; max(numRows, numColumns)</code>.</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/0422.Valid%20Word%20Square/images/validsq1-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;bnrt&quot;,&quot;crmy&quot;,&quot;dtye&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> The 1<sup>st</sup> row and 1<sup>st</sup> column both read &quot;abcd&quot;. The 2<sup>nd</sup> row and 2<sup>nd</sup> column both read &quot;bnrt&quot;. The 3<sup>rd</sup> row and 3<sup>rd</sup> column both read &quot;crmy&quot;. The 4<sup>th</sup> row and 4<sup>th</sup> column both read &quot;dtye&quot;. Therefore, it is a valid word square. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0422.Valid%20Word%20Square/images/validsq2-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;abcd&quot;,&quot;bnrt&quot;,&quot;crm&quot;,&quot;dt&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> The 1<sup>st</sup> row and 1<sup>st</sup> column both read &quot;abcd&quot;. The 2<sup>nd</sup> row and 2<sup>nd</sup> column both read &quot;bnrt&quot;. The 3<sup>rd</sup> row and 3<sup>rd</sup> column both read &quot;crm&quot;. The 4<sup>th</sup> row and 4<sup>th</sup> column both read &quot;dt&quot;. Therefore, it is a valid word square. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0422.Valid%20Word%20Square/images/validsq3-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> words = [&quot;ball&quot;,&quot;area&quot;,&quot;read&quot;,&quot;lady&quot;] <strong>Output:</strong> false <strong>Explanation:</strong> The 3<sup>rd</sup> row reads &quot;read&quot; while the 3<sup>rd</sup> column reads &quot;lead&quot;. Therefore, it is NOT a valid word square. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 500</code></li> <li><code>1 &lt;= words[i].length &lt;= 500</code></li> <li><code>words[i]</code> consists of only lowercase English letters.</li> </ul>
Array; Matrix
TypeScript
function validWordSquare(words: string[]): boolean { const m = words.length; for (let i = 0; i < m; ++i) { const n = words[i].length; for (let j = 0; j < n; ++j) { if (j >= m || i >= words[j].length || words[i][j] !== words[j][i]) { return false; } } } return true; }
423
Reconstruct Original Digits from English
Medium
<p>Given a string <code>s</code> containing an out-of-order English representation of digits <code>0-9</code>, return <em>the digits in <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "owoztneoer" <strong>Output:</strong> "012" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "fviefuro" <strong>Output:</strong> "45" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is one of the characters <code>[&quot;e&quot;,&quot;g&quot;,&quot;f&quot;,&quot;i&quot;,&quot;h&quot;,&quot;o&quot;,&quot;n&quot;,&quot;s&quot;,&quot;r&quot;,&quot;u&quot;,&quot;t&quot;,&quot;w&quot;,&quot;v&quot;,&quot;x&quot;,&quot;z&quot;]</code>.</li> <li><code>s</code> is <strong>guaranteed</strong> to be valid.</li> </ul>
Hash Table; Math; String
C++
class Solution { public: string originalDigits(string s) { vector<int> counter(26); for (char c : s) ++counter[c - 'a']; vector<int> cnt(10); cnt[0] = counter['z' - 'a']; cnt[2] = counter['w' - 'a']; cnt[4] = counter['u' - 'a']; cnt[6] = counter['x' - 'a']; cnt[8] = counter['g' - 'a']; cnt[3] = counter['h' - 'a'] - cnt[8]; cnt[5] = counter['f' - 'a'] - cnt[4]; cnt[7] = counter['s' - 'a'] - cnt[6]; cnt[1] = counter['o' - 'a'] - cnt[0] - cnt[2] - cnt[4]; cnt[9] = counter['i' - 'a'] - cnt[5] - cnt[6] - cnt[8]; string ans; for (int i = 0; i < 10; ++i) for (int j = 0; j < cnt[i]; ++j) ans += char(i + '0'); return ans; } };
423
Reconstruct Original Digits from English
Medium
<p>Given a string <code>s</code> containing an out-of-order English representation of digits <code>0-9</code>, return <em>the digits in <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "owoztneoer" <strong>Output:</strong> "012" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "fviefuro" <strong>Output:</strong> "45" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is one of the characters <code>[&quot;e&quot;,&quot;g&quot;,&quot;f&quot;,&quot;i&quot;,&quot;h&quot;,&quot;o&quot;,&quot;n&quot;,&quot;s&quot;,&quot;r&quot;,&quot;u&quot;,&quot;t&quot;,&quot;w&quot;,&quot;v&quot;,&quot;x&quot;,&quot;z&quot;]</code>.</li> <li><code>s</code> is <strong>guaranteed</strong> to be valid.</li> </ul>
Hash Table; Math; String
Go
func originalDigits(s string) string { counter := make([]int, 26) for _, c := range s { counter[c-'a']++ } cnt := make([]int, 10) cnt[0] = counter['z'-'a'] cnt[2] = counter['w'-'a'] cnt[4] = counter['u'-'a'] cnt[6] = counter['x'-'a'] cnt[8] = counter['g'-'a'] cnt[3] = counter['h'-'a'] - cnt[8] cnt[5] = counter['f'-'a'] - cnt[4] cnt[7] = counter['s'-'a'] - cnt[6] cnt[1] = counter['o'-'a'] - cnt[0] - cnt[2] - cnt[4] cnt[9] = counter['i'-'a'] - cnt[5] - cnt[6] - cnt[8] ans := []byte{} for i, c := range cnt { ans = append(ans, bytes.Repeat([]byte{byte('0' + i)}, c)...) } return string(ans) }
423
Reconstruct Original Digits from English
Medium
<p>Given a string <code>s</code> containing an out-of-order English representation of digits <code>0-9</code>, return <em>the digits in <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "owoztneoer" <strong>Output:</strong> "012" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "fviefuro" <strong>Output:</strong> "45" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is one of the characters <code>[&quot;e&quot;,&quot;g&quot;,&quot;f&quot;,&quot;i&quot;,&quot;h&quot;,&quot;o&quot;,&quot;n&quot;,&quot;s&quot;,&quot;r&quot;,&quot;u&quot;,&quot;t&quot;,&quot;w&quot;,&quot;v&quot;,&quot;x&quot;,&quot;z&quot;]</code>.</li> <li><code>s</code> is <strong>guaranteed</strong> to be valid.</li> </ul>
Hash Table; Math; String
Java
class Solution { public String originalDigits(String s) { int[] counter = new int[26]; for (char c : s.toCharArray()) { ++counter[c - 'a']; } int[] cnt = new int[10]; cnt[0] = counter['z' - 'a']; cnt[2] = counter['w' - 'a']; cnt[4] = counter['u' - 'a']; cnt[6] = counter['x' - 'a']; cnt[8] = counter['g' - 'a']; cnt[3] = counter['h' - 'a'] - cnt[8]; cnt[5] = counter['f' - 'a'] - cnt[4]; cnt[7] = counter['s' - 'a'] - cnt[6]; cnt[1] = counter['o' - 'a'] - cnt[0] - cnt[2] - cnt[4]; cnt[9] = counter['i' - 'a'] - cnt[5] - cnt[6] - cnt[8]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; ++i) { for (int j = 0; j < cnt[i]; ++j) { sb.append(i); } } return sb.toString(); } }
423
Reconstruct Original Digits from English
Medium
<p>Given a string <code>s</code> containing an out-of-order English representation of digits <code>0-9</code>, return <em>the digits in <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "owoztneoer" <strong>Output:</strong> "012" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "fviefuro" <strong>Output:</strong> "45" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is one of the characters <code>[&quot;e&quot;,&quot;g&quot;,&quot;f&quot;,&quot;i&quot;,&quot;h&quot;,&quot;o&quot;,&quot;n&quot;,&quot;s&quot;,&quot;r&quot;,&quot;u&quot;,&quot;t&quot;,&quot;w&quot;,&quot;v&quot;,&quot;x&quot;,&quot;z&quot;]</code>.</li> <li><code>s</code> is <strong>guaranteed</strong> to be valid.</li> </ul>
Hash Table; Math; String
Python
class Solution: def originalDigits(self, s: str) -> str: counter = Counter(s) cnt = [0] * 10 cnt[0] = counter['z'] cnt[2] = counter['w'] cnt[4] = counter['u'] cnt[6] = counter['x'] cnt[8] = counter['g'] cnt[3] = counter['h'] - cnt[8] cnt[5] = counter['f'] - cnt[4] cnt[7] = counter['s'] - cnt[6] cnt[1] = counter['o'] - cnt[0] - cnt[2] - cnt[4] cnt[9] = counter['i'] - cnt[5] - cnt[6] - cnt[8] return ''.join(cnt[i] * str(i) for i in range(10))
424
Longest Repeating Character Replacement
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most <code>k</code> times.</p> <p>Return <em>the length of the longest substring containing the same letter you can get after performing the above operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABAB&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> Replace the two &#39;A&#39;s with two &#39;B&#39;s or vice versa. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AABABBA&quot;, k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> Replace the one &#39;A&#39; in the middle with &#39;B&#39; and form &quot;AABBBBA&quot;. The substring &quot;BBBB&quot; has the longest repeating letters, which is 4. There may exists other ways to achieve this answer too.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only uppercase English letters.</li> <li><code>0 &lt;= k &lt;= s.length</code></li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: int characterReplacement(string s, int k) { int cnt[26]{}; int l = 0, mx = 0; int n = s.length(); for (int r = 0; r < n; ++r) { mx = max(mx, ++cnt[s[r] - 'A']); if (r - l + 1 - mx > k) { --cnt[s[l++] - 'A']; } } return n - l; } };
424
Longest Repeating Character Replacement
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most <code>k</code> times.</p> <p>Return <em>the length of the longest substring containing the same letter you can get after performing the above operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABAB&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> Replace the two &#39;A&#39;s with two &#39;B&#39;s or vice versa. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AABABBA&quot;, k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> Replace the one &#39;A&#39; in the middle with &#39;B&#39; and form &quot;AABBBBA&quot;. The substring &quot;BBBB&quot; has the longest repeating letters, which is 4. There may exists other ways to achieve this answer too.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only uppercase English letters.</li> <li><code>0 &lt;= k &lt;= s.length</code></li> </ul>
Hash Table; String; Sliding Window
Go
func characterReplacement(s string, k int) int { cnt := [26]int{} l, mx := 0, 0 for r, c := range s { cnt[c-'A']++ mx = max(mx, cnt[c-'A']) if r-l+1-mx > k { cnt[s[l]-'A']-- l++ } } return len(s) - l }
424
Longest Repeating Character Replacement
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most <code>k</code> times.</p> <p>Return <em>the length of the longest substring containing the same letter you can get after performing the above operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABAB&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> Replace the two &#39;A&#39;s with two &#39;B&#39;s or vice versa. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AABABBA&quot;, k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> Replace the one &#39;A&#39; in the middle with &#39;B&#39; and form &quot;AABBBBA&quot;. The substring &quot;BBBB&quot; has the longest repeating letters, which is 4. There may exists other ways to achieve this answer too.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only uppercase English letters.</li> <li><code>0 &lt;= k &lt;= s.length</code></li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public int characterReplacement(String s, int k) { int[] cnt = new int[26]; int l = 0, mx = 0; int n = s.length(); for (int r = 0; r < n; ++r) { mx = Math.max(mx, ++cnt[s.charAt(r) - 'A']); if (r - l + 1 - mx > k) { --cnt[s.charAt(l++) - 'A']; } } return n - l; } }
424
Longest Repeating Character Replacement
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most <code>k</code> times.</p> <p>Return <em>the length of the longest substring containing the same letter you can get after performing the above operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABAB&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> Replace the two &#39;A&#39;s with two &#39;B&#39;s or vice versa. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AABABBA&quot;, k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> Replace the one &#39;A&#39; in the middle with &#39;B&#39; and form &quot;AABBBBA&quot;. The substring &quot;BBBB&quot; has the longest repeating letters, which is 4. There may exists other ways to achieve this answer too.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only uppercase English letters.</li> <li><code>0 &lt;= k &lt;= s.length</code></li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def characterReplacement(self, s: str, k: int) -> int: cnt = Counter() l = mx = 0 for r, c in enumerate(s): cnt[c] += 1 mx = max(mx, cnt[c]) if r - l + 1 - mx > k: cnt[s[l]] -= 1 l += 1 return len(s) - l
424
Longest Repeating Character Replacement
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most <code>k</code> times.</p> <p>Return <em>the length of the longest substring containing the same letter you can get after performing the above operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABAB&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> Replace the two &#39;A&#39;s with two &#39;B&#39;s or vice versa. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AABABBA&quot;, k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> Replace the one &#39;A&#39; in the middle with &#39;B&#39; and form &quot;AABBBBA&quot;. The substring &quot;BBBB&quot; has the longest repeating letters, which is 4. There may exists other ways to achieve this answer too.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only uppercase English letters.</li> <li><code>0 &lt;= k &lt;= s.length</code></li> </ul>
Hash Table; String; Sliding Window
TypeScript
function characterReplacement(s: string, k: number): number { const idx = (c: string) => c.charCodeAt(0) - 65; const cnt: number[] = Array(26).fill(0); const n = s.length; let [l, mx] = [0, 0]; for (let r = 0; r < n; ++r) { mx = Math.max(mx, ++cnt[idx(s[r])]); if (r - l + 1 - mx > k) { --cnt[idx(s[l++])]; } } return n - l; }
425
Word Squares
Hard
<p>Given an array of <strong>unique</strong> strings <code>words</code>, return <em>all the </em><strong><a href="https://en.wikipedia.org/wiki/Word_square" target="_blank">word squares</a></strong><em> you can build from </em><code>words</code>. The same word from <code>words</code> can be used <strong>multiple times</strong>. You can return the answer in <strong>any order</strong>.</p> <p>A sequence of strings forms a valid <strong>word square</strong> if the <code>k<sup>th</sup></code> row and column read the same string, where <code>0 &lt;= k &lt; max(numRows, numColumns)</code>.</p> <ul> <li>For example, the word sequence <code>[&quot;ball&quot;,&quot;area&quot;,&quot;lead&quot;,&quot;lady&quot;]</code> forms a word square because each word reads the same both horizontally and vertically.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;area&quot;,&quot;lead&quot;,&quot;wall&quot;,&quot;lady&quot;,&quot;ball&quot;] <strong>Output:</strong> [[&quot;ball&quot;,&quot;area&quot;,&quot;lead&quot;,&quot;lady&quot;],[&quot;wall&quot;,&quot;area&quot;,&quot;lead&quot;,&quot;lady&quot;]] <strong>Explanation:</strong> The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abat&quot;,&quot;baba&quot;,&quot;atan&quot;,&quot;atal&quot;] <strong>Output:</strong> [[&quot;baba&quot;,&quot;abat&quot;,&quot;baba&quot;,&quot;atal&quot;],[&quot;baba&quot;,&quot;abat&quot;,&quot;baba&quot;,&quot;atan&quot;]] <strong>Explanation:</strong> The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 4</code></li> <li>All <code>words[i]</code> have the same length.</li> <li><code>words[i]</code> consists of only lowercase English letters.</li> <li>All <code>words[i]</code> are <strong>unique</strong>.</li> </ul>
Trie; Array; String; Backtracking
Go
type Trie struct { children [26]*Trie v []int } func newTrie() *Trie { return &Trie{} } func (this *Trie) insert(word string, i int) { node := this for _, c := range word { c -= 'a' if node.children[c] == nil { node.children[c] = newTrie() } node = node.children[c] node.v = append(node.v, i) } } func (this *Trie) search(word string) []int { node := this for _, c := range word { c -= 'a' if node.children[c] == nil { return []int{} } node = node.children[c] } return node.v } func wordSquares(words []string) [][]string { trie := newTrie() for i, w := range words { trie.insert(w, i) } ans := [][]string{} var dfs func([]string) dfs = func(t []string) { if len(t) == len(words[0]) { cp := make([]string, len(t)) copy(cp, t) ans = append(ans, cp) return } idx := len(t) pref := []byte{} for _, v := range t { pref = append(pref, v[idx]) } indexes := trie.search(string(pref)) for _, i := range indexes { t = append(t, words[i]) dfs(t) t = t[:len(t)-1] } } for _, w := range words { dfs([]string{w}) } return ans }
425
Word Squares
Hard
<p>Given an array of <strong>unique</strong> strings <code>words</code>, return <em>all the </em><strong><a href="https://en.wikipedia.org/wiki/Word_square" target="_blank">word squares</a></strong><em> you can build from </em><code>words</code>. The same word from <code>words</code> can be used <strong>multiple times</strong>. You can return the answer in <strong>any order</strong>.</p> <p>A sequence of strings forms a valid <strong>word square</strong> if the <code>k<sup>th</sup></code> row and column read the same string, where <code>0 &lt;= k &lt; max(numRows, numColumns)</code>.</p> <ul> <li>For example, the word sequence <code>[&quot;ball&quot;,&quot;area&quot;,&quot;lead&quot;,&quot;lady&quot;]</code> forms a word square because each word reads the same both horizontally and vertically.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;area&quot;,&quot;lead&quot;,&quot;wall&quot;,&quot;lady&quot;,&quot;ball&quot;] <strong>Output:</strong> [[&quot;ball&quot;,&quot;area&quot;,&quot;lead&quot;,&quot;lady&quot;],[&quot;wall&quot;,&quot;area&quot;,&quot;lead&quot;,&quot;lady&quot;]] <strong>Explanation:</strong> The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abat&quot;,&quot;baba&quot;,&quot;atan&quot;,&quot;atal&quot;] <strong>Output:</strong> [[&quot;baba&quot;,&quot;abat&quot;,&quot;baba&quot;,&quot;atal&quot;],[&quot;baba&quot;,&quot;abat&quot;,&quot;baba&quot;,&quot;atan&quot;]] <strong>Explanation:</strong> The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 4</code></li> <li>All <code>words[i]</code> have the same length.</li> <li><code>words[i]</code> consists of only lowercase English letters.</li> <li>All <code>words[i]</code> are <strong>unique</strong>.</li> </ul>
Trie; Array; String; Backtracking
Java
class Trie { Trie[] children = new Trie[26]; List<Integer> v = new ArrayList<>(); void insert(String word, int i) { Trie node = this; for (char c : word.toCharArray()) { c -= 'a'; if (node.children[c] == null) { node.children[c] = new Trie(); } node = node.children[c]; node.v.add(i); } } List<Integer> search(String pref) { Trie node = this; for (char c : pref.toCharArray()) { c -= 'a'; if (node.children[c] == null) { return Collections.emptyList(); } node = node.children[c]; } return node.v; } } class Solution { private Trie trie = new Trie(); private String[] words; private List<List<String>> ans = new ArrayList<>(); public List<List<String>> wordSquares(String[] words) { this.words = words; for (int i = 0; i < words.length; ++i) { trie.insert(words[i], i); } List<String> t = new ArrayList<>(); for (String w : words) { t.add(w); dfs(t); t.remove(t.size() - 1); } return ans; } private void dfs(List<String> t) { if (t.size() == words[0].length()) { ans.add(new ArrayList<>(t)); return; } int idx = t.size(); StringBuilder pref = new StringBuilder(); for (String x : t) { pref.append(x.charAt(idx)); } List<Integer> indexes = trie.search(pref.toString()); for (int i : indexes) { t.add(words[i]); dfs(t); t.remove(t.size() - 1); } } }
425
Word Squares
Hard
<p>Given an array of <strong>unique</strong> strings <code>words</code>, return <em>all the </em><strong><a href="https://en.wikipedia.org/wiki/Word_square" target="_blank">word squares</a></strong><em> you can build from </em><code>words</code>. The same word from <code>words</code> can be used <strong>multiple times</strong>. You can return the answer in <strong>any order</strong>.</p> <p>A sequence of strings forms a valid <strong>word square</strong> if the <code>k<sup>th</sup></code> row and column read the same string, where <code>0 &lt;= k &lt; max(numRows, numColumns)</code>.</p> <ul> <li>For example, the word sequence <code>[&quot;ball&quot;,&quot;area&quot;,&quot;lead&quot;,&quot;lady&quot;]</code> forms a word square because each word reads the same both horizontally and vertically.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;area&quot;,&quot;lead&quot;,&quot;wall&quot;,&quot;lady&quot;,&quot;ball&quot;] <strong>Output:</strong> [[&quot;ball&quot;,&quot;area&quot;,&quot;lead&quot;,&quot;lady&quot;],[&quot;wall&quot;,&quot;area&quot;,&quot;lead&quot;,&quot;lady&quot;]] <strong>Explanation:</strong> The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abat&quot;,&quot;baba&quot;,&quot;atan&quot;,&quot;atal&quot;] <strong>Output:</strong> [[&quot;baba&quot;,&quot;abat&quot;,&quot;baba&quot;,&quot;atal&quot;],[&quot;baba&quot;,&quot;abat&quot;,&quot;baba&quot;,&quot;atan&quot;]] <strong>Explanation:</strong> The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 4</code></li> <li>All <code>words[i]</code> have the same length.</li> <li><code>words[i]</code> consists of only lowercase English letters.</li> <li>All <code>words[i]</code> are <strong>unique</strong>.</li> </ul>
Trie; Array; String; Backtracking
Python
class Trie: def __init__(self): self.children = [None] * 26 self.v = [] def insert(self, w, i): node = self for c in w: idx = ord(c) - ord('a') if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] node.v.append(i) def search(self, w): node = self for c in w: idx = ord(c) - ord('a') if node.children[idx] is None: return [] node = node.children[idx] return node.v class Solution: def wordSquares(self, words: List[str]) -> List[List[str]]: def dfs(t): if len(t) == len(words[0]): ans.append(t[:]) return idx = len(t) pref = [v[idx] for v in t] indexes = trie.search(''.join(pref)) for i in indexes: t.append(words[i]) dfs(t) t.pop() trie = Trie() ans = [] for i, w in enumerate(words): trie.insert(w, i) for w in words: dfs([w]) return ans
426
Convert Binary Search Tree to Sorted Doubly Linked List
Medium
<p>Convert a <strong>Binary Search Tree</strong> to a sorted <strong>Circular Doubly-Linked List</strong> in place.</p> <p>You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.</p> <p>We want to do the transformation <strong>in place</strong>. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdlloriginalbst.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [4,2,5,1,3] <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdllreturndll.png" style="width: 100%; max-width: 450px;" /> <strong>Output:</strong> [1,2,3,4,5] <strong>Explanation:</strong> The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship. <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdllreturnbst.png" style="width: 100%; max-width: 450px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [1,2,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>All the values of the tree are <strong>unique</strong>.</li> </ul>
Stack; Tree; Depth-First Search; Binary Search Tree; Linked List; Binary Tree; Doubly-Linked List
C++
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; */ class Solution { public: Node* prev; Node* head; Node* treeToDoublyList(Node* root) { if (!root) return nullptr; prev = nullptr; head = nullptr; dfs(root); prev->right = head; head->left = prev; return head; } void dfs(Node* root) { if (!root) return; dfs(root->left); if (prev) { prev->right = root; root->left = prev; } else head = root; prev = root; dfs(root->right); } };
426
Convert Binary Search Tree to Sorted Doubly Linked List
Medium
<p>Convert a <strong>Binary Search Tree</strong> to a sorted <strong>Circular Doubly-Linked List</strong> in place.</p> <p>You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.</p> <p>We want to do the transformation <strong>in place</strong>. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdlloriginalbst.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [4,2,5,1,3] <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdllreturndll.png" style="width: 100%; max-width: 450px;" /> <strong>Output:</strong> [1,2,3,4,5] <strong>Explanation:</strong> The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship. <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdllreturnbst.png" style="width: 100%; max-width: 450px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [1,2,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>All the values of the tree are <strong>unique</strong>.</li> </ul>
Stack; Tree; Depth-First Search; Binary Search Tree; Linked List; Binary Tree; Doubly-Linked List
Go
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * } */ func treeToDoublyList(root *Node) *Node { if root == nil { return root } var prev, head *Node var dfs func(root *Node) dfs = func(root *Node) { if root == nil { return } dfs(root.Left) if prev != nil { prev.Right = root root.Left = prev } else { head = root } prev = root dfs(root.Right) } dfs(root) prev.Right = head head.Left = prev return head }
426
Convert Binary Search Tree to Sorted Doubly Linked List
Medium
<p>Convert a <strong>Binary Search Tree</strong> to a sorted <strong>Circular Doubly-Linked List</strong> in place.</p> <p>You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.</p> <p>We want to do the transformation <strong>in place</strong>. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdlloriginalbst.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [4,2,5,1,3] <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdllreturndll.png" style="width: 100%; max-width: 450px;" /> <strong>Output:</strong> [1,2,3,4,5] <strong>Explanation:</strong> The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship. <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdllreturnbst.png" style="width: 100%; max-width: 450px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [1,2,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>All the values of the tree are <strong>unique</strong>.</li> </ul>
Stack; Tree; Depth-First Search; Binary Search Tree; Linked List; Binary Tree; Doubly-Linked List
Java
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node() {} public Node(int _val) { val = _val; } public Node(int _val,Node _left,Node _right) { val = _val; left = _left; right = _right; } }; */ class Solution { private Node prev; private Node head; public Node treeToDoublyList(Node root) { if (root == null) { return null; } prev = null; head = null; dfs(root); prev.right = head; head.left = prev; return head; } private void dfs(Node root) { if (root == null) { return; } dfs(root.left); if (prev != null) { prev.right = root; root.left = prev; } else { head = root; } prev = root; dfs(root.right); } }
426
Convert Binary Search Tree to Sorted Doubly Linked List
Medium
<p>Convert a <strong>Binary Search Tree</strong> to a sorted <strong>Circular Doubly-Linked List</strong> in place.</p> <p>You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.</p> <p>We want to do the transformation <strong>in place</strong>. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdlloriginalbst.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [4,2,5,1,3] <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdllreturndll.png" style="width: 100%; max-width: 450px;" /> <strong>Output:</strong> [1,2,3,4,5] <strong>Explanation:</strong> The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship. <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdllreturnbst.png" style="width: 100%; max-width: 450px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [1,2,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>All the values of the tree are <strong>unique</strong>.</li> </ul>
Stack; Tree; Depth-First Search; Binary Search Tree; Linked List; Binary Tree; Doubly-Linked List
JavaScript
/** * // Definition for a Node. * function Node(val, left, right) { * this.val = val; * this.left = left; * this.right = right; * }; */ /** * @param {Node} root * @return {Node} */ var treeToDoublyList = function (root) { if (!root) return root; let prev = null; let head = null; function dfs(root) { if (!root) return; dfs(root.left); if (prev) { prev.right = root; root.left = prev; } else { head = root; } prev = root; dfs(root.right); } dfs(root); prev.right = head; head.left = prev; return head; };
426
Convert Binary Search Tree to Sorted Doubly Linked List
Medium
<p>Convert a <strong>Binary Search Tree</strong> to a sorted <strong>Circular Doubly-Linked List</strong> in place.</p> <p>You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.</p> <p>We want to do the transformation <strong>in place</strong>. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdlloriginalbst.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [4,2,5,1,3] <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdllreturndll.png" style="width: 100%; max-width: 450px;" /> <strong>Output:</strong> [1,2,3,4,5] <strong>Explanation:</strong> The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship. <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/images/bstdllreturnbst.png" style="width: 100%; max-width: 450px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [1,2,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li>All the values of the tree are <strong>unique</strong>.</li> </ul>
Stack; Tree; Depth-First Search; Binary Search Tree; Linked List; Binary Tree; Doubly-Linked List
Python
""" # Definition for a Node. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right """ class Solution: def treeToDoublyList(self, root: 'Optional[Node]') -> 'Optional[Node]': def dfs(root): if root is None: return nonlocal prev, head dfs(root.left) if prev: prev.right = root root.left = prev else: head = root prev = root dfs(root.right) if root is None: return None head = prev = None dfs(root) prev.right = head head.left = prev return head
427
Construct Quad Tree
Medium
<p>Given a <code>n * n</code> matrix <code>grid</code> of <code>0&#39;s</code> and <code>1&#39;s</code> only. We want to represent <code>grid</code> with a Quad-Tree.</p> <p>Return <em>the root of the Quad-Tree representing </em><code>grid</code>.</p> <p>A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:</p> <ul> <li><code>val</code>: True if the node represents a grid of 1&#39;s or False if the node represents a grid of 0&#39;s. Notice that you can assign the <code>val</code> to True or False when <code>isLeaf</code> is False, and both are accepted in the answer.</li> <li><code>isLeaf</code>: True if the node is a leaf node on the tree or False if the node has four children.</li> </ul> <pre> class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; }</pre> <p>We can construct a Quad-Tree from a two-dimensional area using the following steps:</p> <ol> <li>If the current grid has the same value (i.e all <code>1&#39;s</code> or all <code>0&#39;s</code>) set <code>isLeaf</code> True and set <code>val</code> to the value of the grid and set the four children to Null and stop.</li> <li>If the current grid has different values, set <code>isLeaf</code> to False and set <code>val</code> to any value and divide the current grid into four sub-grids as shown in the photo.</li> <li>Recurse for each of the children with the proper sub-grid.</li> </ol> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/new_top.png" style="width: 777px; height: 181px;" /> <p>If you want to know more about the Quad-Tree, you can refer to the <a href="https://en.wikipedia.org/wiki/Quadtree">wiki</a>.</p> <p><strong>Quad-Tree format:</strong></p> <p>You don&#39;t need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where <code>null</code> signifies a path terminator where no node exists below.</p> <p>It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list <code>[isLeaf, val]</code>.</p> <p>If the value of <code>isLeaf</code> or <code>val</code> is True we represent it as <strong>1</strong> in the list <code>[isLeaf, val]</code> and if the value of <code>isLeaf</code> or <code>val</code> is False we represent it as <strong>0</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/0400-0499/0427.Construct%20Quad%20Tree/images/grid1.png" style="width: 777px; height: 99px;" /> <pre> <strong>Input:</strong> grid = [[0,1],[1,0]] <strong>Output:</strong> [[0,1],[1,0],[1,1],[1,1],[1,0]] <strong>Explanation:</strong> The explanation of this example is shown below: Notice that 0 represents False and 1 represents True in the photo representing the Quad-Tree. <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e1tree.png" style="width: 777px; height: 186px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e2mat.png" style="width: 777px; height: 343px;" /></p> <pre> <strong>Input:</strong> grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]] <strong>Output:</strong> [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]] <strong>Explanation:</strong> All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e2tree.png" style="width: 777px; height: 328px;" /> </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == grid[i].length</code></li> <li><code>n == 2<sup>x</sup></code> where <code>0 &lt;= x &lt;= 6</code></li> </ul>
Tree; Array; Divide and Conquer; Matrix
C++
/* // Definition for a QuadTree node. class Node { public: bool val; bool isLeaf; Node* topLeft; Node* topRight; Node* bottomLeft; Node* bottomRight; Node() { val = false; isLeaf = false; topLeft = NULL; topRight = NULL; bottomLeft = NULL; bottomRight = NULL; } Node(bool _val, bool _isLeaf) { val = _val; isLeaf = _isLeaf; topLeft = NULL; topRight = NULL; bottomLeft = NULL; bottomRight = NULL; } Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { val = _val; isLeaf = _isLeaf; topLeft = _topLeft; topRight = _topRight; bottomLeft = _bottomLeft; bottomRight = _bottomRight; } }; */ class Solution { public: Node* construct(vector<vector<int>>& grid) { return dfs(0, 0, grid.size() - 1, grid[0].size() - 1, grid); } Node* dfs(int a, int b, int c, int d, vector<vector<int>>& grid) { int zero = 0, one = 0; for (int i = a; i <= c; ++i) { for (int j = b; j <= d; ++j) { if (grid[i][j]) one = 1; else zero = 1; } } bool isLeaf = zero + one == 1; bool val = isLeaf && one; Node* node = new Node(val, isLeaf); if (isLeaf) return node; node->topLeft = dfs(a, b, (a + c) / 2, (b + d) / 2, grid); node->topRight = dfs(a, (b + d) / 2 + 1, (a + c) / 2, d, grid); node->bottomLeft = dfs((a + c) / 2 + 1, b, c, (b + d) / 2, grid); node->bottomRight = dfs((a + c) / 2 + 1, (b + d) / 2 + 1, c, d, grid); return node; } };
427
Construct Quad Tree
Medium
<p>Given a <code>n * n</code> matrix <code>grid</code> of <code>0&#39;s</code> and <code>1&#39;s</code> only. We want to represent <code>grid</code> with a Quad-Tree.</p> <p>Return <em>the root of the Quad-Tree representing </em><code>grid</code>.</p> <p>A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:</p> <ul> <li><code>val</code>: True if the node represents a grid of 1&#39;s or False if the node represents a grid of 0&#39;s. Notice that you can assign the <code>val</code> to True or False when <code>isLeaf</code> is False, and both are accepted in the answer.</li> <li><code>isLeaf</code>: True if the node is a leaf node on the tree or False if the node has four children.</li> </ul> <pre> class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; }</pre> <p>We can construct a Quad-Tree from a two-dimensional area using the following steps:</p> <ol> <li>If the current grid has the same value (i.e all <code>1&#39;s</code> or all <code>0&#39;s</code>) set <code>isLeaf</code> True and set <code>val</code> to the value of the grid and set the four children to Null and stop.</li> <li>If the current grid has different values, set <code>isLeaf</code> to False and set <code>val</code> to any value and divide the current grid into four sub-grids as shown in the photo.</li> <li>Recurse for each of the children with the proper sub-grid.</li> </ol> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/new_top.png" style="width: 777px; height: 181px;" /> <p>If you want to know more about the Quad-Tree, you can refer to the <a href="https://en.wikipedia.org/wiki/Quadtree">wiki</a>.</p> <p><strong>Quad-Tree format:</strong></p> <p>You don&#39;t need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where <code>null</code> signifies a path terminator where no node exists below.</p> <p>It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list <code>[isLeaf, val]</code>.</p> <p>If the value of <code>isLeaf</code> or <code>val</code> is True we represent it as <strong>1</strong> in the list <code>[isLeaf, val]</code> and if the value of <code>isLeaf</code> or <code>val</code> is False we represent it as <strong>0</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/0400-0499/0427.Construct%20Quad%20Tree/images/grid1.png" style="width: 777px; height: 99px;" /> <pre> <strong>Input:</strong> grid = [[0,1],[1,0]] <strong>Output:</strong> [[0,1],[1,0],[1,1],[1,1],[1,0]] <strong>Explanation:</strong> The explanation of this example is shown below: Notice that 0 represents False and 1 represents True in the photo representing the Quad-Tree. <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e1tree.png" style="width: 777px; height: 186px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e2mat.png" style="width: 777px; height: 343px;" /></p> <pre> <strong>Input:</strong> grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]] <strong>Output:</strong> [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]] <strong>Explanation:</strong> All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e2tree.png" style="width: 777px; height: 328px;" /> </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == grid[i].length</code></li> <li><code>n == 2<sup>x</sup></code> where <code>0 &lt;= x &lt;= 6</code></li> </ul>
Tree; Array; Divide and Conquer; Matrix
Go
/** * Definition for a QuadTree node. * type Node struct { * Val bool * IsLeaf bool * TopLeft *Node * TopRight *Node * BottomLeft *Node * BottomRight *Node * } */ func construct(grid [][]int) *Node { var dfs func(a, b, c, d int) *Node dfs = func(a, b, c, d int) *Node { zero, one := 0, 0 for i := a; i <= c; i++ { for j := b; j <= d; j++ { if grid[i][j] == 0 { zero = 1 } else { one = 1 } } } isLeaf := zero+one == 1 val := isLeaf && one == 1 node := &Node{Val: val, IsLeaf: isLeaf} if isLeaf { return node } node.TopLeft = dfs(a, b, (a+c)/2, (b+d)/2) node.TopRight = dfs(a, (b+d)/2+1, (a+c)/2, d) node.BottomLeft = dfs((a+c)/2+1, b, c, (b+d)/2) node.BottomRight = dfs((a+c)/2+1, (b+d)/2+1, c, d) return node } return dfs(0, 0, len(grid)-1, len(grid[0])-1) }
427
Construct Quad Tree
Medium
<p>Given a <code>n * n</code> matrix <code>grid</code> of <code>0&#39;s</code> and <code>1&#39;s</code> only. We want to represent <code>grid</code> with a Quad-Tree.</p> <p>Return <em>the root of the Quad-Tree representing </em><code>grid</code>.</p> <p>A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:</p> <ul> <li><code>val</code>: True if the node represents a grid of 1&#39;s or False if the node represents a grid of 0&#39;s. Notice that you can assign the <code>val</code> to True or False when <code>isLeaf</code> is False, and both are accepted in the answer.</li> <li><code>isLeaf</code>: True if the node is a leaf node on the tree or False if the node has four children.</li> </ul> <pre> class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; }</pre> <p>We can construct a Quad-Tree from a two-dimensional area using the following steps:</p> <ol> <li>If the current grid has the same value (i.e all <code>1&#39;s</code> or all <code>0&#39;s</code>) set <code>isLeaf</code> True and set <code>val</code> to the value of the grid and set the four children to Null and stop.</li> <li>If the current grid has different values, set <code>isLeaf</code> to False and set <code>val</code> to any value and divide the current grid into four sub-grids as shown in the photo.</li> <li>Recurse for each of the children with the proper sub-grid.</li> </ol> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/new_top.png" style="width: 777px; height: 181px;" /> <p>If you want to know more about the Quad-Tree, you can refer to the <a href="https://en.wikipedia.org/wiki/Quadtree">wiki</a>.</p> <p><strong>Quad-Tree format:</strong></p> <p>You don&#39;t need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where <code>null</code> signifies a path terminator where no node exists below.</p> <p>It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list <code>[isLeaf, val]</code>.</p> <p>If the value of <code>isLeaf</code> or <code>val</code> is True we represent it as <strong>1</strong> in the list <code>[isLeaf, val]</code> and if the value of <code>isLeaf</code> or <code>val</code> is False we represent it as <strong>0</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/0400-0499/0427.Construct%20Quad%20Tree/images/grid1.png" style="width: 777px; height: 99px;" /> <pre> <strong>Input:</strong> grid = [[0,1],[1,0]] <strong>Output:</strong> [[0,1],[1,0],[1,1],[1,1],[1,0]] <strong>Explanation:</strong> The explanation of this example is shown below: Notice that 0 represents False and 1 represents True in the photo representing the Quad-Tree. <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e1tree.png" style="width: 777px; height: 186px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e2mat.png" style="width: 777px; height: 343px;" /></p> <pre> <strong>Input:</strong> grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]] <strong>Output:</strong> [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]] <strong>Explanation:</strong> All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e2tree.png" style="width: 777px; height: 328px;" /> </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == grid[i].length</code></li> <li><code>n == 2<sup>x</sup></code> where <code>0 &lt;= x &lt;= 6</code></li> </ul>
Tree; Array; Divide and Conquer; Matrix
Java
/* // Definition for a QuadTree node. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; public Node() { this.val = false; this.isLeaf = false; this.topLeft = null; this.topRight = null; this.bottomLeft = null; this.bottomRight = null; } public Node(boolean val, boolean isLeaf) { this.val = val; this.isLeaf = isLeaf; this.topLeft = null; this.topRight = null; this.bottomLeft = null; this.bottomRight = null; } public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) { this.val = val; this.isLeaf = isLeaf; this.topLeft = topLeft; this.topRight = topRight; this.bottomLeft = bottomLeft; this.bottomRight = bottomRight; } }; */ class Solution { public Node construct(int[][] grid) { return dfs(0, 0, grid.length - 1, grid[0].length - 1, grid); } private Node dfs(int a, int b, int c, int d, int[][] grid) { int zero = 0, one = 0; for (int i = a; i <= c; ++i) { for (int j = b; j <= d; ++j) { if (grid[i][j] == 0) { zero = 1; } else { one = 1; } } } boolean isLeaf = zero + one == 1; boolean val = isLeaf && one == 1; Node node = new Node(val, isLeaf); if (isLeaf) { return node; } node.topLeft = dfs(a, b, (a + c) / 2, (b + d) / 2, grid); node.topRight = dfs(a, (b + d) / 2 + 1, (a + c) / 2, d, grid); node.bottomLeft = dfs((a + c) / 2 + 1, b, c, (b + d) / 2, grid); node.bottomRight = dfs((a + c) / 2 + 1, (b + d) / 2 + 1, c, d, grid); return node; } }
427
Construct Quad Tree
Medium
<p>Given a <code>n * n</code> matrix <code>grid</code> of <code>0&#39;s</code> and <code>1&#39;s</code> only. We want to represent <code>grid</code> with a Quad-Tree.</p> <p>Return <em>the root of the Quad-Tree representing </em><code>grid</code>.</p> <p>A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:</p> <ul> <li><code>val</code>: True if the node represents a grid of 1&#39;s or False if the node represents a grid of 0&#39;s. Notice that you can assign the <code>val</code> to True or False when <code>isLeaf</code> is False, and both are accepted in the answer.</li> <li><code>isLeaf</code>: True if the node is a leaf node on the tree or False if the node has four children.</li> </ul> <pre> class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; }</pre> <p>We can construct a Quad-Tree from a two-dimensional area using the following steps:</p> <ol> <li>If the current grid has the same value (i.e all <code>1&#39;s</code> or all <code>0&#39;s</code>) set <code>isLeaf</code> True and set <code>val</code> to the value of the grid and set the four children to Null and stop.</li> <li>If the current grid has different values, set <code>isLeaf</code> to False and set <code>val</code> to any value and divide the current grid into four sub-grids as shown in the photo.</li> <li>Recurse for each of the children with the proper sub-grid.</li> </ol> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/new_top.png" style="width: 777px; height: 181px;" /> <p>If you want to know more about the Quad-Tree, you can refer to the <a href="https://en.wikipedia.org/wiki/Quadtree">wiki</a>.</p> <p><strong>Quad-Tree format:</strong></p> <p>You don&#39;t need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where <code>null</code> signifies a path terminator where no node exists below.</p> <p>It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list <code>[isLeaf, val]</code>.</p> <p>If the value of <code>isLeaf</code> or <code>val</code> is True we represent it as <strong>1</strong> in the list <code>[isLeaf, val]</code> and if the value of <code>isLeaf</code> or <code>val</code> is False we represent it as <strong>0</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/0400-0499/0427.Construct%20Quad%20Tree/images/grid1.png" style="width: 777px; height: 99px;" /> <pre> <strong>Input:</strong> grid = [[0,1],[1,0]] <strong>Output:</strong> [[0,1],[1,0],[1,1],[1,1],[1,0]] <strong>Explanation:</strong> The explanation of this example is shown below: Notice that 0 represents False and 1 represents True in the photo representing the Quad-Tree. <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e1tree.png" style="width: 777px; height: 186px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e2mat.png" style="width: 777px; height: 343px;" /></p> <pre> <strong>Input:</strong> grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]] <strong>Output:</strong> [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]] <strong>Explanation:</strong> All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0427.Construct%20Quad%20Tree/images/e2tree.png" style="width: 777px; height: 328px;" /> </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == grid[i].length</code></li> <li><code>n == 2<sup>x</sup></code> where <code>0 &lt;= x &lt;= 6</code></li> </ul>
Tree; Array; Divide and Conquer; Matrix
Python
""" # Definition for a QuadTree node. class Node: def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): self.val = val self.isLeaf = isLeaf self.topLeft = topLeft self.topRight = topRight self.bottomLeft = bottomLeft self.bottomRight = bottomRight """ class Solution: def construct(self, grid: List[List[int]]) -> 'Node': def dfs(a, b, c, d): zero = one = 0 for i in range(a, c + 1): for j in range(b, d + 1): if grid[i][j] == 0: zero = 1 else: one = 1 isLeaf = zero + one == 1 val = isLeaf and one if isLeaf: return Node(grid[a][b], True) topLeft = dfs(a, b, (a + c) // 2, (b + d) // 2) topRight = dfs(a, (b + d) // 2 + 1, (a + c) // 2, d) bottomLeft = dfs((a + c) // 2 + 1, b, c, (b + d) // 2) bottomRight = dfs((a + c) // 2 + 1, (b + d) // 2 + 1, c, d) return Node(val, isLeaf, topLeft, topRight, bottomLeft, bottomRight) return dfs(0, 0, len(grid) - 1, len(grid[0]) - 1)
429
N-ary Tree Level Order Traversal
Medium
<p>Given an n-ary tree, return the <em>level order</em> traversal of its nodes&#39; values.</p> <p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [[1],[3,2,4],[5,6]] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The height of the n-ary tree is less than or equal to <code>1000</code></li> <li>The total number of nodes is between <code>[0, 10<sup>4</sup>]</code></li> </ul>
Tree; Breadth-First Search
C++
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: vector<vector<int>> levelOrder(Node* root) { vector<vector<int>> ans; if (!root) { return ans; } queue<Node*> q{{root}}; while (!q.empty()) { vector<int> t; for (int n = q.size(); n; --n) { root = q.front(); q.pop(); t.push_back(root->val); for (auto& child : root->children) { q.push(child); } } ans.push_back(t); } return ans; } };
429
N-ary Tree Level Order Traversal
Medium
<p>Given an n-ary tree, return the <em>level order</em> traversal of its nodes&#39; values.</p> <p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [[1],[3,2,4],[5,6]] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The height of the n-ary tree is less than or equal to <code>1000</code></li> <li>The total number of nodes is between <code>[0, 10<sup>4</sup>]</code></li> </ul>
Tree; Breadth-First Search
Go
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */ func levelOrder(root *Node) (ans [][]int) { if root == nil { return } q := []*Node{root} for len(q) > 0 { var t []int for n := len(q); n > 0; n-- { root = q[0] q = q[1:] t = append(t, root.Val) for _, child := range root.Children { q = append(q, child) } } ans = append(ans, t) } return }
429
N-ary Tree Level Order Traversal
Medium
<p>Given an n-ary tree, return the <em>level order</em> traversal of its nodes&#39; values.</p> <p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [[1],[3,2,4],[5,6]] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The height of the n-ary tree is less than or equal to <code>1000</code></li> <li>The total number of nodes is between <code>[0, 10<sup>4</sup>]</code></li> </ul>
Tree; Breadth-First Search
Java
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */ class Solution { public List<List<Integer>> levelOrder(Node root) { List<List<Integer>> ans = new ArrayList<>(); if (root == null) { return ans; } Deque<Node> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { List<Integer> t = new ArrayList<>(); for (int n = q.size(); n > 0; --n) { root = q.poll(); t.add(root.val); q.addAll(root.children); } ans.add(t); } return ans; } }
429
N-ary Tree Level Order Traversal
Medium
<p>Given an n-ary tree, return the <em>level order</em> traversal of its nodes&#39; values.</p> <p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [[1],[3,2,4],[5,6]] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The height of the n-ary tree is less than or equal to <code>1000</code></li> <li>The total number of nodes is between <code>[0, 10<sup>4</sup>]</code></li> </ul>
Tree; Breadth-First Search
Python
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: ans = [] if root is None: return ans q = deque([root]) while q: t = [] for _ in range(len(q)): root = q.popleft() t.append(root.val) q.extend(root.children) ans.append(t) return ans
429
N-ary Tree Level Order Traversal
Medium
<p>Given an n-ary tree, return the <em>level order</em> traversal of its nodes&#39; values.</p> <p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/images/narytreeexample.png" style="width: 100%; max-width: 300px;" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [[1],[3,2,4],[5,6]] </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/images/sample_4_964.png" style="width: 296px; height: 241px;" /></p> <pre> <strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The height of the n-ary tree is less than or equal to <code>1000</code></li> <li>The total number of nodes is between <code>[0, 10<sup>4</sup>]</code></li> </ul>
Tree; Breadth-First Search
TypeScript
/** * Definition for node. * class Node { * val: number * children: Node[] * constructor(val?: number) { * this.val = (val===undefined ? 0 : val) * this.children = [] * } * } */ function levelOrder(root: Node | null): number[][] { const ans: number[][] = []; if (!root) { return ans; } const q: Node[] = [root]; while (q.length) { const qq: Node[] = []; const t: number[] = []; for (const { val, children } of q) { qq.push(...children); t.push(val); } ans.push(t); q.splice(0, q.length, ...qq); } return ans; }
430
Flatten a Multilevel Doubly Linked List
Medium
<p>You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional <strong>child pointer</strong>. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a <strong>multilevel data structure</strong> as shown in the example below.</p> <p>Given the <code>head</code> of the first level of the list, <strong>flatten</strong> the list so that all the nodes appear in a single-level, doubly linked list. Let <code>curr</code> be a node with a child list. The nodes in the child list should appear <strong>after</strong> <code>curr</code> and <strong>before</strong> <code>curr.next</code> in the flattened list.</p> <p>Return <em>the </em><code>head</code><em> of the flattened list. The nodes in the list must have <strong>all</strong> of their child pointers set to </em><code>null</code>.</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/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/flatten11.jpg" style="width: 700px; height: 339px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] <strong>Output:</strong> [1,2,3,7,8,11,12,9,10,4,5,6] <strong>Explanation:</strong> The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/flatten12.jpg" style="width: 1000px; height: 69px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/flatten2.1jpg" style="width: 200px; height: 200px;" /> <pre> <strong>Input:</strong> head = [1,2,null,3] <strong>Output:</strong> [1,3,2] <strong>Explanation:</strong> The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/list.jpg" style="width: 300px; height: 87px;" /> </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] <strong>Explanation:</strong> There could be empty list in the input. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of Nodes will not exceed <code>1000</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>How the multilevel linked list is represented in test cases:</strong></p> <p>We use the multilevel linked list from <strong>Example 1</strong> above:</p> <pre> 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL</pre> <p>The serialization of each level is as follows:</p> <pre> [1,2,3,4,5,6,null] [7,8,9,10,null] [11,12,null] </pre> <p>To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:</p> <pre> [1, 2, 3, 4, 5, 6, null] | [null, null, 7, 8, 9, 10, null] | [ null, 11, 12, null] </pre> <p>Merging the serialization of each level and removing trailing nulls we obtain:</p> <pre> [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] </pre>
Depth-First Search; Linked List; Doubly-Linked List
C++
/* // Definition for a Node. class Node { public: int val; Node* prev; Node* next; Node* child; }; */ class Solution { public: Node* flatten(Node* head) { flattenGetTail(head); return head; } Node* flattenGetTail(Node* head) { Node* cur = head; Node* tail = nullptr; while (cur) { Node* next = cur->next; if (cur->child) { Node* child = cur->child; Node* childTail = flattenGetTail(cur->child); cur->child = nullptr; cur->next = child; child->prev = cur; childTail->next = next; if (next) next->prev = childTail; tail = childTail; } else { tail = cur; } cur = next; } return tail; } };
430
Flatten a Multilevel Doubly Linked List
Medium
<p>You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional <strong>child pointer</strong>. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a <strong>multilevel data structure</strong> as shown in the example below.</p> <p>Given the <code>head</code> of the first level of the list, <strong>flatten</strong> the list so that all the nodes appear in a single-level, doubly linked list. Let <code>curr</code> be a node with a child list. The nodes in the child list should appear <strong>after</strong> <code>curr</code> and <strong>before</strong> <code>curr.next</code> in the flattened list.</p> <p>Return <em>the </em><code>head</code><em> of the flattened list. The nodes in the list must have <strong>all</strong> of their child pointers set to </em><code>null</code>.</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/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/flatten11.jpg" style="width: 700px; height: 339px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] <strong>Output:</strong> [1,2,3,7,8,11,12,9,10,4,5,6] <strong>Explanation:</strong> The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/flatten12.jpg" style="width: 1000px; height: 69px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/flatten2.1jpg" style="width: 200px; height: 200px;" /> <pre> <strong>Input:</strong> head = [1,2,null,3] <strong>Output:</strong> [1,3,2] <strong>Explanation:</strong> The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/list.jpg" style="width: 300px; height: 87px;" /> </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] <strong>Explanation:</strong> There could be empty list in the input. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of Nodes will not exceed <code>1000</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>How the multilevel linked list is represented in test cases:</strong></p> <p>We use the multilevel linked list from <strong>Example 1</strong> above:</p> <pre> 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL</pre> <p>The serialization of each level is as follows:</p> <pre> [1,2,3,4,5,6,null] [7,8,9,10,null] [11,12,null] </pre> <p>To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:</p> <pre> [1, 2, 3, 4, 5, 6, null] | [null, null, 7, 8, 9, 10, null] | [ null, 11, 12, null] </pre> <p>Merging the serialization of each level and removing trailing nulls we obtain:</p> <pre> [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] </pre>
Depth-First Search; Linked List; Doubly-Linked List
Java
/* // Definition for a Node. class Node { public int val; public Node prev; public Node next; public Node child; }; */ class Solution { public Node flatten(Node head) { if (head == null) { return null; } Node dummy = new Node(); dummy.next = head; preorder(dummy, head); dummy.next.prev = null; return dummy.next; } private Node preorder(Node pre, Node cur) { if (cur == null) { return pre; } cur.prev = pre; pre.next = cur; Node t = cur.next; Node tail = preorder(cur, cur.child); cur.child = null; return preorder(tail, t); } }
430
Flatten a Multilevel Doubly Linked List
Medium
<p>You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional <strong>child pointer</strong>. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a <strong>multilevel data structure</strong> as shown in the example below.</p> <p>Given the <code>head</code> of the first level of the list, <strong>flatten</strong> the list so that all the nodes appear in a single-level, doubly linked list. Let <code>curr</code> be a node with a child list. The nodes in the child list should appear <strong>after</strong> <code>curr</code> and <strong>before</strong> <code>curr.next</code> in the flattened list.</p> <p>Return <em>the </em><code>head</code><em> of the flattened list. The nodes in the list must have <strong>all</strong> of their child pointers set to </em><code>null</code>.</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/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/flatten11.jpg" style="width: 700px; height: 339px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] <strong>Output:</strong> [1,2,3,7,8,11,12,9,10,4,5,6] <strong>Explanation:</strong> The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/flatten12.jpg" style="width: 1000px; height: 69px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/flatten2.1jpg" style="width: 200px; height: 200px;" /> <pre> <strong>Input:</strong> head = [1,2,null,3] <strong>Output:</strong> [1,3,2] <strong>Explanation:</strong> The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/images/list.jpg" style="width: 300px; height: 87px;" /> </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] <strong>Explanation:</strong> There could be empty list in the input. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of Nodes will not exceed <code>1000</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>How the multilevel linked list is represented in test cases:</strong></p> <p>We use the multilevel linked list from <strong>Example 1</strong> above:</p> <pre> 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL</pre> <p>The serialization of each level is as follows:</p> <pre> [1,2,3,4,5,6,null] [7,8,9,10,null] [11,12,null] </pre> <p>To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:</p> <pre> [1, 2, 3, 4, 5, 6, null] | [null, null, 7, 8, 9, 10, null] | [ null, 11, 12, null] </pre> <p>Merging the serialization of each level and removing trailing nulls we obtain:</p> <pre> [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] </pre>
Depth-First Search; Linked List; Doubly-Linked List
Python
""" # Definition for a Node. class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child """ class Solution: def flatten(self, head: 'Node') -> 'Node': def preorder(pre, cur): if cur is None: return pre cur.prev = pre pre.next = cur t = cur.next tail = preorder(cur, cur.child) cur.child = None return preorder(tail, t) if head is None: return None dummy = Node(0, None, head, None) preorder(dummy, head) dummy.next.prev = None return dummy.next
431
Encode N-ary Tree to Binary Tree
Hard
<p>Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-nary tree structure.</p> <p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See following example).</em></p> <p>For example, you may encode the following <code>3-ary</code> tree to a binary tree in this way:</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0431.Encode%20N-ary%20Tree%20to%20Binary%20Tree/images/narytreebinarytreeexample.png" style="width: 100%; max-width: 640px" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] </pre> <p>Note that the above is just an example which <em>might or might not</em> work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,null,3,2,4,null,5,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code></li> <li>Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; Binary Tree
C++
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes an n-ary tree to a binary tree. TreeNode* encode(Node* root) { if (root == nullptr) { return nullptr; } TreeNode* node = new TreeNode(root->val); if (root->children.empty()) { return node; } TreeNode* left = encode(root->children[0]); node->left = left; for (int i = 1; i < root->children.size(); i++) { left->right = encode(root->children[i]); left = left->right; } return node; } // Decodes your binary tree to an n-ary tree. Node* decode(TreeNode* data) { if (data == nullptr) { return nullptr; } Node* node = new Node(data->val, vector<Node*>()); if (data->left == nullptr) { return node; } TreeNode* left = data->left; while (left != nullptr) { node->children.push_back(decode(left)); left = left->right; } return node; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.decode(codec.encode(root));
431
Encode N-ary Tree to Binary Tree
Hard
<p>Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-nary tree structure.</p> <p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See following example).</em></p> <p>For example, you may encode the following <code>3-ary</code> tree to a binary tree in this way:</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0431.Encode%20N-ary%20Tree%20to%20Binary%20Tree/images/narytreebinarytreeexample.png" style="width: 100%; max-width: 640px" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] </pre> <p>Note that the above is just an example which <em>might or might not</em> work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,null,3,2,4,null,5,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code></li> <li>Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; Binary Tree
Go
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type Codec struct { } func Constructor() *Codec { return &Codec{} } // Encodes an n-ary tree to a binary tree. func (this *Codec) encode(root *Node) *TreeNode { if root == nil { return nil } node := &TreeNode{Val: root.Val} if len(root.Children) == 0 { return node } left := this.encode(root.Children[0]) node.Left = left for i := 1; i < len(root.Children); i++ { left.Right = this.encode(root.Children[i]) left = left.Right } return node } // Decodes your binary tree to an n-ary tree. func (this *Codec) decode(data *TreeNode) *Node { if data == nil { return nil } node := &Node{Val: data.Val, Children: []*Node{}} if data.Left == nil { return node } left := data.Left for left != nil { node.Children = append(node.Children, this.decode(left)) left = left.Right } return node } /** * Your Codec object will be instantiated and called as such: * obj := Constructor(); * bst := obj.encode(root); * ans := obj.decode(bst); */
431
Encode N-ary Tree to Binary Tree
Hard
<p>Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-nary tree structure.</p> <p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See following example).</em></p> <p>For example, you may encode the following <code>3-ary</code> tree to a binary tree in this way:</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0431.Encode%20N-ary%20Tree%20to%20Binary%20Tree/images/narytreebinarytreeexample.png" style="width: 100%; max-width: 640px" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] </pre> <p>Note that the above is just an example which <em>might or might not</em> work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,null,3,2,4,null,5,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code></li> <li>Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; Binary Tree
Java
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Codec { // Encodes an n-ary tree to a binary tree. public TreeNode encode(Node root) { if (root == null) { return null; } TreeNode node = new TreeNode(root.val); if (root.children == null || root.children.isEmpty()) { return node; } TreeNode left = encode(root.children.get(0)); node.left = left; for (int i = 1; i < root.children.size(); i++) { left.right = encode(root.children.get(i)); left = left.right; } return node; } // Decodes your binary tree to an n-ary tree. public Node decode(TreeNode data) { if (data == null) { return null; } Node node = new Node(data.val, new ArrayList<>()); if (data.left == null) { return node; } TreeNode left = data.left; while (left != null) { node.children.add(decode(left)); left = left.right; } return node; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(root));
431
Encode N-ary Tree to Binary Tree
Hard
<p>Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-nary tree structure.</p> <p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See following example).</em></p> <p>For example, you may encode the following <code>3-ary</code> tree to a binary tree in this way:</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0431.Encode%20N-ary%20Tree%20to%20Binary%20Tree/images/narytreebinarytreeexample.png" style="width: 100%; max-width: 640px" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] </pre> <p>Note that the above is just an example which <em>might or might not</em> work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,null,3,2,4,null,5,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code></li> <li>Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; Binary Tree
Python
""" # Definition for a Node. class Node: def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None): self.val = val self.children = children """ """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None """ class Codec: # Encodes an n-ary tree to a binary tree. def encode(self, root: "Optional[Node]") -> Optional[TreeNode]: if root is None: return None node = TreeNode(root.val) if not root.children: return node left = self.encode(root.children[0]) node.left = left for child in root.children[1:]: left.right = self.encode(child) left = left.right return node # Decodes your binary tree to an n-ary tree. def decode(self, data: Optional[TreeNode]) -> "Optional[Node]": if data is None: return None node = Node(data.val, []) if data.left is None: return node left = data.left while left: node.children.append(self.decode(left)) left = left.right return node # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(root))
431
Encode N-ary Tree to Binary Tree
Hard
<p>Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-nary tree structure.</p> <p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See following example).</em></p> <p>For example, you may encode the following <code>3-ary</code> tree to a binary tree in this way:</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0431.Encode%20N-ary%20Tree%20to%20Binary%20Tree/images/narytreebinarytreeexample.png" style="width: 100%; max-width: 640px" /></p> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,5,6] </pre> <p>Note that the above is just an example which <em>might or might not</em> work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> root = [1,null,3,2,4,null,5,6] <strong>Output:</strong> [1,null,3,2,4,null,5,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] <strong>Output:</strong> [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The height of the n-ary tree is less than or equal to <code>1000</code></li> <li>Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; Binary Tree
TypeScript
/** * Definition for _Node. * class _Node { * val: number * children: _Node[] * * constructor(v: number) { * this.val = v; * this.children = []; * } * } */ /** * 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) * } * } */ class Codec { constructor() {} // Encodes an n-ary tree to a binary tree. serialize(root: _Node | null): TreeNode | null { if (root === null) { return null; } const node = new TreeNode(root.val); if (root.children.length === 0) { return node; } let left: TreeNode | null = this.serialize(root.children[0]); node.left = left; for (let i = 1; i < root.children.length; i++) { if (left) { left.right = this.serialize(root.children[i]); left = left.right; } } return node; } // Decodes your binary tree back to an n-ary tree. deserialize(root: TreeNode | null): _Node | null { if (root === null) { return null; } const node = new _Node(root.val); if (root.left === null) { return node; } let left: TreeNode | null = root.left; while (left !== null) { node.children.push(this.deserialize(left)); left = left.right; } return node; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));
432
All O`one Data Structure
Hard
<p>Design a data structure to store the strings&#39; count with the ability to return the strings with minimum and maximum counts.</p> <p>Implement the <code>AllOne</code> class:</p> <ul> <li><code>AllOne()</code> Initializes the object of the data structure.</li> <li><code>inc(String key)</code> Increments the count of the string <code>key</code> by <code>1</code>. If <code>key</code> does not exist in the data structure, insert it with count <code>1</code>.</li> <li><code>dec(String key)</code> Decrements the count of the string <code>key</code> by <code>1</code>. If the count of <code>key</code> is <code>0</code> after the decrement, remove it from the data structure. It is guaranteed that <code>key</code> exists in the data structure before the decrement.</li> <li><code>getMaxKey()</code> Returns one of the keys with the maximal count. If no element exists, return an empty string <code>&quot;&quot;</code>.</li> <li><code>getMinKey()</code> Returns one of the keys with the minimum count. If no element exists, return an empty string <code>&quot;&quot;</code>.</li> </ul> <p><strong>Note</strong> that each function must run in <code>O(1)</code> average time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;AllOne&quot;, &quot;inc&quot;, &quot;inc&quot;, &quot;getMaxKey&quot;, &quot;getMinKey&quot;, &quot;inc&quot;, &quot;getMaxKey&quot;, &quot;getMinKey&quot;] [[], [&quot;hello&quot;], [&quot;hello&quot;], [], [], [&quot;leet&quot;], [], []] <strong>Output</strong> [null, null, null, &quot;hello&quot;, &quot;hello&quot;, null, &quot;hello&quot;, &quot;leet&quot;] <strong>Explanation</strong> AllOne allOne = new AllOne(); allOne.inc(&quot;hello&quot;); allOne.inc(&quot;hello&quot;); allOne.getMaxKey(); // return &quot;hello&quot; allOne.getMinKey(); // return &quot;hello&quot; allOne.inc(&quot;leet&quot;); allOne.getMaxKey(); // return &quot;hello&quot; allOne.getMinKey(); // return &quot;leet&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= key.length &lt;= 10</code></li> <li><code>key</code> consists of lowercase English letters.</li> <li>It is guaranteed that for each call to <code>dec</code>, <code>key</code> is existing in the data structure.</li> <li>At most <code>5 * 10<sup>4</sup></code>&nbsp;calls will be made to <code>inc</code>, <code>dec</code>, <code>getMaxKey</code>, and <code>getMinKey</code>.</li> </ul>
Design; Hash Table; Linked List; Doubly-Linked List
Java
class AllOne { Node root = new Node(); Map<String, Node> nodes = new HashMap<>(); public AllOne() { root.next = root; root.prev = root; } public void inc(String key) { if (!nodes.containsKey(key)) { if (root.next == root || root.next.cnt > 1) { nodes.put(key, root.insert(new Node(key, 1))); } else { root.next.keys.add(key); nodes.put(key, root.next); } } else { Node curr = nodes.get(key); Node next = curr.next; if (next == root || next.cnt > curr.cnt + 1) { nodes.put(key, curr.insert(new Node(key, curr.cnt + 1))); } else { next.keys.add(key); nodes.put(key, next); } curr.keys.remove(key); if (curr.keys.isEmpty()) { curr.remove(); } } } public void dec(String key) { Node curr = nodes.get(key); if (curr.cnt == 1) { nodes.remove(key); } else { Node prev = curr.prev; if (prev == root || prev.cnt < curr.cnt - 1) { nodes.put(key, prev.insert(new Node(key, curr.cnt - 1))); } else { prev.keys.add(key); nodes.put(key, prev); } } curr.keys.remove(key); if (curr.keys.isEmpty()) { curr.remove(); } } public String getMaxKey() { return root.prev.keys.iterator().next(); } public String getMinKey() { return root.next.keys.iterator().next(); } } class Node { Node prev; Node next; int cnt; Set<String> keys = new HashSet<>(); public Node() { this("", 0); } public Node(String key, int cnt) { this.cnt = cnt; keys.add(key); } public Node insert(Node node) { node.prev = this; node.next = this.next; node.prev.next = node; node.next.prev = node; return node; } public void remove() { this.prev.next = this.next; this.next.prev = this.prev; } } /** * Your AllOne object will be instantiated and called as such: * AllOne obj = new AllOne(); * obj.inc(key); * obj.dec(key); * String param_3 = obj.getMaxKey(); * String param_4 = obj.getMinKey(); */
432
All O`one Data Structure
Hard
<p>Design a data structure to store the strings&#39; count with the ability to return the strings with minimum and maximum counts.</p> <p>Implement the <code>AllOne</code> class:</p> <ul> <li><code>AllOne()</code> Initializes the object of the data structure.</li> <li><code>inc(String key)</code> Increments the count of the string <code>key</code> by <code>1</code>. If <code>key</code> does not exist in the data structure, insert it with count <code>1</code>.</li> <li><code>dec(String key)</code> Decrements the count of the string <code>key</code> by <code>1</code>. If the count of <code>key</code> is <code>0</code> after the decrement, remove it from the data structure. It is guaranteed that <code>key</code> exists in the data structure before the decrement.</li> <li><code>getMaxKey()</code> Returns one of the keys with the maximal count. If no element exists, return an empty string <code>&quot;&quot;</code>.</li> <li><code>getMinKey()</code> Returns one of the keys with the minimum count. If no element exists, return an empty string <code>&quot;&quot;</code>.</li> </ul> <p><strong>Note</strong> that each function must run in <code>O(1)</code> average time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;AllOne&quot;, &quot;inc&quot;, &quot;inc&quot;, &quot;getMaxKey&quot;, &quot;getMinKey&quot;, &quot;inc&quot;, &quot;getMaxKey&quot;, &quot;getMinKey&quot;] [[], [&quot;hello&quot;], [&quot;hello&quot;], [], [], [&quot;leet&quot;], [], []] <strong>Output</strong> [null, null, null, &quot;hello&quot;, &quot;hello&quot;, null, &quot;hello&quot;, &quot;leet&quot;] <strong>Explanation</strong> AllOne allOne = new AllOne(); allOne.inc(&quot;hello&quot;); allOne.inc(&quot;hello&quot;); allOne.getMaxKey(); // return &quot;hello&quot; allOne.getMinKey(); // return &quot;hello&quot; allOne.inc(&quot;leet&quot;); allOne.getMaxKey(); // return &quot;hello&quot; allOne.getMinKey(); // return &quot;leet&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= key.length &lt;= 10</code></li> <li><code>key</code> consists of lowercase English letters.</li> <li>It is guaranteed that for each call to <code>dec</code>, <code>key</code> is existing in the data structure.</li> <li>At most <code>5 * 10<sup>4</sup></code>&nbsp;calls will be made to <code>inc</code>, <code>dec</code>, <code>getMaxKey</code>, and <code>getMinKey</code>.</li> </ul>
Design; Hash Table; Linked List; Doubly-Linked List
Python
class Node: def __init__(self, key='', cnt=0): self.prev = None self.next = None self.cnt = cnt self.keys = {key} def insert(self, node): node.prev = self node.next = self.next node.prev.next = node node.next.prev = node return node def remove(self): self.prev.next = self.next self.next.prev = self.prev class AllOne: def __init__(self): self.root = Node() self.root.next = self.root self.root.prev = self.root self.nodes = {} def inc(self, key: str) -> None: root, nodes = self.root, self.nodes if key not in nodes: if root.next == root or root.next.cnt > 1: nodes[key] = root.insert(Node(key, 1)) else: root.next.keys.add(key) nodes[key] = root.next else: curr = nodes[key] next = curr.next if next == root or next.cnt > curr.cnt + 1: nodes[key] = curr.insert(Node(key, curr.cnt + 1)) else: next.keys.add(key) nodes[key] = next curr.keys.discard(key) if not curr.keys: curr.remove() def dec(self, key: str) -> None: root, nodes = self.root, self.nodes curr = nodes[key] if curr.cnt == 1: nodes.pop(key) else: prev = curr.prev if prev == root or prev.cnt < curr.cnt - 1: nodes[key] = prev.insert(Node(key, curr.cnt - 1)) else: prev.keys.add(key) nodes[key] = prev curr.keys.discard(key) if not curr.keys: curr.remove() def getMaxKey(self) -> str: return next(iter(self.root.prev.keys)) def getMinKey(self) -> str: return next(iter(self.root.next.keys)) # Your AllOne object will be instantiated and called as such: # obj = AllOne() # obj.inc(key) # obj.dec(key) # param_3 = obj.getMaxKey() # param_4 = obj.getMinKey()
433
Minimum Genetic Mutation
Medium
<p>A gene string can be represented by an 8-character long string, with choices from <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <p>Suppose we need to investigate a mutation from a gene string <code>startGene</code> to a gene string <code>endGene</code> where one mutation is defined as one single character changed in the gene string.</p> <ul> <li>For example, <code>&quot;AACCGGTT&quot; --&gt; &quot;AACCGGTA&quot;</code> is one mutation.</li> </ul> <p>There is also a gene bank <code>bank</code> that records all the valid gene mutations. A gene must be in <code>bank</code> to make it a valid gene string.</p> <p>Given the two gene strings <code>startGene</code> and <code>endGene</code> and the gene bank <code>bank</code>, return <em>the minimum number of mutations needed to mutate from </em><code>startGene</code><em> to </em><code>endGene</code>. If there is no such a mutation, return <code>-1</code>.</p> <p>Note that the starting point is assumed to be valid, so it might not be included in the bank.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AACCGGTA&quot;, bank = [&quot;AACCGGTA&quot;] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AAACGGTA&quot;, bank = [&quot;AACCGGTA&quot;,&quot;AACCGCTA&quot;,&quot;AAACGGTA&quot;] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= bank.length &lt;= 10</code></li> <li><code>startGene.length == endGene.length == bank[i].length == 8</code></li> <li><code>startGene</code>, <code>endGene</code>, and <code>bank[i]</code> consist of only the characters <code>[&#39;A&#39;, &#39;C&#39;, &#39;G&#39;, &#39;T&#39;]</code>.</li> </ul>
Breadth-First Search; Hash Table; String
C++
class Solution { public: int minMutation(string startGene, string endGene, vector<string>& bank) { queue<pair<string, int>> q{{{startGene, 0}}}; unordered_set<string> vis = {startGene}; while (!q.empty()) { auto [gene, depth] = q.front(); q.pop(); if (gene == endGene) { return depth; } for (const string& next : bank) { int c = 2; for (int k = 0; k < 8 && c; ++k) { c -= gene[k] != next[k]; } if (c && !vis.contains(next)) { vis.insert(next); q.push({next, depth + 1}); } } } return -1; } };
433
Minimum Genetic Mutation
Medium
<p>A gene string can be represented by an 8-character long string, with choices from <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <p>Suppose we need to investigate a mutation from a gene string <code>startGene</code> to a gene string <code>endGene</code> where one mutation is defined as one single character changed in the gene string.</p> <ul> <li>For example, <code>&quot;AACCGGTT&quot; --&gt; &quot;AACCGGTA&quot;</code> is one mutation.</li> </ul> <p>There is also a gene bank <code>bank</code> that records all the valid gene mutations. A gene must be in <code>bank</code> to make it a valid gene string.</p> <p>Given the two gene strings <code>startGene</code> and <code>endGene</code> and the gene bank <code>bank</code>, return <em>the minimum number of mutations needed to mutate from </em><code>startGene</code><em> to </em><code>endGene</code>. If there is no such a mutation, return <code>-1</code>.</p> <p>Note that the starting point is assumed to be valid, so it might not be included in the bank.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AACCGGTA&quot;, bank = [&quot;AACCGGTA&quot;] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AAACGGTA&quot;, bank = [&quot;AACCGGTA&quot;,&quot;AACCGCTA&quot;,&quot;AAACGGTA&quot;] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= bank.length &lt;= 10</code></li> <li><code>startGene.length == endGene.length == bank[i].length == 8</code></li> <li><code>startGene</code>, <code>endGene</code>, and <code>bank[i]</code> consist of only the characters <code>[&#39;A&#39;, &#39;C&#39;, &#39;G&#39;, &#39;T&#39;]</code>.</li> </ul>
Breadth-First Search; Hash Table; String
Go
func minMutation(startGene string, endGene string, bank []string) int { type pair struct { s string depth int } q := []pair{pair{startGene, 0}} vis := map[string]bool{startGene: true} for len(q) > 0 { p := q[0] q = q[1:] if p.s == endGene { return p.depth } for _, next := range bank { diff := 0 for i := 0; i < len(startGene); i++ { if p.s[i] != next[i] { diff++ } } if diff == 1 && !vis[next] { vis[next] = true q = append(q, pair{next, p.depth + 1}) } } } return -1 }
433
Minimum Genetic Mutation
Medium
<p>A gene string can be represented by an 8-character long string, with choices from <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <p>Suppose we need to investigate a mutation from a gene string <code>startGene</code> to a gene string <code>endGene</code> where one mutation is defined as one single character changed in the gene string.</p> <ul> <li>For example, <code>&quot;AACCGGTT&quot; --&gt; &quot;AACCGGTA&quot;</code> is one mutation.</li> </ul> <p>There is also a gene bank <code>bank</code> that records all the valid gene mutations. A gene must be in <code>bank</code> to make it a valid gene string.</p> <p>Given the two gene strings <code>startGene</code> and <code>endGene</code> and the gene bank <code>bank</code>, return <em>the minimum number of mutations needed to mutate from </em><code>startGene</code><em> to </em><code>endGene</code>. If there is no such a mutation, return <code>-1</code>.</p> <p>Note that the starting point is assumed to be valid, so it might not be included in the bank.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AACCGGTA&quot;, bank = [&quot;AACCGGTA&quot;] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AAACGGTA&quot;, bank = [&quot;AACCGGTA&quot;,&quot;AACCGCTA&quot;,&quot;AAACGGTA&quot;] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= bank.length &lt;= 10</code></li> <li><code>startGene.length == endGene.length == bank[i].length == 8</code></li> <li><code>startGene</code>, <code>endGene</code>, and <code>bank[i]</code> consist of only the characters <code>[&#39;A&#39;, &#39;C&#39;, &#39;G&#39;, &#39;T&#39;]</code>.</li> </ul>
Breadth-First Search; Hash Table; String
Java
class Solution { public int minMutation(String startGene, String endGene, String[] bank) { Deque<String> q = new ArrayDeque<>(); q.offer(startGene); Set<String> vis = new HashSet<>(); vis.add(startGene); int depth = 0; while (!q.isEmpty()) { for (int m = q.size(); m > 0; --m) { String gene = q.poll(); if (gene.equals(endGene)) { return depth; } for (String next : bank) { int c = 2; for (int k = 0; k < 8 && c > 0; ++k) { if (gene.charAt(k) != next.charAt(k)) { --c; } } if (c > 0 && !vis.contains(next)) { q.offer(next); vis.add(next); } } } ++depth; } return -1; } }
433
Minimum Genetic Mutation
Medium
<p>A gene string can be represented by an 8-character long string, with choices from <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <p>Suppose we need to investigate a mutation from a gene string <code>startGene</code> to a gene string <code>endGene</code> where one mutation is defined as one single character changed in the gene string.</p> <ul> <li>For example, <code>&quot;AACCGGTT&quot; --&gt; &quot;AACCGGTA&quot;</code> is one mutation.</li> </ul> <p>There is also a gene bank <code>bank</code> that records all the valid gene mutations. A gene must be in <code>bank</code> to make it a valid gene string.</p> <p>Given the two gene strings <code>startGene</code> and <code>endGene</code> and the gene bank <code>bank</code>, return <em>the minimum number of mutations needed to mutate from </em><code>startGene</code><em> to </em><code>endGene</code>. If there is no such a mutation, return <code>-1</code>.</p> <p>Note that the starting point is assumed to be valid, so it might not be included in the bank.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AACCGGTA&quot;, bank = [&quot;AACCGGTA&quot;] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AAACGGTA&quot;, bank = [&quot;AACCGGTA&quot;,&quot;AACCGCTA&quot;,&quot;AAACGGTA&quot;] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= bank.length &lt;= 10</code></li> <li><code>startGene.length == endGene.length == bank[i].length == 8</code></li> <li><code>startGene</code>, <code>endGene</code>, and <code>bank[i]</code> consist of only the characters <code>[&#39;A&#39;, &#39;C&#39;, &#39;G&#39;, &#39;T&#39;]</code>.</li> </ul>
Breadth-First Search; Hash Table; String
Python
class Solution: def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int: q = deque([(startGene, 0)]) vis = {startGene} while q: gene, depth = q.popleft() if gene == endGene: return depth for nxt in bank: diff = sum(a != b for a, b in zip(gene, nxt)) if diff == 1 and nxt not in vis: q.append((nxt, depth + 1)) vis.add(nxt) return -1
433
Minimum Genetic Mutation
Medium
<p>A gene string can be represented by an 8-character long string, with choices from <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <p>Suppose we need to investigate a mutation from a gene string <code>startGene</code> to a gene string <code>endGene</code> where one mutation is defined as one single character changed in the gene string.</p> <ul> <li>For example, <code>&quot;AACCGGTT&quot; --&gt; &quot;AACCGGTA&quot;</code> is one mutation.</li> </ul> <p>There is also a gene bank <code>bank</code> that records all the valid gene mutations. A gene must be in <code>bank</code> to make it a valid gene string.</p> <p>Given the two gene strings <code>startGene</code> and <code>endGene</code> and the gene bank <code>bank</code>, return <em>the minimum number of mutations needed to mutate from </em><code>startGene</code><em> to </em><code>endGene</code>. If there is no such a mutation, return <code>-1</code>.</p> <p>Note that the starting point is assumed to be valid, so it might not be included in the bank.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AACCGGTA&quot;, bank = [&quot;AACCGGTA&quot;] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AAACGGTA&quot;, bank = [&quot;AACCGGTA&quot;,&quot;AACCGCTA&quot;,&quot;AAACGGTA&quot;] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= bank.length &lt;= 10</code></li> <li><code>startGene.length == endGene.length == bank[i].length == 8</code></li> <li><code>startGene</code>, <code>endGene</code>, and <code>bank[i]</code> consist of only the characters <code>[&#39;A&#39;, &#39;C&#39;, &#39;G&#39;, &#39;T&#39;]</code>.</li> </ul>
Breadth-First Search; Hash Table; String
Rust
use std::collections::{HashSet, VecDeque}; impl Solution { pub fn min_mutation(start_gene: String, end_gene: String, bank: Vec<String>) -> i32 { let mut q = VecDeque::new(); q.push_back((start_gene.clone(), 0)); let mut vis = HashSet::new(); vis.insert(start_gene); while let Some((gene, depth)) = q.pop_front() { if gene == end_gene { return depth; } for next in &bank { let mut c = 2; for k in 0..8 { if gene.as_bytes()[k] != next.as_bytes()[k] { c -= 1; } if c == 0 { break; } } if c > 0 && !vis.contains(next) { vis.insert(next.clone()); q.push_back((next.clone(), depth + 1)); } } } -1 } }
433
Minimum Genetic Mutation
Medium
<p>A gene string can be represented by an 8-character long string, with choices from <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p> <p>Suppose we need to investigate a mutation from a gene string <code>startGene</code> to a gene string <code>endGene</code> where one mutation is defined as one single character changed in the gene string.</p> <ul> <li>For example, <code>&quot;AACCGGTT&quot; --&gt; &quot;AACCGGTA&quot;</code> is one mutation.</li> </ul> <p>There is also a gene bank <code>bank</code> that records all the valid gene mutations. A gene must be in <code>bank</code> to make it a valid gene string.</p> <p>Given the two gene strings <code>startGene</code> and <code>endGene</code> and the gene bank <code>bank</code>, return <em>the minimum number of mutations needed to mutate from </em><code>startGene</code><em> to </em><code>endGene</code>. If there is no such a mutation, return <code>-1</code>.</p> <p>Note that the starting point is assumed to be valid, so it might not be included in the bank.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AACCGGTA&quot;, bank = [&quot;AACCGGTA&quot;] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AAACGGTA&quot;, bank = [&quot;AACCGGTA&quot;,&quot;AACCGCTA&quot;,&quot;AAACGGTA&quot;] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= bank.length &lt;= 10</code></li> <li><code>startGene.length == endGene.length == bank[i].length == 8</code></li> <li><code>startGene</code>, <code>endGene</code>, and <code>bank[i]</code> consist of only the characters <code>[&#39;A&#39;, &#39;C&#39;, &#39;G&#39;, &#39;T&#39;]</code>.</li> </ul>
Breadth-First Search; Hash Table; String
TypeScript
function minMutation(startGene: string, endGene: string, bank: string[]): number { const q: [string, number][] = [[startGene, 0]]; const vis = new Set<string>([startGene]); for (const [gene, depth] of q) { if (gene === endGene) { return depth; } for (const next of bank) { let c = 2; for (let k = 0; k < 8 && c > 0; ++k) { if (gene[k] !== next[k]) { --c; } } if (c && !vis.has(next)) { q.push([next, depth + 1]); vis.add(next); } } } return -1; }
434
Number of Segments in a String
Easy
<p>Given a string <code>s</code>, return <em>the number of segments in the string</em>.</p> <p>A <strong>segment</strong> is defined to be a contiguous sequence of <strong>non-space characters</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello, my name is John&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The five segments are [&quot;Hello,&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;John&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello&quot; <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 300</code></li> <li><code>s</code> consists of lowercase and uppercase English letters, digits, or one of the following characters <code>&quot;!@#$%^&amp;*()_+-=&#39;,.:&quot;</code>.</li> <li>The only space character in <code>s</code> is <code>&#39; &#39;</code>.</li> </ul>
String
C++
class Solution { public: int countSegments(string s) { int ans = 0; istringstream ss(s); while (ss >> s) ++ans; return ans; } };
434
Number of Segments in a String
Easy
<p>Given a string <code>s</code>, return <em>the number of segments in the string</em>.</p> <p>A <strong>segment</strong> is defined to be a contiguous sequence of <strong>non-space characters</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello, my name is John&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The five segments are [&quot;Hello,&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;John&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello&quot; <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 300</code></li> <li><code>s</code> consists of lowercase and uppercase English letters, digits, or one of the following characters <code>&quot;!@#$%^&amp;*()_+-=&#39;,.:&quot;</code>.</li> <li>The only space character in <code>s</code> is <code>&#39; &#39;</code>.</li> </ul>
String
Go
func countSegments(s string) int { ans := 0 for _, t := range strings.Split(s, " ") { if len(t) > 0 { ans++ } } return ans }
434
Number of Segments in a String
Easy
<p>Given a string <code>s</code>, return <em>the number of segments in the string</em>.</p> <p>A <strong>segment</strong> is defined to be a contiguous sequence of <strong>non-space characters</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello, my name is John&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The five segments are [&quot;Hello,&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;John&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello&quot; <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 300</code></li> <li><code>s</code> consists of lowercase and uppercase English letters, digits, or one of the following characters <code>&quot;!@#$%^&amp;*()_+-=&#39;,.:&quot;</code>.</li> <li>The only space character in <code>s</code> is <code>&#39; &#39;</code>.</li> </ul>
String
Java
class Solution { public int countSegments(String s) { int ans = 0; for (String t : s.split(" ")) { if (!"".equals(t)) { ++ans; } } return ans; } }
434
Number of Segments in a String
Easy
<p>Given a string <code>s</code>, return <em>the number of segments in the string</em>.</p> <p>A <strong>segment</strong> is defined to be a contiguous sequence of <strong>non-space characters</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello, my name is John&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The five segments are [&quot;Hello,&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;John&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello&quot; <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 300</code></li> <li><code>s</code> consists of lowercase and uppercase English letters, digits, or one of the following characters <code>&quot;!@#$%^&amp;*()_+-=&#39;,.:&quot;</code>.</li> <li>The only space character in <code>s</code> is <code>&#39; &#39;</code>.</li> </ul>
String
PHP
class Solution { /** * @param String $s * @return Integer */ function countSegments($s) { $arr = explode(' ', $s); $cnt = 0; for ($i = 0; $i < count($arr); $i++) { if (strlen($arr[$i]) != 0) { $cnt++; } } return $cnt; } }
434
Number of Segments in a String
Easy
<p>Given a string <code>s</code>, return <em>the number of segments in the string</em>.</p> <p>A <strong>segment</strong> is defined to be a contiguous sequence of <strong>non-space characters</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello, my name is John&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The five segments are [&quot;Hello,&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;John&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello&quot; <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 300</code></li> <li><code>s</code> consists of lowercase and uppercase English letters, digits, or one of the following characters <code>&quot;!@#$%^&amp;*()_+-=&#39;,.:&quot;</code>.</li> <li>The only space character in <code>s</code> is <code>&#39; &#39;</code>.</li> </ul>
String
Python
class Solution: def countSegments(self, s: str) -> int: return len(s.split())
434
Number of Segments in a String
Easy
<p>Given a string <code>s</code>, return <em>the number of segments in the string</em>.</p> <p>A <strong>segment</strong> is defined to be a contiguous sequence of <strong>non-space characters</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello, my name is John&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The five segments are [&quot;Hello,&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;John&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;Hello&quot; <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 300</code></li> <li><code>s</code> consists of lowercase and uppercase English letters, digits, or one of the following characters <code>&quot;!@#$%^&amp;*()_+-=&#39;,.:&quot;</code>.</li> <li>The only space character in <code>s</code> is <code>&#39; &#39;</code>.</li> </ul>
String
TypeScript
function countSegments(s: string): number { return s.split(/\s+/).filter(Boolean).length; }
435
Non-overlapping Intervals
Medium
<p>Given an array of intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping</em>.</p> <p><strong>Note</strong> that intervals which only touch at a point are <strong>non-overlapping</strong>. For example, <code>[1, 2]</code> and <code>[2, 3]</code> are non-overlapping.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[2,3],[3,4],[1,3]] <strong>Output:</strong> 1 <strong>Explanation:</strong> [1,3] can be removed and the rest of the intervals are non-overlapping. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[1,2],[1,2]] <strong>Output:</strong> 2 <strong>Explanation:</strong> You need to remove two [1,2] to make the rest of the intervals non-overlapping. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[2,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> You don&#39;t need to remove any of the intervals since they&#39;re already non-overlapping. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>-5 * 10<sup>4</sup> &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
C++
class Solution { public: int eraseOverlapIntervals(vector<vector<int>>& intervals) { ranges::sort(intervals, [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; }); int ans = intervals.size(); int pre = INT_MIN; for (const auto& e : intervals) { int l = e[0], r = e[1]; if (pre <= l) { --ans; pre = r; } } return ans; } };
435
Non-overlapping Intervals
Medium
<p>Given an array of intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping</em>.</p> <p><strong>Note</strong> that intervals which only touch at a point are <strong>non-overlapping</strong>. For example, <code>[1, 2]</code> and <code>[2, 3]</code> are non-overlapping.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[2,3],[3,4],[1,3]] <strong>Output:</strong> 1 <strong>Explanation:</strong> [1,3] can be removed and the rest of the intervals are non-overlapping. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[1,2],[1,2]] <strong>Output:</strong> 2 <strong>Explanation:</strong> You need to remove two [1,2] to make the rest of the intervals non-overlapping. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[2,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> You don&#39;t need to remove any of the intervals since they&#39;re already non-overlapping. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>-5 * 10<sup>4</sup> &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
Go
func eraseOverlapIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { return intervals[i][1] < intervals[j][1] }) ans := len(intervals) pre := math.MinInt32 for _, e := range intervals { l, r := e[0], e[1] if pre <= l { ans-- pre = r } } return ans }
435
Non-overlapping Intervals
Medium
<p>Given an array of intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping</em>.</p> <p><strong>Note</strong> that intervals which only touch at a point are <strong>non-overlapping</strong>. For example, <code>[1, 2]</code> and <code>[2, 3]</code> are non-overlapping.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[2,3],[3,4],[1,3]] <strong>Output:</strong> 1 <strong>Explanation:</strong> [1,3] can be removed and the rest of the intervals are non-overlapping. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[1,2],[1,2]] <strong>Output:</strong> 2 <strong>Explanation:</strong> You need to remove two [1,2] to make the rest of the intervals non-overlapping. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[2,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> You don&#39;t need to remove any of the intervals since they&#39;re already non-overlapping. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>-5 * 10<sup>4</sup> &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
Java
class Solution { public int eraseOverlapIntervals(int[][] intervals) { Arrays.sort(intervals, (a, b) -> a[1] - b[1]); int ans = intervals.length; int pre = Integer.MIN_VALUE; for (var e : intervals) { int l = e[0], r = e[1]; if (pre <= l) { --ans; pre = r; } } return ans; } }
435
Non-overlapping Intervals
Medium
<p>Given an array of intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping</em>.</p> <p><strong>Note</strong> that intervals which only touch at a point are <strong>non-overlapping</strong>. For example, <code>[1, 2]</code> and <code>[2, 3]</code> are non-overlapping.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[2,3],[3,4],[1,3]] <strong>Output:</strong> 1 <strong>Explanation:</strong> [1,3] can be removed and the rest of the intervals are non-overlapping. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[1,2],[1,2]] <strong>Output:</strong> 2 <strong>Explanation:</strong> You need to remove two [1,2] to make the rest of the intervals non-overlapping. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[2,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> You don&#39;t need to remove any of the intervals since they&#39;re already non-overlapping. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>-5 * 10<sup>4</sup> &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
Python
class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals.sort(key=lambda x: x[1]) ans = len(intervals) pre = -inf for l, r in intervals: if pre <= l: ans -= 1 pre = r return ans
435
Non-overlapping Intervals
Medium
<p>Given an array of intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping</em>.</p> <p><strong>Note</strong> that intervals which only touch at a point are <strong>non-overlapping</strong>. For example, <code>[1, 2]</code> and <code>[2, 3]</code> are non-overlapping.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[2,3],[3,4],[1,3]] <strong>Output:</strong> 1 <strong>Explanation:</strong> [1,3] can be removed and the rest of the intervals are non-overlapping. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[1,2],[1,2]] <strong>Output:</strong> 2 <strong>Explanation:</strong> You need to remove two [1,2] to make the rest of the intervals non-overlapping. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2],[2,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> You don&#39;t need to remove any of the intervals since they&#39;re already non-overlapping. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>-5 * 10<sup>4</sup> &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
TypeScript
function eraseOverlapIntervals(intervals: number[][]): number { intervals.sort((a, b) => a[1] - b[1]); let [ans, pre] = [intervals.length, -Infinity]; for (const [l, r] of intervals) { if (pre <= l) { --ans; pre = r; } } return ans; }
436
Find Right Interval
Medium
<p>You are given an array of <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> and each <code>start<sub>i</sub></code> is <strong>unique</strong>.</p> <p>The <strong>right interval</strong> for an interval <code>i</code> is an interval <code>j</code> such that <code>start<sub>j</sub> &gt;= end<sub>i</sub></code> and <code>start<sub>j</sub></code> is <strong>minimized</strong>. Note that <code>i</code> may equal <code>j</code>.</p> <p>Return <em>an array of <strong>right interval</strong> indices for each interval <code>i</code></em>. If no <strong>right interval</strong> exists for interval <code>i</code>, then put <code>-1</code> at index <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2]] <strong>Output:</strong> [-1] <strong>Explanation:</strong> There is only one interval in the collection, so it outputs -1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[3,4],[2,3],[1,2]] <strong>Output:</strong> [-1,0,1] <strong>Explanation:</strong> There is no right interval for [3,4]. The right interval for [2,3] is [3,4] since start<sub>0</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3. The right interval for [1,2] is [2,3] since start<sub>1</sub> = 2 is the smallest start that is &gt;= end<sub>2</sub> = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,4],[2,3],[3,4]] <strong>Output:</strong> [-1,2,-1] <strong>Explanation:</strong> There is no right interval for [1,4] and [3,4]. The right interval for [2,3] is [3,4] since start<sub>2</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>-10<sup>6</sup> &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li>The start point of each interval is <strong>unique</strong>.</li> </ul>
Array; Binary Search; Sorting
C++
class Solution { public: vector<int> findRightInterval(vector<vector<int>>& intervals) { int n = intervals.size(); vector<pair<int, int>> arr; for (int i = 0; i < n; ++i) { arr.emplace_back(intervals[i][0], i); } sort(arr.begin(), arr.end()); vector<int> ans; for (auto& e : intervals) { int j = lower_bound(arr.begin(), arr.end(), make_pair(e[1], -1)) - arr.begin(); ans.push_back(j == n ? -1 : arr[j].second); } return ans; } };
436
Find Right Interval
Medium
<p>You are given an array of <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> and each <code>start<sub>i</sub></code> is <strong>unique</strong>.</p> <p>The <strong>right interval</strong> for an interval <code>i</code> is an interval <code>j</code> such that <code>start<sub>j</sub> &gt;= end<sub>i</sub></code> and <code>start<sub>j</sub></code> is <strong>minimized</strong>. Note that <code>i</code> may equal <code>j</code>.</p> <p>Return <em>an array of <strong>right interval</strong> indices for each interval <code>i</code></em>. If no <strong>right interval</strong> exists for interval <code>i</code>, then put <code>-1</code> at index <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2]] <strong>Output:</strong> [-1] <strong>Explanation:</strong> There is only one interval in the collection, so it outputs -1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[3,4],[2,3],[1,2]] <strong>Output:</strong> [-1,0,1] <strong>Explanation:</strong> There is no right interval for [3,4]. The right interval for [2,3] is [3,4] since start<sub>0</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3. The right interval for [1,2] is [2,3] since start<sub>1</sub> = 2 is the smallest start that is &gt;= end<sub>2</sub> = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,4],[2,3],[3,4]] <strong>Output:</strong> [-1,2,-1] <strong>Explanation:</strong> There is no right interval for [1,4] and [3,4]. The right interval for [2,3] is [3,4] since start<sub>2</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>-10<sup>6</sup> &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li>The start point of each interval is <strong>unique</strong>.</li> </ul>
Array; Binary Search; Sorting
Go
func findRightInterval(intervals [][]int) (ans []int) { arr := make([][2]int, len(intervals)) for i, v := range intervals { arr[i] = [2]int{v[0], i} } sort.Slice(arr, func(i, j int) bool { return arr[i][0] < arr[j][0] }) for _, e := range intervals { j := sort.Search(len(arr), func(i int) bool { return arr[i][0] >= e[1] }) if j < len(arr) { ans = append(ans, arr[j][1]) } else { ans = append(ans, -1) } } return }
436
Find Right Interval
Medium
<p>You are given an array of <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> and each <code>start<sub>i</sub></code> is <strong>unique</strong>.</p> <p>The <strong>right interval</strong> for an interval <code>i</code> is an interval <code>j</code> such that <code>start<sub>j</sub> &gt;= end<sub>i</sub></code> and <code>start<sub>j</sub></code> is <strong>minimized</strong>. Note that <code>i</code> may equal <code>j</code>.</p> <p>Return <em>an array of <strong>right interval</strong> indices for each interval <code>i</code></em>. If no <strong>right interval</strong> exists for interval <code>i</code>, then put <code>-1</code> at index <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2]] <strong>Output:</strong> [-1] <strong>Explanation:</strong> There is only one interval in the collection, so it outputs -1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[3,4],[2,3],[1,2]] <strong>Output:</strong> [-1,0,1] <strong>Explanation:</strong> There is no right interval for [3,4]. The right interval for [2,3] is [3,4] since start<sub>0</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3. The right interval for [1,2] is [2,3] since start<sub>1</sub> = 2 is the smallest start that is &gt;= end<sub>2</sub> = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,4],[2,3],[3,4]] <strong>Output:</strong> [-1,2,-1] <strong>Explanation:</strong> There is no right interval for [1,4] and [3,4]. The right interval for [2,3] is [3,4] since start<sub>2</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>-10<sup>6</sup> &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li>The start point of each interval is <strong>unique</strong>.</li> </ul>
Array; Binary Search; Sorting
Java
class Solution { public int[] findRightInterval(int[][] intervals) { int n = intervals.length; int[][] arr = new int[n][0]; for (int i = 0; i < n; ++i) { arr[i] = new int[] {intervals[i][0], i}; } Arrays.sort(arr, (a, b) -> a[0] - b[0]); int[] ans = new int[n]; for (int i = 0; i < n; ++i) { int j = search(arr, intervals[i][1]); ans[i] = j < n ? arr[j][1] : -1; } return ans; } private int search(int[][] arr, int x) { int l = 0, r = arr.length; while (l < r) { int mid = (l + r) >> 1; if (arr[mid][0] >= x) { r = mid; } else { l = mid + 1; } } return l; } }
436
Find Right Interval
Medium
<p>You are given an array of <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> and each <code>start<sub>i</sub></code> is <strong>unique</strong>.</p> <p>The <strong>right interval</strong> for an interval <code>i</code> is an interval <code>j</code> such that <code>start<sub>j</sub> &gt;= end<sub>i</sub></code> and <code>start<sub>j</sub></code> is <strong>minimized</strong>. Note that <code>i</code> may equal <code>j</code>.</p> <p>Return <em>an array of <strong>right interval</strong> indices for each interval <code>i</code></em>. If no <strong>right interval</strong> exists for interval <code>i</code>, then put <code>-1</code> at index <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2]] <strong>Output:</strong> [-1] <strong>Explanation:</strong> There is only one interval in the collection, so it outputs -1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[3,4],[2,3],[1,2]] <strong>Output:</strong> [-1,0,1] <strong>Explanation:</strong> There is no right interval for [3,4]. The right interval for [2,3] is [3,4] since start<sub>0</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3. The right interval for [1,2] is [2,3] since start<sub>1</sub> = 2 is the smallest start that is &gt;= end<sub>2</sub> = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,4],[2,3],[3,4]] <strong>Output:</strong> [-1,2,-1] <strong>Explanation:</strong> There is no right interval for [1,4] and [3,4]. The right interval for [2,3] is [3,4] since start<sub>2</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>-10<sup>6</sup> &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li>The start point of each interval is <strong>unique</strong>.</li> </ul>
Array; Binary Search; Sorting
Python
class Solution: def findRightInterval(self, intervals: List[List[int]]) -> List[int]: n = len(intervals) ans = [-1] * n arr = sorted((st, i) for i, (st, _) in enumerate(intervals)) for i, (_, ed) in enumerate(intervals): j = bisect_left(arr, (ed, -inf)) if j < n: ans[i] = arr[j][1] return ans
436
Find Right Interval
Medium
<p>You are given an array of <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> and each <code>start<sub>i</sub></code> is <strong>unique</strong>.</p> <p>The <strong>right interval</strong> for an interval <code>i</code> is an interval <code>j</code> such that <code>start<sub>j</sub> &gt;= end<sub>i</sub></code> and <code>start<sub>j</sub></code> is <strong>minimized</strong>. Note that <code>i</code> may equal <code>j</code>.</p> <p>Return <em>an array of <strong>right interval</strong> indices for each interval <code>i</code></em>. If no <strong>right interval</strong> exists for interval <code>i</code>, then put <code>-1</code> at index <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,2]] <strong>Output:</strong> [-1] <strong>Explanation:</strong> There is only one interval in the collection, so it outputs -1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> intervals = [[3,4],[2,3],[1,2]] <strong>Output:</strong> [-1,0,1] <strong>Explanation:</strong> There is no right interval for [3,4]. The right interval for [2,3] is [3,4] since start<sub>0</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3. The right interval for [1,2] is [2,3] since start<sub>1</sub> = 2 is the smallest start that is &gt;= end<sub>2</sub> = 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> intervals = [[1,4],[2,3],[3,4]] <strong>Output:</strong> [-1,2,-1] <strong>Explanation:</strong> There is no right interval for [1,4] and [3,4]. The right interval for [2,3] is [3,4] since start<sub>2</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>intervals[i].length == 2</code></li> <li><code>-10<sup>6</sup> &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li>The start point of each interval is <strong>unique</strong>.</li> </ul>
Array; Binary Search; Sorting
TypeScript
function findRightInterval(intervals: number[][]): number[] { const n = intervals.length; const arr: number[][] = Array.from({ length: n }, (_, i) => [intervals[i][0], i]); arr.sort((a, b) => a[0] - b[0]); return intervals.map(([_, ed]) => { let [l, r] = [0, n]; while (l < r) { const mid = (l + r) >> 1; if (arr[mid][0] >= ed) { r = mid; } else { l = mid + 1; } } return l < n ? arr[l][1] : -1; }); }
437
Path Sum III
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>the number of paths where the sum of the values&nbsp;along the path equals</em>&nbsp;<code>targetSum</code>.</p> <p>The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).</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/0437.Path%20Sum%20III/images/pathsum3-1-tree.jpg" style="width: 450px; height: 386px;" /> <pre> <strong>Input:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> The paths that sum to 8 are shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 1000]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-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 pathSum(TreeNode* root, int targetSum) { unordered_map<long long, int> cnt; cnt[0] = 1; auto dfs = [&](this auto&& dfs, TreeNode* node, long long s) -> int { if (!node) { return 0; } s += node->val; int ans = cnt[s - targetSum]; ++cnt[s]; ans += dfs(node->left, s) + dfs(node->right, s); --cnt[s]; return ans; }; return dfs(root, 0); } };
437
Path Sum III
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>the number of paths where the sum of the values&nbsp;along the path equals</em>&nbsp;<code>targetSum</code>.</p> <p>The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).</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/0437.Path%20Sum%20III/images/pathsum3-1-tree.jpg" style="width: 450px; height: 386px;" /> <pre> <strong>Input:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> The paths that sum to 8 are shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 1000]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Binary Tree
C#
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public int PathSum(TreeNode root, int targetSum) { Dictionary<long, int> cnt = new Dictionary<long, int>(); int Dfs(TreeNode node, long s) { if (node == null) { return 0; } s += node.val; int ans = cnt.GetValueOrDefault(s - targetSum, 0); cnt[s] = cnt.GetValueOrDefault(s, 0) + 1; ans += Dfs(node.left, s); ans += Dfs(node.right, s); cnt[s]--; return ans; } cnt[0] = 1; return Dfs(root, 0); } }
437
Path Sum III
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>the number of paths where the sum of the values&nbsp;along the path equals</em>&nbsp;<code>targetSum</code>.</p> <p>The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).</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/0437.Path%20Sum%20III/images/pathsum3-1-tree.jpg" style="width: 450px; height: 386px;" /> <pre> <strong>Input:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> The paths that sum to 8 are shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 1000]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func pathSum(root *TreeNode, targetSum int) int { cnt := map[int]int{0: 1} var dfs func(*TreeNode, int) int dfs = func(node *TreeNode, s int) int { if node == nil { return 0 } s += node.Val ans := cnt[s-targetSum] cnt[s]++ ans += dfs(node.Left, s) + dfs(node.Right, s) cnt[s]-- return ans } return dfs(root, 0) }
437
Path Sum III
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>the number of paths where the sum of the values&nbsp;along the path equals</em>&nbsp;<code>targetSum</code>.</p> <p>The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).</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/0437.Path%20Sum%20III/images/pathsum3-1-tree.jpg" style="width: 450px; height: 386px;" /> <pre> <strong>Input:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> The paths that sum to 8 are shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 1000]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-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 { private Map<Long, Integer> cnt = new HashMap<>(); private int targetSum; public int pathSum(TreeNode root, int targetSum) { cnt.put(0L, 1); this.targetSum = targetSum; return dfs(root, 0); } private int dfs(TreeNode node, long s) { if (node == null) { return 0; } s += node.val; int ans = cnt.getOrDefault(s - targetSum, 0); cnt.merge(s, 1, Integer::sum); ans += dfs(node.left, s); ans += dfs(node.right, s); cnt.merge(s, -1, Integer::sum); return ans; } }
437
Path Sum III
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>the number of paths where the sum of the values&nbsp;along the path equals</em>&nbsp;<code>targetSum</code>.</p> <p>The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).</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/0437.Path%20Sum%20III/images/pathsum3-1-tree.jpg" style="width: 450px; height: 386px;" /> <pre> <strong>Input:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> The paths that sum to 8 are shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 1000]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} targetSum * @return {number} */ var pathSum = function (root, targetSum) { const cnt = new Map(); const dfs = (node, s) => { if (!node) { return 0; } s += node.val; let ans = cnt.get(s - targetSum) || 0; cnt.set(s, (cnt.get(s) || 0) + 1); ans += dfs(node.left, s); ans += dfs(node.right, s); cnt.set(s, cnt.get(s) - 1); return ans; }; cnt.set(0, 1); return dfs(root, 0); };
437
Path Sum III
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>the number of paths where the sum of the values&nbsp;along the path equals</em>&nbsp;<code>targetSum</code>.</p> <p>The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).</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/0437.Path%20Sum%20III/images/pathsum3-1-tree.jpg" style="width: 450px; height: 386px;" /> <pre> <strong>Input:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> The paths that sum to 8 are shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 1000]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> int: def dfs(node, s): if node is None: return 0 s += node.val ans = cnt[s - targetSum] cnt[s] += 1 ans += dfs(node.left, s) ans += dfs(node.right, s) cnt[s] -= 1 return ans cnt = Counter({0: 1}) return dfs(root, 0)
437
Path Sum III
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>the number of paths where the sum of the values&nbsp;along the path equals</em>&nbsp;<code>targetSum</code>.</p> <p>The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).</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/0437.Path%20Sum%20III/images/pathsum3-1-tree.jpg" style="width: 450px; height: 386px;" /> <pre> <strong>Input:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> The paths that sum to 8 are shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 1000]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-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::HashMap; use std::rc::Rc; impl Solution { pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> i32 { let mut cnt = HashMap::new(); cnt.insert(0, 1); fn dfs( node: Option<Rc<RefCell<TreeNode>>>, s: i64, target: i64, cnt: &mut HashMap<i64, i32>, ) -> i32 { if let Some(n) = node { let n = n.borrow(); let s = s + n.val as i64; let ans = cnt.get(&(s - target)).copied().unwrap_or(0); *cnt.entry(s).or_insert(0) += 1; let ans = ans + dfs(n.left.clone(), s, target, cnt) + dfs(n.right.clone(), s, target, cnt); *cnt.get_mut(&s).unwrap() -= 1; ans } else { 0 } } dfs(root, 0, target_sum as i64, &mut cnt) } }
437
Path Sum III
Medium
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>the number of paths where the sum of the values&nbsp;along the path equals</em>&nbsp;<code>targetSum</code>.</p> <p>The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).</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/0437.Path%20Sum%20III/images/pathsum3-1-tree.jpg" style="width: 450px; height: 386px;" /> <pre> <strong>Input:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> The paths that sum to 8 are shown. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 1000]</code>.</li> <li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-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 pathSum(root: TreeNode | null, targetSum: number): number { const cnt: Map<number, number> = new Map(); const dfs = (node: TreeNode | null, s: number): number => { if (!node) { return 0; } s += node.val; let ans = cnt.get(s - targetSum) ?? 0; cnt.set(s, (cnt.get(s) ?? 0) + 1); ans += dfs(node.left, s); ans += dfs(node.right, s); cnt.set(s, (cnt.get(s) ?? 0) - 1); return ans; }; cnt.set(0, 1); return dfs(root, 0); }
438
Find All Anagrams in a String
Medium
<p>Given two strings <code>s</code> and <code>p</code>, return an array of all the start indices of <code>p</code>&#39;s <span data-keyword="anagram">anagrams</span> in <code>s</code>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbaebabacd&quot;, p = &quot;abc&quot; <strong>Output:</strong> [0,6] <strong>Explanation:</strong> The substring with start index = 0 is &quot;cba&quot;, which is an anagram of &quot;abc&quot;. The substring with start index = 6 is &quot;bac&quot;, which is an anagram of &quot;abc&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abab&quot;, p = &quot;ab&quot; <strong>Output:</strong> [0,1,2] <strong>Explanation:</strong> The substring with start index = 0 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 1 is &quot;ba&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 2 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, p.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>p</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: vector<int> findAnagrams(string s, string p) { int m = s.size(), n = p.size(); vector<int> ans; if (m < n) { return ans; } vector<int> cnt1(26); for (char& c : p) { ++cnt1[c - 'a']; } vector<int> cnt2(26); for (int i = 0; i < n - 1; ++i) { ++cnt2[s[i] - 'a']; } for (int i = n - 1; i < m; ++i) { ++cnt2[s[i] - 'a']; if (cnt1 == cnt2) { ans.push_back(i - n + 1); } --cnt2[s[i - n + 1] - 'a']; } return ans; } };
438
Find All Anagrams in a String
Medium
<p>Given two strings <code>s</code> and <code>p</code>, return an array of all the start indices of <code>p</code>&#39;s <span data-keyword="anagram">anagrams</span> in <code>s</code>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbaebabacd&quot;, p = &quot;abc&quot; <strong>Output:</strong> [0,6] <strong>Explanation:</strong> The substring with start index = 0 is &quot;cba&quot;, which is an anagram of &quot;abc&quot;. The substring with start index = 6 is &quot;bac&quot;, which is an anagram of &quot;abc&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abab&quot;, p = &quot;ab&quot; <strong>Output:</strong> [0,1,2] <strong>Explanation:</strong> The substring with start index = 0 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 1 is &quot;ba&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 2 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, p.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>p</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
C#
public class Solution { public IList<int> FindAnagrams(string s, string p) { int m = s.Length, n = p.Length; IList<int> ans = new List<int>(); if (m < n) { return ans; } int[] cnt1 = new int[26]; int[] cnt2 = new int[26]; for (int i = 0; i < n; ++i) { ++cnt1[p[i] - 'a']; } for (int i = 0, j = 0; i < m; ++i) { int k = s[i] - 'a'; ++cnt2[k]; while (cnt2[k] > cnt1[k]) { --cnt2[s[j++] - 'a']; } if (i - j + 1 == n) { ans.Add(j); } } return ans; } }
438
Find All Anagrams in a String
Medium
<p>Given two strings <code>s</code> and <code>p</code>, return an array of all the start indices of <code>p</code>&#39;s <span data-keyword="anagram">anagrams</span> in <code>s</code>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbaebabacd&quot;, p = &quot;abc&quot; <strong>Output:</strong> [0,6] <strong>Explanation:</strong> The substring with start index = 0 is &quot;cba&quot;, which is an anagram of &quot;abc&quot;. The substring with start index = 6 is &quot;bac&quot;, which is an anagram of &quot;abc&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abab&quot;, p = &quot;ab&quot; <strong>Output:</strong> [0,1,2] <strong>Explanation:</strong> The substring with start index = 0 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 1 is &quot;ba&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 2 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, p.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>p</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Go
func findAnagrams(s string, p string) (ans []int) { m, n := len(s), len(p) if m < n { return } cnt1 := [26]int{} cnt2 := [26]int{} for _, c := range p { cnt1[c-'a']++ } for _, c := range s[:n-1] { cnt2[c-'a']++ } for i := n - 1; i < m; i++ { cnt2[s[i]-'a']++ if cnt1 == cnt2 { ans = append(ans, i-n+1) } cnt2[s[i-n+1]-'a']-- } return }
438
Find All Anagrams in a String
Medium
<p>Given two strings <code>s</code> and <code>p</code>, return an array of all the start indices of <code>p</code>&#39;s <span data-keyword="anagram">anagrams</span> in <code>s</code>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbaebabacd&quot;, p = &quot;abc&quot; <strong>Output:</strong> [0,6] <strong>Explanation:</strong> The substring with start index = 0 is &quot;cba&quot;, which is an anagram of &quot;abc&quot;. The substring with start index = 6 is &quot;bac&quot;, which is an anagram of &quot;abc&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abab&quot;, p = &quot;ab&quot; <strong>Output:</strong> [0,1,2] <strong>Explanation:</strong> The substring with start index = 0 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 1 is &quot;ba&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 2 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, p.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>p</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public List<Integer> findAnagrams(String s, String p) { int m = s.length(), n = p.length(); List<Integer> ans = new ArrayList<>(); if (m < n) { return ans; } int[] cnt1 = new int[26]; for (int i = 0; i < n; ++i) { ++cnt1[p.charAt(i) - 'a']; } int[] cnt2 = new int[26]; for (int i = 0; i < n - 1; ++i) { ++cnt2[s.charAt(i) - 'a']; } for (int i = n - 1; i < m; ++i) { ++cnt2[s.charAt(i) - 'a']; if (Arrays.equals(cnt1, cnt2)) { ans.add(i - n + 1); } --cnt2[s.charAt(i - n + 1) - 'a']; } return ans; } }
438
Find All Anagrams in a String
Medium
<p>Given two strings <code>s</code> and <code>p</code>, return an array of all the start indices of <code>p</code>&#39;s <span data-keyword="anagram">anagrams</span> in <code>s</code>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbaebabacd&quot;, p = &quot;abc&quot; <strong>Output:</strong> [0,6] <strong>Explanation:</strong> The substring with start index = 0 is &quot;cba&quot;, which is an anagram of &quot;abc&quot;. The substring with start index = 6 is &quot;bac&quot;, which is an anagram of &quot;abc&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abab&quot;, p = &quot;ab&quot; <strong>Output:</strong> [0,1,2] <strong>Explanation:</strong> The substring with start index = 0 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 1 is &quot;ba&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 2 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, p.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>p</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: m, n = len(s), len(p) ans = [] if m < n: return ans cnt1 = Counter(p) cnt2 = Counter(s[: n - 1]) for i in range(n - 1, m): cnt2[s[i]] += 1 if cnt1 == cnt2: ans.append(i - n + 1) cnt2[s[i - n + 1]] -= 1 return ans
438
Find All Anagrams in a String
Medium
<p>Given two strings <code>s</code> and <code>p</code>, return an array of all the start indices of <code>p</code>&#39;s <span data-keyword="anagram">anagrams</span> in <code>s</code>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbaebabacd&quot;, p = &quot;abc&quot; <strong>Output:</strong> [0,6] <strong>Explanation:</strong> The substring with start index = 0 is &quot;cba&quot;, which is an anagram of &quot;abc&quot;. The substring with start index = 6 is &quot;bac&quot;, which is an anagram of &quot;abc&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abab&quot;, p = &quot;ab&quot; <strong>Output:</strong> [0,1,2] <strong>Explanation:</strong> The substring with start index = 0 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 1 is &quot;ba&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 2 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, p.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>p</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Rust
impl Solution { pub fn find_anagrams(s: String, p: String) -> Vec<i32> { let (s, p) = (s.as_bytes(), p.as_bytes()); let (m, n) = (s.len(), p.len()); let mut ans = vec![]; if m < n { return ans; } let mut cnt = [0; 26]; for i in 0..n { cnt[(p[i] - b'a') as usize] += 1; cnt[(s[i] - b'a') as usize] -= 1; } for i in n..m { if cnt.iter().all(|&v| v == 0) { ans.push((i - n) as i32); } cnt[(s[i] - b'a') as usize] -= 1; cnt[(s[i - n] - b'a') as usize] += 1; } if cnt.iter().all(|&v| v == 0) { ans.push((m - n) as i32); } ans } }
438
Find All Anagrams in a String
Medium
<p>Given two strings <code>s</code> and <code>p</code>, return an array of all the start indices of <code>p</code>&#39;s <span data-keyword="anagram">anagrams</span> in <code>s</code>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbaebabacd&quot;, p = &quot;abc&quot; <strong>Output:</strong> [0,6] <strong>Explanation:</strong> The substring with start index = 0 is &quot;cba&quot;, which is an anagram of &quot;abc&quot;. The substring with start index = 6 is &quot;bac&quot;, which is an anagram of &quot;abc&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abab&quot;, p = &quot;ab&quot; <strong>Output:</strong> [0,1,2] <strong>Explanation:</strong> The substring with start index = 0 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 1 is &quot;ba&quot;, which is an anagram of &quot;ab&quot;. The substring with start index = 2 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, p.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> and <code>p</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
TypeScript
function findAnagrams(s: string, p: string): number[] { const m = s.length; const n = p.length; const ans: number[] = []; if (m < n) { return ans; } const cnt1: number[] = new Array(26).fill(0); const cnt2: number[] = new Array(26).fill(0); const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); for (const c of p) { ++cnt1[idx(c)]; } for (const c of s.slice(0, n - 1)) { ++cnt2[idx(c)]; } for (let i = n - 1; i < m; ++i) { ++cnt2[idx(s[i])]; if (cnt1.toString() === cnt2.toString()) { ans.push(i - n + 1); } --cnt2[idx(s[i - n + 1])]; } return ans; }
439
Ternary Expression Parser
Medium
<p>Given a string <code>expression</code> representing arbitrarily nested ternary expressions, evaluate the expression, and return <em>the result of it</em>.</p> <p>You can always assume that the given expression is valid and only contains digits, <code>&#39;?&#39;</code>, <code>&#39;:&#39;</code>, <code>&#39;T&#39;</code>, and <code>&#39;F&#39;</code> where <code>&#39;T&#39;</code> is true and <code>&#39;F&#39;</code> is false. All the numbers in the expression are <strong>one-digit</strong> numbers (i.e., in the range <code>[0, 9]</code>).</p> <p>The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, <code>&#39;T&#39;</code> or <code>&#39;F&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;T?2:3&quot; <strong>Output:</strong> &quot;2&quot; <strong>Explanation:</strong> If true, then result is 2; otherwise result is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;F?1:T?4:5&quot; <strong>Output:</strong> &quot;4&quot; <strong>Explanation:</strong> The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: &quot;(F ? 1 : (T ? 4 : 5))&quot; --&gt; &quot;(F ? 1 : 4)&quot; --&gt; &quot;4&quot; or &quot;(F ? 1 : (T ? 4 : 5))&quot; --&gt; &quot;(T ? 4 : 5)&quot; --&gt; &quot;4&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> expression = &quot;T?T?F:5:3&quot; <strong>Output:</strong> &quot;F&quot; <strong>Explanation:</strong> The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: &quot;(T ? (T ? F : 5) : 3)&quot; --&gt; &quot;(T ? F : 3)&quot; --&gt; &quot;F&quot; &quot;(T ? (T ? F : 5) : 3)&quot; --&gt; &quot;(T ? F : 5)&quot; --&gt; &quot;F&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>5 &lt;= expression.length &lt;= 10<sup>4</sup></code></li> <li><code>expression</code> consists of digits, <code>&#39;T&#39;</code>, <code>&#39;F&#39;</code>, <code>&#39;?&#39;</code>, and <code>&#39;:&#39;</code>.</li> <li>It is <strong>guaranteed</strong> that <code>expression</code> is a valid ternary expression and that each number is a <strong>one-digit number</strong>.</li> </ul>
Stack; Recursion; String
C++
class Solution { public: string parseTernary(string expression) { string stk; bool cond = false; reverse(expression.begin(), expression.end()); for (char& c : expression) { if (c == ':') { continue; } if (c == '?') { cond = true; } else { if (cond) { if (c == 'T') { char x = stk.back(); stk.pop_back(); stk.pop_back(); stk.push_back(x); } else { stk.pop_back(); } cond = false; } else { stk.push_back(c); } } } return {stk[0]}; } };
439
Ternary Expression Parser
Medium
<p>Given a string <code>expression</code> representing arbitrarily nested ternary expressions, evaluate the expression, and return <em>the result of it</em>.</p> <p>You can always assume that the given expression is valid and only contains digits, <code>&#39;?&#39;</code>, <code>&#39;:&#39;</code>, <code>&#39;T&#39;</code>, and <code>&#39;F&#39;</code> where <code>&#39;T&#39;</code> is true and <code>&#39;F&#39;</code> is false. All the numbers in the expression are <strong>one-digit</strong> numbers (i.e., in the range <code>[0, 9]</code>).</p> <p>The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, <code>&#39;T&#39;</code> or <code>&#39;F&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;T?2:3&quot; <strong>Output:</strong> &quot;2&quot; <strong>Explanation:</strong> If true, then result is 2; otherwise result is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;F?1:T?4:5&quot; <strong>Output:</strong> &quot;4&quot; <strong>Explanation:</strong> The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: &quot;(F ? 1 : (T ? 4 : 5))&quot; --&gt; &quot;(F ? 1 : 4)&quot; --&gt; &quot;4&quot; or &quot;(F ? 1 : (T ? 4 : 5))&quot; --&gt; &quot;(T ? 4 : 5)&quot; --&gt; &quot;4&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> expression = &quot;T?T?F:5:3&quot; <strong>Output:</strong> &quot;F&quot; <strong>Explanation:</strong> The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: &quot;(T ? (T ? F : 5) : 3)&quot; --&gt; &quot;(T ? F : 3)&quot; --&gt; &quot;F&quot; &quot;(T ? (T ? F : 5) : 3)&quot; --&gt; &quot;(T ? F : 5)&quot; --&gt; &quot;F&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>5 &lt;= expression.length &lt;= 10<sup>4</sup></code></li> <li><code>expression</code> consists of digits, <code>&#39;T&#39;</code>, <code>&#39;F&#39;</code>, <code>&#39;?&#39;</code>, and <code>&#39;:&#39;</code>.</li> <li>It is <strong>guaranteed</strong> that <code>expression</code> is a valid ternary expression and that each number is a <strong>one-digit number</strong>.</li> </ul>
Stack; Recursion; String
Go
func parseTernary(expression string) string { stk := []byte{} cond := false for i := len(expression) - 1; i >= 0; i-- { c := expression[i] if c == ':' { continue } if c == '?' { cond = true } else { if cond { if c == 'T' { x := stk[len(stk)-1] stk = stk[:len(stk)-2] stk = append(stk, x) } else { stk = stk[:len(stk)-1] } cond = false } else { stk = append(stk, c) } } } return string(stk[0]) }
439
Ternary Expression Parser
Medium
<p>Given a string <code>expression</code> representing arbitrarily nested ternary expressions, evaluate the expression, and return <em>the result of it</em>.</p> <p>You can always assume that the given expression is valid and only contains digits, <code>&#39;?&#39;</code>, <code>&#39;:&#39;</code>, <code>&#39;T&#39;</code>, and <code>&#39;F&#39;</code> where <code>&#39;T&#39;</code> is true and <code>&#39;F&#39;</code> is false. All the numbers in the expression are <strong>one-digit</strong> numbers (i.e., in the range <code>[0, 9]</code>).</p> <p>The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, <code>&#39;T&#39;</code> or <code>&#39;F&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;T?2:3&quot; <strong>Output:</strong> &quot;2&quot; <strong>Explanation:</strong> If true, then result is 2; otherwise result is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;F?1:T?4:5&quot; <strong>Output:</strong> &quot;4&quot; <strong>Explanation:</strong> The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: &quot;(F ? 1 : (T ? 4 : 5))&quot; --&gt; &quot;(F ? 1 : 4)&quot; --&gt; &quot;4&quot; or &quot;(F ? 1 : (T ? 4 : 5))&quot; --&gt; &quot;(T ? 4 : 5)&quot; --&gt; &quot;4&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> expression = &quot;T?T?F:5:3&quot; <strong>Output:</strong> &quot;F&quot; <strong>Explanation:</strong> The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: &quot;(T ? (T ? F : 5) : 3)&quot; --&gt; &quot;(T ? F : 3)&quot; --&gt; &quot;F&quot; &quot;(T ? (T ? F : 5) : 3)&quot; --&gt; &quot;(T ? F : 5)&quot; --&gt; &quot;F&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>5 &lt;= expression.length &lt;= 10<sup>4</sup></code></li> <li><code>expression</code> consists of digits, <code>&#39;T&#39;</code>, <code>&#39;F&#39;</code>, <code>&#39;?&#39;</code>, and <code>&#39;:&#39;</code>.</li> <li>It is <strong>guaranteed</strong> that <code>expression</code> is a valid ternary expression and that each number is a <strong>one-digit number</strong>.</li> </ul>
Stack; Recursion; String
Java
class Solution { public String parseTernary(String expression) { Deque<Character> stk = new ArrayDeque<>(); boolean cond = false; for (int i = expression.length() - 1; i >= 0; --i) { char c = expression.charAt(i); if (c == ':') { continue; } if (c == '?') { cond = true; } else { if (cond) { if (c == 'T') { char x = stk.pop(); stk.pop(); stk.push(x); } else { stk.pop(); } cond = false; } else { stk.push(c); } } } return String.valueOf(stk.peek()); } }