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
|
|---|---|---|---|---|---|---|
557
|
Reverse Words in a String III
|
Easy
|
<p>Given a string <code>s</code>, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Let's take LeetCode contest"
<strong>Output:</strong> "s'teL ekat edoCteeL tsetnoc"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "Mr Ding"
<strong>Output:</strong> "rM gniD"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> contains printable <strong>ASCII</strong> characters.</li>
<li><code>s</code> does not contain any leading or trailing spaces.</li>
<li>There is <strong>at least one</strong> word in <code>s</code>.</li>
<li>All the words in <code>s</code> are separated by a single space.</li>
</ul>
|
Two Pointers; String
|
JavaScript
|
/**
* @param {string} s
* @return {string}
*/
var reverseWords = function (s) {
return s
.split(' ')
.map(t => t.split('').reverse().join(''))
.join(' ');
};
|
557
|
Reverse Words in a String III
|
Easy
|
<p>Given a string <code>s</code>, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Let's take LeetCode contest"
<strong>Output:</strong> "s'teL ekat edoCteeL tsetnoc"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "Mr Ding"
<strong>Output:</strong> "rM gniD"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> contains printable <strong>ASCII</strong> characters.</li>
<li><code>s</code> does not contain any leading or trailing spaces.</li>
<li>There is <strong>at least one</strong> word in <code>s</code>.</li>
<li>All the words in <code>s</code> are separated by a single space.</li>
</ul>
|
Two Pointers; String
|
PHP
|
class Solution {
/**
* @param String $s
* @return String
*/
function reverseWords($s) {
$words = explode(' ', $s);
foreach ($words as $i => $word) {
$words[$i] = strrev($word);
}
return implode(' ', $words);
}
}
|
557
|
Reverse Words in a String III
|
Easy
|
<p>Given a string <code>s</code>, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Let's take LeetCode contest"
<strong>Output:</strong> "s'teL ekat edoCteeL tsetnoc"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "Mr Ding"
<strong>Output:</strong> "rM gniD"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> contains printable <strong>ASCII</strong> characters.</li>
<li><code>s</code> does not contain any leading or trailing spaces.</li>
<li>There is <strong>at least one</strong> word in <code>s</code>.</li>
<li>All the words in <code>s</code> are separated by a single space.</li>
</ul>
|
Two Pointers; String
|
Python
|
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(t[::-1] for t in s.split())
|
557
|
Reverse Words in a String III
|
Easy
|
<p>Given a string <code>s</code>, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Let's take LeetCode contest"
<strong>Output:</strong> "s'teL ekat edoCteeL tsetnoc"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "Mr Ding"
<strong>Output:</strong> "rM gniD"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> contains printable <strong>ASCII</strong> characters.</li>
<li><code>s</code> does not contain any leading or trailing spaces.</li>
<li>There is <strong>at least one</strong> word in <code>s</code>.</li>
<li>All the words in <code>s</code> are separated by a single space.</li>
</ul>
|
Two Pointers; String
|
Rust
|
impl Solution {
pub fn reverse_words(s: String) -> String {
s.split(' ')
.map(|s| s.chars().rev().collect::<String>())
.collect::<Vec<_>>()
.join(" ")
}
}
|
557
|
Reverse Words in a String III
|
Easy
|
<p>Given a string <code>s</code>, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Let's take LeetCode contest"
<strong>Output:</strong> "s'teL ekat edoCteeL tsetnoc"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "Mr Ding"
<strong>Output:</strong> "rM gniD"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> contains printable <strong>ASCII</strong> characters.</li>
<li><code>s</code> does not contain any leading or trailing spaces.</li>
<li>There is <strong>at least one</strong> word in <code>s</code>.</li>
<li>All the words in <code>s</code> are separated by a single space.</li>
</ul>
|
Two Pointers; String
|
TypeScript
|
function reverseWords(s: string): string {
return s
.split(' ')
.map(t => t.split('').reverse().join(''))
.join(' ');
}
|
558
|
Logical OR of Two Binary Grids Represented as Quad-Trees
|
Medium
|
<p>A Binary Matrix is a matrix in which all the elements are either <strong>0</strong> or <strong>1</strong>.</p>
<p>Given <code>quadTree1</code> and <code>quadTree2</code>. <code>quadTree1</code> represents a <code>n * n</code> binary matrix and <code>quadTree2</code> represents another <code>n * n</code> binary matrix.</p>
<p>Return <em>a Quad-Tree</em> representing the <code>n * n</code> binary matrix which is the result of <strong>logical bitwise OR</strong> of the two binary matrixes represented by <code>quadTree1</code> and <code>quadTree2</code>.</p>
<p>Notice that you can assign the value of a node to <strong>True</strong> or <strong>False</strong> when <code>isLeaf</code> is <strong>False</strong>, and both are <strong>accepted</strong> in the answer.</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's or False if the node represents a grid of 0's.</li>
<li><code>isLeaf</code>: True if the node is leaf node on the tree or False if the node has the 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's</code> or all <code>0'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/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/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>The input/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> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qt1.png" style="width: 550px; height: 196px;" /> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qt2.png" style="width: 550px; height: 278px;" />
<pre>
<strong>Input:</strong> quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]
, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
<strong>Output:</strong> [[0,0],[1,1],[1,1],[1,1],[1,0]]
<strong>Explanation:</strong> quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.
If we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.
Notice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree.
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qtr.png" style="width: 777px; height: 222px;" />
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> quadTree1 = [[1,0]], quadTree2 = [[1,0]]
<strong>Output:</strong> [[1,0]]
<strong>Explanation:</strong> Each tree represents a binary matrix of size 1*1. Each matrix contains only zero.
The resulting matrix is of size 1*1 with also zero.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>quadTree1</code> and <code>quadTree2</code> are both <strong>valid</strong> Quad-Trees each representing a <code>n * n</code> grid.</li>
<li><code>n == 2<sup>x</sup></code> where <code>0 <= x <= 9</code>.</li>
</ul>
|
Tree; Divide and Conquer
|
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* intersect(Node* quadTree1, Node* quadTree2) {
return dfs(quadTree1, quadTree2);
}
Node* dfs(Node* t1, Node* t2) {
if (t1->isLeaf && t2->isLeaf) return new Node(t1->val || t2->val, true);
if (t1->isLeaf) return t1->val ? t1 : t2;
if (t2->isLeaf) return t2->val ? t2 : t1;
Node* res = new Node();
res->topLeft = dfs(t1->topLeft, t2->topLeft);
res->topRight = dfs(t1->topRight, t2->topRight);
res->bottomLeft = dfs(t1->bottomLeft, t2->bottomLeft);
res->bottomRight = dfs(t1->bottomRight, t2->bottomRight);
bool isLeaf = res->topLeft->isLeaf && res->topRight->isLeaf && res->bottomLeft->isLeaf && res->bottomRight->isLeaf;
bool sameVal = res->topLeft->val == res->topRight->val && res->topRight->val == res->bottomLeft->val && res->bottomLeft->val == res->bottomRight->val;
if (isLeaf && sameVal) res = res->topLeft;
return res;
}
};
|
558
|
Logical OR of Two Binary Grids Represented as Quad-Trees
|
Medium
|
<p>A Binary Matrix is a matrix in which all the elements are either <strong>0</strong> or <strong>1</strong>.</p>
<p>Given <code>quadTree1</code> and <code>quadTree2</code>. <code>quadTree1</code> represents a <code>n * n</code> binary matrix and <code>quadTree2</code> represents another <code>n * n</code> binary matrix.</p>
<p>Return <em>a Quad-Tree</em> representing the <code>n * n</code> binary matrix which is the result of <strong>logical bitwise OR</strong> of the two binary matrixes represented by <code>quadTree1</code> and <code>quadTree2</code>.</p>
<p>Notice that you can assign the value of a node to <strong>True</strong> or <strong>False</strong> when <code>isLeaf</code> is <strong>False</strong>, and both are <strong>accepted</strong> in the answer.</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's or False if the node represents a grid of 0's.</li>
<li><code>isLeaf</code>: True if the node is leaf node on the tree or False if the node has the 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's</code> or all <code>0'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/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/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>The input/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> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qt1.png" style="width: 550px; height: 196px;" /> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qt2.png" style="width: 550px; height: 278px;" />
<pre>
<strong>Input:</strong> quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]
, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
<strong>Output:</strong> [[0,0],[1,1],[1,1],[1,1],[1,0]]
<strong>Explanation:</strong> quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.
If we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.
Notice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree.
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qtr.png" style="width: 777px; height: 222px;" />
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> quadTree1 = [[1,0]], quadTree2 = [[1,0]]
<strong>Output:</strong> [[1,0]]
<strong>Explanation:</strong> Each tree represents a binary matrix of size 1*1. Each matrix contains only zero.
The resulting matrix is of size 1*1 with also zero.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>quadTree1</code> and <code>quadTree2</code> are both <strong>valid</strong> Quad-Trees each representing a <code>n * n</code> grid.</li>
<li><code>n == 2<sup>x</sup></code> where <code>0 <= x <= 9</code>.</li>
</ul>
|
Tree; Divide and Conquer
|
Go
|
/**
* Definition for a QuadTree node.
* type Node struct {
* Val bool
* IsLeaf bool
* TopLeft *Node
* TopRight *Node
* BottomLeft *Node
* BottomRight *Node
* }
*/
func intersect(quadTree1 *Node, quadTree2 *Node) *Node {
var dfs func(*Node, *Node) *Node
dfs = func(t1, t2 *Node) *Node {
if t1.IsLeaf && t2.IsLeaf {
return &Node{Val: t1.Val || t2.Val, IsLeaf: true}
}
if t1.IsLeaf {
if t1.Val {
return t1
}
return t2
}
if t2.IsLeaf {
if t2.Val {
return t2
}
return t1
}
res := &Node{}
res.TopLeft = dfs(t1.TopLeft, t2.TopLeft)
res.TopRight = dfs(t1.TopRight, t2.TopRight)
res.BottomLeft = dfs(t1.BottomLeft, t2.BottomLeft)
res.BottomRight = dfs(t1.BottomRight, t2.BottomRight)
isLeaf := res.TopLeft.IsLeaf && res.TopRight.IsLeaf && res.BottomLeft.IsLeaf && res.BottomRight.IsLeaf
sameVal := res.TopLeft.Val == res.TopRight.Val && res.TopRight.Val == res.BottomLeft.Val && res.BottomLeft.Val == res.BottomRight.Val
if isLeaf && sameVal {
res = res.TopLeft
}
return res
}
return dfs(quadTree1, quadTree2)
}
|
558
|
Logical OR of Two Binary Grids Represented as Quad-Trees
|
Medium
|
<p>A Binary Matrix is a matrix in which all the elements are either <strong>0</strong> or <strong>1</strong>.</p>
<p>Given <code>quadTree1</code> and <code>quadTree2</code>. <code>quadTree1</code> represents a <code>n * n</code> binary matrix and <code>quadTree2</code> represents another <code>n * n</code> binary matrix.</p>
<p>Return <em>a Quad-Tree</em> representing the <code>n * n</code> binary matrix which is the result of <strong>logical bitwise OR</strong> of the two binary matrixes represented by <code>quadTree1</code> and <code>quadTree2</code>.</p>
<p>Notice that you can assign the value of a node to <strong>True</strong> or <strong>False</strong> when <code>isLeaf</code> is <strong>False</strong>, and both are <strong>accepted</strong> in the answer.</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's or False if the node represents a grid of 0's.</li>
<li><code>isLeaf</code>: True if the node is leaf node on the tree or False if the node has the 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's</code> or all <code>0'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/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/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>The input/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> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qt1.png" style="width: 550px; height: 196px;" /> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qt2.png" style="width: 550px; height: 278px;" />
<pre>
<strong>Input:</strong> quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]
, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
<strong>Output:</strong> [[0,0],[1,1],[1,1],[1,1],[1,0]]
<strong>Explanation:</strong> quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.
If we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.
Notice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree.
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qtr.png" style="width: 777px; height: 222px;" />
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> quadTree1 = [[1,0]], quadTree2 = [[1,0]]
<strong>Output:</strong> [[1,0]]
<strong>Explanation:</strong> Each tree represents a binary matrix of size 1*1. Each matrix contains only zero.
The resulting matrix is of size 1*1 with also zero.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>quadTree1</code> and <code>quadTree2</code> are both <strong>valid</strong> Quad-Trees each representing a <code>n * n</code> grid.</li>
<li><code>n == 2<sup>x</sup></code> where <code>0 <= x <= 9</code>.</li>
</ul>
|
Tree; Divide and Conquer
|
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() {}
public Node(boolean _val,boolean _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 intersect(Node quadTree1, Node quadTree2) {
return dfs(quadTree1, quadTree2);
}
private Node dfs(Node t1, Node t2) {
if (t1.isLeaf && t2.isLeaf) {
return new Node(t1.val || t2.val, true);
}
if (t1.isLeaf) {
return t1.val ? t1 : t2;
}
if (t2.isLeaf) {
return t2.val ? t2 : t1;
}
Node res = new Node();
res.topLeft = dfs(t1.topLeft, t2.topLeft);
res.topRight = dfs(t1.topRight, t2.topRight);
res.bottomLeft = dfs(t1.bottomLeft, t2.bottomLeft);
res.bottomRight = dfs(t1.bottomRight, t2.bottomRight);
boolean isLeaf = res.topLeft.isLeaf && res.topRight.isLeaf && res.bottomLeft.isLeaf
&& res.bottomRight.isLeaf;
boolean sameVal = res.topLeft.val == res.topRight.val
&& res.topRight.val == res.bottomLeft.val && res.bottomLeft.val == res.bottomRight.val;
if (isLeaf && sameVal) {
res = res.topLeft;
}
return res;
}
}
|
558
|
Logical OR of Two Binary Grids Represented as Quad-Trees
|
Medium
|
<p>A Binary Matrix is a matrix in which all the elements are either <strong>0</strong> or <strong>1</strong>.</p>
<p>Given <code>quadTree1</code> and <code>quadTree2</code>. <code>quadTree1</code> represents a <code>n * n</code> binary matrix and <code>quadTree2</code> represents another <code>n * n</code> binary matrix.</p>
<p>Return <em>a Quad-Tree</em> representing the <code>n * n</code> binary matrix which is the result of <strong>logical bitwise OR</strong> of the two binary matrixes represented by <code>quadTree1</code> and <code>quadTree2</code>.</p>
<p>Notice that you can assign the value of a node to <strong>True</strong> or <strong>False</strong> when <code>isLeaf</code> is <strong>False</strong>, and both are <strong>accepted</strong> in the answer.</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's or False if the node represents a grid of 0's.</li>
<li><code>isLeaf</code>: True if the node is leaf node on the tree or False if the node has the 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's</code> or all <code>0'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/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/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>The input/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> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qt1.png" style="width: 550px; height: 196px;" /> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qt2.png" style="width: 550px; height: 278px;" />
<pre>
<strong>Input:</strong> quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]
, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
<strong>Output:</strong> [[0,0],[1,1],[1,1],[1,1],[1,0]]
<strong>Explanation:</strong> quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.
If we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.
Notice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree.
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/images/qtr.png" style="width: 777px; height: 222px;" />
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> quadTree1 = [[1,0]], quadTree2 = [[1,0]]
<strong>Output:</strong> [[1,0]]
<strong>Explanation:</strong> Each tree represents a binary matrix of size 1*1. Each matrix contains only zero.
The resulting matrix is of size 1*1 with also zero.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>quadTree1</code> and <code>quadTree2</code> are both <strong>valid</strong> Quad-Trees each representing a <code>n * n</code> grid.</li>
<li><code>n == 2<sup>x</sup></code> where <code>0 <= x <= 9</code>.</li>
</ul>
|
Tree; Divide and Conquer
|
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 intersect(self, quadTree1: "Node", quadTree2: "Node") -> "Node":
def dfs(t1, t2):
if t1.isLeaf and t2.isLeaf:
return Node(t1.val or t2.val, True)
if t1.isLeaf:
return t1 if t1.val else t2
if t2.isLeaf:
return t2 if t2.val else t1
res = Node()
res.topLeft = dfs(t1.topLeft, t2.topLeft)
res.topRight = dfs(t1.topRight, t2.topRight)
res.bottomLeft = dfs(t1.bottomLeft, t2.bottomLeft)
res.bottomRight = dfs(t1.bottomRight, t2.bottomRight)
isLeaf = (
res.topLeft.isLeaf
and res.topRight.isLeaf
and res.bottomLeft.isLeaf
and res.bottomRight.isLeaf
)
sameVal = (
res.topLeft.val
== res.topRight.val
== res.bottomLeft.val
== res.bottomRight.val
)
if isLeaf and sameVal:
res = res.topLeft
return res
return dfs(quadTree1, quadTree2)
|
559
|
Maximum Depth of N-ary Tree
|
Easy
|
<p>Given a n-ary tree, find its maximum depth.</p>
<p>The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.</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> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/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> 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/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> 5
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The total number of nodes is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li>The depth of the n-ary tree is less than or equal to <code>1000</code>.</li>
</ul>
|
Tree; Depth-First Search; 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:
int maxDepth(Node* root) {
if (!root) {
return 0;
}
int mx = 0;
for (Node* child : root->children) {
mx = max(mx, maxDepth(child));
}
return mx + 1;
}
};
|
559
|
Maximum Depth of N-ary Tree
|
Easy
|
<p>Given a n-ary tree, find its maximum depth.</p>
<p>The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.</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> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/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> 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/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> 5
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The total number of nodes is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li>The depth of the n-ary tree is less than or equal to <code>1000</code>.</li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
Go
|
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/
func maxDepth(root *Node) int {
if root == nil {
return 0
}
mx := 0
for _, child := range root.Children {
mx = max(mx, maxDepth(child))
}
return 1 + mx
}
|
559
|
Maximum Depth of N-ary Tree
|
Easy
|
<p>Given a n-ary tree, find its maximum depth.</p>
<p>The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.</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> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/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> 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/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> 5
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The total number of nodes is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li>The depth of the n-ary tree is less than or equal to <code>1000</code>.</li>
</ul>
|
Tree; Depth-First Search; 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 int maxDepth(Node root) {
if (root == null) {
return 0;
}
int mx = 0;
for (Node child : root.children) {
mx = Math.max(mx, maxDepth(child));
}
return 1 + mx;
}
}
|
559
|
Maximum Depth of N-ary Tree
|
Easy
|
<p>Given a n-ary tree, find its maximum depth.</p>
<p>The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.</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> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/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> 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/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> 5
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The total number of nodes is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li>The depth of the n-ary tree is less than or equal to <code>1000</code>.</li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
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
"""
class Solution:
def maxDepth(self, root: "Node") -> int:
if root is None:
return 0
mx = 0
for child in root.children:
mx = max(mx, self.maxDepth(child))
return 1 + mx
|
559
|
Maximum Depth of N-ary Tree
|
Easy
|
<p>Given a n-ary tree, find its maximum depth.</p>
<p>The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.</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> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/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> 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/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> 5
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The total number of nodes is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
<li>The depth of the n-ary tree is less than or equal to <code>1000</code>.</li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
TypeScript
|
/**
* Definition for _Node.
* class _Node {
* val: number
* children: _Node[]
*
* constructor(val?: number, children?: _Node[]) {
* this.val = (val===undefined ? 0 : val)
* this.children = (children===undefined ? [] : children)
* }
* }
*/
function maxDepth(root: _Node | null): number {
if (!root) {
return 0;
}
return 1 + Math.max(...root.children.map(child => maxDepth(child)), 0);
}
|
560
|
Subarray Sum Equals K
|
Medium
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the total number of subarrays whose sum equals to</em> <code>k</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [1,1,1], k = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [1,2,3], k = 3
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li><code>-10<sup>7</sup> <= k <= 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
C++
|
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> cnt{{0, 1}};
int ans = 0, s = 0;
for (int x : nums) {
s += x;
ans += cnt[s - k];
++cnt[s];
}
return ans;
}
};
|
560
|
Subarray Sum Equals K
|
Medium
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the total number of subarrays whose sum equals to</em> <code>k</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [1,1,1], k = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [1,2,3], k = 3
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li><code>-10<sup>7</sup> <= k <= 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Go
|
func subarraySum(nums []int, k int) (ans int) {
cnt := map[int]int{0: 1}
s := 0
for _, x := range nums {
s += x
ans += cnt[s-k]
cnt[s]++
}
return
}
|
560
|
Subarray Sum Equals K
|
Medium
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the total number of subarrays whose sum equals to</em> <code>k</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [1,1,1], k = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [1,2,3], k = 3
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li><code>-10<sup>7</sup> <= k <= 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Java
|
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> cnt = new HashMap<>();
cnt.put(0, 1);
int ans = 0, s = 0;
for (int x : nums) {
s += x;
ans += cnt.getOrDefault(s - k, 0);
cnt.merge(s, 1, Integer::sum);
}
return ans;
}
}
|
560
|
Subarray Sum Equals K
|
Medium
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the total number of subarrays whose sum equals to</em> <code>k</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [1,1,1], k = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [1,2,3], k = 3
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li><code>-10<sup>7</sup> <= k <= 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Python
|
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
cnt = Counter({0: 1})
ans = s = 0
for x in nums:
s += x
ans += cnt[s - k]
cnt[s] += 1
return ans
|
560
|
Subarray Sum Equals K
|
Medium
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the total number of subarrays whose sum equals to</em> <code>k</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [1,1,1], k = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [1,2,3], k = 3
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li><code>-10<sup>7</sup> <= k <= 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Rust
|
use std::collections::HashMap;
impl Solution {
pub fn subarray_sum(nums: Vec<i32>, k: i32) -> i32 {
let mut cnt = HashMap::new();
cnt.insert(0, 1);
let mut ans = 0;
let mut s = 0;
for &x in &nums {
s += x;
if let Some(&v) = cnt.get(&(s - k)) {
ans += v;
}
*cnt.entry(s).or_insert(0) += 1;
}
ans
}
}
|
560
|
Subarray Sum Equals K
|
Medium
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the total number of subarrays whose sum equals to</em> <code>k</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [1,1,1], k = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [1,2,3], k = 3
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li><code>-10<sup>7</sup> <= k <= 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
TypeScript
|
function subarraySum(nums: number[], k: number): number {
const cnt: Map<number, number> = new Map();
cnt.set(0, 1);
let [ans, s] = [0, 0];
for (const x of nums) {
s += x;
ans += cnt.get(s - k) || 0;
cnt.set(s, (cnt.get(s) || 0) + 1);
}
return ans;
}
|
561
|
Array Partition
|
Easy
|
<p>Given an integer array <code>nums</code> of <code>2n</code> integers, group these integers into <code>n</code> pairs <code>(a<sub>1</sub>, b<sub>1</sub>), (a<sub>2</sub>, b<sub>2</sub>), ..., (a<sub>n</sub>, b<sub>n</sub>)</code> such that the sum of <code>min(a<sub>i</sub>, b<sub>i</sub>)</code> for all <code>i</code> is <strong>maximized</strong>. Return<em> the maximized sum</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,2,6,5,1,2]
<strong>Output:</strong> 9
<strong>Explanation:</strong> The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>nums.length == 2 * n</code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array; Counting Sort; Sorting
|
C++
|
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ans = 0;
for (int i = 0; i < nums.size(); i += 2) {
ans += nums[i];
}
return ans;
}
};
|
561
|
Array Partition
|
Easy
|
<p>Given an integer array <code>nums</code> of <code>2n</code> integers, group these integers into <code>n</code> pairs <code>(a<sub>1</sub>, b<sub>1</sub>), (a<sub>2</sub>, b<sub>2</sub>), ..., (a<sub>n</sub>, b<sub>n</sub>)</code> such that the sum of <code>min(a<sub>i</sub>, b<sub>i</sub>)</code> for all <code>i</code> is <strong>maximized</strong>. Return<em> the maximized sum</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,2,6,5,1,2]
<strong>Output:</strong> 9
<strong>Explanation:</strong> The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>nums.length == 2 * n</code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array; Counting Sort; Sorting
|
Go
|
func arrayPairSum(nums []int) (ans int) {
sort.Ints(nums)
for i := 0; i < len(nums); i += 2 {
ans += nums[i]
}
return
}
|
561
|
Array Partition
|
Easy
|
<p>Given an integer array <code>nums</code> of <code>2n</code> integers, group these integers into <code>n</code> pairs <code>(a<sub>1</sub>, b<sub>1</sub>), (a<sub>2</sub>, b<sub>2</sub>), ..., (a<sub>n</sub>, b<sub>n</sub>)</code> such that the sum of <code>min(a<sub>i</sub>, b<sub>i</sub>)</code> for all <code>i</code> is <strong>maximized</strong>. Return<em> the maximized sum</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,2,6,5,1,2]
<strong>Output:</strong> 9
<strong>Explanation:</strong> The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>nums.length == 2 * n</code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array; Counting Sort; Sorting
|
Java
|
class Solution {
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int ans = 0;
for (int i = 0; i < nums.length; i += 2) {
ans += nums[i];
}
return ans;
}
}
|
561
|
Array Partition
|
Easy
|
<p>Given an integer array <code>nums</code> of <code>2n</code> integers, group these integers into <code>n</code> pairs <code>(a<sub>1</sub>, b<sub>1</sub>), (a<sub>2</sub>, b<sub>2</sub>), ..., (a<sub>n</sub>, b<sub>n</sub>)</code> such that the sum of <code>min(a<sub>i</sub>, b<sub>i</sub>)</code> for all <code>i</code> is <strong>maximized</strong>. Return<em> the maximized sum</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,2,6,5,1,2]
<strong>Output:</strong> 9
<strong>Explanation:</strong> The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>nums.length == 2 * n</code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array; Counting Sort; Sorting
|
JavaScript
|
/**
* @param {number[]} nums
* @return {number}
*/
var arrayPairSum = function (nums) {
nums.sort((a, b) => a - b);
return nums.reduce((acc, cur, i) => (i % 2 === 0 ? acc + cur : acc), 0);
};
|
561
|
Array Partition
|
Easy
|
<p>Given an integer array <code>nums</code> of <code>2n</code> integers, group these integers into <code>n</code> pairs <code>(a<sub>1</sub>, b<sub>1</sub>), (a<sub>2</sub>, b<sub>2</sub>), ..., (a<sub>n</sub>, b<sub>n</sub>)</code> such that the sum of <code>min(a<sub>i</sub>, b<sub>i</sub>)</code> for all <code>i</code> is <strong>maximized</strong>. Return<em> the maximized sum</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,2,6,5,1,2]
<strong>Output:</strong> 9
<strong>Explanation:</strong> The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>nums.length == 2 * n</code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array; Counting Sort; Sorting
|
Python
|
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
return sum(nums[::2])
|
561
|
Array Partition
|
Easy
|
<p>Given an integer array <code>nums</code> of <code>2n</code> integers, group these integers into <code>n</code> pairs <code>(a<sub>1</sub>, b<sub>1</sub>), (a<sub>2</sub>, b<sub>2</sub>), ..., (a<sub>n</sub>, b<sub>n</sub>)</code> such that the sum of <code>min(a<sub>i</sub>, b<sub>i</sub>)</code> for all <code>i</code> is <strong>maximized</strong>. Return<em> the maximized sum</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,2,6,5,1,2]
<strong>Output:</strong> 9
<strong>Explanation:</strong> The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>nums.length == 2 * n</code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array; Counting Sort; Sorting
|
Rust
|
impl Solution {
pub fn array_pair_sum(mut nums: Vec<i32>) -> i32 {
nums.sort();
nums.iter().step_by(2).sum()
}
}
|
562
|
Longest Line of Consecutive One in Matrix
|
Medium
|
<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the length of the longest line of consecutive one in the matrix</em>.</p>
<p>The line could be horizontal, vertical, diagonal, or anti-diagonal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0562.Longest%20Line%20of%20Consecutive%20One%20in%20Matrix/images/long1-grid.jpg" style="width: 333px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0562.Longest%20Line%20of%20Consecutive%20One%20in%20Matrix/images/long2-grid.jpg" style="width: 333px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
C++
|
class Solution {
public:
int longestLine(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<vector<int>> a(m + 2, vector<int>(n + 2));
vector<vector<int>> b(m + 2, vector<int>(n + 2));
vector<vector<int>> c(m + 2, vector<int>(n + 2));
vector<vector<int>> d(m + 2, vector<int>(n + 2));
int ans = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (mat[i - 1][j - 1]) {
a[i][j] = a[i - 1][j] + 1;
b[i][j] = b[i][j - 1] + 1;
c[i][j] = c[i - 1][j - 1] + 1;
d[i][j] = d[i - 1][j + 1] + 1;
ans = max(ans, max(a[i][j], max(b[i][j], max(c[i][j], d[i][j]))));
}
}
}
return ans;
}
};
|
562
|
Longest Line of Consecutive One in Matrix
|
Medium
|
<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the length of the longest line of consecutive one in the matrix</em>.</p>
<p>The line could be horizontal, vertical, diagonal, or anti-diagonal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0562.Longest%20Line%20of%20Consecutive%20One%20in%20Matrix/images/long1-grid.jpg" style="width: 333px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0562.Longest%20Line%20of%20Consecutive%20One%20in%20Matrix/images/long2-grid.jpg" style="width: 333px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Go
|
func longestLine(mat [][]int) (ans int) {
m, n := len(mat), len(mat[0])
f := make([][][4]int, m+2)
for i := range f {
f[i] = make([][4]int, n+2)
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
if mat[i-1][j-1] == 1 {
f[i][j][0] = f[i-1][j][0] + 1
f[i][j][1] = f[i][j-1][1] + 1
f[i][j][2] = f[i-1][j-1][2] + 1
f[i][j][3] = f[i-1][j+1][3] + 1
for _, v := range f[i][j] {
if ans < v {
ans = v
}
}
}
}
}
return
}
|
562
|
Longest Line of Consecutive One in Matrix
|
Medium
|
<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the length of the longest line of consecutive one in the matrix</em>.</p>
<p>The line could be horizontal, vertical, diagonal, or anti-diagonal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0562.Longest%20Line%20of%20Consecutive%20One%20in%20Matrix/images/long1-grid.jpg" style="width: 333px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0562.Longest%20Line%20of%20Consecutive%20One%20in%20Matrix/images/long2-grid.jpg" style="width: 333px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Java
|
class Solution {
public int longestLine(int[][] mat) {
int m = mat.length, n = mat[0].length;
int[][] a = new int[m + 2][n + 2];
int[][] b = new int[m + 2][n + 2];
int[][] c = new int[m + 2][n + 2];
int[][] d = new int[m + 2][n + 2];
int ans = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (mat[i - 1][j - 1] == 1) {
a[i][j] = a[i - 1][j] + 1;
b[i][j] = b[i][j - 1] + 1;
c[i][j] = c[i - 1][j - 1] + 1;
d[i][j] = d[i - 1][j + 1] + 1;
ans = max(ans, a[i][j], b[i][j], c[i][j], d[i][j]);
}
}
}
return ans;
}
private int max(int... arr) {
int ans = 0;
for (int v : arr) {
ans = Math.max(ans, v);
}
return ans;
}
}
|
562
|
Longest Line of Consecutive One in Matrix
|
Medium
|
<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the length of the longest line of consecutive one in the matrix</em>.</p>
<p>The line could be horizontal, vertical, diagonal, or anti-diagonal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0562.Longest%20Line%20of%20Consecutive%20One%20in%20Matrix/images/long1-grid.jpg" style="width: 333px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
<strong>Output:</strong> 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0562.Longest%20Line%20of%20Consecutive%20One%20in%20Matrix/images/long2-grid.jpg" style="width: 333px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Python
|
class Solution:
def longestLine(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
a = [[0] * (n + 2) for _ in range(m + 2)]
b = [[0] * (n + 2) for _ in range(m + 2)]
c = [[0] * (n + 2) for _ in range(m + 2)]
d = [[0] * (n + 2) for _ in range(m + 2)]
ans = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if mat[i - 1][j - 1]:
a[i][j] = a[i - 1][j] + 1
b[i][j] = b[i][j - 1] + 1
c[i][j] = c[i - 1][j - 1] + 1
d[i][j] = d[i - 1][j + 1] + 1
ans = max(ans, a[i][j], b[i][j], c[i][j], d[i][j])
return ans
|
563
|
Binary Tree Tilt
|
Easy
|
<p>Given the <code>root</code> of a binary tree, return <em>the sum of every tree node's <strong>tilt</strong>.</em></p>
<p>The <strong>tilt</strong> of a tree node is the <strong>absolute difference</strong> between the sum of all left subtree node <strong>values</strong> and all right subtree node <strong>values</strong>. If a node does not have a left child, then the sum of the left subtree node <strong>values</strong> is treated as <code>0</code>. The rule is similar if the node does not have a right child.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt1.jpg" style="width: 712px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Tilt of node 2 : |0-0| = 0 (no children)
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
Sum of every tilt : 0 + 0 + 1 = 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt2.jpg" style="width: 800px; height: 203px;" />
<pre>
<strong>Input:</strong> root = [4,2,9,3,5,null,7]
<strong>Output:</strong> 15
<strong>Explanation:</strong>
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 5 : |0-0| = 0 (no children)
Tilt of node 7 : |0-0| = 0 (no children)
Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt3.jpg" style="width: 800px; height: 293px;" />
<pre>
<strong>Input:</strong> root = [21,7,14,1,1,2,2,3,3]
<strong>Output:</strong> 9
</pre>
<p> </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>-1000 <= Node.val <= 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 findTilt(TreeNode* root) {
int ans = 0;
auto dfs = [&](this auto&& dfs, TreeNode* root) -> int {
if (!root) {
return 0;
}
int l = dfs(root->left), r = dfs(root->right);
ans += abs(l - r);
return l + r + root->val;
};
dfs(root);
return ans;
}
};
|
563
|
Binary Tree Tilt
|
Easy
|
<p>Given the <code>root</code> of a binary tree, return <em>the sum of every tree node's <strong>tilt</strong>.</em></p>
<p>The <strong>tilt</strong> of a tree node is the <strong>absolute difference</strong> between the sum of all left subtree node <strong>values</strong> and all right subtree node <strong>values</strong>. If a node does not have a left child, then the sum of the left subtree node <strong>values</strong> is treated as <code>0</code>. The rule is similar if the node does not have a right child.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt1.jpg" style="width: 712px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Tilt of node 2 : |0-0| = 0 (no children)
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
Sum of every tilt : 0 + 0 + 1 = 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt2.jpg" style="width: 800px; height: 203px;" />
<pre>
<strong>Input:</strong> root = [4,2,9,3,5,null,7]
<strong>Output:</strong> 15
<strong>Explanation:</strong>
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 5 : |0-0| = 0 (no children)
Tilt of node 7 : |0-0| = 0 (no children)
Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt3.jpg" style="width: 800px; height: 293px;" />
<pre>
<strong>Input:</strong> root = [21,7,14,1,1,2,2,3,3]
<strong>Output:</strong> 9
</pre>
<p> </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>-1000 <= Node.val <= 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 findTilt(root *TreeNode) (ans int) {
var dfs func(*TreeNode) int
dfs = func(root *TreeNode) int {
if root == nil {
return 0
}
l, r := dfs(root.Left), dfs(root.Right)
ans += abs(l - r)
return l + r + root.Val
}
dfs(root)
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
563
|
Binary Tree Tilt
|
Easy
|
<p>Given the <code>root</code> of a binary tree, return <em>the sum of every tree node's <strong>tilt</strong>.</em></p>
<p>The <strong>tilt</strong> of a tree node is the <strong>absolute difference</strong> between the sum of all left subtree node <strong>values</strong> and all right subtree node <strong>values</strong>. If a node does not have a left child, then the sum of the left subtree node <strong>values</strong> is treated as <code>0</code>. The rule is similar if the node does not have a right child.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt1.jpg" style="width: 712px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Tilt of node 2 : |0-0| = 0 (no children)
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
Sum of every tilt : 0 + 0 + 1 = 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt2.jpg" style="width: 800px; height: 203px;" />
<pre>
<strong>Input:</strong> root = [4,2,9,3,5,null,7]
<strong>Output:</strong> 15
<strong>Explanation:</strong>
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 5 : |0-0| = 0 (no children)
Tilt of node 7 : |0-0| = 0 (no children)
Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt3.jpg" style="width: 800px; height: 293px;" />
<pre>
<strong>Input:</strong> root = [21,7,14,1,1,2,2,3,3]
<strong>Output:</strong> 9
</pre>
<p> </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>-1000 <= Node.val <= 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 int ans;
public int findTilt(TreeNode root) {
dfs(root);
return ans;
}
private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int l = dfs(root.left), r = dfs(root.right);
ans += Math.abs(l - r);
return l + r + root.val;
}
}
|
563
|
Binary Tree Tilt
|
Easy
|
<p>Given the <code>root</code> of a binary tree, return <em>the sum of every tree node's <strong>tilt</strong>.</em></p>
<p>The <strong>tilt</strong> of a tree node is the <strong>absolute difference</strong> between the sum of all left subtree node <strong>values</strong> and all right subtree node <strong>values</strong>. If a node does not have a left child, then the sum of the left subtree node <strong>values</strong> is treated as <code>0</code>. The rule is similar if the node does not have a right child.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt1.jpg" style="width: 712px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Tilt of node 2 : |0-0| = 0 (no children)
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
Sum of every tilt : 0 + 0 + 1 = 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt2.jpg" style="width: 800px; height: 203px;" />
<pre>
<strong>Input:</strong> root = [4,2,9,3,5,null,7]
<strong>Output:</strong> 15
<strong>Explanation:</strong>
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 5 : |0-0| = 0 (no children)
Tilt of node 7 : |0-0| = 0 (no children)
Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt3.jpg" style="width: 800px; height: 293px;" />
<pre>
<strong>Input:</strong> root = [21,7,14,1,1,2,2,3,3]
<strong>Output:</strong> 9
</pre>
<p> </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>-1000 <= Node.val <= 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 findTilt(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
l, r = dfs(root.left), dfs(root.right)
nonlocal ans
ans += abs(l - r)
return l + r + root.val
ans = 0
dfs(root)
return ans
|
563
|
Binary Tree Tilt
|
Easy
|
<p>Given the <code>root</code> of a binary tree, return <em>the sum of every tree node's <strong>tilt</strong>.</em></p>
<p>The <strong>tilt</strong> of a tree node is the <strong>absolute difference</strong> between the sum of all left subtree node <strong>values</strong> and all right subtree node <strong>values</strong>. If a node does not have a left child, then the sum of the left subtree node <strong>values</strong> is treated as <code>0</code>. The rule is similar if the node does not have a right child.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt1.jpg" style="width: 712px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Tilt of node 2 : |0-0| = 0 (no children)
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
Sum of every tilt : 0 + 0 + 1 = 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt2.jpg" style="width: 800px; height: 203px;" />
<pre>
<strong>Input:</strong> root = [4,2,9,3,5,null,7]
<strong>Output:</strong> 15
<strong>Explanation:</strong>
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 5 : |0-0| = 0 (no children)
Tilt of node 7 : |0-0| = 0 (no children)
Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0563.Binary%20Tree%20Tilt/images/tilt3.jpg" style="width: 800px; height: 293px;" />
<pre>
<strong>Input:</strong> root = [21,7,14,1,1,2,2,3,3]
<strong>Output:</strong> 9
</pre>
<p> </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>-1000 <= Node.val <= 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 findTilt(root: TreeNode | null): number {
let ans: number = 0;
const dfs = (root: TreeNode | null): number => {
if (!root) {
return 0;
}
const [l, r] = [dfs(root.left), dfs(root.right)];
ans += Math.abs(l - r);
return l + r + root.val;
};
dfs(root);
return ans;
}
|
564
|
Find the Closest Palindrome
|
Hard
|
<p>Given a string <code>n</code> representing an integer, return <em>the closest integer (not including itself), which is a palindrome</em>. If there is a tie, return <em><strong>the smaller one</strong></em>.</p>
<p>The closest is defined as the absolute difference minimized between two integers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = "123"
<strong>Output:</strong> "121"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = "1"
<strong>Output:</strong> "0"
<strong>Explanation:</strong> 0 and 2 are the closest palindromes but we return the smallest which is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n.length <= 18</code></li>
<li><code>n</code> consists of only digits.</li>
<li><code>n</code> does not have leading zeros.</li>
<li><code>n</code> is representing an integer in the range <code>[1, 10<sup>18</sup> - 1]</code>.</li>
</ul>
|
Math; String
|
C++
|
class Solution {
public:
string nearestPalindromic(string n) {
long x = stol(n);
long ans = -1;
for (long t : get(n))
if (ans == -1 || abs(t - x) < abs(ans - x) || (abs(t - x) == abs(ans - x) && t < ans))
ans = t;
return to_string(ans);
}
unordered_set<long> get(string& n) {
int l = n.size();
unordered_set<long> res;
res.insert((long) pow(10, l - 1) - 1);
res.insert((long) pow(10, l) + 1);
long left = stol(n.substr(0, (l + 1) / 2));
for (long i = left - 1; i <= left + 1; ++i) {
string prefix = to_string(i);
string t = prefix + string(prefix.rbegin() + (l & 1), prefix.rend());
res.insert(stol(t));
}
res.erase(stol(n));
return res;
}
};
|
564
|
Find the Closest Palindrome
|
Hard
|
<p>Given a string <code>n</code> representing an integer, return <em>the closest integer (not including itself), which is a palindrome</em>. If there is a tie, return <em><strong>the smaller one</strong></em>.</p>
<p>The closest is defined as the absolute difference minimized between two integers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = "123"
<strong>Output:</strong> "121"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = "1"
<strong>Output:</strong> "0"
<strong>Explanation:</strong> 0 and 2 are the closest palindromes but we return the smallest which is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n.length <= 18</code></li>
<li><code>n</code> consists of only digits.</li>
<li><code>n</code> does not have leading zeros.</li>
<li><code>n</code> is representing an integer in the range <code>[1, 10<sup>18</sup> - 1]</code>.</li>
</ul>
|
Math; String
|
Go
|
func nearestPalindromic(n string) string {
l := len(n)
res := []int{int(math.Pow10(l-1)) - 1, int(math.Pow10(l)) + 1}
left, _ := strconv.Atoi(n[:(l+1)/2])
for _, x := range []int{left - 1, left, left + 1} {
y := x
if l&1 == 1 {
y /= 10
}
for ; y > 0; y /= 10 {
x = x*10 + y%10
}
res = append(res, x)
}
ans := -1
x, _ := strconv.Atoi(n)
for _, t := range res {
if t != x {
if ans == -1 || abs(t-x) < abs(ans-x) || abs(t-x) == abs(ans-x) && t < ans {
ans = t
}
}
}
return strconv.Itoa(ans)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
564
|
Find the Closest Palindrome
|
Hard
|
<p>Given a string <code>n</code> representing an integer, return <em>the closest integer (not including itself), which is a palindrome</em>. If there is a tie, return <em><strong>the smaller one</strong></em>.</p>
<p>The closest is defined as the absolute difference minimized between two integers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = "123"
<strong>Output:</strong> "121"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = "1"
<strong>Output:</strong> "0"
<strong>Explanation:</strong> 0 and 2 are the closest palindromes but we return the smallest which is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n.length <= 18</code></li>
<li><code>n</code> consists of only digits.</li>
<li><code>n</code> does not have leading zeros.</li>
<li><code>n</code> is representing an integer in the range <code>[1, 10<sup>18</sup> - 1]</code>.</li>
</ul>
|
Math; String
|
Java
|
class Solution {
public String nearestPalindromic(String n) {
long x = Long.parseLong(n);
long ans = -1;
for (long t : get(n)) {
if (ans == -1 || Math.abs(t - x) < Math.abs(ans - x)
|| (Math.abs(t - x) == Math.abs(ans - x) && t < ans)) {
ans = t;
}
}
return Long.toString(ans);
}
private Set<Long> get(String n) {
int l = n.length();
Set<Long> res = new HashSet<>();
res.add((long) Math.pow(10, l - 1) - 1);
res.add((long) Math.pow(10, l) + 1);
long left = Long.parseLong(n.substring(0, (l + 1) / 2));
for (long i = left - 1; i <= left + 1; ++i) {
StringBuilder sb = new StringBuilder();
sb.append(i);
sb.append(new StringBuilder(i + "").reverse().substring(l & 1));
res.add(Long.parseLong(sb.toString()));
}
res.remove(Long.parseLong(n));
return res;
}
}
|
564
|
Find the Closest Palindrome
|
Hard
|
<p>Given a string <code>n</code> representing an integer, return <em>the closest integer (not including itself), which is a palindrome</em>. If there is a tie, return <em><strong>the smaller one</strong></em>.</p>
<p>The closest is defined as the absolute difference minimized between two integers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = "123"
<strong>Output:</strong> "121"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = "1"
<strong>Output:</strong> "0"
<strong>Explanation:</strong> 0 and 2 are the closest palindromes but we return the smallest which is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n.length <= 18</code></li>
<li><code>n</code> consists of only digits.</li>
<li><code>n</code> does not have leading zeros.</li>
<li><code>n</code> is representing an integer in the range <code>[1, 10<sup>18</sup> - 1]</code>.</li>
</ul>
|
Math; String
|
JavaScript
|
/**
* @param {string} n
* @return {string}
*/
function nearestPalindromic(n) {
const x = BigInt(n);
let ans = null;
for (const t of getCandidates(n)) {
if (
ans === null ||
absDiff(t, x) < absDiff(ans, x) ||
(absDiff(t, x) === absDiff(ans, x) && t < ans)
) {
ans = t;
}
}
return ans.toString();
}
function getCandidates(n) {
const length = n.length;
const res = new Set();
res.add(BigInt(Math.pow(10, length - 1) - 1));
res.add(BigInt(Math.pow(10, length) + 1));
const left = BigInt(n.substring(0, Math.ceil(length / 2)));
for (let i = left - 1n; i <= left + 1n; i++) {
const prefix = i.toString();
const t =
prefix +
prefix
.split('')
.reverse()
.slice(length % 2)
.join('');
res.add(BigInt(t));
}
res.delete(BigInt(n));
return res;
}
function absDiff(a, b) {
return a > b ? a - b : b - a;
}
|
564
|
Find the Closest Palindrome
|
Hard
|
<p>Given a string <code>n</code> representing an integer, return <em>the closest integer (not including itself), which is a palindrome</em>. If there is a tie, return <em><strong>the smaller one</strong></em>.</p>
<p>The closest is defined as the absolute difference minimized between two integers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = "123"
<strong>Output:</strong> "121"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = "1"
<strong>Output:</strong> "0"
<strong>Explanation:</strong> 0 and 2 are the closest palindromes but we return the smallest which is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n.length <= 18</code></li>
<li><code>n</code> consists of only digits.</li>
<li><code>n</code> does not have leading zeros.</li>
<li><code>n</code> is representing an integer in the range <code>[1, 10<sup>18</sup> - 1]</code>.</li>
</ul>
|
Math; String
|
Python
|
class Solution:
def nearestPalindromic(self, n: str) -> str:
x = int(n)
l = len(n)
res = {10 ** (l - 1) - 1, 10**l + 1}
left = int(n[: (l + 1) >> 1])
for i in range(left - 1, left + 2):
j = i if l % 2 == 0 else i // 10
while j:
i = i * 10 + j % 10
j //= 10
res.add(i)
res.discard(x)
ans = -1
for t in res:
if (
ans == -1
or abs(t - x) < abs(ans - x)
or (abs(t - x) == abs(ans - x) and t < ans)
):
ans = t
return str(ans)
|
565
|
Array Nesting
|
Medium
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> where <code>nums</code> is a permutation of the numbers in the range <code>[0, n - 1]</code>.</p>
<p>You should build a set <code>s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }</code> subjected to the following rule:</p>
<ul>
<li>The first element in <code>s[k]</code> starts with the selection of the element <code>nums[k]</code> of <code>index = k</code>.</li>
<li>The next element in <code>s[k]</code> should be <code>nums[nums[k]]</code>, and then <code>nums[nums[nums[k]]]</code>, and so on.</li>
<li>We stop adding right before a duplicate element occurs in <code>s[k]</code>.</li>
</ul>
<p>Return <em>the longest length of a set</em> <code>s[k]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,0,3,1,6,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
One of the longest sets s[k]:
s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,2]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] < nums.length</code></li>
<li>All the values of <code>nums</code> are <strong>unique</strong>.</li>
</ul>
|
Depth-First Search; Array
|
C++
|
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int n = nums.size();
vector<bool> vis(n);
int res = 0;
for (int i = 0; i < n; ++i) {
if (vis[i]) continue;
int cur = nums[i], m = 1;
vis[cur] = true;
while (nums[cur] != nums[i]) {
cur = nums[cur];
++m;
vis[cur] = true;
}
res = max(res, m);
}
return res;
}
};
|
565
|
Array Nesting
|
Medium
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> where <code>nums</code> is a permutation of the numbers in the range <code>[0, n - 1]</code>.</p>
<p>You should build a set <code>s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }</code> subjected to the following rule:</p>
<ul>
<li>The first element in <code>s[k]</code> starts with the selection of the element <code>nums[k]</code> of <code>index = k</code>.</li>
<li>The next element in <code>s[k]</code> should be <code>nums[nums[k]]</code>, and then <code>nums[nums[nums[k]]]</code>, and so on.</li>
<li>We stop adding right before a duplicate element occurs in <code>s[k]</code>.</li>
</ul>
<p>Return <em>the longest length of a set</em> <code>s[k]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,0,3,1,6,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
One of the longest sets s[k]:
s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,2]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] < nums.length</code></li>
<li>All the values of <code>nums</code> are <strong>unique</strong>.</li>
</ul>
|
Depth-First Search; Array
|
Go
|
func arrayNesting(nums []int) int {
n := len(nums)
vis := make([]bool, n)
ans := 0
for i := 0; i < n; i++ {
if vis[i] {
continue
}
cur, m := nums[i], 1
vis[cur] = true
for nums[cur] != nums[i] {
cur = nums[cur]
m++
vis[cur] = true
}
if m > ans {
ans = m
}
}
return ans
}
|
565
|
Array Nesting
|
Medium
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> where <code>nums</code> is a permutation of the numbers in the range <code>[0, n - 1]</code>.</p>
<p>You should build a set <code>s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }</code> subjected to the following rule:</p>
<ul>
<li>The first element in <code>s[k]</code> starts with the selection of the element <code>nums[k]</code> of <code>index = k</code>.</li>
<li>The next element in <code>s[k]</code> should be <code>nums[nums[k]]</code>, and then <code>nums[nums[nums[k]]]</code>, and so on.</li>
<li>We stop adding right before a duplicate element occurs in <code>s[k]</code>.</li>
</ul>
<p>Return <em>the longest length of a set</em> <code>s[k]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,0,3,1,6,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
One of the longest sets s[k]:
s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,2]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] < nums.length</code></li>
<li>All the values of <code>nums</code> are <strong>unique</strong>.</li>
</ul>
|
Depth-First Search; Array
|
Java
|
class Solution {
public int arrayNesting(int[] nums) {
int n = nums.length;
boolean[] vis = new boolean[n];
int res = 0;
for (int i = 0; i < n; i++) {
if (vis[i]) {
continue;
}
int cur = nums[i], m = 1;
vis[cur] = true;
while (nums[cur] != nums[i]) {
cur = nums[cur];
m++;
vis[cur] = true;
}
res = Math.max(res, m);
}
return res;
}
}
|
565
|
Array Nesting
|
Medium
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> where <code>nums</code> is a permutation of the numbers in the range <code>[0, n - 1]</code>.</p>
<p>You should build a set <code>s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }</code> subjected to the following rule:</p>
<ul>
<li>The first element in <code>s[k]</code> starts with the selection of the element <code>nums[k]</code> of <code>index = k</code>.</li>
<li>The next element in <code>s[k]</code> should be <code>nums[nums[k]]</code>, and then <code>nums[nums[nums[k]]]</code>, and so on.</li>
<li>We stop adding right before a duplicate element occurs in <code>s[k]</code>.</li>
</ul>
<p>Return <em>the longest length of a set</em> <code>s[k]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,0,3,1,6,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
One of the longest sets s[k]:
s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,2]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] < nums.length</code></li>
<li>All the values of <code>nums</code> are <strong>unique</strong>.</li>
</ul>
|
Depth-First Search; Array
|
Python
|
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
n = len(nums)
vis = [False] * n
res = 0
for i in range(n):
if vis[i]:
continue
cur, m = nums[i], 1
vis[cur] = True
while nums[cur] != nums[i]:
cur = nums[cur]
m += 1
vis[cur] = True
res = max(res, m)
return res
|
566
|
Reshape the Matrix
|
Easy
|
<p>In MATLAB, there is a handy function called <code>reshape</code> which can reshape an <code>m x n</code> matrix into a new one with a different size <code>r x c</code> keeping its original data.</p>
<p>You are given an <code>m x n</code> matrix <code>mat</code> and two integers <code>r</code> and <code>c</code> representing the number of rows and the number of columns of the wanted reshaped matrix.</p>
<p>The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.</p>
<p>If the <code>reshape</code> operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape1-grid.jpg" style="width: 613px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 1, c = 4
<strong>Output:</strong> [[1,2,3,4]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape2-grid.jpg" style="width: 453px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 2, c = 4
<strong>Output:</strong> [[1,2],[3,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>-1000 <= mat[i][j] <= 1000</code></li>
<li><code>1 <= r, c <= 300</code></li>
</ul>
|
Array; Matrix; Simulation
|
C
|
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** matrixReshape(int** mat, int matSize, int* matColSize, int r, int c, int* returnSize, int** returnColumnSizes) {
if (matSize * matColSize[0] != r * c) {
*returnSize = matSize;
*returnColumnSizes = matColSize;
return mat;
}
*returnSize = r;
*returnColumnSizes = malloc(sizeof(int) * r);
int** ans = malloc(sizeof(int*) * r);
for (int i = 0; i < r; i++) {
(*returnColumnSizes)[i] = c;
ans[i] = malloc(sizeof(int) * c);
}
for (int i = 0; i < r * c; i++) {
ans[i / c][i % c] = mat[i / matColSize[0]][i % matColSize[0]];
}
return ans;
}
|
566
|
Reshape the Matrix
|
Easy
|
<p>In MATLAB, there is a handy function called <code>reshape</code> which can reshape an <code>m x n</code> matrix into a new one with a different size <code>r x c</code> keeping its original data.</p>
<p>You are given an <code>m x n</code> matrix <code>mat</code> and two integers <code>r</code> and <code>c</code> representing the number of rows and the number of columns of the wanted reshaped matrix.</p>
<p>The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.</p>
<p>If the <code>reshape</code> operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape1-grid.jpg" style="width: 613px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 1, c = 4
<strong>Output:</strong> [[1,2,3,4]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape2-grid.jpg" style="width: 453px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 2, c = 4
<strong>Output:</strong> [[1,2],[3,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>-1000 <= mat[i][j] <= 1000</code></li>
<li><code>1 <= r, c <= 300</code></li>
</ul>
|
Array; Matrix; Simulation
|
C++
|
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
int m = mat.size(), n = mat[0].size();
if (m * n != r * c) {
return mat;
}
vector<vector<int>> ans(r, vector<int>(c));
for (int i = 0; i < m * n; ++i) {
ans[i / c][i % c] = mat[i / n][i % n];
}
return ans;
}
};
|
566
|
Reshape the Matrix
|
Easy
|
<p>In MATLAB, there is a handy function called <code>reshape</code> which can reshape an <code>m x n</code> matrix into a new one with a different size <code>r x c</code> keeping its original data.</p>
<p>You are given an <code>m x n</code> matrix <code>mat</code> and two integers <code>r</code> and <code>c</code> representing the number of rows and the number of columns of the wanted reshaped matrix.</p>
<p>The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.</p>
<p>If the <code>reshape</code> operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape1-grid.jpg" style="width: 613px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 1, c = 4
<strong>Output:</strong> [[1,2,3,4]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape2-grid.jpg" style="width: 453px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 2, c = 4
<strong>Output:</strong> [[1,2],[3,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>-1000 <= mat[i][j] <= 1000</code></li>
<li><code>1 <= r, c <= 300</code></li>
</ul>
|
Array; Matrix; Simulation
|
Go
|
func matrixReshape(mat [][]int, r int, c int) [][]int {
m, n := len(mat), len(mat[0])
if m*n != r*c {
return mat
}
ans := make([][]int, r)
for i := range ans {
ans[i] = make([]int, c)
}
for i := 0; i < m*n; i++ {
ans[i/c][i%c] = mat[i/n][i%n]
}
return ans
}
|
566
|
Reshape the Matrix
|
Easy
|
<p>In MATLAB, there is a handy function called <code>reshape</code> which can reshape an <code>m x n</code> matrix into a new one with a different size <code>r x c</code> keeping its original data.</p>
<p>You are given an <code>m x n</code> matrix <code>mat</code> and two integers <code>r</code> and <code>c</code> representing the number of rows and the number of columns of the wanted reshaped matrix.</p>
<p>The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.</p>
<p>If the <code>reshape</code> operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape1-grid.jpg" style="width: 613px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 1, c = 4
<strong>Output:</strong> [[1,2,3,4]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape2-grid.jpg" style="width: 453px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 2, c = 4
<strong>Output:</strong> [[1,2],[3,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>-1000 <= mat[i][j] <= 1000</code></li>
<li><code>1 <= r, c <= 300</code></li>
</ul>
|
Array; Matrix; Simulation
|
Java
|
class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int m = mat.length, n = mat[0].length;
if (m * n != r * c) {
return mat;
}
int[][] ans = new int[r][c];
for (int i = 0; i < m * n; ++i) {
ans[i / c][i % c] = mat[i / n][i % n];
}
return ans;
}
}
|
566
|
Reshape the Matrix
|
Easy
|
<p>In MATLAB, there is a handy function called <code>reshape</code> which can reshape an <code>m x n</code> matrix into a new one with a different size <code>r x c</code> keeping its original data.</p>
<p>You are given an <code>m x n</code> matrix <code>mat</code> and two integers <code>r</code> and <code>c</code> representing the number of rows and the number of columns of the wanted reshaped matrix.</p>
<p>The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.</p>
<p>If the <code>reshape</code> operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape1-grid.jpg" style="width: 613px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 1, c = 4
<strong>Output:</strong> [[1,2,3,4]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape2-grid.jpg" style="width: 453px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 2, c = 4
<strong>Output:</strong> [[1,2],[3,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>-1000 <= mat[i][j] <= 1000</code></li>
<li><code>1 <= r, c <= 300</code></li>
</ul>
|
Array; Matrix; Simulation
|
Python
|
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
m, n = len(mat), len(mat[0])
if m * n != r * c:
return mat
ans = [[0] * c for _ in range(r)]
for i in range(m * n):
ans[i // c][i % c] = mat[i // n][i % n]
return ans
|
566
|
Reshape the Matrix
|
Easy
|
<p>In MATLAB, there is a handy function called <code>reshape</code> which can reshape an <code>m x n</code> matrix into a new one with a different size <code>r x c</code> keeping its original data.</p>
<p>You are given an <code>m x n</code> matrix <code>mat</code> and two integers <code>r</code> and <code>c</code> representing the number of rows and the number of columns of the wanted reshaped matrix.</p>
<p>The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.</p>
<p>If the <code>reshape</code> operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape1-grid.jpg" style="width: 613px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 1, c = 4
<strong>Output:</strong> [[1,2,3,4]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape2-grid.jpg" style="width: 453px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 2, c = 4
<strong>Output:</strong> [[1,2],[3,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>-1000 <= mat[i][j] <= 1000</code></li>
<li><code>1 <= r, c <= 300</code></li>
</ul>
|
Array; Matrix; Simulation
|
Rust
|
impl Solution {
pub fn matrix_reshape(mat: Vec<Vec<i32>>, r: i32, c: i32) -> Vec<Vec<i32>> {
let r = r as usize;
let c = c as usize;
let m = mat.len();
let n = mat[0].len();
if m * n != r * c {
return mat;
}
let mut i = 0;
let mut j = 0;
(0..r)
.into_iter()
.map(|_| {
(0..c)
.into_iter()
.map(|_| {
let res = mat[i][j];
j += 1;
if j == n {
j = 0;
i += 1;
}
res
})
.collect()
})
.collect()
}
}
|
566
|
Reshape the Matrix
|
Easy
|
<p>In MATLAB, there is a handy function called <code>reshape</code> which can reshape an <code>m x n</code> matrix into a new one with a different size <code>r x c</code> keeping its original data.</p>
<p>You are given an <code>m x n</code> matrix <code>mat</code> and two integers <code>r</code> and <code>c</code> representing the number of rows and the number of columns of the wanted reshaped matrix.</p>
<p>The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.</p>
<p>If the <code>reshape</code> operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape1-grid.jpg" style="width: 613px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 1, c = 4
<strong>Output:</strong> [[1,2,3,4]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0566.Reshape%20the%20Matrix/images/reshape2-grid.jpg" style="width: 453px; height: 173px;" />
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]], r = 2, c = 4
<strong>Output:</strong> [[1,2],[3,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>-1000 <= mat[i][j] <= 1000</code></li>
<li><code>1 <= r, c <= 300</code></li>
</ul>
|
Array; Matrix; Simulation
|
TypeScript
|
function matrixReshape(mat: number[][], r: number, c: number): number[][] {
let m = mat.length,
n = mat[0].length;
if (m * n != r * c) return mat;
let ans = Array.from({ length: r }, v => new Array(c).fill(0));
let k = 0;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
ans[Math.floor(k / c)][k % c] = mat[i][j];
++k;
}
}
return ans;
}
|
567
|
Permutation in String
|
Medium
|
<p>Given two strings <code>s1</code> and <code>s2</code>, return <code>true</code> if <code>s2</code> contains a <span data-keyword="permutation-string">permutation</span> of <code>s1</code>, or <code>false</code> otherwise.</p>
<p>In other words, return <code>true</code> if one of <code>s1</code>'s permutations is the substring of <code>s2</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidbaooo"
<strong>Output:</strong> true
<strong>Explanation:</strong> s2 contains one permutation of s1 ("ba").
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidboaoo"
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 10<sup>4</sup></code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
</ul>
|
Hash Table; Two Pointers; String; Sliding Window
|
C++
|
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int need = 0;
int cnt[26]{};
for (char c : s1) {
if (++cnt[c - 'a'] == 1) {
++need;
}
}
int m = s1.size(), n = s2.size();
for (int i = 0; i < n; ++i) {
int c = s2[i] - 'a';
if (--cnt[c] == 0) {
--need;
}
if (i >= m) {
c = s2[i - m] - 'a';
if (++cnt[c] == 1) {
++need;
}
}
if (need == 0) {
return true;
}
}
return false;
}
};
|
567
|
Permutation in String
|
Medium
|
<p>Given two strings <code>s1</code> and <code>s2</code>, return <code>true</code> if <code>s2</code> contains a <span data-keyword="permutation-string">permutation</span> of <code>s1</code>, or <code>false</code> otherwise.</p>
<p>In other words, return <code>true</code> if one of <code>s1</code>'s permutations is the substring of <code>s2</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidbaooo"
<strong>Output:</strong> true
<strong>Explanation:</strong> s2 contains one permutation of s1 ("ba").
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidboaoo"
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 10<sup>4</sup></code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
</ul>
|
Hash Table; Two Pointers; String; Sliding Window
|
C#
|
public class Solution {
public bool CheckInclusion(string s1, string s2) {
int need = 0;
int[] cnt = new int[26];
foreach (char c in s1) {
if (++cnt[c - 'a'] == 1) {
need++;
}
}
int m = s1.Length, n = s2.Length;
for (int i = 0; i < n; i++) {
int c = s2[i] - 'a';
if (--cnt[c] == 0) {
need--;
}
if (i >= m) {
c = s2[i - m] - 'a';
if (++cnt[c] == 1) {
need++;
}
}
if (need == 0) {
return true;
}
}
return false;
}
}
|
567
|
Permutation in String
|
Medium
|
<p>Given two strings <code>s1</code> and <code>s2</code>, return <code>true</code> if <code>s2</code> contains a <span data-keyword="permutation-string">permutation</span> of <code>s1</code>, or <code>false</code> otherwise.</p>
<p>In other words, return <code>true</code> if one of <code>s1</code>'s permutations is the substring of <code>s2</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidbaooo"
<strong>Output:</strong> true
<strong>Explanation:</strong> s2 contains one permutation of s1 ("ba").
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidboaoo"
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 10<sup>4</sup></code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
</ul>
|
Hash Table; Two Pointers; String; Sliding Window
|
Go
|
func checkInclusion(s1 string, s2 string) bool {
need := 0
cnt := [26]int{}
for _, c := range s1 {
if cnt[c-'a']++; cnt[c-'a'] == 1 {
need++
}
}
m, n := len(s1), len(s2)
for i := 0; i < n; i++ {
c := s2[i] - 'a'
if cnt[c]--; cnt[c] == 0 {
need--
}
if i >= m {
c = s2[i-m] - 'a'
if cnt[c]++; cnt[c] == 1 {
need++
}
}
if need == 0 {
return true
}
}
return false
}
|
567
|
Permutation in String
|
Medium
|
<p>Given two strings <code>s1</code> and <code>s2</code>, return <code>true</code> if <code>s2</code> contains a <span data-keyword="permutation-string">permutation</span> of <code>s1</code>, or <code>false</code> otherwise.</p>
<p>In other words, return <code>true</code> if one of <code>s1</code>'s permutations is the substring of <code>s2</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidbaooo"
<strong>Output:</strong> true
<strong>Explanation:</strong> s2 contains one permutation of s1 ("ba").
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidboaoo"
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 10<sup>4</sup></code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
</ul>
|
Hash Table; Two Pointers; String; Sliding Window
|
Java
|
class Solution {
public boolean checkInclusion(String s1, String s2) {
int need = 0;
int[] cnt = new int[26];
for (char c : s1.toCharArray()) {
if (++cnt[c - 'a'] == 1) {
++need;
}
}
int m = s1.length(), n = s2.length();
for (int i = 0; i < n; ++i) {
int c = s2.charAt(i) - 'a';
if (--cnt[c] == 0) {
--need;
}
if (i >= m) {
c = s2.charAt(i - m) - 'a';
if (++cnt[c] == 1) {
++need;
}
}
if (need == 0) {
return true;
}
}
return false;
}
}
|
567
|
Permutation in String
|
Medium
|
<p>Given two strings <code>s1</code> and <code>s2</code>, return <code>true</code> if <code>s2</code> contains a <span data-keyword="permutation-string">permutation</span> of <code>s1</code>, or <code>false</code> otherwise.</p>
<p>In other words, return <code>true</code> if one of <code>s1</code>'s permutations is the substring of <code>s2</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidbaooo"
<strong>Output:</strong> true
<strong>Explanation:</strong> s2 contains one permutation of s1 ("ba").
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidboaoo"
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 10<sup>4</sup></code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
</ul>
|
Hash Table; Two Pointers; String; Sliding Window
|
Python
|
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
cnt = Counter(s1)
need = len(cnt)
m = len(s1)
for i, c in enumerate(s2):
cnt[c] -= 1
if cnt[c] == 0:
need -= 1
if i >= m:
cnt[s2[i - m]] += 1
if cnt[s2[i - m]] == 1:
need += 1
if need == 0:
return True
return False
|
567
|
Permutation in String
|
Medium
|
<p>Given two strings <code>s1</code> and <code>s2</code>, return <code>true</code> if <code>s2</code> contains a <span data-keyword="permutation-string">permutation</span> of <code>s1</code>, or <code>false</code> otherwise.</p>
<p>In other words, return <code>true</code> if one of <code>s1</code>'s permutations is the substring of <code>s2</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidbaooo"
<strong>Output:</strong> true
<strong>Explanation:</strong> s2 contains one permutation of s1 ("ba").
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidboaoo"
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 10<sup>4</sup></code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
</ul>
|
Hash Table; Two Pointers; String; Sliding Window
|
Rust
|
impl Solution {
pub fn check_inclusion(s1: String, s2: String) -> bool {
let mut need = 0;
let mut cnt = vec![0; 26];
for c in s1.chars() {
let index = (c as u8 - b'a') as usize;
if cnt[index] == 0 {
need += 1;
}
cnt[index] += 1;
}
let m = s1.len();
let n = s2.len();
let s2_bytes = s2.as_bytes();
for i in 0..n {
let c = (s2_bytes[i] - b'a') as usize;
cnt[c] -= 1;
if cnt[c] == 0 {
need -= 1;
}
if i >= m {
let c = (s2_bytes[i - m] - b'a') as usize;
cnt[c] += 1;
if cnt[c] == 1 {
need += 1;
}
}
if need == 0 {
return true;
}
}
false
}
}
|
567
|
Permutation in String
|
Medium
|
<p>Given two strings <code>s1</code> and <code>s2</code>, return <code>true</code> if <code>s2</code> contains a <span data-keyword="permutation-string">permutation</span> of <code>s1</code>, or <code>false</code> otherwise.</p>
<p>In other words, return <code>true</code> if one of <code>s1</code>'s permutations is the substring of <code>s2</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidbaooo"
<strong>Output:</strong> true
<strong>Explanation:</strong> s2 contains one permutation of s1 ("ba").
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s1 = "ab", s2 = "eidboaoo"
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 10<sup>4</sup></code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
</ul>
|
Hash Table; Two Pointers; String; Sliding Window
|
TypeScript
|
function checkInclusion(s1: string, s2: string): boolean {
let need = 0;
const cnt: number[] = Array(26).fill(0);
const a = 'a'.charCodeAt(0);
for (const c of s1) {
if (++cnt[c.charCodeAt(0) - a] === 1) {
need++;
}
}
const [m, n] = [s1.length, s2.length];
for (let i = 0; i < n; i++) {
let c = s2.charCodeAt(i) - a;
if (--cnt[c] === 0) {
need--;
}
if (i >= m) {
c = s2.charCodeAt(i - m) - a;
if (++cnt[c] === 1) {
need++;
}
}
if (need === 0) {
return true;
}
}
return false;
}
|
568
|
Maximum Vacation Days
|
Hard
|
<p>LeetCode wants to give one of its best employees the option to travel among <code>n</code> cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could take, but there are certain rules and restrictions you need to follow.</p>
<p>Rules and restrictions:</p>
<ol>
<li>You can only travel among <code>n</code> cities, represented by indexes from <code>0</code> to <code>n - 1</code>. Initially, you are in the city indexed <code>0</code> on <strong>Monday</strong>.</li>
<li>The cities are connected by flights. The flights are represented as an <code>n x n</code> matrix (not necessarily symmetrical), called <code>flights</code> representing the airline status from the city <code>i</code> to the city <code>j</code>. If there is no flight from the city <code>i</code> to the city <code>j</code>, <code>flights[i][j] == 0</code>; Otherwise, <code>flights[i][j] == 1</code>. Also, <code>flights[i][i] == 0</code> for all <code>i</code>.</li>
<li>You totally have <code>k</code> weeks (each week has <strong>seven days</strong>) to travel. You can only take flights at most once per day and can only take flights on each week's Monday morning. Since flight time is so short, we do not consider the impact of flight time.</li>
<li>For each city, you can only have restricted vacation days in different weeks, given an <code>n x k</code> matrix called <code>days</code> representing this relationship. For the value of <code>days[i][j]</code>, it represents the maximum days you could take a vacation in the city <code>i</code> in the week <code>j</code>.</li>
<li>You could stay in a city beyond the number of vacation days, but you should work on the extra days, which will not be counted as vacation days.</li>
<li>If you fly from city <code>A</code> to city <code>B</code> and take the vacation on that day, the deduction towards vacation days will count towards the vacation days of city <code>B</code> in that week.</li>
<li>We do not consider the impact of flight hours on the calculation of vacation days.</li>
</ol>
<p>Given the two matrices <code>flights</code> and <code>days</code>, return <em>the maximum vacation days you could take during </em><code>k</code><em> weeks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[1,3,1],[6,0,3],[3,3,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong>
One of the best strategies is:
1st week : fly from city 0 to city 1 on Monday, and play 6 days and work 1 day.
(Although you start at city 0, we could also fly to and start at other cities since it is Monday.)
2nd week : fly from city 1 to city 2 on Monday, and play 3 days and work 4 days.
3rd week : stay at city 2, and play 3 days and work 4 days.
Ans = 6 + 3 + 3 = 12.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,0,0],[0,0,0],[0,0,0]], days = [[1,1,1],[7,7,7],[7,7,7]]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Since there are no flights that enable you to move to another city, you have to stay at city 0 for the whole 3 weeks.
For each week, you only have one day to play and six days to work.
So the maximum number of vacation days is 3.
Ans = 1 + 1 + 1 = 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[7,0,0],[0,7,0],[0,0,7]]
<strong>Output:</strong> 21
<strong>Explanation:</strong>
One of the best strategies is:
1st week : stay at city 0, and play 7 days.
2nd week : fly from city 0 to city 1 on Monday, and play 7 days.
3rd week : fly from city 1 to city 2 on Monday, and play 7 days.
Ans = 7 + 7 + 7 = 21
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == flights.length</code></li>
<li><code>n == flights[i].length</code></li>
<li><code>n == days.length</code></li>
<li><code>k == days[i].length</code></li>
<li><code>1 <= n, k <= 100</code></li>
<li><code>flights[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= days[i][j] <= 7</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
C++
|
class Solution {
public:
int maxVacationDays(vector<vector<int>>& flights, vector<vector<int>>& days) {
int n = flights.size();
int K = days[0].size();
int f[K + 1][n];
memset(f, -0x3f, sizeof(f));
f[0][0] = 0;
for (int k = 1; k <= K; ++k) {
for (int j = 0; j < n; ++j) {
f[k][j] = f[k - 1][j];
for (int i = 0; i < n; ++i) {
if (flights[i][j] == 1) {
f[k][j] = max(f[k][j], f[k - 1][i]);
}
}
f[k][j] += days[j][k - 1];
}
}
int ans = 0;
for (int j = 0; j < n; ++j) {
ans = max(ans, f[K][j]);
}
return ans;
}
};
|
568
|
Maximum Vacation Days
|
Hard
|
<p>LeetCode wants to give one of its best employees the option to travel among <code>n</code> cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could take, but there are certain rules and restrictions you need to follow.</p>
<p>Rules and restrictions:</p>
<ol>
<li>You can only travel among <code>n</code> cities, represented by indexes from <code>0</code> to <code>n - 1</code>. Initially, you are in the city indexed <code>0</code> on <strong>Monday</strong>.</li>
<li>The cities are connected by flights. The flights are represented as an <code>n x n</code> matrix (not necessarily symmetrical), called <code>flights</code> representing the airline status from the city <code>i</code> to the city <code>j</code>. If there is no flight from the city <code>i</code> to the city <code>j</code>, <code>flights[i][j] == 0</code>; Otherwise, <code>flights[i][j] == 1</code>. Also, <code>flights[i][i] == 0</code> for all <code>i</code>.</li>
<li>You totally have <code>k</code> weeks (each week has <strong>seven days</strong>) to travel. You can only take flights at most once per day and can only take flights on each week's Monday morning. Since flight time is so short, we do not consider the impact of flight time.</li>
<li>For each city, you can only have restricted vacation days in different weeks, given an <code>n x k</code> matrix called <code>days</code> representing this relationship. For the value of <code>days[i][j]</code>, it represents the maximum days you could take a vacation in the city <code>i</code> in the week <code>j</code>.</li>
<li>You could stay in a city beyond the number of vacation days, but you should work on the extra days, which will not be counted as vacation days.</li>
<li>If you fly from city <code>A</code> to city <code>B</code> and take the vacation on that day, the deduction towards vacation days will count towards the vacation days of city <code>B</code> in that week.</li>
<li>We do not consider the impact of flight hours on the calculation of vacation days.</li>
</ol>
<p>Given the two matrices <code>flights</code> and <code>days</code>, return <em>the maximum vacation days you could take during </em><code>k</code><em> weeks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[1,3,1],[6,0,3],[3,3,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong>
One of the best strategies is:
1st week : fly from city 0 to city 1 on Monday, and play 6 days and work 1 day.
(Although you start at city 0, we could also fly to and start at other cities since it is Monday.)
2nd week : fly from city 1 to city 2 on Monday, and play 3 days and work 4 days.
3rd week : stay at city 2, and play 3 days and work 4 days.
Ans = 6 + 3 + 3 = 12.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,0,0],[0,0,0],[0,0,0]], days = [[1,1,1],[7,7,7],[7,7,7]]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Since there are no flights that enable you to move to another city, you have to stay at city 0 for the whole 3 weeks.
For each week, you only have one day to play and six days to work.
So the maximum number of vacation days is 3.
Ans = 1 + 1 + 1 = 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[7,0,0],[0,7,0],[0,0,7]]
<strong>Output:</strong> 21
<strong>Explanation:</strong>
One of the best strategies is:
1st week : stay at city 0, and play 7 days.
2nd week : fly from city 0 to city 1 on Monday, and play 7 days.
3rd week : fly from city 1 to city 2 on Monday, and play 7 days.
Ans = 7 + 7 + 7 = 21
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == flights.length</code></li>
<li><code>n == flights[i].length</code></li>
<li><code>n == days.length</code></li>
<li><code>k == days[i].length</code></li>
<li><code>1 <= n, k <= 100</code></li>
<li><code>flights[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= days[i][j] <= 7</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Go
|
func maxVacationDays(flights [][]int, days [][]int) (ans int) {
n, K := len(flights), len(days[0])
f := make([][]int, K+1)
for i := range f {
f[i] = make([]int, n)
for j := range f[i] {
f[i][j] = -(1 << 30)
}
}
f[0][0] = 0
for k := 1; k <= K; k++ {
for j := 0; j < n; j++ {
f[k][j] = f[k-1][j]
for i := 0; i < n; i++ {
if flights[i][j] == 1 {
f[k][j] = max(f[k][j], f[k-1][i])
}
}
f[k][j] += days[j][k-1]
}
}
for j := 0; j < n; j++ {
ans = max(ans, f[K][j])
}
return
}
|
568
|
Maximum Vacation Days
|
Hard
|
<p>LeetCode wants to give one of its best employees the option to travel among <code>n</code> cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could take, but there are certain rules and restrictions you need to follow.</p>
<p>Rules and restrictions:</p>
<ol>
<li>You can only travel among <code>n</code> cities, represented by indexes from <code>0</code> to <code>n - 1</code>. Initially, you are in the city indexed <code>0</code> on <strong>Monday</strong>.</li>
<li>The cities are connected by flights. The flights are represented as an <code>n x n</code> matrix (not necessarily symmetrical), called <code>flights</code> representing the airline status from the city <code>i</code> to the city <code>j</code>. If there is no flight from the city <code>i</code> to the city <code>j</code>, <code>flights[i][j] == 0</code>; Otherwise, <code>flights[i][j] == 1</code>. Also, <code>flights[i][i] == 0</code> for all <code>i</code>.</li>
<li>You totally have <code>k</code> weeks (each week has <strong>seven days</strong>) to travel. You can only take flights at most once per day and can only take flights on each week's Monday morning. Since flight time is so short, we do not consider the impact of flight time.</li>
<li>For each city, you can only have restricted vacation days in different weeks, given an <code>n x k</code> matrix called <code>days</code> representing this relationship. For the value of <code>days[i][j]</code>, it represents the maximum days you could take a vacation in the city <code>i</code> in the week <code>j</code>.</li>
<li>You could stay in a city beyond the number of vacation days, but you should work on the extra days, which will not be counted as vacation days.</li>
<li>If you fly from city <code>A</code> to city <code>B</code> and take the vacation on that day, the deduction towards vacation days will count towards the vacation days of city <code>B</code> in that week.</li>
<li>We do not consider the impact of flight hours on the calculation of vacation days.</li>
</ol>
<p>Given the two matrices <code>flights</code> and <code>days</code>, return <em>the maximum vacation days you could take during </em><code>k</code><em> weeks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[1,3,1],[6,0,3],[3,3,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong>
One of the best strategies is:
1st week : fly from city 0 to city 1 on Monday, and play 6 days and work 1 day.
(Although you start at city 0, we could also fly to and start at other cities since it is Monday.)
2nd week : fly from city 1 to city 2 on Monday, and play 3 days and work 4 days.
3rd week : stay at city 2, and play 3 days and work 4 days.
Ans = 6 + 3 + 3 = 12.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,0,0],[0,0,0],[0,0,0]], days = [[1,1,1],[7,7,7],[7,7,7]]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Since there are no flights that enable you to move to another city, you have to stay at city 0 for the whole 3 weeks.
For each week, you only have one day to play and six days to work.
So the maximum number of vacation days is 3.
Ans = 1 + 1 + 1 = 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[7,0,0],[0,7,0],[0,0,7]]
<strong>Output:</strong> 21
<strong>Explanation:</strong>
One of the best strategies is:
1st week : stay at city 0, and play 7 days.
2nd week : fly from city 0 to city 1 on Monday, and play 7 days.
3rd week : fly from city 1 to city 2 on Monday, and play 7 days.
Ans = 7 + 7 + 7 = 21
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == flights.length</code></li>
<li><code>n == flights[i].length</code></li>
<li><code>n == days.length</code></li>
<li><code>k == days[i].length</code></li>
<li><code>1 <= n, k <= 100</code></li>
<li><code>flights[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= days[i][j] <= 7</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Java
|
class Solution {
public int maxVacationDays(int[][] flights, int[][] days) {
int n = flights.length;
int K = days[0].length;
final int inf = 1 << 30;
int[][] f = new int[K + 1][n];
for (var g : f) {
Arrays.fill(g, -inf);
}
f[0][0] = 0;
for (int k = 1; k <= K; ++k) {
for (int j = 0; j < n; ++j) {
f[k][j] = f[k - 1][j];
for (int i = 0; i < n; ++i) {
if (flights[i][j] == 1) {
f[k][j] = Math.max(f[k][j], f[k - 1][i]);
}
}
f[k][j] += days[j][k - 1];
}
}
int ans = 0;
for (int j = 0; j < n; ++j) {
ans = Math.max(ans, f[K][j]);
}
return ans;
}
}
|
568
|
Maximum Vacation Days
|
Hard
|
<p>LeetCode wants to give one of its best employees the option to travel among <code>n</code> cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could take, but there are certain rules and restrictions you need to follow.</p>
<p>Rules and restrictions:</p>
<ol>
<li>You can only travel among <code>n</code> cities, represented by indexes from <code>0</code> to <code>n - 1</code>. Initially, you are in the city indexed <code>0</code> on <strong>Monday</strong>.</li>
<li>The cities are connected by flights. The flights are represented as an <code>n x n</code> matrix (not necessarily symmetrical), called <code>flights</code> representing the airline status from the city <code>i</code> to the city <code>j</code>. If there is no flight from the city <code>i</code> to the city <code>j</code>, <code>flights[i][j] == 0</code>; Otherwise, <code>flights[i][j] == 1</code>. Also, <code>flights[i][i] == 0</code> for all <code>i</code>.</li>
<li>You totally have <code>k</code> weeks (each week has <strong>seven days</strong>) to travel. You can only take flights at most once per day and can only take flights on each week's Monday morning. Since flight time is so short, we do not consider the impact of flight time.</li>
<li>For each city, you can only have restricted vacation days in different weeks, given an <code>n x k</code> matrix called <code>days</code> representing this relationship. For the value of <code>days[i][j]</code>, it represents the maximum days you could take a vacation in the city <code>i</code> in the week <code>j</code>.</li>
<li>You could stay in a city beyond the number of vacation days, but you should work on the extra days, which will not be counted as vacation days.</li>
<li>If you fly from city <code>A</code> to city <code>B</code> and take the vacation on that day, the deduction towards vacation days will count towards the vacation days of city <code>B</code> in that week.</li>
<li>We do not consider the impact of flight hours on the calculation of vacation days.</li>
</ol>
<p>Given the two matrices <code>flights</code> and <code>days</code>, return <em>the maximum vacation days you could take during </em><code>k</code><em> weeks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[1,3,1],[6,0,3],[3,3,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong>
One of the best strategies is:
1st week : fly from city 0 to city 1 on Monday, and play 6 days and work 1 day.
(Although you start at city 0, we could also fly to and start at other cities since it is Monday.)
2nd week : fly from city 1 to city 2 on Monday, and play 3 days and work 4 days.
3rd week : stay at city 2, and play 3 days and work 4 days.
Ans = 6 + 3 + 3 = 12.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,0,0],[0,0,0],[0,0,0]], days = [[1,1,1],[7,7,7],[7,7,7]]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Since there are no flights that enable you to move to another city, you have to stay at city 0 for the whole 3 weeks.
For each week, you only have one day to play and six days to work.
So the maximum number of vacation days is 3.
Ans = 1 + 1 + 1 = 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[7,0,0],[0,7,0],[0,0,7]]
<strong>Output:</strong> 21
<strong>Explanation:</strong>
One of the best strategies is:
1st week : stay at city 0, and play 7 days.
2nd week : fly from city 0 to city 1 on Monday, and play 7 days.
3rd week : fly from city 1 to city 2 on Monday, and play 7 days.
Ans = 7 + 7 + 7 = 21
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == flights.length</code></li>
<li><code>n == flights[i].length</code></li>
<li><code>n == days.length</code></li>
<li><code>k == days[i].length</code></li>
<li><code>1 <= n, k <= 100</code></li>
<li><code>flights[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= days[i][j] <= 7</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Python
|
class Solution:
def maxVacationDays(self, flights: List[List[int]], days: List[List[int]]) -> int:
n = len(flights)
K = len(days[0])
f = [[-inf] * n for _ in range(K + 1)]
f[0][0] = 0
for k in range(1, K + 1):
for j in range(n):
f[k][j] = f[k - 1][j]
for i in range(n):
if flights[i][j]:
f[k][j] = max(f[k][j], f[k - 1][i])
f[k][j] += days[j][k - 1]
return max(f[-1][j] for j in range(n))
|
568
|
Maximum Vacation Days
|
Hard
|
<p>LeetCode wants to give one of its best employees the option to travel among <code>n</code> cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could take, but there are certain rules and restrictions you need to follow.</p>
<p>Rules and restrictions:</p>
<ol>
<li>You can only travel among <code>n</code> cities, represented by indexes from <code>0</code> to <code>n - 1</code>. Initially, you are in the city indexed <code>0</code> on <strong>Monday</strong>.</li>
<li>The cities are connected by flights. The flights are represented as an <code>n x n</code> matrix (not necessarily symmetrical), called <code>flights</code> representing the airline status from the city <code>i</code> to the city <code>j</code>. If there is no flight from the city <code>i</code> to the city <code>j</code>, <code>flights[i][j] == 0</code>; Otherwise, <code>flights[i][j] == 1</code>. Also, <code>flights[i][i] == 0</code> for all <code>i</code>.</li>
<li>You totally have <code>k</code> weeks (each week has <strong>seven days</strong>) to travel. You can only take flights at most once per day and can only take flights on each week's Monday morning. Since flight time is so short, we do not consider the impact of flight time.</li>
<li>For each city, you can only have restricted vacation days in different weeks, given an <code>n x k</code> matrix called <code>days</code> representing this relationship. For the value of <code>days[i][j]</code>, it represents the maximum days you could take a vacation in the city <code>i</code> in the week <code>j</code>.</li>
<li>You could stay in a city beyond the number of vacation days, but you should work on the extra days, which will not be counted as vacation days.</li>
<li>If you fly from city <code>A</code> to city <code>B</code> and take the vacation on that day, the deduction towards vacation days will count towards the vacation days of city <code>B</code> in that week.</li>
<li>We do not consider the impact of flight hours on the calculation of vacation days.</li>
</ol>
<p>Given the two matrices <code>flights</code> and <code>days</code>, return <em>the maximum vacation days you could take during </em><code>k</code><em> weeks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[1,3,1],[6,0,3],[3,3,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong>
One of the best strategies is:
1st week : fly from city 0 to city 1 on Monday, and play 6 days and work 1 day.
(Although you start at city 0, we could also fly to and start at other cities since it is Monday.)
2nd week : fly from city 1 to city 2 on Monday, and play 3 days and work 4 days.
3rd week : stay at city 2, and play 3 days and work 4 days.
Ans = 6 + 3 + 3 = 12.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,0,0],[0,0,0],[0,0,0]], days = [[1,1,1],[7,7,7],[7,7,7]]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Since there are no flights that enable you to move to another city, you have to stay at city 0 for the whole 3 weeks.
For each week, you only have one day to play and six days to work.
So the maximum number of vacation days is 3.
Ans = 1 + 1 + 1 = 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[7,0,0],[0,7,0],[0,0,7]]
<strong>Output:</strong> 21
<strong>Explanation:</strong>
One of the best strategies is:
1st week : stay at city 0, and play 7 days.
2nd week : fly from city 0 to city 1 on Monday, and play 7 days.
3rd week : fly from city 1 to city 2 on Monday, and play 7 days.
Ans = 7 + 7 + 7 = 21
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == flights.length</code></li>
<li><code>n == flights[i].length</code></li>
<li><code>n == days.length</code></li>
<li><code>k == days[i].length</code></li>
<li><code>1 <= n, k <= 100</code></li>
<li><code>flights[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= days[i][j] <= 7</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Rust
|
impl Solution {
pub fn max_vacation_days(flights: Vec<Vec<i32>>, days: Vec<Vec<i32>>) -> i32 {
let n = flights.len();
let k = days[0].len();
let inf = i32::MIN;
let mut f = vec![vec![inf; n]; k + 1];
f[0][0] = 0;
for step in 1..=k {
for j in 0..n {
f[step][j] = f[step - 1][j];
for i in 0..n {
if flights[i][j] == 1 {
f[step][j] = f[step][j].max(f[step - 1][i]);
}
}
f[step][j] += days[j][step - 1];
}
}
*f[k].iter().max().unwrap()
}
}
|
568
|
Maximum Vacation Days
|
Hard
|
<p>LeetCode wants to give one of its best employees the option to travel among <code>n</code> cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could take, but there are certain rules and restrictions you need to follow.</p>
<p>Rules and restrictions:</p>
<ol>
<li>You can only travel among <code>n</code> cities, represented by indexes from <code>0</code> to <code>n - 1</code>. Initially, you are in the city indexed <code>0</code> on <strong>Monday</strong>.</li>
<li>The cities are connected by flights. The flights are represented as an <code>n x n</code> matrix (not necessarily symmetrical), called <code>flights</code> representing the airline status from the city <code>i</code> to the city <code>j</code>. If there is no flight from the city <code>i</code> to the city <code>j</code>, <code>flights[i][j] == 0</code>; Otherwise, <code>flights[i][j] == 1</code>. Also, <code>flights[i][i] == 0</code> for all <code>i</code>.</li>
<li>You totally have <code>k</code> weeks (each week has <strong>seven days</strong>) to travel. You can only take flights at most once per day and can only take flights on each week's Monday morning. Since flight time is so short, we do not consider the impact of flight time.</li>
<li>For each city, you can only have restricted vacation days in different weeks, given an <code>n x k</code> matrix called <code>days</code> representing this relationship. For the value of <code>days[i][j]</code>, it represents the maximum days you could take a vacation in the city <code>i</code> in the week <code>j</code>.</li>
<li>You could stay in a city beyond the number of vacation days, but you should work on the extra days, which will not be counted as vacation days.</li>
<li>If you fly from city <code>A</code> to city <code>B</code> and take the vacation on that day, the deduction towards vacation days will count towards the vacation days of city <code>B</code> in that week.</li>
<li>We do not consider the impact of flight hours on the calculation of vacation days.</li>
</ol>
<p>Given the two matrices <code>flights</code> and <code>days</code>, return <em>the maximum vacation days you could take during </em><code>k</code><em> weeks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[1,3,1],[6,0,3],[3,3,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong>
One of the best strategies is:
1st week : fly from city 0 to city 1 on Monday, and play 6 days and work 1 day.
(Although you start at city 0, we could also fly to and start at other cities since it is Monday.)
2nd week : fly from city 1 to city 2 on Monday, and play 3 days and work 4 days.
3rd week : stay at city 2, and play 3 days and work 4 days.
Ans = 6 + 3 + 3 = 12.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,0,0],[0,0,0],[0,0,0]], days = [[1,1,1],[7,7,7],[7,7,7]]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Since there are no flights that enable you to move to another city, you have to stay at city 0 for the whole 3 weeks.
For each week, you only have one day to play and six days to work.
So the maximum number of vacation days is 3.
Ans = 1 + 1 + 1 = 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[7,0,0],[0,7,0],[0,0,7]]
<strong>Output:</strong> 21
<strong>Explanation:</strong>
One of the best strategies is:
1st week : stay at city 0, and play 7 days.
2nd week : fly from city 0 to city 1 on Monday, and play 7 days.
3rd week : fly from city 1 to city 2 on Monday, and play 7 days.
Ans = 7 + 7 + 7 = 21
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == flights.length</code></li>
<li><code>n == flights[i].length</code></li>
<li><code>n == days.length</code></li>
<li><code>k == days[i].length</code></li>
<li><code>1 <= n, k <= 100</code></li>
<li><code>flights[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= days[i][j] <= 7</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
TypeScript
|
function maxVacationDays(flights: number[][], days: number[][]): number {
const n = flights.length;
const K = days[0].length;
const inf = Number.NEGATIVE_INFINITY;
const f: number[][] = Array.from({ length: K + 1 }, () => Array(n).fill(inf));
f[0][0] = 0;
for (let k = 1; k <= K; k++) {
for (let j = 0; j < n; j++) {
f[k][j] = f[k - 1][j];
for (let i = 0; i < n; i++) {
if (flights[i][j]) {
f[k][j] = Math.max(f[k][j], f[k - 1][i]);
}
}
f[k][j] += days[j][k - 1];
}
}
return Math.max(...f[K]);
}
|
569
|
Median Employee Salary
|
Hard
|
<p>Table: <code>Employee</code></p>
<pre>
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| id | int |
| company | varchar |
| salary | int |
+--------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the company and the salary of one employee.
</pre>
<p> </p>
<p>Write a solution to find the rows that contain the median salary of each company. While calculating the median, when you sort the salaries of the company, break the ties by <code>id</code>.</p>
<p>Return the result table in <strong>any order</strong>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Employee table:
+----+---------+--------+
| id | company | salary |
+----+---------+--------+
| 1 | A | 2341 |
| 2 | A | 341 |
| 3 | A | 15 |
| 4 | A | 15314 |
| 5 | A | 451 |
| 6 | A | 513 |
| 7 | B | 15 |
| 8 | B | 13 |
| 9 | B | 1154 |
| 10 | B | 1345 |
| 11 | B | 1221 |
| 12 | B | 234 |
| 13 | C | 2345 |
| 14 | C | 2645 |
| 15 | C | 2645 |
| 16 | C | 2652 |
| 17 | C | 65 |
+----+---------+--------+
<strong>Output:</strong>
+----+---------+--------+
| id | company | salary |
+----+---------+--------+
| 5 | A | 451 |
| 6 | A | 513 |
| 12 | B | 234 |
| 9 | B | 1154 |
| 14 | C | 2645 |
+----+---------+--------+
<strong>Explanation:</strong>
For company A, the rows sorted are as follows:
+----+---------+--------+
| id | company | salary |
+----+---------+--------+
| 3 | A | 15 |
| 2 | A | 341 |
| 5 | A | 451 | <-- median
| 6 | A | 513 | <-- median
| 1 | A | 2341 |
| 4 | A | 15314 |
+----+---------+--------+
For company B, the rows sorted are as follows:
+----+---------+--------+
| id | company | salary |
+----+---------+--------+
| 8 | B | 13 |
| 7 | B | 15 |
| 12 | B | 234 | <-- median
| 11 | B | 1221 | <-- median
| 9 | B | 1154 |
| 10 | B | 1345 |
+----+---------+--------+
For company C, the rows sorted are as follows:
+----+---------+--------+
| id | company | salary |
+----+---------+--------+
| 17 | C | 65 |
| 13 | C | 2345 |
| 14 | C | 2645 | <-- median
| 15 | C | 2645 |
| 16 | C | 2652 |
+----+---------+--------+
</pre>
<p> </p>
<p><strong>Follow up:</strong> Could you solve it without using any built-in or window functions?</p>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
t AS (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY company
ORDER BY salary ASC
) AS rk,
COUNT(id) OVER (PARTITION BY company) AS n
FROM Employee
)
SELECT
id,
company,
salary
FROM t
WHERE rk >= n / 2 AND rk <= n / 2 + 1;
|
570
|
Managers with at Least 5 Direct Reports
|
Medium
|
<p>Table: <code>Employee</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
| department | varchar |
| managerId | int |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the name of an employee, their department, and the id of their manager.
If managerId is null, then the employee does not have a manager.
No employee will be the manager of themself.
</pre>
<p> </p>
<p>Write a solution to find managers with at least <strong>five direct reports</strong>.</p>
<p>Return the result table in <strong>any order</strong>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Employee table:
+-----+-------+------------+-----------+
| id | name | department | managerId |
+-----+-------+------------+-----------+
| 101 | John | A | null |
| 102 | Dan | A | 101 |
| 103 | James | A | 101 |
| 104 | Amy | A | 101 |
| 105 | Anne | A | 101 |
| 106 | Ron | B | 101 |
+-----+-------+------------+-----------+
<strong>Output:</strong>
+------+
| name |
+------+
| John |
+------+
</pre>
|
Database
|
Python
|
import pandas as pd
def find_managers(employee: pd.DataFrame) -> pd.DataFrame:
# Group the employees by managerId and count the number of direct reports
manager_report_count = (
employee.groupby("managerId").size().reset_index(name="directReports")
)
# Filter managers with at least five direct reports
result = manager_report_count[manager_report_count["directReports"] >= 5]
# Merge with the Employee table to get the names of these managers
result = result.merge(
employee[["id", "name"]], left_on="managerId", right_on="id", how="inner"
)
# Select only the 'name' column and drop the 'id' and 'directReports' columns
result = result[["name"]]
return result
|
570
|
Managers with at Least 5 Direct Reports
|
Medium
|
<p>Table: <code>Employee</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
| department | varchar |
| managerId | int |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the name of an employee, their department, and the id of their manager.
If managerId is null, then the employee does not have a manager.
No employee will be the manager of themself.
</pre>
<p> </p>
<p>Write a solution to find managers with at least <strong>five direct reports</strong>.</p>
<p>Return the result table in <strong>any order</strong>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Employee table:
+-----+-------+------------+-----------+
| id | name | department | managerId |
+-----+-------+------------+-----------+
| 101 | John | A | null |
| 102 | Dan | A | 101 |
| 103 | James | A | 101 |
| 104 | Amy | A | 101 |
| 105 | Anne | A | 101 |
| 106 | Ron | B | 101 |
+-----+-------+------------+-----------+
<strong>Output:</strong>
+------+
| name |
+------+
| John |
+------+
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT name
FROM
Employee
JOIN (
SELECT managerId AS id, COUNT(1) AS cnt
FROM Employee
GROUP BY 1
HAVING cnt >= 5
) AS t
USING (id);
|
571
|
Find Median Given Frequency of Numbers
|
Hard
|
<p>Table: <code>Numbers</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| num | int |
| frequency | int |
+-------------+------+
num is the primary key (column with unique values) for this table.
Each row of this table shows the frequency of a number in the database.
</pre>
<p> </p>
<p>The <a href="https://en.wikipedia.org/wiki/Median" target="_blank"><strong>median</strong></a> is the value separating the higher half from the lower half of a data sample.</p>
<p>Write a solution to report the <strong>median</strong> of all the numbers in the database after decompressing the <code>Numbers</code> table. Round the median to <strong>one decimal point</strong>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Numbers table:
+-----+-----------+
| num | frequency |
+-----+-----------+
| 0 | 7 |
| 1 | 1 |
| 2 | 3 |
| 3 | 1 |
+-----+-----------+
<strong>Output:</strong>
+--------+
| median |
+--------+
| 0.0 |
+--------+
<strong>Explanation:</strong>
If we decompress the Numbers table, we will get [0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3], so the median is (0 + 0) / 2 = 0.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
t AS (
SELECT
*,
SUM(frequency) OVER (ORDER BY num ASC) AS rk1,
SUM(frequency) OVER (ORDER BY num DESC) AS rk2,
SUM(frequency) OVER () AS s
FROM Numbers
)
SELECT
ROUND(AVG(num), 1) AS median
FROM t
WHERE rk1 >= s / 2 AND rk2 >= s / 2;
|
572
|
Subtree of Another Tree
|
Easy
|
<p>Given the roots of two binary trees <code>root</code> and <code>subRoot</code>, return <code>true</code> if there is a subtree of <code>root</code> with the same structure and node values of<code> subRoot</code> and <code>false</code> otherwise.</p>
<p>A subtree of a binary tree <code>tree</code> is a tree that consists of a node in <code>tree</code> and all of this node's descendants. The tree <code>tree</code> could also be considered as a subtree of itself.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree1-tree.jpg" style="width: 532px; height: 400px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2], subRoot = [4,1,2]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree2-tree.jpg" style="width: 502px; height: 458px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the <code>root</code> tree is in the range <code>[1, 2000]</code>.</li>
<li>The number of nodes in the <code>subRoot</code> tree is in the range <code>[1, 1000]</code>.</li>
<li><code>-10<sup>4</sup> <= root.val <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= subRoot.val <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; String Matching; Hash Function
|
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:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if (!root) {
return false;
}
return same(root, subRoot) || isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
bool same(TreeNode* p, TreeNode* q) {
if (!p || !q) {
return p == q;
}
return p->val == q->val && same(p->left, q->left) && same(p->right, q->right);
}
};
|
572
|
Subtree of Another Tree
|
Easy
|
<p>Given the roots of two binary trees <code>root</code> and <code>subRoot</code>, return <code>true</code> if there is a subtree of <code>root</code> with the same structure and node values of<code> subRoot</code> and <code>false</code> otherwise.</p>
<p>A subtree of a binary tree <code>tree</code> is a tree that consists of a node in <code>tree</code> and all of this node's descendants. The tree <code>tree</code> could also be considered as a subtree of itself.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree1-tree.jpg" style="width: 532px; height: 400px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2], subRoot = [4,1,2]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree2-tree.jpg" style="width: 502px; height: 458px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the <code>root</code> tree is in the range <code>[1, 2000]</code>.</li>
<li>The number of nodes in the <code>subRoot</code> tree is in the range <code>[1, 1000]</code>.</li>
<li><code>-10<sup>4</sup> <= root.val <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= subRoot.val <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; String Matching; Hash Function
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSubtree(root *TreeNode, subRoot *TreeNode) bool {
var same func(p, q *TreeNode) bool
same = func(p, q *TreeNode) bool {
if p == nil || q == nil {
return p == q
}
return p.Val == q.Val && same(p.Left, q.Left) && same(p.Right, q.Right)
}
if root == nil {
return false
}
return same(root, subRoot) || isSubtree(root.Left, subRoot) || isSubtree(root.Right, subRoot)
}
|
572
|
Subtree of Another Tree
|
Easy
|
<p>Given the roots of two binary trees <code>root</code> and <code>subRoot</code>, return <code>true</code> if there is a subtree of <code>root</code> with the same structure and node values of<code> subRoot</code> and <code>false</code> otherwise.</p>
<p>A subtree of a binary tree <code>tree</code> is a tree that consists of a node in <code>tree</code> and all of this node's descendants. The tree <code>tree</code> could also be considered as a subtree of itself.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree1-tree.jpg" style="width: 532px; height: 400px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2], subRoot = [4,1,2]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree2-tree.jpg" style="width: 502px; height: 458px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the <code>root</code> tree is in the range <code>[1, 2000]</code>.</li>
<li>The number of nodes in the <code>subRoot</code> tree is in the range <code>[1, 1000]</code>.</li>
<li><code>-10<sup>4</sup> <= root.val <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= subRoot.val <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; String Matching; Hash Function
|
Java
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null) {
return false;
}
return same(root, subRoot) || isSubtree(root.left, subRoot)
|| isSubtree(root.right, subRoot);
}
private boolean same(TreeNode p, TreeNode q) {
if (p == null || q == null) {
return p == q;
}
return p.val == q.val && same(p.left, q.left) && same(p.right, q.right);
}
}
|
572
|
Subtree of Another Tree
|
Easy
|
<p>Given the roots of two binary trees <code>root</code> and <code>subRoot</code>, return <code>true</code> if there is a subtree of <code>root</code> with the same structure and node values of<code> subRoot</code> and <code>false</code> otherwise.</p>
<p>A subtree of a binary tree <code>tree</code> is a tree that consists of a node in <code>tree</code> and all of this node's descendants. The tree <code>tree</code> could also be considered as a subtree of itself.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree1-tree.jpg" style="width: 532px; height: 400px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2], subRoot = [4,1,2]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree2-tree.jpg" style="width: 502px; height: 458px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the <code>root</code> tree is in the range <code>[1, 2000]</code>.</li>
<li>The number of nodes in the <code>subRoot</code> tree is in the range <code>[1, 1000]</code>.</li>
<li><code>-10<sup>4</sup> <= root.val <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= subRoot.val <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; String Matching; Hash Function
|
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 {TreeNode} subRoot
* @return {boolean}
*/
var isSubtree = function (root, subRoot) {
const same = (p, q) => {
if (!p || !q) {
return p === q;
}
return p.val === q.val && same(p.left, q.left) && same(p.right, q.right);
};
if (!root) {
return false;
}
return same(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
};
|
572
|
Subtree of Another Tree
|
Easy
|
<p>Given the roots of two binary trees <code>root</code> and <code>subRoot</code>, return <code>true</code> if there is a subtree of <code>root</code> with the same structure and node values of<code> subRoot</code> and <code>false</code> otherwise.</p>
<p>A subtree of a binary tree <code>tree</code> is a tree that consists of a node in <code>tree</code> and all of this node's descendants. The tree <code>tree</code> could also be considered as a subtree of itself.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree1-tree.jpg" style="width: 532px; height: 400px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2], subRoot = [4,1,2]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree2-tree.jpg" style="width: 502px; height: 458px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the <code>root</code> tree is in the range <code>[1, 2000]</code>.</li>
<li>The number of nodes in the <code>subRoot</code> tree is in the range <code>[1, 1000]</code>.</li>
<li><code>-10<sup>4</sup> <= root.val <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= subRoot.val <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; String Matching; Hash Function
|
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 isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
def same(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p is None or q is None:
return p is q
return p.val == q.val and same(p.left, q.left) and same(p.right, q.right)
if root is None:
return False
return (
same(root, subRoot)
or self.isSubtree(root.left, subRoot)
or self.isSubtree(root.right, subRoot)
)
|
572
|
Subtree of Another Tree
|
Easy
|
<p>Given the roots of two binary trees <code>root</code> and <code>subRoot</code>, return <code>true</code> if there is a subtree of <code>root</code> with the same structure and node values of<code> subRoot</code> and <code>false</code> otherwise.</p>
<p>A subtree of a binary tree <code>tree</code> is a tree that consists of a node in <code>tree</code> and all of this node's descendants. The tree <code>tree</code> could also be considered as a subtree of itself.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree1-tree.jpg" style="width: 532px; height: 400px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2], subRoot = [4,1,2]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree2-tree.jpg" style="width: 502px; height: 458px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the <code>root</code> tree is in the range <code>[1, 2000]</code>.</li>
<li>The number of nodes in the <code>subRoot</code> tree is in the range <code>[1, 1000]</code>.</li>
<li><code>-10<sup>4</sup> <= root.val <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= subRoot.val <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; String Matching; Hash Function
|
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::rc::Rc;
impl Solution {
pub fn is_subtree(
root: Option<Rc<RefCell<TreeNode>>>,
sub_root: Option<Rc<RefCell<TreeNode>>>,
) -> bool {
if root.is_none() {
return false;
}
Self::same(&root, &sub_root)
|| Self::is_subtree(
root.as_ref().unwrap().borrow().left.clone(),
sub_root.clone(),
)
|| Self::is_subtree(
root.as_ref().unwrap().borrow().right.clone(),
sub_root.clone(),
)
}
fn same(p: &Option<Rc<RefCell<TreeNode>>>, q: &Option<Rc<RefCell<TreeNode>>>) -> bool {
match (p, q) {
(None, None) => true,
(Some(p), Some(q)) => {
let p = p.borrow();
let q = q.borrow();
p.val == q.val && Self::same(&p.left, &q.left) && Self::same(&p.right, &q.right)
}
_ => false,
}
}
}
|
572
|
Subtree of Another Tree
|
Easy
|
<p>Given the roots of two binary trees <code>root</code> and <code>subRoot</code>, return <code>true</code> if there is a subtree of <code>root</code> with the same structure and node values of<code> subRoot</code> and <code>false</code> otherwise.</p>
<p>A subtree of a binary tree <code>tree</code> is a tree that consists of a node in <code>tree</code> and all of this node's descendants. The tree <code>tree</code> could also be considered as a subtree of itself.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree1-tree.jpg" style="width: 532px; height: 400px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2], subRoot = [4,1,2]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0572.Subtree%20of%20Another%20Tree/images/subtree2-tree.jpg" style="width: 502px; height: 458px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the <code>root</code> tree is in the range <code>[1, 2000]</code>.</li>
<li>The number of nodes in the <code>subRoot</code> tree is in the range <code>[1, 1000]</code>.</li>
<li><code>-10<sup>4</sup> <= root.val <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= subRoot.val <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; String Matching; Hash Function
|
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 isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean {
const same = (p: TreeNode | null, q: TreeNode | null): boolean => {
if (!p || !q) {
return p === q;
}
return p.val === q.val && same(p.left, q.left) && same(p.right, q.right);
};
if (!root) {
return false;
}
return same(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
|
573
|
Squirrel Simulation
|
Medium
|
<p>You are given two integers <code>height</code> and <code>width</code> representing a garden of size <code>height x width</code>. You are also given:</p>
<ul>
<li>an array <code>tree</code> where <code>tree = [tree<sub>r</sub>, tree<sub>c</sub>]</code> is the position of the tree in the garden,</li>
<li>an array <code>squirrel</code> where <code>squirrel = [squirrel<sub>r</sub>, squirrel<sub>c</sub>]</code> is the position of the squirrel in the garden,</li>
<li>and an array <code>nuts</code> where <code>nuts[i] = [nut<sub>i<sub>r</sub></sub>, nut<sub>i<sub>c</sub></sub>]</code> is the position of the <code>i<sup>th</sup></code> nut in the garden.</li>
</ul>
<p>The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.</p>
<p>Return <em>the <strong>minimal distance</strong> for the squirrel to collect all the nuts and put them under the tree one by one</em>.</p>
<p>The <strong>distance</strong> is the number of moves.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel1-grid.jpg" style="width: 573px; height: 413px;" />
<pre>
<strong>Input:</strong> height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel2-grid.jpg" style="width: 253px; height: 93px;" />
<pre>
<strong>Input:</strong> height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= height, width <= 100</code></li>
<li><code>tree.length == 2</code></li>
<li><code>squirrel.length == 2</code></li>
<li><code>1 <= nuts.length <= 5000</code></li>
<li><code>nuts[i].length == 2</code></li>
<li><code>0 <= tree<sub>r</sub>, squirrel<sub>r</sub>, nut<sub>i<sub>r</sub></sub> <= height</code></li>
<li><code>0 <= tree<sub>c</sub>, squirrel<sub>c</sub>, nut<sub>i<sub>c</sub></sub> <= width</code></li>
</ul>
|
Array; Math
|
C++
|
class Solution {
public:
int minDistance(int height, int width, vector<int>& tree, vector<int>& squirrel, vector<vector<int>>& nuts) {
int tr = tree[0], tc = tree[1];
int sr = squirrel[0], sc = squirrel[1];
int s = 0;
for (const auto& e : nuts) {
s += abs(e[0] - tr) + abs(e[1] - tc);
}
s <<= 1;
int ans = INT_MAX;
for (const auto& e : nuts) {
int a = abs(e[0] - tr) + abs(e[1] - tc);
int b = abs(e[0] - sr) + abs(e[1] - sc);
ans = min(ans, s - a + b);
}
return ans;
}
};
|
573
|
Squirrel Simulation
|
Medium
|
<p>You are given two integers <code>height</code> and <code>width</code> representing a garden of size <code>height x width</code>. You are also given:</p>
<ul>
<li>an array <code>tree</code> where <code>tree = [tree<sub>r</sub>, tree<sub>c</sub>]</code> is the position of the tree in the garden,</li>
<li>an array <code>squirrel</code> where <code>squirrel = [squirrel<sub>r</sub>, squirrel<sub>c</sub>]</code> is the position of the squirrel in the garden,</li>
<li>and an array <code>nuts</code> where <code>nuts[i] = [nut<sub>i<sub>r</sub></sub>, nut<sub>i<sub>c</sub></sub>]</code> is the position of the <code>i<sup>th</sup></code> nut in the garden.</li>
</ul>
<p>The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.</p>
<p>Return <em>the <strong>minimal distance</strong> for the squirrel to collect all the nuts and put them under the tree one by one</em>.</p>
<p>The <strong>distance</strong> is the number of moves.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel1-grid.jpg" style="width: 573px; height: 413px;" />
<pre>
<strong>Input:</strong> height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel2-grid.jpg" style="width: 253px; height: 93px;" />
<pre>
<strong>Input:</strong> height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= height, width <= 100</code></li>
<li><code>tree.length == 2</code></li>
<li><code>squirrel.length == 2</code></li>
<li><code>1 <= nuts.length <= 5000</code></li>
<li><code>nuts[i].length == 2</code></li>
<li><code>0 <= tree<sub>r</sub>, squirrel<sub>r</sub>, nut<sub>i<sub>r</sub></sub> <= height</code></li>
<li><code>0 <= tree<sub>c</sub>, squirrel<sub>c</sub>, nut<sub>i<sub>c</sub></sub> <= width</code></li>
</ul>
|
Array; Math
|
C#
|
public class Solution {
public int MinDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) {
int tr = tree[0], tc = tree[1];
int sr = squirrel[0], sc = squirrel[1];
int s = 0;
foreach (var e in nuts) {
s += Math.Abs(e[0] - tr) + Math.Abs(e[1] - tc);
}
s <<= 1;
int ans = int.MaxValue;
foreach (var e in nuts) {
int a = Math.Abs(e[0] - tr) + Math.Abs(e[1] - tc);
int b = Math.Abs(e[0] - sr) + Math.Abs(e[1] - sc);
ans = Math.Min(ans, s - a + b);
}
return ans;
}
}
|
573
|
Squirrel Simulation
|
Medium
|
<p>You are given two integers <code>height</code> and <code>width</code> representing a garden of size <code>height x width</code>. You are also given:</p>
<ul>
<li>an array <code>tree</code> where <code>tree = [tree<sub>r</sub>, tree<sub>c</sub>]</code> is the position of the tree in the garden,</li>
<li>an array <code>squirrel</code> where <code>squirrel = [squirrel<sub>r</sub>, squirrel<sub>c</sub>]</code> is the position of the squirrel in the garden,</li>
<li>and an array <code>nuts</code> where <code>nuts[i] = [nut<sub>i<sub>r</sub></sub>, nut<sub>i<sub>c</sub></sub>]</code> is the position of the <code>i<sup>th</sup></code> nut in the garden.</li>
</ul>
<p>The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.</p>
<p>Return <em>the <strong>minimal distance</strong> for the squirrel to collect all the nuts and put them under the tree one by one</em>.</p>
<p>The <strong>distance</strong> is the number of moves.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel1-grid.jpg" style="width: 573px; height: 413px;" />
<pre>
<strong>Input:</strong> height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel2-grid.jpg" style="width: 253px; height: 93px;" />
<pre>
<strong>Input:</strong> height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= height, width <= 100</code></li>
<li><code>tree.length == 2</code></li>
<li><code>squirrel.length == 2</code></li>
<li><code>1 <= nuts.length <= 5000</code></li>
<li><code>nuts[i].length == 2</code></li>
<li><code>0 <= tree<sub>r</sub>, squirrel<sub>r</sub>, nut<sub>i<sub>r</sub></sub> <= height</code></li>
<li><code>0 <= tree<sub>c</sub>, squirrel<sub>c</sub>, nut<sub>i<sub>c</sub></sub> <= width</code></li>
</ul>
|
Array; Math
|
Go
|
func minDistance(height int, width int, tree []int, squirrel []int, nuts [][]int) int {
tr, tc := tree[0], tree[1]
sr, sc := squirrel[0], squirrel[1]
s := 0
for _, e := range nuts {
s += abs(e[0]-tr) + abs(e[1]-tc)
}
s <<= 1
ans := math.MaxInt32
for _, e := range nuts {
a := abs(e[0]-tr) + abs(e[1]-tc)
b := abs(e[0]-sr) + abs(e[1]-sc)
ans = min(ans, s-a+b)
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
573
|
Squirrel Simulation
|
Medium
|
<p>You are given two integers <code>height</code> and <code>width</code> representing a garden of size <code>height x width</code>. You are also given:</p>
<ul>
<li>an array <code>tree</code> where <code>tree = [tree<sub>r</sub>, tree<sub>c</sub>]</code> is the position of the tree in the garden,</li>
<li>an array <code>squirrel</code> where <code>squirrel = [squirrel<sub>r</sub>, squirrel<sub>c</sub>]</code> is the position of the squirrel in the garden,</li>
<li>and an array <code>nuts</code> where <code>nuts[i] = [nut<sub>i<sub>r</sub></sub>, nut<sub>i<sub>c</sub></sub>]</code> is the position of the <code>i<sup>th</sup></code> nut in the garden.</li>
</ul>
<p>The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.</p>
<p>Return <em>the <strong>minimal distance</strong> for the squirrel to collect all the nuts and put them under the tree one by one</em>.</p>
<p>The <strong>distance</strong> is the number of moves.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel1-grid.jpg" style="width: 573px; height: 413px;" />
<pre>
<strong>Input:</strong> height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel2-grid.jpg" style="width: 253px; height: 93px;" />
<pre>
<strong>Input:</strong> height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= height, width <= 100</code></li>
<li><code>tree.length == 2</code></li>
<li><code>squirrel.length == 2</code></li>
<li><code>1 <= nuts.length <= 5000</code></li>
<li><code>nuts[i].length == 2</code></li>
<li><code>0 <= tree<sub>r</sub>, squirrel<sub>r</sub>, nut<sub>i<sub>r</sub></sub> <= height</code></li>
<li><code>0 <= tree<sub>c</sub>, squirrel<sub>c</sub>, nut<sub>i<sub>c</sub></sub> <= width</code></li>
</ul>
|
Array; Math
|
Java
|
import static java.lang.Math.*;
class Solution {
public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) {
int tr = tree[0], tc = tree[1];
int sr = squirrel[0], sc = squirrel[1];
int s = 0;
for (var e : nuts) {
s += abs(e[0] - tr) + abs(e[1] - tc);
}
s <<= 1;
int ans = Integer.MAX_VALUE;
for (var e : nuts) {
int a = abs(e[0] - tr) + abs(e[1] - tc);
int b = abs(e[0] - sr) + abs(e[1] - sc);
ans = min(ans, s - a + b);
}
return ans;
}
}
|
573
|
Squirrel Simulation
|
Medium
|
<p>You are given two integers <code>height</code> and <code>width</code> representing a garden of size <code>height x width</code>. You are also given:</p>
<ul>
<li>an array <code>tree</code> where <code>tree = [tree<sub>r</sub>, tree<sub>c</sub>]</code> is the position of the tree in the garden,</li>
<li>an array <code>squirrel</code> where <code>squirrel = [squirrel<sub>r</sub>, squirrel<sub>c</sub>]</code> is the position of the squirrel in the garden,</li>
<li>and an array <code>nuts</code> where <code>nuts[i] = [nut<sub>i<sub>r</sub></sub>, nut<sub>i<sub>c</sub></sub>]</code> is the position of the <code>i<sup>th</sup></code> nut in the garden.</li>
</ul>
<p>The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.</p>
<p>Return <em>the <strong>minimal distance</strong> for the squirrel to collect all the nuts and put them under the tree one by one</em>.</p>
<p>The <strong>distance</strong> is the number of moves.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel1-grid.jpg" style="width: 573px; height: 413px;" />
<pre>
<strong>Input:</strong> height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel2-grid.jpg" style="width: 253px; height: 93px;" />
<pre>
<strong>Input:</strong> height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= height, width <= 100</code></li>
<li><code>tree.length == 2</code></li>
<li><code>squirrel.length == 2</code></li>
<li><code>1 <= nuts.length <= 5000</code></li>
<li><code>nuts[i].length == 2</code></li>
<li><code>0 <= tree<sub>r</sub>, squirrel<sub>r</sub>, nut<sub>i<sub>r</sub></sub> <= height</code></li>
<li><code>0 <= tree<sub>c</sub>, squirrel<sub>c</sub>, nut<sub>i<sub>c</sub></sub> <= width</code></li>
</ul>
|
Array; Math
|
Python
|
class Solution:
def minDistance(
self,
height: int,
width: int,
tree: List[int],
squirrel: List[int],
nuts: List[List[int]],
) -> int:
tr, tc = tree
sr, sc = squirrel
s = sum(abs(r - tr) + abs(c - tc) for r, c in nuts) * 2
ans = inf
for r, c in nuts:
a = abs(r - tr) + abs(c - tc)
b = abs(r - sr) + abs(c - sc)
ans = min(ans, s - a + b)
return ans
|
573
|
Squirrel Simulation
|
Medium
|
<p>You are given two integers <code>height</code> and <code>width</code> representing a garden of size <code>height x width</code>. You are also given:</p>
<ul>
<li>an array <code>tree</code> where <code>tree = [tree<sub>r</sub>, tree<sub>c</sub>]</code> is the position of the tree in the garden,</li>
<li>an array <code>squirrel</code> where <code>squirrel = [squirrel<sub>r</sub>, squirrel<sub>c</sub>]</code> is the position of the squirrel in the garden,</li>
<li>and an array <code>nuts</code> where <code>nuts[i] = [nut<sub>i<sub>r</sub></sub>, nut<sub>i<sub>c</sub></sub>]</code> is the position of the <code>i<sup>th</sup></code> nut in the garden.</li>
</ul>
<p>The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.</p>
<p>Return <em>the <strong>minimal distance</strong> for the squirrel to collect all the nuts and put them under the tree one by one</em>.</p>
<p>The <strong>distance</strong> is the number of moves.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel1-grid.jpg" style="width: 573px; height: 413px;" />
<pre>
<strong>Input:</strong> height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel2-grid.jpg" style="width: 253px; height: 93px;" />
<pre>
<strong>Input:</strong> height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= height, width <= 100</code></li>
<li><code>tree.length == 2</code></li>
<li><code>squirrel.length == 2</code></li>
<li><code>1 <= nuts.length <= 5000</code></li>
<li><code>nuts[i].length == 2</code></li>
<li><code>0 <= tree<sub>r</sub>, squirrel<sub>r</sub>, nut<sub>i<sub>r</sub></sub> <= height</code></li>
<li><code>0 <= tree<sub>c</sub>, squirrel<sub>c</sub>, nut<sub>i<sub>c</sub></sub> <= width</code></li>
</ul>
|
Array; Math
|
Rust
|
impl Solution {
pub fn min_distance(
height: i32,
width: i32,
tree: Vec<i32>,
squirrel: Vec<i32>,
nuts: Vec<Vec<i32>>,
) -> i32 {
let (tr, tc) = (tree[0], tree[1]);
let (sr, sc) = (squirrel[0], squirrel[1]);
let s: i32 = nuts
.iter()
.map(|nut| (nut[0] - tr).abs() + (nut[1] - tc).abs())
.sum::<i32>()
* 2;
let mut ans = i32::MAX;
for nut in &nuts {
let a = (nut[0] - tr).abs() + (nut[1] - tc).abs();
let b = (nut[0] - sr).abs() + (nut[1] - sc).abs();
ans = ans.min(s - a + b);
}
ans
}
}
|
573
|
Squirrel Simulation
|
Medium
|
<p>You are given two integers <code>height</code> and <code>width</code> representing a garden of size <code>height x width</code>. You are also given:</p>
<ul>
<li>an array <code>tree</code> where <code>tree = [tree<sub>r</sub>, tree<sub>c</sub>]</code> is the position of the tree in the garden,</li>
<li>an array <code>squirrel</code> where <code>squirrel = [squirrel<sub>r</sub>, squirrel<sub>c</sub>]</code> is the position of the squirrel in the garden,</li>
<li>and an array <code>nuts</code> where <code>nuts[i] = [nut<sub>i<sub>r</sub></sub>, nut<sub>i<sub>c</sub></sub>]</code> is the position of the <code>i<sup>th</sup></code> nut in the garden.</li>
</ul>
<p>The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.</p>
<p>Return <em>the <strong>minimal distance</strong> for the squirrel to collect all the nuts and put them under the tree one by one</em>.</p>
<p>The <strong>distance</strong> is the number of moves.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel1-grid.jpg" style="width: 573px; height: 413px;" />
<pre>
<strong>Input:</strong> height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0573.Squirrel%20Simulation/images/squirrel2-grid.jpg" style="width: 253px; height: 93px;" />
<pre>
<strong>Input:</strong> height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= height, width <= 100</code></li>
<li><code>tree.length == 2</code></li>
<li><code>squirrel.length == 2</code></li>
<li><code>1 <= nuts.length <= 5000</code></li>
<li><code>nuts[i].length == 2</code></li>
<li><code>0 <= tree<sub>r</sub>, squirrel<sub>r</sub>, nut<sub>i<sub>r</sub></sub> <= height</code></li>
<li><code>0 <= tree<sub>c</sub>, squirrel<sub>c</sub>, nut<sub>i<sub>c</sub></sub> <= width</code></li>
</ul>
|
Array; Math
|
TypeScript
|
function minDistance(
height: number,
width: number,
tree: number[],
squirrel: number[],
nuts: number[][],
): number {
const [tr, tc] = tree;
const [sr, sc] = squirrel;
const s = nuts.reduce((acc, [r, c]) => acc + (Math.abs(tr - r) + Math.abs(tc - c)) * 2, 0);
let ans = Infinity;
for (const [r, c] of nuts) {
const a = Math.abs(tr - r) + Math.abs(tc - c);
const b = Math.abs(sr - r) + Math.abs(sc - c);
ans = Math.min(ans, s - a + b);
}
return ans;
}
|
574
|
Winning Candidate
|
Medium
|
<p>Table: <code>Candidate</code></p>
<pre>
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| id | int |
| name | varchar |
+-------------+----------+
id is the column with unique values for this table.
Each row of this table contains information about the id and the name of a candidate.
</pre>
<p> </p>
<p>Table: <code>Vote</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| candidateId | int |
+-------------+------+
id is an auto-increment primary key (column with unique values).
candidateId is a foreign key (reference column) to id from the Candidate table.
Each row of this table determines the candidate who got the i<sup>th</sup> vote in the elections.
</pre>
<p> </p>
<p>Write a solution to report the name of the winning candidate (i.e., the candidate who got the largest number of votes).</p>
<p>The test cases are generated so that <strong>exactly one candidate wins</strong> the elections.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Candidate table:
+----+------+
| id | name |
+----+------+
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
| 5 | E |
+----+------+
Vote table:
+----+-------------+
| id | candidateId |
+----+-------------+
| 1 | 2 |
| 2 | 4 |
| 3 | 3 |
| 4 | 2 |
| 5 | 5 |
+----+-------------+
<strong>Output:</strong>
+------+
| name |
+------+
| B |
+------+
<strong>Explanation:</strong>
Candidate B has 2 votes. Candidates C, D, and E have 1 vote each.
The winner is candidate B.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
Name
FROM
(
SELECT
CandidateId AS id
FROM Vote
GROUP BY CandidateId
ORDER BY COUNT(id) DESC
LIMIT 1
) AS t
INNER JOIN Candidate AS c ON t.id = c.id;
|
575
|
Distribute Candies
|
Easy
|
<p>Alice has <code>n</code> candies, where the <code>i<sup>th</sup></code> candy is of type <code>candyType[i]</code>. Alice noticed that she started to gain weight, so she visited a doctor.</p>
<p>The doctor advised Alice to only eat <code>n / 2</code> of the candies she has (<code>n</code> is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.</p>
<p>Given the integer array <code>candyType</code> of length <code>n</code>, return <em>the <strong>maximum</strong> number of different types of candies she can eat if she only eats </em><code>n / 2</code><em> of them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> candyType = [1,1,2,2,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> candyType = [1,1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> candyType = [6,6,6,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == candyType.length</code></li>
<li><code>2 <= n <= 10<sup>4</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>-10<sup>5</sup> <= candyType[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
int distributeCandies(vector<int>& candyType) {
unordered_set<int> s(candyType.begin(), candyType.end());
return min(candyType.size() >> 1, s.size());
}
};
|
575
|
Distribute Candies
|
Easy
|
<p>Alice has <code>n</code> candies, where the <code>i<sup>th</sup></code> candy is of type <code>candyType[i]</code>. Alice noticed that she started to gain weight, so she visited a doctor.</p>
<p>The doctor advised Alice to only eat <code>n / 2</code> of the candies she has (<code>n</code> is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.</p>
<p>Given the integer array <code>candyType</code> of length <code>n</code>, return <em>the <strong>maximum</strong> number of different types of candies she can eat if she only eats </em><code>n / 2</code><em> of them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> candyType = [1,1,2,2,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> candyType = [1,1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> candyType = [6,6,6,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == candyType.length</code></li>
<li><code>2 <= n <= 10<sup>4</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>-10<sup>5</sup> <= candyType[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table
|
Go
|
func distributeCandies(candyType []int) int {
s := hashset.New()
for _, c := range candyType {
s.Add(c)
}
return min(len(candyType)>>1, s.Size())
}
|
575
|
Distribute Candies
|
Easy
|
<p>Alice has <code>n</code> candies, where the <code>i<sup>th</sup></code> candy is of type <code>candyType[i]</code>. Alice noticed that she started to gain weight, so she visited a doctor.</p>
<p>The doctor advised Alice to only eat <code>n / 2</code> of the candies she has (<code>n</code> is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.</p>
<p>Given the integer array <code>candyType</code> of length <code>n</code>, return <em>the <strong>maximum</strong> number of different types of candies she can eat if she only eats </em><code>n / 2</code><em> of them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> candyType = [1,1,2,2,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> candyType = [1,1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> candyType = [6,6,6,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == candyType.length</code></li>
<li><code>2 <= n <= 10<sup>4</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>-10<sup>5</sup> <= candyType[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public int distributeCandies(int[] candyType) {
Set<Integer> s = new HashSet<>();
for (int c : candyType) {
s.add(c);
}
return Math.min(candyType.length >> 1, s.size());
}
}
|
575
|
Distribute Candies
|
Easy
|
<p>Alice has <code>n</code> candies, where the <code>i<sup>th</sup></code> candy is of type <code>candyType[i]</code>. Alice noticed that she started to gain weight, so she visited a doctor.</p>
<p>The doctor advised Alice to only eat <code>n / 2</code> of the candies she has (<code>n</code> is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.</p>
<p>Given the integer array <code>candyType</code> of length <code>n</code>, return <em>the <strong>maximum</strong> number of different types of candies she can eat if she only eats </em><code>n / 2</code><em> of them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> candyType = [1,1,2,2,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> candyType = [1,1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> candyType = [6,6,6,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == candyType.length</code></li>
<li><code>2 <= n <= 10<sup>4</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>-10<sup>5</sup> <= candyType[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
return min(len(candyType) >> 1, len(set(candyType)))
|
575
|
Distribute Candies
|
Easy
|
<p>Alice has <code>n</code> candies, where the <code>i<sup>th</sup></code> candy is of type <code>candyType[i]</code>. Alice noticed that she started to gain weight, so she visited a doctor.</p>
<p>The doctor advised Alice to only eat <code>n / 2</code> of the candies she has (<code>n</code> is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.</p>
<p>Given the integer array <code>candyType</code> of length <code>n</code>, return <em>the <strong>maximum</strong> number of different types of candies she can eat if she only eats </em><code>n / 2</code><em> of them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> candyType = [1,1,2,2,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> candyType = [1,1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> candyType = [6,6,6,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == candyType.length</code></li>
<li><code>2 <= n <= 10<sup>4</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>-10<sup>5</sup> <= candyType[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function distributeCandies(candyType: number[]): number {
const s = new Set(candyType);
return Math.min(s.size, candyType.length >> 1);
}
|
576
|
Out of Boundary Paths
|
Medium
|
<p>There is an <code>m x n</code> grid with a ball. The ball is initially at the position <code>[startRow, startColumn]</code>. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply <strong>at most</strong> <code>maxMove</code> moves to the ball.</p>
<p>Given the five integers <code>m</code>, <code>n</code>, <code>maxMove</code>, <code>startRow</code>, <code>startColumn</code>, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0576.Out%20of%20Boundary%20Paths/images/out_of_boundary_paths_1.png" style="width: 500px; height: 296px;" />
<pre>
<strong>Input:</strong> m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
<strong>Output:</strong> 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0576.Out%20of%20Boundary%20Paths/images/out_of_boundary_paths_2.png" style="width: 500px; height: 293px;" />
<pre>
<strong>Input:</strong> m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= maxMove <= 50</code></li>
<li><code>0 <= startRow < m</code></li>
<li><code>0 <= startColumn < n</code></li>
</ul>
|
Dynamic Programming
|
C++
|
class Solution {
public:
int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
int f[m][n][maxMove + 1];
memset(f, -1, sizeof(f));
const int mod = 1e9 + 7;
const int dirs[5] = {-1, 0, 1, 0, -1};
auto dfs = [&](this auto&& dfs, int i, int j, int k) -> int {
if (i < 0 || i >= m || j < 0 || j >= n) {
return k >= 0;
}
if (k <= 0) {
return 0;
}
if (f[i][j][k] != -1) {
return f[i][j][k];
}
int ans = 0;
for (int d = 0; d < 4; ++d) {
int x = i + dirs[d], y = j + dirs[d + 1];
ans = (ans + dfs(x, y, k - 1)) % mod;
}
return f[i][j][k] = ans;
};
return dfs(startRow, startColumn, maxMove);
}
};
|
576
|
Out of Boundary Paths
|
Medium
|
<p>There is an <code>m x n</code> grid with a ball. The ball is initially at the position <code>[startRow, startColumn]</code>. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply <strong>at most</strong> <code>maxMove</code> moves to the ball.</p>
<p>Given the five integers <code>m</code>, <code>n</code>, <code>maxMove</code>, <code>startRow</code>, <code>startColumn</code>, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0576.Out%20of%20Boundary%20Paths/images/out_of_boundary_paths_1.png" style="width: 500px; height: 296px;" />
<pre>
<strong>Input:</strong> m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
<strong>Output:</strong> 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0576.Out%20of%20Boundary%20Paths/images/out_of_boundary_paths_2.png" style="width: 500px; height: 293px;" />
<pre>
<strong>Input:</strong> m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= maxMove <= 50</code></li>
<li><code>0 <= startRow < m</code></li>
<li><code>0 <= startColumn < n</code></li>
</ul>
|
Dynamic Programming
|
Go
|
func findPaths(m int, n int, maxMove int, startRow int, startColumn int) int {
f := make([][][]int, m)
for i := range f {
f[i] = make([][]int, n)
for j := range f[i] {
f[i][j] = make([]int, maxMove+1)
for k := range f[i][j] {
f[i][j][k] = -1
}
}
}
const mod int = 1e9 + 7
var dfs func(int, int, int) int
dirs := [5]int{-1, 0, 1, 0, -1}
dfs = func(i, j, k int) int {
if i < 0 || i >= m || j < 0 || j >= n {
if k >= 0 {
return 1
}
return 0
}
if k <= 0 {
return 0
}
if f[i][j][k] != -1 {
return f[i][j][k]
}
ans := 0
for d := 0; d < 4; d++ {
x, y := i+dirs[d], j+dirs[d+1]
ans = (ans + dfs(x, y, k-1)) % mod
}
f[i][j][k] = ans
return ans
}
return dfs(startRow, startColumn, maxMove)
}
|
576
|
Out of Boundary Paths
|
Medium
|
<p>There is an <code>m x n</code> grid with a ball. The ball is initially at the position <code>[startRow, startColumn]</code>. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply <strong>at most</strong> <code>maxMove</code> moves to the ball.</p>
<p>Given the five integers <code>m</code>, <code>n</code>, <code>maxMove</code>, <code>startRow</code>, <code>startColumn</code>, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0576.Out%20of%20Boundary%20Paths/images/out_of_boundary_paths_1.png" style="width: 500px; height: 296px;" />
<pre>
<strong>Input:</strong> m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
<strong>Output:</strong> 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0576.Out%20of%20Boundary%20Paths/images/out_of_boundary_paths_2.png" style="width: 500px; height: 293px;" />
<pre>
<strong>Input:</strong> m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= maxMove <= 50</code></li>
<li><code>0 <= startRow < m</code></li>
<li><code>0 <= startColumn < n</code></li>
</ul>
|
Dynamic Programming
|
Java
|
class Solution {
private int m, n;
private Integer[][][] f;
private final int mod = (int) 1e9 + 7;
public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
this.m = m;
this.n = n;
f = new Integer[m][n][maxMove + 1];
return dfs(startRow, startColumn, maxMove);
}
private int dfs(int i, int j, int k) {
if (i < 0 || i >= m || j < 0 || j >= n) {
return k >= 0 ? 1 : 0;
}
if (k <= 0) {
return 0;
}
if (f[i][j][k] != null) {
return f[i][j][k];
}
int ans = 0;
final int[] dirs = {-1, 0, 1, 0, -1};
for (int d = 0; d < 4; ++d) {
int x = i + dirs[d], y = j + dirs[d + 1];
ans = (ans + dfs(x, y, k - 1)) % mod;
}
return f[i][j][k] = ans;
}
}
|
576
|
Out of Boundary Paths
|
Medium
|
<p>There is an <code>m x n</code> grid with a ball. The ball is initially at the position <code>[startRow, startColumn]</code>. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply <strong>at most</strong> <code>maxMove</code> moves to the ball.</p>
<p>Given the five integers <code>m</code>, <code>n</code>, <code>maxMove</code>, <code>startRow</code>, <code>startColumn</code>, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0576.Out%20of%20Boundary%20Paths/images/out_of_boundary_paths_1.png" style="width: 500px; height: 296px;" />
<pre>
<strong>Input:</strong> m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
<strong>Output:</strong> 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0576.Out%20of%20Boundary%20Paths/images/out_of_boundary_paths_2.png" style="width: 500px; height: 293px;" />
<pre>
<strong>Input:</strong> m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= maxMove <= 50</code></li>
<li><code>0 <= startRow < m</code></li>
<li><code>0 <= startColumn < n</code></li>
</ul>
|
Dynamic Programming
|
Python
|
class Solution:
def findPaths(
self, m: int, n: int, maxMove: int, startRow: int, startColumn: int
) -> int:
@cache
def dfs(i: int, j: int, k: int) -> int:
if not 0 <= i < m or not 0 <= j < n:
return int(k >= 0)
if k <= 0:
return 0
ans = 0
for a, b in pairwise(dirs):
x, y = i + a, j + b
ans = (ans + dfs(x, y, k - 1)) % mod
return ans
mod = 10**9 + 7
dirs = (-1, 0, 1, 0, -1)
return dfs(startRow, startColumn, maxMove)
|
576
|
Out of Boundary Paths
|
Medium
|
<p>There is an <code>m x n</code> grid with a ball. The ball is initially at the position <code>[startRow, startColumn]</code>. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply <strong>at most</strong> <code>maxMove</code> moves to the ball.</p>
<p>Given the five integers <code>m</code>, <code>n</code>, <code>maxMove</code>, <code>startRow</code>, <code>startColumn</code>, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0576.Out%20of%20Boundary%20Paths/images/out_of_boundary_paths_1.png" style="width: 500px; height: 296px;" />
<pre>
<strong>Input:</strong> m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
<strong>Output:</strong> 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0576.Out%20of%20Boundary%20Paths/images/out_of_boundary_paths_2.png" style="width: 500px; height: 293px;" />
<pre>
<strong>Input:</strong> m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= maxMove <= 50</code></li>
<li><code>0 <= startRow < m</code></li>
<li><code>0 <= startColumn < n</code></li>
</ul>
|
Dynamic Programming
|
TypeScript
|
function findPaths(
m: number,
n: number,
maxMove: number,
startRow: number,
startColumn: number,
): number {
const f = Array.from({ length: m }, () =>
Array.from({ length: n }, () => Array(maxMove + 1).fill(-1)),
);
const mod = 1000000007;
const dirs = [-1, 0, 1, 0, -1];
const dfs = (i: number, j: number, k: number): number => {
if (i < 0 || i >= m || j < 0 || j >= n) {
return k >= 0 ? 1 : 0;
}
if (k <= 0) {
return 0;
}
if (f[i][j][k] !== -1) {
return f[i][j][k];
}
let ans = 0;
for (let d = 0; d < 4; ++d) {
const [x, y] = [i + dirs[d], j + dirs[d + 1]];
ans = (ans + dfs(x, y, k - 1)) % mod;
}
return (f[i][j][k] = ans);
};
return dfs(startRow, startColumn, maxMove);
}
|
577
|
Employee Bonus
|
Easy
|
<p>Table: <code>Employee</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| empId | int |
| name | varchar |
| supervisor | int |
| salary | int |
+-------------+---------+
empId is the column with unique values for this table.
Each row of this table indicates the name and the ID of an employee in addition to their salary and the id of their manager.
</pre>
<p> </p>
<p>Table: <code>Bonus</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| empId | int |
| bonus | int |
+-------------+------+
empId is the column of unique values for this table.
empId is a foreign key (reference column) to empId from the Employee table.
Each row of this table contains the id of an employee and their respective bonus.
</pre>
<p> </p>
<p>Write a solution to report the name and bonus amount of each employee with a bonus <strong>less than</strong> <code>1000</code>.</p>
<p>Return the result table in <strong>any order</strong>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Employee table:
+-------+--------+------------+--------+
| empId | name | supervisor | salary |
+-------+--------+------------+--------+
| 3 | Brad | null | 4000 |
| 1 | John | 3 | 1000 |
| 2 | Dan | 3 | 2000 |
| 4 | Thomas | 3 | 4000 |
+-------+--------+------------+--------+
Bonus table:
+-------+-------+
| empId | bonus |
+-------+-------+
| 2 | 500 |
| 4 | 2000 |
+-------+-------+
<strong>Output:</strong>
+------+-------+
| name | bonus |
+------+-------+
| Brad | null |
| John | null |
| Dan | 500 |
+------+-------+
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT name, bonus
FROM
Employee
LEFT JOIN Bonus USING (empId)
WHERE IFNULL(bonus, 0) < 1000;
|
578
|
Get Highest Answer Rate Question
|
Medium
|
<p>Table: <code>SurveyLog</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| action | ENUM |
| question_id | int |
| answer_id | int |
| q_num | int |
| timestamp | int |
+-------------+------+
This table may contain duplicate rows.
action is an ENUM (category) of the type: "show", "answer", or "skip".
Each row of this table indicates the user with ID = id has taken an action with the question question_id at time timestamp.
If the action taken by the user is "answer", answer_id will contain the id of that answer, otherwise, it will be null.
q_num is the numeral order of the question in the current session.
</pre>
<p> </p>
<p>The <strong>answer rate</strong> for a question is the number of times a user answered the question by the number of times a user showed the question.</p>
<p>Write a solution to report the question that has the highest <strong>answer rate</strong>. If multiple questions have the same maximum <strong>answer rate</strong>, report the question with the smallest <code>question_id</code>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
SurveyLog table:
+----+--------+-------------+-----------+-------+-----------+
| id | action | question_id | answer_id | q_num | timestamp |
+----+--------+-------------+-----------+-------+-----------+
| 5 | show | 285 | null | 1 | 123 |
| 5 | answer | 285 | 124124 | 1 | 124 |
| 5 | show | 369 | null | 2 | 125 |
| 5 | skip | 369 | null | 2 | 126 |
+----+--------+-------------+-----------+-------+-----------+
<strong>Output:</strong>
+------------+
| survey_log |
+------------+
| 285 |
+------------+
<strong>Explanation:</strong>
Question 285 was showed 1 time and answered 1 time. The answer rate of question 285 is 1.0
Question 369 was showed 1 time and was not answered. The answer rate of question 369 is 0.0
Question 285 has the highest answer rate.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT question_id AS survey_log
FROM SurveyLog
GROUP BY 1
ORDER BY SUM(action = 'answer') / SUM(action = 'show') DESC, 1
LIMIT 1;
|
579
|
Find Cumulative Salary of an Employee
|
Hard
|
<p>Table: <code>Employee</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| month | int |
| salary | int |
+-------------+------+
(id, month) is the primary key (combination of columns with unique values) for this table.
Each row in the table indicates the salary of an employee in one month during the year 2020.
</pre>
<p> </p>
<p>Write a solution to calculate the <strong>cumulative salary summary</strong> for every employee in a single unified table.</p>
<p>The <strong>cumulative salary summary</strong> for an employee can be calculated as follows:</p>
<ul>
<li>For each month that the employee worked, <strong>sum</strong> up the salaries in <strong>that month</strong> and the <strong>previous two months</strong>. This is their <strong>3-month sum</strong> for that month. If an employee did not work for the company in previous months, their effective salary for those months is <code>0</code>.</li>
<li>Do <strong>not</strong> include the 3-month sum for the <strong>most recent month</strong> that the employee worked for in the summary.</li>
<li>Do <strong>not</strong> include the 3-month sum for any month the employee <strong>did not work</strong>.</li>
</ul>
<p>Return the result table ordered by <code>id</code> in <strong>ascending order</strong>. In case of a tie, order it by <code>month</code> in <strong>descending order</strong>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Employee table:
+----+-------+--------+
| id | month | salary |
+----+-------+--------+
| 1 | 1 | 20 |
| 2 | 1 | 20 |
| 1 | 2 | 30 |
| 2 | 2 | 30 |
| 3 | 2 | 40 |
| 1 | 3 | 40 |
| 3 | 3 | 60 |
| 1 | 4 | 60 |
| 3 | 4 | 70 |
| 1 | 7 | 90 |
| 1 | 8 | 90 |
+----+-------+--------+
<strong>Output:</strong>
+----+-------+--------+
| id | month | Salary |
+----+-------+--------+
| 1 | 7 | 90 |
| 1 | 4 | 130 |
| 1 | 3 | 90 |
| 1 | 2 | 50 |
| 1 | 1 | 20 |
| 2 | 1 | 20 |
| 3 | 3 | 100 |
| 3 | 2 | 40 |
+----+-------+--------+
<strong>Explanation:</strong>
Employee '1' has five salary records excluding their most recent month '8':
- 90 for month '7'.
- 60 for month '4'.
- 40 for month '3'.
- 30 for month '2'.
- 20 for month '1'.
So the cumulative salary summary for this employee is:
+----+-------+--------+
| id | month | salary |
+----+-------+--------+
| 1 | 7 | 90 | (90 + 0 + 0)
| 1 | 4 | 130 | (60 + 40 + 30)
| 1 | 3 | 90 | (40 + 30 + 20)
| 1 | 2 | 50 | (30 + 20 + 0)
| 1 | 1 | 20 | (20 + 0 + 0)
+----+-------+--------+
Note that the 3-month sum for month '7' is 90 because they did not work during month '6' or month '5'.
Employee '2' only has one salary record (month '1') excluding their most recent month '2'.
+----+-------+--------+
| id | month | salary |
+----+-------+--------+
| 2 | 1 | 20 | (20 + 0 + 0)
+----+-------+--------+
Employee '3' has two salary records excluding their most recent month '4':
- 60 for month '3'.
- 40 for month '2'.
So the cumulative salary summary for this employee is:
+----+-------+--------+
| id | month | salary |
+----+-------+--------+
| 3 | 3 | 100 | (60 + 40 + 0)
| 3 | 2 | 40 | (40 + 0 + 0)
+----+-------+--------+
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
id,
month,
SUM(salary) OVER (
PARTITION BY id
ORDER BY month
RANGE 2 PRECEDING
) AS Salary
FROM employee
WHERE
(id, month) NOT IN (
SELECT
id,
MAX(month)
FROM Employee
GROUP BY id
)
ORDER BY id, month DESC;
|
580
|
Count Student Number in Departments
|
Medium
|
<p>Table: <code>Student</code></p>
<pre>
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| student_id | int |
| student_name | varchar |
| gender | varchar |
| dept_id | int |
+--------------+---------+
student_id is the primary key (column with unique values) for this table.
dept_id is a foreign key (reference column) to dept_id in the Department tables.
Each row of this table indicates the name of a student, their gender, and the id of their department.
</pre>
<p> </p>
<p>Table: <code>Department</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| dept_id | int |
| dept_name | varchar |
+-------------+---------+
dept_id is the primary key (column with unique values) for this table.
Each row of this table contains the id and the name of a department.
</pre>
<p> </p>
<p>Write a solution to report the respective department name and number of students majoring in each department for all departments in the <code>Department</code> table (even ones with no current students).</p>
<p>Return the result table <strong>ordered</strong> by <code>student_number</code> <strong>in descending order</strong>. In case of a tie, order them by <code>dept_name</code> <strong>alphabetically</strong>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Student table:
+------------+--------------+--------+---------+
| student_id | student_name | gender | dept_id |
+------------+--------------+--------+---------+
| 1 | Jack | M | 1 |
| 2 | Jane | F | 1 |
| 3 | Mark | M | 2 |
+------------+--------------+--------+---------+
Department table:
+---------+-------------+
| dept_id | dept_name |
+---------+-------------+
| 1 | Engineering |
| 2 | Science |
| 3 | Law |
+---------+-------------+
<strong>Output:</strong>
+-------------+----------------+
| dept_name | student_number |
+-------------+----------------+
| Engineering | 2 |
| Science | 1 |
| Law | 0 |
+-------------+----------------+
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT dept_name, COUNT(student_id) AS student_number
FROM
Department
LEFT JOIN Student USING (dept_id)
GROUP BY dept_id
ORDER BY 2 DESC, 1;
|
581
|
Shortest Unsorted Continuous Subarray
|
Medium
|
<p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.</p>
<p>Return <em>the shortest such subarray and output its length</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,6,4,8,10,9,15]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
<p> </p>
<strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?
|
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
|
C++
|
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
vector<int> arr = nums;
sort(arr.begin(), arr.end());
int l = 0, r = arr.size() - 1;
while (l <= r && arr[l] == nums[l]) {
l++;
}
while (l <= r && arr[r] == nums[r]) {
r--;
}
return r - l + 1;
}
};
|
581
|
Shortest Unsorted Continuous Subarray
|
Medium
|
<p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.</p>
<p>Return <em>the shortest such subarray and output its length</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,6,4,8,10,9,15]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
<p> </p>
<strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?
|
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
|
Go
|
func findUnsortedSubarray(nums []int) int {
arr := make([]int, len(nums))
copy(arr, nums)
sort.Ints(arr)
l, r := 0, len(arr)-1
for l <= r && nums[l] == arr[l] {
l++
}
for l <= r && nums[r] == arr[r] {
r--
}
return r - l + 1
}
|
581
|
Shortest Unsorted Continuous Subarray
|
Medium
|
<p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.</p>
<p>Return <em>the shortest such subarray and output its length</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,6,4,8,10,9,15]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
<p> </p>
<strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?
|
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
|
Java
|
class Solution {
public int findUnsortedSubarray(int[] nums) {
int[] arr = nums.clone();
Arrays.sort(arr);
int l = 0, r = arr.length - 1;
while (l <= r && nums[l] == arr[l]) {
l++;
}
while (l <= r && nums[r] == arr[r]) {
r--;
}
return r - l + 1;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.