id
int64 1
3.65k
| 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
|
---|---|---|---|---|---|---|
304 |
Range Sum Query 2D - Immutable
|
Medium
|
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p>
<ul>
<li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ul>
<p>Implement the <code>NumMatrix</code> class:</p>
<ul>
<li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li>
<li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ul>
<p>You must design an algorithm where <code>sumRegion</code> works on <code>O(1)</code> time complexity.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0304.Range%20Sum%20Query%202D%20-%20Immutable/images/sum-grid.jpg" style="width: 415px; height: 415px;" />
<pre>
<strong>Input</strong>
["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]
<strong>Output</strong>
[null, 8, 11, 12]
<strong>Explanation</strong>
NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>-10<sup>4</sup> <= matrix[i][j] <= 10<sup>4</sup></code></li>
<li><code>0 <= row1 <= row2 < m</code></li>
<li><code>0 <= col1 <= col2 < n</code></li>
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li>
</ul>
|
Design; Array; Matrix; Prefix Sum
|
Python
|
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
m, n = len(matrix), len(matrix[0])
self.s = [[0] * (n + 1) for _ in range(m + 1)]
for i, row in enumerate(matrix):
for j, v in enumerate(row):
self.s[i + 1][j + 1] = (
self.s[i][j + 1] + self.s[i + 1][j] - self.s[i][j] + v
)
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
return (
self.s[row2 + 1][col2 + 1]
- self.s[row2 + 1][col1]
- self.s[row1][col2 + 1]
+ self.s[row1][col1]
)
# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# param_1 = obj.sumRegion(row1,col1,row2,col2)
|
304 |
Range Sum Query 2D - Immutable
|
Medium
|
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p>
<ul>
<li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ul>
<p>Implement the <code>NumMatrix</code> class:</p>
<ul>
<li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li>
<li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ul>
<p>You must design an algorithm where <code>sumRegion</code> works on <code>O(1)</code> time complexity.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0304.Range%20Sum%20Query%202D%20-%20Immutable/images/sum-grid.jpg" style="width: 415px; height: 415px;" />
<pre>
<strong>Input</strong>
["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]
<strong>Output</strong>
[null, 8, 11, 12]
<strong>Explanation</strong>
NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>-10<sup>4</sup> <= matrix[i][j] <= 10<sup>4</sup></code></li>
<li><code>0 <= row1 <= row2 < m</code></li>
<li><code>0 <= col1 <= col2 < n</code></li>
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li>
</ul>
|
Design; Array; Matrix; Prefix Sum
|
Rust
|
/**
* Your NumMatrix object will be instantiated and called as such:
* let obj = NumMatrix::new(matrix);
* let ret_1: i32 = obj.sum_region(row1, col1, row2, col2);
*/
struct NumMatrix {
// Of size (N + 1) * (M + 1)
prefix_vec: Vec<Vec<i32>>,
n: usize,
m: usize,
is_initialized: bool,
ref_vec: Vec<Vec<i32>>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl NumMatrix {
fn new(matrix: Vec<Vec<i32>>) -> Self {
NumMatrix {
prefix_vec: vec![vec![0; matrix[0].len() + 1]; matrix.len() + 1],
n: matrix.len(),
m: matrix[0].len(),
is_initialized: false,
ref_vec: matrix,
}
}
fn sum_region(&mut self, row1: i32, col1: i32, row2: i32, col2: i32) -> i32 {
if !self.is_initialized {
self.initialize_prefix_vec();
}
// Since i32 will let `rustc` complain, just make it happy
let row1: usize = row1 as usize;
let col1: usize = col1 as usize;
let row2: usize = row2 as usize;
let col2: usize = col2 as usize;
// Return the value in O(1)
self.prefix_vec[row2 + 1][col2 + 1]
- self.prefix_vec[row2 + 1][col1]
- self.prefix_vec[row1][col2 + 1]
+ self.prefix_vec[row1][col1]
}
fn initialize_prefix_vec(&mut self) {
// Initialize the prefix sum vector
for i in 0..self.n {
for j in 0..self.m {
self.prefix_vec[i + 1][j + 1] =
self.prefix_vec[i][j + 1] + self.prefix_vec[i + 1][j] - self.prefix_vec[i][j]
+ self.ref_vec[i][j];
}
}
self.is_initialized = true;
}
}
|
304 |
Range Sum Query 2D - Immutable
|
Medium
|
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p>
<ul>
<li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ul>
<p>Implement the <code>NumMatrix</code> class:</p>
<ul>
<li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li>
<li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ul>
<p>You must design an algorithm where <code>sumRegion</code> works on <code>O(1)</code> time complexity.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0304.Range%20Sum%20Query%202D%20-%20Immutable/images/sum-grid.jpg" style="width: 415px; height: 415px;" />
<pre>
<strong>Input</strong>
["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]
<strong>Output</strong>
[null, 8, 11, 12]
<strong>Explanation</strong>
NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>-10<sup>4</sup> <= matrix[i][j] <= 10<sup>4</sup></code></li>
<li><code>0 <= row1 <= row2 < m</code></li>
<li><code>0 <= col1 <= col2 < n</code></li>
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li>
</ul>
|
Design; Array; Matrix; Prefix Sum
|
TypeScript
|
class NumMatrix {
private s: number[][];
constructor(matrix: number[][]) {
const m = matrix.length;
const n = matrix[0].length;
this.s = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0));
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
this.s[i + 1][j + 1] =
this.s[i + 1][j] + this.s[i][j + 1] - this.s[i][j] + matrix[i][j];
}
}
}
sumRegion(row1: number, col1: number, row2: number, col2: number): number {
return (
this.s[row2 + 1][col2 + 1] -
this.s[row2 + 1][col1] -
this.s[row1][col2 + 1] +
this.s[row1][col1]
);
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* var obj = new NumMatrix(matrix)
* var param_1 = obj.sumRegion(row1,col1,row2,col2)
*/
|
305 |
Number of Islands II
|
Hard
|
<p>You are given an empty 2D binary grid <code>grid</code> of size <code>m x n</code>. The grid represents a map where <code>0</code>'s represent water and <code>1</code>'s represent land. Initially, all the cells of <code>grid</code> are water cells (i.e., all the cells are <code>0</code>'s).</p>
<p>We may perform an add land operation which turns the water at position into a land. You are given an array <code>positions</code> where <code>positions[i] = [r<sub>i</sub>, c<sub>i</sub>]</code> is the position <code>(r<sub>i</sub>, c<sub>i</sub>)</code> at which we should operate the <code>i<sup>th</sup></code> operation.</p>
<p>Return <em>an array of integers</em> <code>answer</code> <em>where</em> <code>answer[i]</code> <em>is the number of islands after turning the cell</em> <code>(r<sub>i</sub>, c<sub>i</sub>)</code> <em>into a land</em>.</p>
<p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0305.Number%20of%20Islands%20II/images/tmp-grid.jpg" style="width: 500px; height: 294px;" />
<pre>
<strong>Input:</strong> m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
<strong>Output:</strong> [1,1,2,3]
<strong>Explanation:</strong>
Initially, the 2d grid is filled with water.
- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island.
- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island.
- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands.
- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 1, n = 1, positions = [[0,0]]
<strong>Output:</strong> [1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n, positions.length <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>positions[i].length == 2</code></li>
<li><code>0 <= r<sub>i</sub> < m</code></li>
<li><code>0 <= c<sub>i</sub> < n</code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Could you solve it in time complexity <code>O(k log(mn))</code>, where <code>k == positions.length</code>?</p>
|
Union Find; Array; Hash Table
|
C++
|
class UnionFind {
public:
UnionFind(int n) {
p = vector<int>(n);
size = vector<int>(n, 1);
iota(p.begin(), p.end(), 0);
}
bool unite(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) {
return false;
}
if (size[pa] > size[pb]) {
p[pb] = pa;
size[pa] += size[pb];
} else {
p[pa] = pb;
size[pb] += size[pa];
}
return true;
}
int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
private:
vector<int> p, size;
};
class Solution {
public:
vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
int grid[m][n];
memset(grid, 0, sizeof(grid));
UnionFind uf(m * n);
int dirs[5] = {-1, 0, 1, 0, -1};
int cnt = 0;
vector<int> ans;
for (auto& p : positions) {
int i = p[0], j = p[1];
if (grid[i][j]) {
ans.push_back(cnt);
continue;
}
grid[i][j] = 1;
++cnt;
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] && uf.unite(i * n + j, x * n + y)) {
--cnt;
}
}
ans.push_back(cnt);
}
return ans;
}
};
|
305 |
Number of Islands II
|
Hard
|
<p>You are given an empty 2D binary grid <code>grid</code> of size <code>m x n</code>. The grid represents a map where <code>0</code>'s represent water and <code>1</code>'s represent land. Initially, all the cells of <code>grid</code> are water cells (i.e., all the cells are <code>0</code>'s).</p>
<p>We may perform an add land operation which turns the water at position into a land. You are given an array <code>positions</code> where <code>positions[i] = [r<sub>i</sub>, c<sub>i</sub>]</code> is the position <code>(r<sub>i</sub>, c<sub>i</sub>)</code> at which we should operate the <code>i<sup>th</sup></code> operation.</p>
<p>Return <em>an array of integers</em> <code>answer</code> <em>where</em> <code>answer[i]</code> <em>is the number of islands after turning the cell</em> <code>(r<sub>i</sub>, c<sub>i</sub>)</code> <em>into a land</em>.</p>
<p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0305.Number%20of%20Islands%20II/images/tmp-grid.jpg" style="width: 500px; height: 294px;" />
<pre>
<strong>Input:</strong> m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
<strong>Output:</strong> [1,1,2,3]
<strong>Explanation:</strong>
Initially, the 2d grid is filled with water.
- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island.
- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island.
- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands.
- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 1, n = 1, positions = [[0,0]]
<strong>Output:</strong> [1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n, positions.length <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>positions[i].length == 2</code></li>
<li><code>0 <= r<sub>i</sub> < m</code></li>
<li><code>0 <= c<sub>i</sub> < n</code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Could you solve it in time complexity <code>O(k log(mn))</code>, where <code>k == positions.length</code>?</p>
|
Union Find; Array; Hash Table
|
Go
|
type unionFind struct {
p, size []int
}
func newUnionFind(n int) *unionFind {
p := make([]int, n)
size := make([]int, n)
for i := range p {
p[i] = i
size[i] = 1
}
return &unionFind{p, size}
}
func (uf *unionFind) find(x int) int {
if uf.p[x] != x {
uf.p[x] = uf.find(uf.p[x])
}
return uf.p[x]
}
func (uf *unionFind) union(a, b int) bool {
pa, pb := uf.find(a), uf.find(b)
if pa == pb {
return false
}
if uf.size[pa] > uf.size[pb] {
uf.p[pb] = pa
uf.size[pa] += uf.size[pb]
} else {
uf.p[pa] = pb
uf.size[pb] += uf.size[pa]
}
return true
}
func numIslands2(m int, n int, positions [][]int) (ans []int) {
uf := newUnionFind(m * n)
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
dirs := [5]int{-1, 0, 1, 0, -1}
cnt := 0
for _, p := range positions {
i, j := p[0], p[1]
if grid[i][j] == 1 {
ans = append(ans, cnt)
continue
}
grid[i][j] = 1
cnt++
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 && uf.union(i*n+j, x*n+y) {
cnt--
}
}
ans = append(ans, cnt)
}
return
}
|
305 |
Number of Islands II
|
Hard
|
<p>You are given an empty 2D binary grid <code>grid</code> of size <code>m x n</code>. The grid represents a map where <code>0</code>'s represent water and <code>1</code>'s represent land. Initially, all the cells of <code>grid</code> are water cells (i.e., all the cells are <code>0</code>'s).</p>
<p>We may perform an add land operation which turns the water at position into a land. You are given an array <code>positions</code> where <code>positions[i] = [r<sub>i</sub>, c<sub>i</sub>]</code> is the position <code>(r<sub>i</sub>, c<sub>i</sub>)</code> at which we should operate the <code>i<sup>th</sup></code> operation.</p>
<p>Return <em>an array of integers</em> <code>answer</code> <em>where</em> <code>answer[i]</code> <em>is the number of islands after turning the cell</em> <code>(r<sub>i</sub>, c<sub>i</sub>)</code> <em>into a land</em>.</p>
<p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0305.Number%20of%20Islands%20II/images/tmp-grid.jpg" style="width: 500px; height: 294px;" />
<pre>
<strong>Input:</strong> m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
<strong>Output:</strong> [1,1,2,3]
<strong>Explanation:</strong>
Initially, the 2d grid is filled with water.
- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island.
- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island.
- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands.
- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 1, n = 1, positions = [[0,0]]
<strong>Output:</strong> [1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n, positions.length <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>positions[i].length == 2</code></li>
<li><code>0 <= r<sub>i</sub> < m</code></li>
<li><code>0 <= c<sub>i</sub> < n</code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Could you solve it in time complexity <code>O(k log(mn))</code>, where <code>k == positions.length</code>?</p>
|
Union Find; Array; Hash Table
|
Java
|
class UnionFind {
private final int[] p;
private final int[] size;
public UnionFind(int n) {
p = new int[n];
size = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
size[i] = 1;
}
}
public int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
public boolean union(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) {
return false;
}
if (size[pa] > size[pb]) {
p[pb] = pa;
size[pa] += size[pb];
} else {
p[pa] = pb;
size[pb] += size[pa];
}
return true;
}
}
class Solution {
public List<Integer> numIslands2(int m, int n, int[][] positions) {
int[][] grid = new int[m][n];
UnionFind uf = new UnionFind(m * n);
int[] dirs = {-1, 0, 1, 0, -1};
int cnt = 0;
List<Integer> ans = new ArrayList<>();
for (var p : positions) {
int i = p[0], j = p[1];
if (grid[i][j] == 1) {
ans.add(cnt);
continue;
}
grid[i][j] = 1;
++cnt;
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1
&& uf.union(i * n + j, x * n + y)) {
--cnt;
}
}
ans.add(cnt);
}
return ans;
}
}
|
305 |
Number of Islands II
|
Hard
|
<p>You are given an empty 2D binary grid <code>grid</code> of size <code>m x n</code>. The grid represents a map where <code>0</code>'s represent water and <code>1</code>'s represent land. Initially, all the cells of <code>grid</code> are water cells (i.e., all the cells are <code>0</code>'s).</p>
<p>We may perform an add land operation which turns the water at position into a land. You are given an array <code>positions</code> where <code>positions[i] = [r<sub>i</sub>, c<sub>i</sub>]</code> is the position <code>(r<sub>i</sub>, c<sub>i</sub>)</code> at which we should operate the <code>i<sup>th</sup></code> operation.</p>
<p>Return <em>an array of integers</em> <code>answer</code> <em>where</em> <code>answer[i]</code> <em>is the number of islands after turning the cell</em> <code>(r<sub>i</sub>, c<sub>i</sub>)</code> <em>into a land</em>.</p>
<p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0305.Number%20of%20Islands%20II/images/tmp-grid.jpg" style="width: 500px; height: 294px;" />
<pre>
<strong>Input:</strong> m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
<strong>Output:</strong> [1,1,2,3]
<strong>Explanation:</strong>
Initially, the 2d grid is filled with water.
- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island.
- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island.
- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands.
- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 1, n = 1, positions = [[0,0]]
<strong>Output:</strong> [1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n, positions.length <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>positions[i].length == 2</code></li>
<li><code>0 <= r<sub>i</sub> < m</code></li>
<li><code>0 <= c<sub>i</sub> < n</code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Could you solve it in time complexity <code>O(k log(mn))</code>, where <code>k == positions.length</code>?</p>
|
Union Find; Array; Hash Table
|
Python
|
class UnionFind:
def __init__(self, n: int):
self.p = list(range(n))
self.size = [1] * n
def find(self, x: int):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a: int, b: int) -> bool:
pa, pb = self.find(a - 1), self.find(b - 1)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
return True
class Solution:
def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]:
uf = UnionFind(m * n)
grid = [[0] * n for _ in range(m)]
ans = []
dirs = (-1, 0, 1, 0, -1)
cnt = 0
for i, j in positions:
if grid[i][j]:
ans.append(cnt)
continue
grid[i][j] = 1
cnt += 1
for a, b in pairwise(dirs):
x, y = i + a, j + b
if (
0 <= x < m
and 0 <= y < n
and grid[x][y]
and uf.union(i * n + j, x * n + y)
):
cnt -= 1
ans.append(cnt)
return ans
|
305 |
Number of Islands II
|
Hard
|
<p>You are given an empty 2D binary grid <code>grid</code> of size <code>m x n</code>. The grid represents a map where <code>0</code>'s represent water and <code>1</code>'s represent land. Initially, all the cells of <code>grid</code> are water cells (i.e., all the cells are <code>0</code>'s).</p>
<p>We may perform an add land operation which turns the water at position into a land. You are given an array <code>positions</code> where <code>positions[i] = [r<sub>i</sub>, c<sub>i</sub>]</code> is the position <code>(r<sub>i</sub>, c<sub>i</sub>)</code> at which we should operate the <code>i<sup>th</sup></code> operation.</p>
<p>Return <em>an array of integers</em> <code>answer</code> <em>where</em> <code>answer[i]</code> <em>is the number of islands after turning the cell</em> <code>(r<sub>i</sub>, c<sub>i</sub>)</code> <em>into a land</em>.</p>
<p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0305.Number%20of%20Islands%20II/images/tmp-grid.jpg" style="width: 500px; height: 294px;" />
<pre>
<strong>Input:</strong> m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
<strong>Output:</strong> [1,1,2,3]
<strong>Explanation:</strong>
Initially, the 2d grid is filled with water.
- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island.
- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island.
- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands.
- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 1, n = 1, positions = [[0,0]]
<strong>Output:</strong> [1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n, positions.length <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>positions[i].length == 2</code></li>
<li><code>0 <= r<sub>i</sub> < m</code></li>
<li><code>0 <= c<sub>i</sub> < n</code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Could you solve it in time complexity <code>O(k log(mn))</code>, where <code>k == positions.length</code>?</p>
|
Union Find; Array; Hash Table
|
TypeScript
|
class UnionFind {
p: number[];
size: number[];
constructor(n: number) {
this.p = Array(n)
.fill(0)
.map((_, i) => i);
this.size = Array(n).fill(1);
}
find(x: number): number {
if (this.p[x] !== x) {
this.p[x] = this.find(this.p[x]);
}
return this.p[x];
}
union(a: number, b: number): boolean {
const [pa, pb] = [this.find(a), this.find(b)];
if (pa === pb) {
return false;
}
if (this.size[pa] > this.size[pb]) {
this.p[pb] = pa;
this.size[pa] += this.size[pb];
} else {
this.p[pa] = pb;
this.size[pb] += this.size[pa];
}
return true;
}
}
function numIslands2(m: number, n: number, positions: number[][]): number[] {
const grid: number[][] = Array.from({ length: m }, () => Array(n).fill(0));
const uf = new UnionFind(m * n);
const ans: number[] = [];
const dirs: number[] = [-1, 0, 1, 0, -1];
let cnt = 0;
for (const [i, j] of positions) {
if (grid[i][j]) {
ans.push(cnt);
continue;
}
grid[i][j] = 1;
++cnt;
for (let k = 0; k < 4; ++k) {
const [x, y] = [i + dirs[k], j + dirs[k + 1]];
if (x < 0 || x >= m || y < 0 || y >= n || !grid[x][y]) {
continue;
}
if (uf.union(i * n + j, x * n + y)) {
--cnt;
}
}
ans.push(cnt);
}
return ans;
}
|
306 |
Additive Number
|
Medium
|
<p>An <strong>additive number</strong> is a string whose digits can form an <strong>additive sequence</strong>.</p>
<p>A valid <strong>additive sequence</strong> should contain <strong>at least</strong> three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.</p>
<p>Given a string containing only digits, return <code>true</code> if it is an <strong>additive number</strong> or <code>false</code> otherwise.</p>
<p><strong>Note:</strong> Numbers in the additive sequence <strong>cannot</strong> have leading zeros, so sequence <code>1, 2, 03</code> or <code>1, 02, 3</code> is invalid.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> "112358"
<strong>Output:</strong> true
<strong>Explanation:</strong>
The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> "199100199"
<strong>Output:</strong> true
<strong>Explanation:</strong>
The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num.length <= 35</code></li>
<li><code>num</code> consists only of digits.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> How would you handle overflow for very large input integers?</p>
|
String; Backtracking
|
C++
|
class Solution {
public:
bool isAdditiveNumber(string num) {
int n = num.size();
for (int i = 1; i < min(n - 1, 19); ++i) {
for (int j = i + 1; j < min(n, i + 19); ++j) {
if (i > 1 && num[0] == '0') break;
if (j - i > 1 && num[i] == '0') continue;
auto a = stoll(num.substr(0, i));
auto b = stoll(num.substr(i, j - i));
if (dfs(a, b, num.substr(j, n - j))) return true;
}
}
return false;
}
bool dfs(long long a, long long b, string num) {
if (num == "") return true;
if (a + b > 0 && num[0] == '0') return false;
for (int i = 1; i < min((int) num.size() + 1, 19); ++i)
if (a + b == stoll(num.substr(0, i)))
if (dfs(b, a + b, num.substr(i, num.size() - i)))
return true;
return false;
}
};
|
306 |
Additive Number
|
Medium
|
<p>An <strong>additive number</strong> is a string whose digits can form an <strong>additive sequence</strong>.</p>
<p>A valid <strong>additive sequence</strong> should contain <strong>at least</strong> three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.</p>
<p>Given a string containing only digits, return <code>true</code> if it is an <strong>additive number</strong> or <code>false</code> otherwise.</p>
<p><strong>Note:</strong> Numbers in the additive sequence <strong>cannot</strong> have leading zeros, so sequence <code>1, 2, 03</code> or <code>1, 02, 3</code> is invalid.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> "112358"
<strong>Output:</strong> true
<strong>Explanation:</strong>
The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> "199100199"
<strong>Output:</strong> true
<strong>Explanation:</strong>
The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num.length <= 35</code></li>
<li><code>num</code> consists only of digits.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> How would you handle overflow for very large input integers?</p>
|
String; Backtracking
|
Go
|
func isAdditiveNumber(num string) bool {
n := len(num)
var dfs func(a, b int64, num string) bool
dfs = func(a, b int64, num string) bool {
if num == "" {
return true
}
if a+b > 0 && num[0] == '0' {
return false
}
for i := 1; i < min(len(num)+1, 19); i++ {
c, _ := strconv.ParseInt(num[:i], 10, 64)
if a+b == c {
if dfs(b, c, num[i:]) {
return true
}
}
}
return false
}
for i := 1; i < min(n-1, 19); i++ {
for j := i + 1; j < min(n, i+19); j++ {
if i > 1 && num[0] == '0' {
break
}
if j-i > 1 && num[i] == '0' {
continue
}
a, _ := strconv.ParseInt(num[:i], 10, 64)
b, _ := strconv.ParseInt(num[i:j], 10, 64)
if dfs(a, b, num[j:]) {
return true
}
}
}
return false
}
|
306 |
Additive Number
|
Medium
|
<p>An <strong>additive number</strong> is a string whose digits can form an <strong>additive sequence</strong>.</p>
<p>A valid <strong>additive sequence</strong> should contain <strong>at least</strong> three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.</p>
<p>Given a string containing only digits, return <code>true</code> if it is an <strong>additive number</strong> or <code>false</code> otherwise.</p>
<p><strong>Note:</strong> Numbers in the additive sequence <strong>cannot</strong> have leading zeros, so sequence <code>1, 2, 03</code> or <code>1, 02, 3</code> is invalid.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> "112358"
<strong>Output:</strong> true
<strong>Explanation:</strong>
The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> "199100199"
<strong>Output:</strong> true
<strong>Explanation:</strong>
The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num.length <= 35</code></li>
<li><code>num</code> consists only of digits.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> How would you handle overflow for very large input integers?</p>
|
String; Backtracking
|
Java
|
class Solution {
public boolean isAdditiveNumber(String num) {
int n = num.length();
for (int i = 1; i < Math.min(n - 1, 19); ++i) {
for (int j = i + 1; j < Math.min(n, i + 19); ++j) {
if (i > 1 && num.charAt(0) == '0') {
break;
}
if (j - i > 1 && num.charAt(i) == '0') {
continue;
}
long a = Long.parseLong(num.substring(0, i));
long b = Long.parseLong(num.substring(i, j));
if (dfs(a, b, num.substring(j))) {
return true;
}
}
}
return false;
}
private boolean dfs(long a, long b, String num) {
if ("".equals(num)) {
return true;
}
if (a + b > 0 && num.charAt(0) == '0') {
return false;
}
for (int i = 1; i < Math.min(num.length() + 1, 19); ++i) {
if (a + b == Long.parseLong(num.substring(0, i))) {
if (dfs(b, a + b, num.substring(i))) {
return true;
}
}
}
return false;
}
}
|
306 |
Additive Number
|
Medium
|
<p>An <strong>additive number</strong> is a string whose digits can form an <strong>additive sequence</strong>.</p>
<p>A valid <strong>additive sequence</strong> should contain <strong>at least</strong> three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.</p>
<p>Given a string containing only digits, return <code>true</code> if it is an <strong>additive number</strong> or <code>false</code> otherwise.</p>
<p><strong>Note:</strong> Numbers in the additive sequence <strong>cannot</strong> have leading zeros, so sequence <code>1, 2, 03</code> or <code>1, 02, 3</code> is invalid.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> "112358"
<strong>Output:</strong> true
<strong>Explanation:</strong>
The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> "199100199"
<strong>Output:</strong> true
<strong>Explanation:</strong>
The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num.length <= 35</code></li>
<li><code>num</code> consists only of digits.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> How would you handle overflow for very large input integers?</p>
|
String; Backtracking
|
Python
|
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
def dfs(a, b, num):
if not num:
return True
if a + b > 0 and num[0] == '0':
return False
for i in range(1, len(num) + 1):
if a + b == int(num[:i]):
if dfs(b, a + b, num[i:]):
return True
return False
n = len(num)
for i in range(1, n - 1):
for j in range(i + 1, n):
if i > 1 and num[0] == '0':
break
if j - i > 1 and num[i] == '0':
continue
if dfs(int(num[:i]), int(num[i:j]), num[j:]):
return True
return False
|
307 |
Range Sum Query - Mutable
|
Medium
|
<p>Given an integer array <code>nums</code>, handle multiple queries of the following types:</p>
<ol>
<li><strong>Update</strong> the value of an element in <code>nums</code>.</li>
<li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left <= right</code>.</li>
</ol>
<p>Implement the <code>NumArray</code> class:</p>
<ul>
<li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>
<li><code>void update(int index, int val)</code> <strong>Updates</strong> the value of <code>nums[index]</code> to be <code>val</code>.</li>
<li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
<strong>Output</strong>
[null, 9, null, 8]
<strong>Explanation</strong>
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = [1, 2, 5]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
<li><code>0 <= index < nums.length</code></li>
<li><code>-100 <= val <= 100</code></li>
<li><code>0 <= left <= right < nums.length</code></li>
<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>update</code> and <code>sumRange</code>.</li>
</ul>
|
Design; Binary Indexed Tree; Segment Tree; Array; Divide and Conquer
|
C++
|
class BinaryIndexedTree {
public:
int n;
vector<int> c;
BinaryIndexedTree(int _n)
: n(_n)
, c(_n + 1) {}
void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += x & -x;
}
}
int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= x & -x;
}
return s;
}
};
class NumArray {
public:
BinaryIndexedTree* tree;
NumArray(vector<int>& nums) {
int n = nums.size();
tree = new BinaryIndexedTree(n);
for (int i = 0; i < n; ++i) tree->update(i + 1, nums[i]);
}
void update(int index, int val) {
int prev = sumRange(index, index);
tree->update(index + 1, val - prev);
}
int sumRange(int left, int right) {
return tree->query(right + 1) - tree->query(left);
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* obj->update(index,val);
* int param_2 = obj->sumRange(left,right);
*/
|
307 |
Range Sum Query - Mutable
|
Medium
|
<p>Given an integer array <code>nums</code>, handle multiple queries of the following types:</p>
<ol>
<li><strong>Update</strong> the value of an element in <code>nums</code>.</li>
<li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left <= right</code>.</li>
</ol>
<p>Implement the <code>NumArray</code> class:</p>
<ul>
<li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>
<li><code>void update(int index, int val)</code> <strong>Updates</strong> the value of <code>nums[index]</code> to be <code>val</code>.</li>
<li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
<strong>Output</strong>
[null, 9, null, 8]
<strong>Explanation</strong>
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = [1, 2, 5]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
<li><code>0 <= index < nums.length</code></li>
<li><code>-100 <= val <= 100</code></li>
<li><code>0 <= left <= right < nums.length</code></li>
<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>update</code> and <code>sumRange</code>.</li>
</ul>
|
Design; Binary Indexed Tree; Segment Tree; Array; Divide and Conquer
|
C#
|
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void Update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += x & -x;
}
}
public int Query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= x & -x;
}
return s;
}
}
public class NumArray {
private BinaryIndexedTree tree;
public NumArray(int[] nums) {
int n = nums.Length;
tree = new BinaryIndexedTree(n);
for (int i = 0; i < n; ++i) {
tree.Update(i + 1, nums[i]);
}
}
public void Update(int index, int val) {
int prev = SumRange(index, index);
tree.Update(index + 1, val - prev);
}
public int SumRange(int left, int right) {
return tree.Query(right + 1) - tree.Query(left);
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* obj.Update(index,val);
* int param_2 = obj.SumRange(left,right);
*/
|
307 |
Range Sum Query - Mutable
|
Medium
|
<p>Given an integer array <code>nums</code>, handle multiple queries of the following types:</p>
<ol>
<li><strong>Update</strong> the value of an element in <code>nums</code>.</li>
<li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left <= right</code>.</li>
</ol>
<p>Implement the <code>NumArray</code> class:</p>
<ul>
<li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>
<li><code>void update(int index, int val)</code> <strong>Updates</strong> the value of <code>nums[index]</code> to be <code>val</code>.</li>
<li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
<strong>Output</strong>
[null, 9, null, 8]
<strong>Explanation</strong>
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = [1, 2, 5]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
<li><code>0 <= index < nums.length</code></li>
<li><code>-100 <= val <= 100</code></li>
<li><code>0 <= left <= right < nums.length</code></li>
<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>update</code> and <code>sumRange</code>.</li>
</ul>
|
Design; Binary Indexed Tree; Segment Tree; Array; Divide and Conquer
|
Go
|
type BinaryIndexedTree struct {
n int
c []int
}
func newBinaryIndexedTree(n int) *BinaryIndexedTree {
c := make([]int, n+1)
return &BinaryIndexedTree{n, c}
}
func (t *BinaryIndexedTree) update(x, delta int) {
for ; x <= t.n; x += x & -x {
t.c[x] += delta
}
}
func (t *BinaryIndexedTree) query(x int) (s int) {
for ; x > 0; x -= x & -x {
s += t.c[x]
}
return s
}
type NumArray struct {
tree *BinaryIndexedTree
}
func Constructor(nums []int) NumArray {
tree := newBinaryIndexedTree(len(nums))
for i, v := range nums {
tree.update(i+1, v)
}
return NumArray{tree}
}
func (t *NumArray) Update(index int, val int) {
prev := t.SumRange(index, index)
t.tree.update(index+1, val-prev)
}
func (t *NumArray) SumRange(left int, right int) int {
return t.tree.query(right+1) - t.tree.query(left)
}
/**
* Your NumArray object will be instantiated and called as such:
* obj := Constructor(nums);
* obj.Update(index,val);
* param_2 := obj.SumRange(left,right);
*/
|
307 |
Range Sum Query - Mutable
|
Medium
|
<p>Given an integer array <code>nums</code>, handle multiple queries of the following types:</p>
<ol>
<li><strong>Update</strong> the value of an element in <code>nums</code>.</li>
<li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left <= right</code>.</li>
</ol>
<p>Implement the <code>NumArray</code> class:</p>
<ul>
<li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>
<li><code>void update(int index, int val)</code> <strong>Updates</strong> the value of <code>nums[index]</code> to be <code>val</code>.</li>
<li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
<strong>Output</strong>
[null, 9, null, 8]
<strong>Explanation</strong>
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = [1, 2, 5]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
<li><code>0 <= index < nums.length</code></li>
<li><code>-100 <= val <= 100</code></li>
<li><code>0 <= left <= right < nums.length</code></li>
<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>update</code> and <code>sumRange</code>.</li>
</ul>
|
Design; Binary Indexed Tree; Segment Tree; Array; Divide and Conquer
|
Java
|
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += x & -x;
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= x & -x;
}
return s;
}
}
class NumArray {
private BinaryIndexedTree tree;
public NumArray(int[] nums) {
int n = nums.length;
tree = new BinaryIndexedTree(n);
for (int i = 0; i < n; ++i) {
tree.update(i + 1, nums[i]);
}
}
public void update(int index, int val) {
int prev = sumRange(index, index);
tree.update(index + 1, val - prev);
}
public int sumRange(int left, int right) {
return tree.query(right + 1) - tree.query(left);
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* obj.update(index,val);
* int param_2 = obj.sumRange(left,right);
*/
|
307 |
Range Sum Query - Mutable
|
Medium
|
<p>Given an integer array <code>nums</code>, handle multiple queries of the following types:</p>
<ol>
<li><strong>Update</strong> the value of an element in <code>nums</code>.</li>
<li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left <= right</code>.</li>
</ol>
<p>Implement the <code>NumArray</code> class:</p>
<ul>
<li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>
<li><code>void update(int index, int val)</code> <strong>Updates</strong> the value of <code>nums[index]</code> to be <code>val</code>.</li>
<li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
<strong>Output</strong>
[null, 9, null, 8]
<strong>Explanation</strong>
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = [1, 2, 5]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
<li><code>0 <= index < nums.length</code></li>
<li><code>-100 <= val <= 100</code></li>
<li><code>0 <= left <= right < nums.length</code></li>
<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>update</code> and <code>sumRange</code>.</li>
</ul>
|
Design; Binary Indexed Tree; Segment Tree; Array; Divide and Conquer
|
Python
|
class BinaryIndexedTree:
__slots__ = ["n", "c"]
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, delta: int):
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x: int) -> int:
s = 0
while x > 0:
s += self.c[x]
x -= x & -x
return s
class NumArray:
__slots__ = ["tree"]
def __init__(self, nums: List[int]):
self.tree = BinaryIndexedTree(len(nums))
for i, v in enumerate(nums, 1):
self.tree.update(i, v)
def update(self, index: int, val: int) -> None:
prev = self.sumRange(index, index)
self.tree.update(index + 1, val - prev)
def sumRange(self, left: int, right: int) -> int:
return self.tree.query(right + 1) - self.tree.query(left)
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(index,val)
# param_2 = obj.sumRange(left,right)
|
307 |
Range Sum Query - Mutable
|
Medium
|
<p>Given an integer array <code>nums</code>, handle multiple queries of the following types:</p>
<ol>
<li><strong>Update</strong> the value of an element in <code>nums</code>.</li>
<li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left <= right</code>.</li>
</ol>
<p>Implement the <code>NumArray</code> class:</p>
<ul>
<li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>
<li><code>void update(int index, int val)</code> <strong>Updates</strong> the value of <code>nums[index]</code> to be <code>val</code>.</li>
<li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
<strong>Output</strong>
[null, 9, null, 8]
<strong>Explanation</strong>
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = [1, 2, 5]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>4</sup></code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
<li><code>0 <= index < nums.length</code></li>
<li><code>-100 <= val <= 100</code></li>
<li><code>0 <= left <= right < nums.length</code></li>
<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>update</code> and <code>sumRange</code>.</li>
</ul>
|
Design; Binary Indexed Tree; Segment Tree; Array; Divide and Conquer
|
TypeScript
|
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(0);
}
update(x: number, delta: number): void {
while (x <= this.n) {
this.c[x] += delta;
x += x & -x;
}
}
query(x: number): number {
let s = 0;
while (x > 0) {
s += this.c[x];
x -= x & -x;
}
return s;
}
}
class NumArray {
private tree: BinaryIndexedTree;
constructor(nums: number[]) {
const n = nums.length;
this.tree = new BinaryIndexedTree(n);
for (let i = 0; i < n; ++i) {
this.tree.update(i + 1, nums[i]);
}
}
update(index: number, val: number): void {
const prev = this.sumRange(index, index);
this.tree.update(index + 1, val - prev);
}
sumRange(left: number, right: number): number {
return this.tree.query(right + 1) - this.tree.query(left);
}
}
/**
* Your NumArray object will be instantiated and called as such:
* var obj = new NumArray(nums)
* obj.update(index,val)
* var param_2 = obj.sumRange(left,right)
*/
|
308 |
Range Sum Query 2D - Mutable
|
Medium
|
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following types:</p>
<ol>
<li><strong>Update</strong> the value of a cell in <code>matrix</code>.</li>
<li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ol>
<p>Implement the NumMatrix class:</p>
<ul>
<li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li>
<li><code>void update(int row, int col, int val)</code> <strong>Updates</strong> the value of <code>matrix[row][col]</code> to be <code>val</code>.</li>
<li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0308.Range%20Sum%20Query%202D%20-%20Mutable/images/summut-grid.jpg" style="width: 500px; height: 222px;" />
<pre>
<strong>Input</strong>
["NumMatrix", "sumRegion", "update", "sumRegion"]
[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [3, 2, 2], [2, 1, 4, 3]]
<strong>Output</strong>
[null, 8, null, 10]
<strong>Explanation</strong>
NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e. sum of the left red rectangle)
numMatrix.update(3, 2, 2); // matrix changes from left image to right image
numMatrix.sumRegion(2, 1, 4, 3); // return 10 (i.e. sum of the right red rectangle)
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>-1000 <= matrix[i][j] <= 1000</code></li>
<li><code>0 <= row < m</code></li>
<li><code>0 <= col < n</code></li>
<li><code>-1000 <= val <= 1000</code></li>
<li><code>0 <= row1 <= row2 < m</code></li>
<li><code>0 <= col1 <= col2 < n</code></li>
<li>At most <code>5000</code> calls will be made to <code>sumRegion</code> and <code>update</code>.</li>
</ul>
|
Design; Binary Indexed Tree; Segment Tree; Array; Matrix
|
C++
|
class BinaryIndexedTree {
public:
int n;
vector<int> c;
BinaryIndexedTree(int _n)
: n(_n)
, c(_n + 1) {}
void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += lowbit(x);
}
}
int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
}
return s;
}
int lowbit(int x) {
return x & -x;
}
};
class NumMatrix {
public:
vector<BinaryIndexedTree*> trees;
NumMatrix(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
trees.resize(m);
for (int i = 0; i < m; ++i) {
BinaryIndexedTree* tree = new BinaryIndexedTree(n);
for (int j = 0; j < n; ++j) tree->update(j + 1, matrix[i][j]);
trees[i] = tree;
}
}
void update(int row, int col, int val) {
BinaryIndexedTree* tree = trees[row];
int prev = tree->query(col + 1) - tree->query(col);
tree->update(col + 1, val - prev);
}
int sumRegion(int row1, int col1, int row2, int col2) {
int s = 0;
for (int i = row1; i <= row2; ++i) {
BinaryIndexedTree* tree = trees[i];
s += tree->query(col2 + 1) - tree->query(col1);
}
return s;
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* obj->update(row,col,val);
* int param_2 = obj->sumRegion(row1,col1,row2,col2);
*/
|
308 |
Range Sum Query 2D - Mutable
|
Medium
|
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following types:</p>
<ol>
<li><strong>Update</strong> the value of a cell in <code>matrix</code>.</li>
<li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ol>
<p>Implement the NumMatrix class:</p>
<ul>
<li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li>
<li><code>void update(int row, int col, int val)</code> <strong>Updates</strong> the value of <code>matrix[row][col]</code> to be <code>val</code>.</li>
<li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0308.Range%20Sum%20Query%202D%20-%20Mutable/images/summut-grid.jpg" style="width: 500px; height: 222px;" />
<pre>
<strong>Input</strong>
["NumMatrix", "sumRegion", "update", "sumRegion"]
[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [3, 2, 2], [2, 1, 4, 3]]
<strong>Output</strong>
[null, 8, null, 10]
<strong>Explanation</strong>
NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e. sum of the left red rectangle)
numMatrix.update(3, 2, 2); // matrix changes from left image to right image
numMatrix.sumRegion(2, 1, 4, 3); // return 10 (i.e. sum of the right red rectangle)
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>-1000 <= matrix[i][j] <= 1000</code></li>
<li><code>0 <= row < m</code></li>
<li><code>0 <= col < n</code></li>
<li><code>-1000 <= val <= 1000</code></li>
<li><code>0 <= row1 <= row2 < m</code></li>
<li><code>0 <= col1 <= col2 < n</code></li>
<li>At most <code>5000</code> calls will be made to <code>sumRegion</code> and <code>update</code>.</li>
</ul>
|
Design; Binary Indexed Tree; Segment Tree; Array; Matrix
|
Go
|
type BinaryIndexedTree struct {
n int
c []int
}
func newBinaryIndexedTree(n int) *BinaryIndexedTree {
c := make([]int, n+1)
return &BinaryIndexedTree{n, c}
}
func (this *BinaryIndexedTree) lowbit(x int) int {
return x & -x
}
func (this *BinaryIndexedTree) update(x, delta int) {
for x <= this.n {
this.c[x] += delta
x += this.lowbit(x)
}
}
func (this *BinaryIndexedTree) query(x int) int {
s := 0
for x > 0 {
s += this.c[x]
x -= this.lowbit(x)
}
return s
}
type NumMatrix struct {
trees []*BinaryIndexedTree
}
func Constructor(matrix [][]int) NumMatrix {
n := len(matrix[0])
var trees []*BinaryIndexedTree
for _, row := range matrix {
tree := newBinaryIndexedTree(n)
for j, v := range row {
tree.update(j+1, v)
}
trees = append(trees, tree)
}
return NumMatrix{trees}
}
func (this *NumMatrix) Update(row int, col int, val int) {
tree := this.trees[row]
prev := tree.query(col+1) - tree.query(col)
tree.update(col+1, val-prev)
}
func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
s := 0
for i := row1; i <= row2; i++ {
tree := this.trees[i]
s += tree.query(col2+1) - tree.query(col1)
}
return s
}
/**
* Your NumMatrix object will be instantiated and called as such:
* obj := Constructor(matrix);
* obj.Update(row,col,val);
* param_2 := obj.SumRegion(row1,col1,row2,col2);
*/
|
308 |
Range Sum Query 2D - Mutable
|
Medium
|
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following types:</p>
<ol>
<li><strong>Update</strong> the value of a cell in <code>matrix</code>.</li>
<li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ol>
<p>Implement the NumMatrix class:</p>
<ul>
<li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li>
<li><code>void update(int row, int col, int val)</code> <strong>Updates</strong> the value of <code>matrix[row][col]</code> to be <code>val</code>.</li>
<li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0308.Range%20Sum%20Query%202D%20-%20Mutable/images/summut-grid.jpg" style="width: 500px; height: 222px;" />
<pre>
<strong>Input</strong>
["NumMatrix", "sumRegion", "update", "sumRegion"]
[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [3, 2, 2], [2, 1, 4, 3]]
<strong>Output</strong>
[null, 8, null, 10]
<strong>Explanation</strong>
NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e. sum of the left red rectangle)
numMatrix.update(3, 2, 2); // matrix changes from left image to right image
numMatrix.sumRegion(2, 1, 4, 3); // return 10 (i.e. sum of the right red rectangle)
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>-1000 <= matrix[i][j] <= 1000</code></li>
<li><code>0 <= row < m</code></li>
<li><code>0 <= col < n</code></li>
<li><code>-1000 <= val <= 1000</code></li>
<li><code>0 <= row1 <= row2 < m</code></li>
<li><code>0 <= col1 <= col2 < n</code></li>
<li>At most <code>5000</code> calls will be made to <code>sumRegion</code> and <code>update</code>.</li>
</ul>
|
Design; Binary Indexed Tree; Segment Tree; Array; Matrix
|
Java
|
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += lowbit(x);
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
}
return s;
}
public static int lowbit(int x) {
return x & -x;
}
}
class NumMatrix {
private BinaryIndexedTree[] trees;
public NumMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
trees = new BinaryIndexedTree[m];
for (int i = 0; i < m; ++i) {
BinaryIndexedTree tree = new BinaryIndexedTree(n);
for (int j = 0; j < n; ++j) {
tree.update(j + 1, matrix[i][j]);
}
trees[i] = tree;
}
}
public void update(int row, int col, int val) {
BinaryIndexedTree tree = trees[row];
int prev = tree.query(col + 1) - tree.query(col);
tree.update(col + 1, val - prev);
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int s = 0;
for (int i = row1; i <= row2; ++i) {
BinaryIndexedTree tree = trees[i];
s += tree.query(col2 + 1) - tree.query(col1);
}
return s;
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* obj.update(row,col,val);
* int param_2 = obj.sumRegion(row1,col1,row2,col2);
*/
|
308 |
Range Sum Query 2D - Mutable
|
Medium
|
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following types:</p>
<ol>
<li><strong>Update</strong> the value of a cell in <code>matrix</code>.</li>
<li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ol>
<p>Implement the NumMatrix class:</p>
<ul>
<li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li>
<li><code>void update(int row, int col, int val)</code> <strong>Updates</strong> the value of <code>matrix[row][col]</code> to be <code>val</code>.</li>
<li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0308.Range%20Sum%20Query%202D%20-%20Mutable/images/summut-grid.jpg" style="width: 500px; height: 222px;" />
<pre>
<strong>Input</strong>
["NumMatrix", "sumRegion", "update", "sumRegion"]
[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [3, 2, 2], [2, 1, 4, 3]]
<strong>Output</strong>
[null, 8, null, 10]
<strong>Explanation</strong>
NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e. sum of the left red rectangle)
numMatrix.update(3, 2, 2); // matrix changes from left image to right image
numMatrix.sumRegion(2, 1, 4, 3); // return 10 (i.e. sum of the right red rectangle)
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>-1000 <= matrix[i][j] <= 1000</code></li>
<li><code>0 <= row < m</code></li>
<li><code>0 <= col < n</code></li>
<li><code>-1000 <= val <= 1000</code></li>
<li><code>0 <= row1 <= row2 < m</code></li>
<li><code>0 <= col1 <= col2 < n</code></li>
<li>At most <code>5000</code> calls will be made to <code>sumRegion</code> and <code>update</code>.</li>
</ul>
|
Design; Binary Indexed Tree; Segment Tree; Array; Matrix
|
Python
|
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
@staticmethod
def lowbit(x):
return x & -x
def update(self, x, delta):
while x <= self.n:
self.c[x] += delta
x += BinaryIndexedTree.lowbit(x)
def query(self, x):
s = 0
while x > 0:
s += self.c[x]
x -= BinaryIndexedTree.lowbit(x)
return s
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
self.trees = []
n = len(matrix[0])
for row in matrix:
tree = BinaryIndexedTree(n)
for j, v in enumerate(row):
tree.update(j + 1, v)
self.trees.append(tree)
def update(self, row: int, col: int, val: int) -> None:
tree = self.trees[row]
prev = tree.query(col + 1) - tree.query(col)
tree.update(col + 1, val - prev)
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
return sum(
tree.query(col2 + 1) - tree.query(col1)
for tree in self.trees[row1 : row2 + 1]
)
# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# obj.update(row,col,val)
# param_2 = obj.sumRegion(row1,col1,row2,col2)
|
309 |
Best Time to Buy and Sell Stock with Cooldown
|
Medium
|
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p>
<p>Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:</p>
<ul>
<li>After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).</li>
</ul>
<p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,0,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> transactions = [buy, sell, cooldown, buy, sell]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= prices.length <= 5000</code></li>
<li><code>0 <= prices[i] <= 1000</code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int f[n][2];
memset(f, -1, sizeof(f));
function<int(int, int)> dfs = [&](int i, int j) {
if (i >= n) {
return 0;
}
if (f[i][j] != -1) {
return f[i][j];
}
int ans = dfs(i + 1, j);
if (j) {
ans = max(ans, prices[i] + dfs(i + 2, 0));
} else {
ans = max(ans, -prices[i] + dfs(i + 1, 1));
}
return f[i][j] = ans;
};
return dfs(0, 0);
}
};
|
309 |
Best Time to Buy and Sell Stock with Cooldown
|
Medium
|
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p>
<p>Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:</p>
<ul>
<li>After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).</li>
</ul>
<p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,0,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> transactions = [buy, sell, cooldown, buy, sell]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= prices.length <= 5000</code></li>
<li><code>0 <= prices[i] <= 1000</code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func maxProfit(prices []int) int {
n := len(prices)
f := make([][2]int, n)
for i := range f {
f[i] = [2]int{-1, -1}
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
if i >= n {
return 0
}
if f[i][j] != -1 {
return f[i][j]
}
ans := dfs(i+1, j)
if j > 0 {
ans = max(ans, prices[i]+dfs(i+2, 0))
} else {
ans = max(ans, -prices[i]+dfs(i+1, 1))
}
f[i][j] = ans
return ans
}
return dfs(0, 0)
}
|
309 |
Best Time to Buy and Sell Stock with Cooldown
|
Medium
|
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p>
<p>Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:</p>
<ul>
<li>After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).</li>
</ul>
<p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,0,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> transactions = [buy, sell, cooldown, buy, sell]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= prices.length <= 5000</code></li>
<li><code>0 <= prices[i] <= 1000</code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
private int[] prices;
private Integer[][] f;
public int maxProfit(int[] prices) {
this.prices = prices;
f = new Integer[prices.length][2];
return dfs(0, 0);
}
private int dfs(int i, int j) {
if (i >= prices.length) {
return 0;
}
if (f[i][j] != null) {
return f[i][j];
}
int ans = dfs(i + 1, j);
if (j > 0) {
ans = Math.max(ans, prices[i] + dfs(i + 2, 0));
} else {
ans = Math.max(ans, -prices[i] + dfs(i + 1, 1));
}
return f[i][j] = ans;
}
}
|
309 |
Best Time to Buy and Sell Stock with Cooldown
|
Medium
|
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p>
<p>Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:</p>
<ul>
<li>After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).</li>
</ul>
<p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,0,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> transactions = [buy, sell, cooldown, buy, sell]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= prices.length <= 5000</code></li>
<li><code>0 <= prices[i] <= 1000</code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def maxProfit(self, prices: List[int]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= len(prices):
return 0
ans = dfs(i + 1, j)
if j:
ans = max(ans, prices[i] + dfs(i + 2, 0))
else:
ans = max(ans, -prices[i] + dfs(i + 1, 1))
return ans
return dfs(0, 0)
|
309 |
Best Time to Buy and Sell Stock with Cooldown
|
Medium
|
<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p>
<p>Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:</p>
<ul>
<li>After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).</li>
</ul>
<p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,0,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> transactions = [buy, sell, cooldown, buy, sell]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1]
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= prices.length <= 5000</code></li>
<li><code>0 <= prices[i] <= 1000</code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function maxProfit(prices: number[]): number {
const n = prices.length;
const f: number[][] = Array.from({ length: n }, () => Array.from({ length: 2 }, () => -1));
const dfs = (i: number, j: number): number => {
if (i >= n) {
return 0;
}
if (f[i][j] !== -1) {
return f[i][j];
}
let ans = dfs(i + 1, j);
if (j) {
ans = Math.max(ans, prices[i] + dfs(i + 2, 0));
} else {
ans = Math.max(ans, -prices[i] + dfs(i + 1, 1));
}
return (f[i][j] = ans);
};
return dfs(0, 0);
}
|
310 |
Minimum Height Trees
|
Medium
|
<p>A tree is an undirected graph in which any two vertices are connected by <i>exactly</i> one path. In other words, any connected graph without simple cycles is a tree.</p>
<p>Given a tree of <code>n</code> nodes labelled from <code>0</code> to <code>n - 1</code>, and an array of <code>n - 1</code> <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between the two nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree, you can choose any node of the tree as the root. When you select a node <code>x</code> as the root, the result tree has height <code>h</code>. Among all possible rooted trees, those with minimum height (i.e. <code>min(h)</code>) are called <strong>minimum height trees</strong> (MHTs).</p>
<p>Return <em>a list of all <strong>MHTs'</strong> root labels</em>. You can return the answer in <strong>any order</strong>.</p>
<p>The <strong>height</strong> of a rooted tree is the number of edges on the longest downward path between the root and a leaf.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0310.Minimum%20Height%20Trees/images/e1.jpg" style="width: 800px; height: 213px;" />
<pre>
<strong>Input:</strong> n = 4, edges = [[1,0],[1,2],[1,3]]
<strong>Output:</strong> [1]
<strong>Explanation:</strong> As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0310.Minimum%20Height%20Trees/images/e2.jpg" style="width: 800px; height: 321px;" />
<pre>
<strong>Input:</strong> n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
<strong>Output:</strong> [3,4]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>All the pairs <code>(a<sub>i</sub>, b<sub>i</sub>)</code> are distinct.</li>
<li>The given input is <strong>guaranteed</strong> to be a tree and there will be <strong>no repeated</strong> edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Topological Sort
|
C++
|
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
if (n == 1) {
return {0};
}
vector<vector<int>> g(n);
vector<int> degree(n);
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
g[b].push_back(a);
++degree[a];
++degree[b];
}
queue<int> q;
for (int i = 0; i < n; ++i) {
if (degree[i] == 1) {
q.push(i);
}
}
vector<int> ans;
while (!q.empty()) {
ans.clear();
for (int i = q.size(); i > 0; --i) {
int a = q.front();
q.pop();
ans.push_back(a);
for (int b : g[a]) {
if (--degree[b] == 1) {
q.push(b);
}
}
}
}
return ans;
}
};
|
310 |
Minimum Height Trees
|
Medium
|
<p>A tree is an undirected graph in which any two vertices are connected by <i>exactly</i> one path. In other words, any connected graph without simple cycles is a tree.</p>
<p>Given a tree of <code>n</code> nodes labelled from <code>0</code> to <code>n - 1</code>, and an array of <code>n - 1</code> <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between the two nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree, you can choose any node of the tree as the root. When you select a node <code>x</code> as the root, the result tree has height <code>h</code>. Among all possible rooted trees, those with minimum height (i.e. <code>min(h)</code>) are called <strong>minimum height trees</strong> (MHTs).</p>
<p>Return <em>a list of all <strong>MHTs'</strong> root labels</em>. You can return the answer in <strong>any order</strong>.</p>
<p>The <strong>height</strong> of a rooted tree is the number of edges on the longest downward path between the root and a leaf.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0310.Minimum%20Height%20Trees/images/e1.jpg" style="width: 800px; height: 213px;" />
<pre>
<strong>Input:</strong> n = 4, edges = [[1,0],[1,2],[1,3]]
<strong>Output:</strong> [1]
<strong>Explanation:</strong> As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0310.Minimum%20Height%20Trees/images/e2.jpg" style="width: 800px; height: 321px;" />
<pre>
<strong>Input:</strong> n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
<strong>Output:</strong> [3,4]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>All the pairs <code>(a<sub>i</sub>, b<sub>i</sub>)</code> are distinct.</li>
<li>The given input is <strong>guaranteed</strong> to be a tree and there will be <strong>no repeated</strong> edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Topological Sort
|
Go
|
func findMinHeightTrees(n int, edges [][]int) (ans []int) {
if n == 1 {
return []int{0}
}
g := make([][]int, n)
degree := make([]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
degree[a]++
degree[b]++
}
q := []int{}
for i, d := range degree {
if d == 1 {
q = append(q, i)
}
}
for len(q) > 0 {
ans = []int{}
for i := len(q); i > 0; i-- {
a := q[0]
q = q[1:]
ans = append(ans, a)
for _, b := range g[a] {
degree[b]--
if degree[b] == 1 {
q = append(q, b)
}
}
}
}
return
}
|
310 |
Minimum Height Trees
|
Medium
|
<p>A tree is an undirected graph in which any two vertices are connected by <i>exactly</i> one path. In other words, any connected graph without simple cycles is a tree.</p>
<p>Given a tree of <code>n</code> nodes labelled from <code>0</code> to <code>n - 1</code>, and an array of <code>n - 1</code> <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between the two nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree, you can choose any node of the tree as the root. When you select a node <code>x</code> as the root, the result tree has height <code>h</code>. Among all possible rooted trees, those with minimum height (i.e. <code>min(h)</code>) are called <strong>minimum height trees</strong> (MHTs).</p>
<p>Return <em>a list of all <strong>MHTs'</strong> root labels</em>. You can return the answer in <strong>any order</strong>.</p>
<p>The <strong>height</strong> of a rooted tree is the number of edges on the longest downward path between the root and a leaf.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0310.Minimum%20Height%20Trees/images/e1.jpg" style="width: 800px; height: 213px;" />
<pre>
<strong>Input:</strong> n = 4, edges = [[1,0],[1,2],[1,3]]
<strong>Output:</strong> [1]
<strong>Explanation:</strong> As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0310.Minimum%20Height%20Trees/images/e2.jpg" style="width: 800px; height: 321px;" />
<pre>
<strong>Input:</strong> n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
<strong>Output:</strong> [3,4]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>All the pairs <code>(a<sub>i</sub>, b<sub>i</sub>)</code> are distinct.</li>
<li>The given input is <strong>guaranteed</strong> to be a tree and there will be <strong>no repeated</strong> edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Topological Sort
|
Java
|
class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
if (n == 1) {
return List.of(0);
}
List<Integer>[] g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
int[] degree = new int[n];
for (int[] e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
++degree[a];
++degree[b];
}
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; ++i) {
if (degree[i] == 1) {
q.offer(i);
}
}
List<Integer> ans = new ArrayList<>();
while (!q.isEmpty()) {
ans.clear();
for (int i = q.size(); i > 0; --i) {
int a = q.poll();
ans.add(a);
for (int b : g[a]) {
if (--degree[b] == 1) {
q.offer(b);
}
}
}
}
return ans;
}
}
|
310 |
Minimum Height Trees
|
Medium
|
<p>A tree is an undirected graph in which any two vertices are connected by <i>exactly</i> one path. In other words, any connected graph without simple cycles is a tree.</p>
<p>Given a tree of <code>n</code> nodes labelled from <code>0</code> to <code>n - 1</code>, and an array of <code>n - 1</code> <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between the two nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree, you can choose any node of the tree as the root. When you select a node <code>x</code> as the root, the result tree has height <code>h</code>. Among all possible rooted trees, those with minimum height (i.e. <code>min(h)</code>) are called <strong>minimum height trees</strong> (MHTs).</p>
<p>Return <em>a list of all <strong>MHTs'</strong> root labels</em>. You can return the answer in <strong>any order</strong>.</p>
<p>The <strong>height</strong> of a rooted tree is the number of edges on the longest downward path between the root and a leaf.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0310.Minimum%20Height%20Trees/images/e1.jpg" style="width: 800px; height: 213px;" />
<pre>
<strong>Input:</strong> n = 4, edges = [[1,0],[1,2],[1,3]]
<strong>Output:</strong> [1]
<strong>Explanation:</strong> As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0310.Minimum%20Height%20Trees/images/e2.jpg" style="width: 800px; height: 321px;" />
<pre>
<strong>Input:</strong> n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
<strong>Output:</strong> [3,4]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>All the pairs <code>(a<sub>i</sub>, b<sub>i</sub>)</code> are distinct.</li>
<li>The given input is <strong>guaranteed</strong> to be a tree and there will be <strong>no repeated</strong> edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Topological Sort
|
Python
|
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1:
return [0]
g = [[] for _ in range(n)]
degree = [0] * n
for a, b in edges:
g[a].append(b)
g[b].append(a)
degree[a] += 1
degree[b] += 1
q = deque(i for i in range(n) if degree[i] == 1)
ans = []
while q:
ans.clear()
for _ in range(len(q)):
a = q.popleft()
ans.append(a)
for b in g[a]:
degree[b] -= 1
if degree[b] == 1:
q.append(b)
return ans
|
310 |
Minimum Height Trees
|
Medium
|
<p>A tree is an undirected graph in which any two vertices are connected by <i>exactly</i> one path. In other words, any connected graph without simple cycles is a tree.</p>
<p>Given a tree of <code>n</code> nodes labelled from <code>0</code> to <code>n - 1</code>, and an array of <code>n - 1</code> <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between the two nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree, you can choose any node of the tree as the root. When you select a node <code>x</code> as the root, the result tree has height <code>h</code>. Among all possible rooted trees, those with minimum height (i.e. <code>min(h)</code>) are called <strong>minimum height trees</strong> (MHTs).</p>
<p>Return <em>a list of all <strong>MHTs'</strong> root labels</em>. You can return the answer in <strong>any order</strong>.</p>
<p>The <strong>height</strong> of a rooted tree is the number of edges on the longest downward path between the root and a leaf.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0310.Minimum%20Height%20Trees/images/e1.jpg" style="width: 800px; height: 213px;" />
<pre>
<strong>Input:</strong> n = 4, edges = [[1,0],[1,2],[1,3]]
<strong>Output:</strong> [1]
<strong>Explanation:</strong> As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0310.Minimum%20Height%20Trees/images/e2.jpg" style="width: 800px; height: 321px;" />
<pre>
<strong>Input:</strong> n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
<strong>Output:</strong> [3,4]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>All the pairs <code>(a<sub>i</sub>, b<sub>i</sub>)</code> are distinct.</li>
<li>The given input is <strong>guaranteed</strong> to be a tree and there will be <strong>no repeated</strong> edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Topological Sort
|
TypeScript
|
function findMinHeightTrees(n: number, edges: number[][]): number[] {
if (n === 1) {
return [0];
}
const g: number[][] = Array.from({ length: n }, () => []);
const degree: number[] = Array(n).fill(0);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
++degree[a];
++degree[b];
}
const q: number[] = [];
for (let i = 0; i < n; ++i) {
if (degree[i] === 1) {
q.push(i);
}
}
const ans: number[] = [];
while (q.length > 0) {
ans.length = 0;
const t: number[] = [];
for (const a of q) {
ans.push(a);
for (const b of g[a]) {
if (--degree[b] === 1) {
t.push(b);
}
}
}
q.splice(0, q.length, ...t);
}
return ans;
}
|
311 |
Sparse Matrix Multiplication
|
Medium
|
<p>Given two <a href="https://en.wikipedia.org/wiki/Sparse_matrix" target="_blank">sparse matrices</a> <code>mat1</code> of size <code>m x k</code> and <code>mat2</code> of size <code>k x n</code>, return the result of <code>mat1 x mat2</code>. You may assume that multiplication is always possible.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0311.Sparse%20Matrix%20Multiplication/images/mult-grid.jpg" style="width: 500px; height: 142px;" />
<pre>
<strong>Input:</strong> mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> [[7,0,0],[-7,0,3]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat1 = [[0]], mat2 = [[0]]
<strong>Output:</strong> [[0]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat1.length</code></li>
<li><code>k == mat1[i].length == mat2.length</code></li>
<li><code>n == mat2[i].length</code></li>
<li><code>1 <= m, n, k <= 100</code></li>
<li><code>-100 <= mat1[i][j], mat2[i][j] <= 100</code></li>
</ul>
|
Array; Hash Table; Matrix
|
C++
|
class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2) {
int m = mat1.size(), n = mat2[0].size();
vector<vector<int>> ans(m, vector<int>(n));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
for (int k = 0; k < mat2.size(); ++k) {
ans[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
return ans;
}
};
|
311 |
Sparse Matrix Multiplication
|
Medium
|
<p>Given two <a href="https://en.wikipedia.org/wiki/Sparse_matrix" target="_blank">sparse matrices</a> <code>mat1</code> of size <code>m x k</code> and <code>mat2</code> of size <code>k x n</code>, return the result of <code>mat1 x mat2</code>. You may assume that multiplication is always possible.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0311.Sparse%20Matrix%20Multiplication/images/mult-grid.jpg" style="width: 500px; height: 142px;" />
<pre>
<strong>Input:</strong> mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> [[7,0,0],[-7,0,3]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat1 = [[0]], mat2 = [[0]]
<strong>Output:</strong> [[0]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat1.length</code></li>
<li><code>k == mat1[i].length == mat2.length</code></li>
<li><code>n == mat2[i].length</code></li>
<li><code>1 <= m, n, k <= 100</code></li>
<li><code>-100 <= mat1[i][j], mat2[i][j] <= 100</code></li>
</ul>
|
Array; Hash Table; Matrix
|
Go
|
func multiply(mat1 [][]int, mat2 [][]int) [][]int {
m, n := len(mat1), len(mat2[0])
ans := make([][]int, m)
for i := range ans {
ans[i] = make([]int, n)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
for k := 0; k < len(mat2); k++ {
ans[i][j] += mat1[i][k] * mat2[k][j]
}
}
}
return ans
}
|
311 |
Sparse Matrix Multiplication
|
Medium
|
<p>Given two <a href="https://en.wikipedia.org/wiki/Sparse_matrix" target="_blank">sparse matrices</a> <code>mat1</code> of size <code>m x k</code> and <code>mat2</code> of size <code>k x n</code>, return the result of <code>mat1 x mat2</code>. You may assume that multiplication is always possible.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0311.Sparse%20Matrix%20Multiplication/images/mult-grid.jpg" style="width: 500px; height: 142px;" />
<pre>
<strong>Input:</strong> mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> [[7,0,0],[-7,0,3]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat1 = [[0]], mat2 = [[0]]
<strong>Output:</strong> [[0]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat1.length</code></li>
<li><code>k == mat1[i].length == mat2.length</code></li>
<li><code>n == mat2[i].length</code></li>
<li><code>1 <= m, n, k <= 100</code></li>
<li><code>-100 <= mat1[i][j], mat2[i][j] <= 100</code></li>
</ul>
|
Array; Hash Table; Matrix
|
Java
|
class Solution {
public int[][] multiply(int[][] mat1, int[][] mat2) {
int m = mat1.length, n = mat2[0].length;
int[][] ans = new int[m][n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
for (int k = 0; k < mat2.length; ++k) {
ans[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
return ans;
}
}
|
311 |
Sparse Matrix Multiplication
|
Medium
|
<p>Given two <a href="https://en.wikipedia.org/wiki/Sparse_matrix" target="_blank">sparse matrices</a> <code>mat1</code> of size <code>m x k</code> and <code>mat2</code> of size <code>k x n</code>, return the result of <code>mat1 x mat2</code>. You may assume that multiplication is always possible.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0311.Sparse%20Matrix%20Multiplication/images/mult-grid.jpg" style="width: 500px; height: 142px;" />
<pre>
<strong>Input:</strong> mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> [[7,0,0],[-7,0,3]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat1 = [[0]], mat2 = [[0]]
<strong>Output:</strong> [[0]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat1.length</code></li>
<li><code>k == mat1[i].length == mat2.length</code></li>
<li><code>n == mat2[i].length</code></li>
<li><code>1 <= m, n, k <= 100</code></li>
<li><code>-100 <= mat1[i][j], mat2[i][j] <= 100</code></li>
</ul>
|
Array; Hash Table; Matrix
|
Python
|
class Solution:
def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:
m, n = len(mat1), len(mat2[0])
ans = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
for k in range(len(mat2)):
ans[i][j] += mat1[i][k] * mat2[k][j]
return ans
|
311 |
Sparse Matrix Multiplication
|
Medium
|
<p>Given two <a href="https://en.wikipedia.org/wiki/Sparse_matrix" target="_blank">sparse matrices</a> <code>mat1</code> of size <code>m x k</code> and <code>mat2</code> of size <code>k x n</code>, return the result of <code>mat1 x mat2</code>. You may assume that multiplication is always possible.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0311.Sparse%20Matrix%20Multiplication/images/mult-grid.jpg" style="width: 500px; height: 142px;" />
<pre>
<strong>Input:</strong> mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> [[7,0,0],[-7,0,3]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat1 = [[0]], mat2 = [[0]]
<strong>Output:</strong> [[0]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat1.length</code></li>
<li><code>k == mat1[i].length == mat2.length</code></li>
<li><code>n == mat2[i].length</code></li>
<li><code>1 <= m, n, k <= 100</code></li>
<li><code>-100 <= mat1[i][j], mat2[i][j] <= 100</code></li>
</ul>
|
Array; Hash Table; Matrix
|
TypeScript
|
function multiply(mat1: number[][], mat2: number[][]): number[][] {
const [m, n] = [mat1.length, mat2[0].length];
const ans: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0));
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
for (let k = 0; k < mat2.length; ++k) {
ans[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
return ans;
}
|
312 |
Burst Balloons
|
Hard
|
<p>You are given <code>n</code> balloons, indexed from <code>0</code> to <code>n - 1</code>. Each balloon is painted with a number on it represented by an array <code>nums</code>. You are asked to burst all the balloons.</p>
<p>If you burst the <code>i<sup>th</sup></code> balloon, you will get <code>nums[i - 1] * nums[i] * nums[i + 1]</code> coins. If <code>i - 1</code> or <code>i + 1</code> goes out of bounds of the array, then treat it as if there is a balloon with a <code>1</code> painted on it.</p>
<p>Return <em>the maximum coins you can collect by bursting the balloons wisely</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,5,8]
<strong>Output:</strong> 167
<strong>Explanation:</strong>
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5]
<strong>Output:</strong> 10
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 300</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size();
vector<int> arr(n + 2, 1);
for (int i = 0; i < n; ++i) {
arr[i + 1] = nums[i];
}
vector<vector<int>> f(n + 2, vector<int>(n + 2, 0));
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 2; j <= n + 1; ++j) {
for (int k = i + 1; k < j; ++k) {
f[i][j] = max(f[i][j], f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j]);
}
}
}
return f[0][n + 1];
}
};
|
312 |
Burst Balloons
|
Hard
|
<p>You are given <code>n</code> balloons, indexed from <code>0</code> to <code>n - 1</code>. Each balloon is painted with a number on it represented by an array <code>nums</code>. You are asked to burst all the balloons.</p>
<p>If you burst the <code>i<sup>th</sup></code> balloon, you will get <code>nums[i - 1] * nums[i] * nums[i + 1]</code> coins. If <code>i - 1</code> or <code>i + 1</code> goes out of bounds of the array, then treat it as if there is a balloon with a <code>1</code> painted on it.</p>
<p>Return <em>the maximum coins you can collect by bursting the balloons wisely</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,5,8]
<strong>Output:</strong> 167
<strong>Explanation:</strong>
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5]
<strong>Output:</strong> 10
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 300</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func maxCoins(nums []int) int {
n := len(nums)
arr := make([]int, n+2)
arr[0] = 1
arr[n+1] = 1
copy(arr[1:], nums)
f := make([][]int, n+2)
for i := range f {
f[i] = make([]int, n+2)
}
for i := n - 1; i >= 0; i-- {
for j := i + 2; j <= n+1; j++ {
for k := i + 1; k < j; k++ {
f[i][j] = max(f[i][j], f[i][k] + f[k][j] + arr[i]*arr[k]*arr[j])
}
}
}
return f[0][n+1]
}
|
312 |
Burst Balloons
|
Hard
|
<p>You are given <code>n</code> balloons, indexed from <code>0</code> to <code>n - 1</code>. Each balloon is painted with a number on it represented by an array <code>nums</code>. You are asked to burst all the balloons.</p>
<p>If you burst the <code>i<sup>th</sup></code> balloon, you will get <code>nums[i - 1] * nums[i] * nums[i + 1]</code> coins. If <code>i - 1</code> or <code>i + 1</code> goes out of bounds of the array, then treat it as if there is a balloon with a <code>1</code> painted on it.</p>
<p>Return <em>the maximum coins you can collect by bursting the balloons wisely</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,5,8]
<strong>Output:</strong> 167
<strong>Explanation:</strong>
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5]
<strong>Output:</strong> 10
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 300</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public int maxCoins(int[] nums) {
int n = nums.length;
int[] arr = new int[n + 2];
arr[0] = 1;
arr[n + 1] = 1;
System.arraycopy(nums, 0, arr, 1, n);
int[][] f = new int[n + 2][n + 2];
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 2; j <= n + 1; j++) {
for (int k = i + 1; k < j; k++) {
f[i][j] = Math.max(f[i][j], f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j]);
}
}
}
return f[0][n + 1];
}
}
|
312 |
Burst Balloons
|
Hard
|
<p>You are given <code>n</code> balloons, indexed from <code>0</code> to <code>n - 1</code>. Each balloon is painted with a number on it represented by an array <code>nums</code>. You are asked to burst all the balloons.</p>
<p>If you burst the <code>i<sup>th</sup></code> balloon, you will get <code>nums[i - 1] * nums[i] * nums[i + 1]</code> coins. If <code>i - 1</code> or <code>i + 1</code> goes out of bounds of the array, then treat it as if there is a balloon with a <code>1</code> painted on it.</p>
<p>Return <em>the maximum coins you can collect by bursting the balloons wisely</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,5,8]
<strong>Output:</strong> 167
<strong>Explanation:</strong>
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5]
<strong>Output:</strong> 10
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 300</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def maxCoins(self, nums: List[int]) -> int:
n = len(nums)
arr = [1] + nums + [1]
f = [[0] * (n + 2) for _ in range(n + 2)]
for i in range(n - 1, -1, -1):
for j in range(i + 2, n + 2):
for k in range(i + 1, j):
f[i][j] = max(f[i][j], f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j])
return f[0][-1]
|
312 |
Burst Balloons
|
Hard
|
<p>You are given <code>n</code> balloons, indexed from <code>0</code> to <code>n - 1</code>. Each balloon is painted with a number on it represented by an array <code>nums</code>. You are asked to burst all the balloons.</p>
<p>If you burst the <code>i<sup>th</sup></code> balloon, you will get <code>nums[i - 1] * nums[i] * nums[i + 1]</code> coins. If <code>i - 1</code> or <code>i + 1</code> goes out of bounds of the array, then treat it as if there is a balloon with a <code>1</code> painted on it.</p>
<p>Return <em>the maximum coins you can collect by bursting the balloons wisely</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,5,8]
<strong>Output:</strong> 167
<strong>Explanation:</strong>
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5]
<strong>Output:</strong> 10
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 300</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
Rust
|
impl Solution {
pub fn max_coins(nums: Vec<i32>) -> i32 {
let n = nums.len();
let mut arr = vec![1; n + 2];
for i in 0..n {
arr[i + 1] = nums[i];
}
let mut f = vec![vec![0; n + 2]; n + 2];
for i in (0..n).rev() {
for j in i + 2..n + 2 {
for k in i + 1..j {
f[i][j] = f[i][j].max(f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j]);
}
}
}
f[0][n + 1]
}
}
|
312 |
Burst Balloons
|
Hard
|
<p>You are given <code>n</code> balloons, indexed from <code>0</code> to <code>n - 1</code>. Each balloon is painted with a number on it represented by an array <code>nums</code>. You are asked to burst all the balloons.</p>
<p>If you burst the <code>i<sup>th</sup></code> balloon, you will get <code>nums[i - 1] * nums[i] * nums[i + 1]</code> coins. If <code>i - 1</code> or <code>i + 1</code> goes out of bounds of the array, then treat it as if there is a balloon with a <code>1</code> painted on it.</p>
<p>Return <em>the maximum coins you can collect by bursting the balloons wisely</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,5,8]
<strong>Output:</strong> 167
<strong>Explanation:</strong>
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5]
<strong>Output:</strong> 10
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 300</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function maxCoins(nums: number[]): number {
const n = nums.length;
const arr = Array(n + 2).fill(1);
for (let i = 0; i < n; i++) {
arr[i + 1] = nums[i];
}
const f: number[][] = Array.from({ length: n + 2 }, () => Array(n + 2).fill(0));
for (let i = n - 1; i >= 0; i--) {
for (let j = i + 2; j <= n + 1; j++) {
for (let k = i + 1; k < j; k++) {
f[i][j] = Math.max(f[i][j], f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j]);
}
}
}
return f[0][n + 1];
}
|
313 |
Super Ugly Number
|
Medium
|
<p>A <strong>super ugly number</strong> is a positive integer whose prime factors are in the array <code>primes</code>.</p>
<p>Given an integer <code>n</code> and an array of integers <code>primes</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>super ugly number</strong></em>.</p>
<p>The <code>n<sup>th</sup></code> <strong>super ugly number</strong> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> signed integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 12, primes = [2,7,13,19]
<strong>Output:</strong> 32
<strong>Explanation:</strong> [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1, primes = [2,3,5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= primes.length <= 100</code></li>
<li><code>2 <= primes[i] <= 1000</code></li>
<li><code>primes[i]</code> is <strong>guaranteed</strong> to be a prime number.</li>
<li>All the values of <code>primes</code> are <strong>unique</strong> and sorted in <strong>ascending order</strong>.</li>
</ul>
|
Array; Math; Dynamic Programming
|
C++
|
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
priority_queue<int, vector<int>, greater<int>> q;
q.push(1);
int x = 0;
while (n--) {
x = q.top();
q.pop();
for (int& k : primes) {
if (x <= INT_MAX / k) {
q.push(k * x);
}
if (x % k == 0) {
break;
}
}
}
return x;
}
};
|
313 |
Super Ugly Number
|
Medium
|
<p>A <strong>super ugly number</strong> is a positive integer whose prime factors are in the array <code>primes</code>.</p>
<p>Given an integer <code>n</code> and an array of integers <code>primes</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>super ugly number</strong></em>.</p>
<p>The <code>n<sup>th</sup></code> <strong>super ugly number</strong> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> signed integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 12, primes = [2,7,13,19]
<strong>Output:</strong> 32
<strong>Explanation:</strong> [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1, primes = [2,3,5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= primes.length <= 100</code></li>
<li><code>2 <= primes[i] <= 1000</code></li>
<li><code>primes[i]</code> is <strong>guaranteed</strong> to be a prime number.</li>
<li>All the values of <code>primes</code> are <strong>unique</strong> and sorted in <strong>ascending order</strong>.</li>
</ul>
|
Array; Math; Dynamic Programming
|
Go
|
func nthSuperUglyNumber(n int, primes []int) (x int) {
q := hp{[]int{1}}
for n > 0 {
n--
x = heap.Pop(&q).(int)
for _, k := range primes {
if x <= math.MaxInt32/k {
heap.Push(&q, k*x)
}
if x%k == 0 {
break
}
}
}
return
}
type hp struct{ sort.IntSlice }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
|
313 |
Super Ugly Number
|
Medium
|
<p>A <strong>super ugly number</strong> is a positive integer whose prime factors are in the array <code>primes</code>.</p>
<p>Given an integer <code>n</code> and an array of integers <code>primes</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>super ugly number</strong></em>.</p>
<p>The <code>n<sup>th</sup></code> <strong>super ugly number</strong> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> signed integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 12, primes = [2,7,13,19]
<strong>Output:</strong> 32
<strong>Explanation:</strong> [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1, primes = [2,3,5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= primes.length <= 100</code></li>
<li><code>2 <= primes[i] <= 1000</code></li>
<li><code>primes[i]</code> is <strong>guaranteed</strong> to be a prime number.</li>
<li>All the values of <code>primes</code> are <strong>unique</strong> and sorted in <strong>ascending order</strong>.</li>
</ul>
|
Array; Math; Dynamic Programming
|
Java
|
class Solution {
public int nthSuperUglyNumber(int n, int[] primes) {
PriorityQueue<Integer> q = new PriorityQueue<>();
q.offer(1);
int x = 0;
while (n-- > 0) {
x = q.poll();
while (!q.isEmpty() && q.peek() == x) {
q.poll();
}
for (int k : primes) {
if (k <= Integer.MAX_VALUE / x) {
q.offer(k * x);
}
if (x % k == 0) {
break;
}
}
}
return x;
}
}
|
313 |
Super Ugly Number
|
Medium
|
<p>A <strong>super ugly number</strong> is a positive integer whose prime factors are in the array <code>primes</code>.</p>
<p>Given an integer <code>n</code> and an array of integers <code>primes</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>super ugly number</strong></em>.</p>
<p>The <code>n<sup>th</sup></code> <strong>super ugly number</strong> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> signed integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 12, primes = [2,7,13,19]
<strong>Output:</strong> 32
<strong>Explanation:</strong> [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1, primes = [2,3,5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= primes.length <= 100</code></li>
<li><code>2 <= primes[i] <= 1000</code></li>
<li><code>primes[i]</code> is <strong>guaranteed</strong> to be a prime number.</li>
<li>All the values of <code>primes</code> are <strong>unique</strong> and sorted in <strong>ascending order</strong>.</li>
</ul>
|
Array; Math; Dynamic Programming
|
Python
|
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
q = [1]
x = 0
mx = (1 << 31) - 1
for _ in range(n):
x = heappop(q)
for k in primes:
if x <= mx // k:
heappush(q, k * x)
if x % k == 0:
break
return x
|
314 |
Binary Tree Vertical Order Traversal
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <em><strong>the vertical order traversal</strong> of its nodes' values</em>. (i.e., from top to bottom, column by column).</p>
<p>If two nodes are in the same row and column, the order should be from <strong>left to right</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image1.png" style="width: 400px; height: 273px;" />
<pre>
<strong>Input:</strong> root = [3,9,20,null,null,15,7]
<strong>Output:</strong> [[9],[3,15],[20],[7]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image3.png" style="width: 450px; height: 285px;" />
<pre>
<strong>Input:</strong> root = [3,9,8,4,0,1,7]
<strong>Output:</strong> [[4],[9],[3,0,1],[8],[7]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image2.png" style="width: 350px; height: 342px;" />
<pre>
<strong>Input:</strong> root = [1,2,3,4,10,9,11,null,5,null,null,null,null,null,null,null,6]
<strong>Output:</strong> [[4],[2,5],[1,10,9,6],[3],[11]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search; Hash Table; Binary Tree; Sorting
|
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) {}
* };
*/
using pii = pair<int, int>;
class Solution {
public:
map<int, vector<pii>> d;
vector<vector<int>> verticalOrder(TreeNode* root) {
dfs(root, 0, 0);
vector<vector<int>> ans;
for (auto& [_, v] : d) {
sort(v.begin(), v.end(), [&](pii& a, pii& b) {
return a.first < b.first;
});
vector<int> t;
for (auto& x : v) {
t.push_back(x.second);
}
ans.push_back(t);
}
return ans;
}
void dfs(TreeNode* root, int depth, int offset) {
if (!root) return;
d[offset].push_back({depth, root->val});
dfs(root->left, depth + 1, offset - 1);
dfs(root->right, depth + 1, offset + 1);
}
};
|
314 |
Binary Tree Vertical Order Traversal
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <em><strong>the vertical order traversal</strong> of its nodes' values</em>. (i.e., from top to bottom, column by column).</p>
<p>If two nodes are in the same row and column, the order should be from <strong>left to right</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image1.png" style="width: 400px; height: 273px;" />
<pre>
<strong>Input:</strong> root = [3,9,20,null,null,15,7]
<strong>Output:</strong> [[9],[3,15],[20],[7]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image3.png" style="width: 450px; height: 285px;" />
<pre>
<strong>Input:</strong> root = [3,9,8,4,0,1,7]
<strong>Output:</strong> [[4],[9],[3,0,1],[8],[7]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image2.png" style="width: 350px; height: 342px;" />
<pre>
<strong>Input:</strong> root = [1,2,3,4,10,9,11,null,5,null,null,null,null,null,null,null,6]
<strong>Output:</strong> [[4],[2,5],[1,10,9,6],[3],[11]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search; Hash Table; Binary Tree; Sorting
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func verticalOrder(root *TreeNode) [][]int {
d := map[int][][]int{}
var dfs func(*TreeNode, int, int)
dfs = func(root *TreeNode, depth, offset int) {
if root == nil {
return
}
d[offset] = append(d[offset], []int{depth, root.Val})
dfs(root.Left, depth+1, offset-1)
dfs(root.Right, depth+1, offset+1)
}
dfs(root, 0, 0)
idx := []int{}
for i := range d {
idx = append(idx, i)
}
sort.Ints(idx)
ans := [][]int{}
for _, i := range idx {
v := d[i]
sort.SliceStable(v, func(i, j int) bool { return v[i][0] < v[j][0] })
t := []int{}
for _, x := range v {
t = append(t, x[1])
}
ans = append(ans, t)
}
return ans
}
|
314 |
Binary Tree Vertical Order Traversal
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <em><strong>the vertical order traversal</strong> of its nodes' values</em>. (i.e., from top to bottom, column by column).</p>
<p>If two nodes are in the same row and column, the order should be from <strong>left to right</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image1.png" style="width: 400px; height: 273px;" />
<pre>
<strong>Input:</strong> root = [3,9,20,null,null,15,7]
<strong>Output:</strong> [[9],[3,15],[20],[7]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image3.png" style="width: 450px; height: 285px;" />
<pre>
<strong>Input:</strong> root = [3,9,8,4,0,1,7]
<strong>Output:</strong> [[4],[9],[3,0,1],[8],[7]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image2.png" style="width: 350px; height: 342px;" />
<pre>
<strong>Input:</strong> root = [1,2,3,4,10,9,11,null,5,null,null,null,null,null,null,null,6]
<strong>Output:</strong> [[4],[2,5],[1,10,9,6],[3],[11]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search; Hash Table; Binary Tree; Sorting
|
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 TreeMap<Integer, List<int[]>> d = new TreeMap<>();
public List<List<Integer>> verticalOrder(TreeNode root) {
dfs(root, 0, 0);
List<List<Integer>> ans = new ArrayList<>();
for (var v : d.values()) {
Collections.sort(v, (a, b) -> a[0] - b[0]);
List<Integer> t = new ArrayList<>();
for (var e : v) {
t.add(e[1]);
}
ans.add(t);
}
return ans;
}
private void dfs(TreeNode root, int depth, int offset) {
if (root == null) {
return;
}
d.computeIfAbsent(offset, k -> new ArrayList<>()).add(new int[] {depth, root.val});
dfs(root.left, depth + 1, offset - 1);
dfs(root.right, depth + 1, offset + 1);
}
}
|
314 |
Binary Tree Vertical Order Traversal
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <em><strong>the vertical order traversal</strong> of its nodes' values</em>. (i.e., from top to bottom, column by column).</p>
<p>If two nodes are in the same row and column, the order should be from <strong>left to right</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image1.png" style="width: 400px; height: 273px;" />
<pre>
<strong>Input:</strong> root = [3,9,20,null,null,15,7]
<strong>Output:</strong> [[9],[3,15],[20],[7]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image3.png" style="width: 450px; height: 285px;" />
<pre>
<strong>Input:</strong> root = [3,9,8,4,0,1,7]
<strong>Output:</strong> [[4],[9],[3,0,1],[8],[7]]
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/images/image2.png" style="width: 350px; height: 342px;" />
<pre>
<strong>Input:</strong> root = [1,2,3,4,10,9,11,null,5,null,null,null,null,null,null,null,6]
<strong>Output:</strong> [[4],[2,5],[1,10,9,6],[3],[11]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search; Hash Table; Binary Tree; Sorting
|
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 verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
def dfs(root, depth, offset):
if root is None:
return
d[offset].append((depth, root.val))
dfs(root.left, depth + 1, offset - 1)
dfs(root.right, depth + 1, offset + 1)
d = defaultdict(list)
dfs(root, 0, 0)
ans = []
for _, v in sorted(d.items()):
v.sort(key=lambda x: x[0])
ans.append([x[1] for x in v])
return ans
|
315 |
Count of Smaller Numbers After Self
|
Hard
|
<p>Given an integer array <code>nums</code>, return<em> an integer array </em><code>counts</code><em> where </em><code>counts[i]</code><em> is the number of smaller elements to the right of </em><code>nums[i]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,2,6,1]
<strong>Output:</strong> [2,1,1,0]
<strong>Explanation:</strong>
To the right of 5 there are <b>2</b> smaller elements (2 and 1).
To the right of 2 there is only <b>1</b> smaller element (1).
To the right of 6 there is <b>1</b> smaller element (1).
To the right of 1 there is <b>0</b> smaller element.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1]
<strong>Output:</strong> [0]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,-1]
<strong>Output:</strong> [0,0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
C++
|
class BinaryIndexedTree {
public:
int n;
vector<int> c;
BinaryIndexedTree(int _n)
: n(_n)
, c(_n + 1) {}
void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += lowbit(x);
}
}
int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
}
return s;
}
int lowbit(int x) {
return x & -x;
}
};
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
unordered_set<int> s(nums.begin(), nums.end());
vector<int> alls(s.begin(), s.end());
sort(alls.begin(), alls.end());
unordered_map<int, int> m;
int n = alls.size();
for (int i = 0; i < n; ++i) m[alls[i]] = i + 1;
BinaryIndexedTree* tree = new BinaryIndexedTree(n);
vector<int> ans(nums.size());
for (int i = nums.size() - 1; i >= 0; --i) {
int x = m[nums[i]];
tree->update(x, 1);
ans[i] = tree->query(x - 1);
}
return ans;
}
};
|
315 |
Count of Smaller Numbers After Self
|
Hard
|
<p>Given an integer array <code>nums</code>, return<em> an integer array </em><code>counts</code><em> where </em><code>counts[i]</code><em> is the number of smaller elements to the right of </em><code>nums[i]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,2,6,1]
<strong>Output:</strong> [2,1,1,0]
<strong>Explanation:</strong>
To the right of 5 there are <b>2</b> smaller elements (2 and 1).
To the right of 2 there is only <b>1</b> smaller element (1).
To the right of 6 there is <b>1</b> smaller element (1).
To the right of 1 there is <b>0</b> smaller element.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1]
<strong>Output:</strong> [0]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,-1]
<strong>Output:</strong> [0,0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
Go
|
type BinaryIndexedTree struct {
n int
c []int
}
func newBinaryIndexedTree(n int) *BinaryIndexedTree {
c := make([]int, n+1)
return &BinaryIndexedTree{n, c}
}
func (this *BinaryIndexedTree) lowbit(x int) int {
return x & -x
}
func (this *BinaryIndexedTree) update(x, delta int) {
for x <= this.n {
this.c[x] += delta
x += this.lowbit(x)
}
}
func (this *BinaryIndexedTree) query(x int) int {
s := 0
for x > 0 {
s += this.c[x]
x -= this.lowbit(x)
}
return s
}
func countSmaller(nums []int) []int {
s := make(map[int]bool)
for _, v := range nums {
s[v] = true
}
var alls []int
for v := range s {
alls = append(alls, v)
}
sort.Ints(alls)
m := make(map[int]int)
for i, v := range alls {
m[v] = i + 1
}
ans := make([]int, len(nums))
tree := newBinaryIndexedTree(len(alls))
for i := len(nums) - 1; i >= 0; i-- {
x := m[nums[i]]
tree.update(x, 1)
ans[i] = tree.query(x - 1)
}
return ans
}
|
315 |
Count of Smaller Numbers After Self
|
Hard
|
<p>Given an integer array <code>nums</code>, return<em> an integer array </em><code>counts</code><em> where </em><code>counts[i]</code><em> is the number of smaller elements to the right of </em><code>nums[i]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,2,6,1]
<strong>Output:</strong> [2,1,1,0]
<strong>Explanation:</strong>
To the right of 5 there are <b>2</b> smaller elements (2 and 1).
To the right of 2 there is only <b>1</b> smaller element (1).
To the right of 6 there is <b>1</b> smaller element (1).
To the right of 1 there is <b>0</b> smaller element.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1]
<strong>Output:</strong> [0]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,-1]
<strong>Output:</strong> [0,0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
Java
|
class Solution {
public List<Integer> countSmaller(int[] nums) {
Set<Integer> s = new HashSet<>();
for (int v : nums) {
s.add(v);
}
List<Integer> alls = new ArrayList<>(s);
alls.sort(Comparator.comparingInt(a -> a));
int n = alls.size();
Map<Integer, Integer> m = new HashMap<>(n);
for (int i = 0; i < n; ++i) {
m.put(alls.get(i), i + 1);
}
BinaryIndexedTree tree = new BinaryIndexedTree(n);
LinkedList<Integer> ans = new LinkedList<>();
for (int i = nums.length - 1; i >= 0; --i) {
int x = m.get(nums[i]);
tree.update(x, 1);
ans.addFirst(tree.query(x - 1));
}
return ans;
}
}
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += lowbit(x);
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
}
return s;
}
public static int lowbit(int x) {
return x & -x;
}
}
|
315 |
Count of Smaller Numbers After Self
|
Hard
|
<p>Given an integer array <code>nums</code>, return<em> an integer array </em><code>counts</code><em> where </em><code>counts[i]</code><em> is the number of smaller elements to the right of </em><code>nums[i]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,2,6,1]
<strong>Output:</strong> [2,1,1,0]
<strong>Explanation:</strong>
To the right of 5 there are <b>2</b> smaller elements (2 and 1).
To the right of 2 there is only <b>1</b> smaller element (1).
To the right of 6 there is <b>1</b> smaller element (1).
To the right of 1 there is <b>0</b> smaller element.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1]
<strong>Output:</strong> [0]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,-1]
<strong>Output:</strong> [0,0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
Python
|
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
@staticmethod
def lowbit(x):
return x & -x
def update(self, x, delta):
while x <= self.n:
self.c[x] += delta
x += BinaryIndexedTree.lowbit(x)
def query(self, x):
s = 0
while x > 0:
s += self.c[x]
x -= BinaryIndexedTree.lowbit(x)
return s
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
alls = sorted(set(nums))
m = {v: i for i, v in enumerate(alls, 1)}
tree = BinaryIndexedTree(len(m))
ans = []
for v in nums[::-1]:
x = m[v]
tree.update(x, 1)
ans.append(tree.query(x - 1))
return ans[::-1]
|
316 |
Remove Duplicate Letters
|
Medium
|
<p>Given a string <code>s</code>, remove duplicate letters so that every letter appears once and only once. You must make sure your result is <span data-keyword="lexicographically-smaller-string"><strong>the smallest in lexicographical order</strong></span> among all possible results.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "bcabc"
<strong>Output:</strong> "abc"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "cbacdcbc"
<strong>Output:</strong> "acdb"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
<p> </p>
<p><strong>Note:</strong> This question is the same as 1081: <a href="https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/" target="_blank">https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/</a></p>
|
Stack; Greedy; String; Monotonic Stack
|
C++
|
class Solution {
public:
string removeDuplicateLetters(string s) {
int n = s.size();
int last[26] = {0};
for (int i = 0; i < n; ++i) {
last[s[i] - 'a'] = i;
}
string ans;
int mask = 0;
for (int i = 0; i < n; ++i) {
char c = s[i];
if ((mask >> (c - 'a')) & 1) {
continue;
}
while (!ans.empty() && ans.back() > c && last[ans.back() - 'a'] > i) {
mask ^= 1 << (ans.back() - 'a');
ans.pop_back();
}
ans.push_back(c);
mask |= 1 << (c - 'a');
}
return ans;
}
};
|
316 |
Remove Duplicate Letters
|
Medium
|
<p>Given a string <code>s</code>, remove duplicate letters so that every letter appears once and only once. You must make sure your result is <span data-keyword="lexicographically-smaller-string"><strong>the smallest in lexicographical order</strong></span> among all possible results.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "bcabc"
<strong>Output:</strong> "abc"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "cbacdcbc"
<strong>Output:</strong> "acdb"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
<p> </p>
<p><strong>Note:</strong> This question is the same as 1081: <a href="https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/" target="_blank">https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/</a></p>
|
Stack; Greedy; String; Monotonic Stack
|
Go
|
func removeDuplicateLetters(s string) string {
last := make([]int, 26)
for i, c := range s {
last[c-'a'] = i
}
stk := []rune{}
vis := make([]bool, 128)
for i, c := range s {
if vis[c] {
continue
}
for len(stk) > 0 && stk[len(stk)-1] > c && last[stk[len(stk)-1]-'a'] > i {
vis[stk[len(stk)-1]] = false
stk = stk[:len(stk)-1]
}
stk = append(stk, c)
vis[c] = true
}
return string(stk)
}
|
316 |
Remove Duplicate Letters
|
Medium
|
<p>Given a string <code>s</code>, remove duplicate letters so that every letter appears once and only once. You must make sure your result is <span data-keyword="lexicographically-smaller-string"><strong>the smallest in lexicographical order</strong></span> among all possible results.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "bcabc"
<strong>Output:</strong> "abc"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "cbacdcbc"
<strong>Output:</strong> "acdb"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
<p> </p>
<p><strong>Note:</strong> This question is the same as 1081: <a href="https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/" target="_blank">https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/</a></p>
|
Stack; Greedy; String; Monotonic Stack
|
Java
|
class Solution {
public String removeDuplicateLetters(String s) {
int n = s.length();
int[] last = new int[26];
for (int i = 0; i < n; ++i) {
last[s.charAt(i) - 'a'] = i;
}
Deque<Character> stk = new ArrayDeque<>();
int mask = 0;
for (int i = 0; i < n; ++i) {
char c = s.charAt(i);
if (((mask >> (c - 'a')) & 1) == 1) {
continue;
}
while (!stk.isEmpty() && stk.peek() > c && last[stk.peek() - 'a'] > i) {
mask ^= 1 << (stk.pop() - 'a');
}
stk.push(c);
mask |= 1 << (c - 'a');
}
StringBuilder ans = new StringBuilder();
for (char c : stk) {
ans.append(c);
}
return ans.reverse().toString();
}
}
|
316 |
Remove Duplicate Letters
|
Medium
|
<p>Given a string <code>s</code>, remove duplicate letters so that every letter appears once and only once. You must make sure your result is <span data-keyword="lexicographically-smaller-string"><strong>the smallest in lexicographical order</strong></span> among all possible results.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "bcabc"
<strong>Output:</strong> "abc"
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "cbacdcbc"
<strong>Output:</strong> "acdb"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
<p> </p>
<p><strong>Note:</strong> This question is the same as 1081: <a href="https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/" target="_blank">https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/</a></p>
|
Stack; Greedy; String; Monotonic Stack
|
Python
|
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
last = {c: i for i, c in enumerate(s)}
stk = []
vis = set()
for i, c in enumerate(s):
if c in vis:
continue
while stk and stk[-1] > c and last[stk[-1]] > i:
vis.remove(stk.pop())
stk.append(c)
vis.add(c)
return ''.join(stk)
|
317 |
Shortest Distance from All Buildings
|
Hard
|
<p>You are given an <code>m x n</code> grid <code>grid</code> of values <code>0</code>, <code>1</code>, or <code>2</code>, where:</p>
<ul>
<li>each <code>0</code> marks <strong>an empty land</strong> that you can pass by freely,</li>
<li>each <code>1</code> marks <strong>a building</strong> that you cannot pass through, and</li>
<li>each <code>2</code> marks <strong>an obstacle</strong> that you cannot pass through.</li>
</ul>
<p>You want to build a house on an empty land that reaches all buildings in the <strong>shortest total travel</strong> distance. You can only move up, down, left, and right.</p>
<p>Return <em>the <strong>shortest travel distance</strong> for such a house</em>. If it is not possible to build such a house according to the above rules, return <code>-1</code>.</p>
<p>The <strong>total travel distance</strong> is the sum of the distances between the houses of the friends and the meeting point.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0317.Shortest%20Distance%20from%20All%20Buildings/images/buildings-grid.jpg" style="width: 413px; height: 253px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2).
The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal.
So return 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,0]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1]]
<strong>Output:</strong> -1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>grid[i][j]</code> is either <code>0</code>, <code>1</code>, or <code>2</code>.</li>
<li>There will be <strong>at least one</strong> building in the <code>grid</code>.</li>
</ul>
|
Breadth-First Search; Array; Matrix
|
C++
|
class Solution {
public:
int shortestDistance(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
typedef pair<int, int> pii;
queue<pii> q;
int total = 0;
vector<vector<int>> cnt(m, vector<int>(n));
vector<vector<int>> dist(m, vector<int>(n));
vector<int> dirs = {-1, 0, 1, 0, -1};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
++total;
q.push({i, j});
vector<vector<bool>> vis(m, vector<bool>(n));
int d = 0;
while (!q.empty()) {
++d;
for (int k = q.size(); k > 0; --k) {
auto p = q.front();
q.pop();
for (int l = 0; l < 4; ++l) {
int x = p.first + dirs[l];
int y = p.second + dirs[l + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0 && !vis[x][y]) {
++cnt[x][y];
dist[x][y] += d;
q.push({x, y});
vis[x][y] = true;
}
}
}
}
}
}
}
int ans = INT_MAX;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j] == 0 && cnt[i][j] == total)
ans = min(ans, dist[i][j]);
return ans == INT_MAX ? -1 : ans;
}
};
|
317 |
Shortest Distance from All Buildings
|
Hard
|
<p>You are given an <code>m x n</code> grid <code>grid</code> of values <code>0</code>, <code>1</code>, or <code>2</code>, where:</p>
<ul>
<li>each <code>0</code> marks <strong>an empty land</strong> that you can pass by freely,</li>
<li>each <code>1</code> marks <strong>a building</strong> that you cannot pass through, and</li>
<li>each <code>2</code> marks <strong>an obstacle</strong> that you cannot pass through.</li>
</ul>
<p>You want to build a house on an empty land that reaches all buildings in the <strong>shortest total travel</strong> distance. You can only move up, down, left, and right.</p>
<p>Return <em>the <strong>shortest travel distance</strong> for such a house</em>. If it is not possible to build such a house according to the above rules, return <code>-1</code>.</p>
<p>The <strong>total travel distance</strong> is the sum of the distances between the houses of the friends and the meeting point.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0317.Shortest%20Distance%20from%20All%20Buildings/images/buildings-grid.jpg" style="width: 413px; height: 253px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2).
The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal.
So return 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,0]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1]]
<strong>Output:</strong> -1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>grid[i][j]</code> is either <code>0</code>, <code>1</code>, or <code>2</code>.</li>
<li>There will be <strong>at least one</strong> building in the <code>grid</code>.</li>
</ul>
|
Breadth-First Search; Array; Matrix
|
Go
|
func shortestDistance(grid [][]int) int {
m, n := len(grid), len(grid[0])
var q [][]int
total := 0
cnt := make([][]int, m)
dist := make([][]int, m)
for i := range cnt {
cnt[i] = make([]int, n)
dist[i] = make([]int, n)
}
dirs := []int{-1, 0, 1, 0, -1}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
total++
q = append(q, []int{i, j})
vis := make([]bool, m*n)
d := 0
for len(q) > 0 {
d++
for k := len(q); k > 0; k-- {
p := q[0]
q = q[1:]
for l := 0; l < 4; l++ {
x, y := p[0]+dirs[l], p[1]+dirs[l+1]
if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0 && !vis[x*n+y] {
cnt[x][y]++
dist[x][y] += d
q = append(q, []int{x, y})
vis[x*n+y] = true
}
}
}
}
}
}
}
ans := math.MaxInt32
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 0 && cnt[i][j] == total {
if ans > dist[i][j] {
ans = dist[i][j]
}
}
}
}
if ans == math.MaxInt32 {
return -1
}
return ans
}
|
317 |
Shortest Distance from All Buildings
|
Hard
|
<p>You are given an <code>m x n</code> grid <code>grid</code> of values <code>0</code>, <code>1</code>, or <code>2</code>, where:</p>
<ul>
<li>each <code>0</code> marks <strong>an empty land</strong> that you can pass by freely,</li>
<li>each <code>1</code> marks <strong>a building</strong> that you cannot pass through, and</li>
<li>each <code>2</code> marks <strong>an obstacle</strong> that you cannot pass through.</li>
</ul>
<p>You want to build a house on an empty land that reaches all buildings in the <strong>shortest total travel</strong> distance. You can only move up, down, left, and right.</p>
<p>Return <em>the <strong>shortest travel distance</strong> for such a house</em>. If it is not possible to build such a house according to the above rules, return <code>-1</code>.</p>
<p>The <strong>total travel distance</strong> is the sum of the distances between the houses of the friends and the meeting point.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0317.Shortest%20Distance%20from%20All%20Buildings/images/buildings-grid.jpg" style="width: 413px; height: 253px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2).
The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal.
So return 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,0]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1]]
<strong>Output:</strong> -1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>grid[i][j]</code> is either <code>0</code>, <code>1</code>, or <code>2</code>.</li>
<li>There will be <strong>at least one</strong> building in the <code>grid</code>.</li>
</ul>
|
Breadth-First Search; Array; Matrix
|
Java
|
class Solution {
public int shortestDistance(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
Deque<int[]> q = new LinkedList<>();
int total = 0;
int[][] cnt = new int[m][n];
int[][] dist = new int[m][n];
int[] dirs = {-1, 0, 1, 0, -1};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
++total;
q.offer(new int[] {i, j});
int d = 0;
boolean[][] vis = new boolean[m][n];
while (!q.isEmpty()) {
++d;
for (int k = q.size(); k > 0; --k) {
int[] p = q.poll();
for (int l = 0; l < 4; ++l) {
int x = p[0] + dirs[l];
int y = p[1] + dirs[l + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0
&& !vis[x][y]) {
++cnt[x][y];
dist[x][y] += d;
q.offer(new int[] {x, y});
vis[x][y] = true;
}
}
}
}
}
}
}
int ans = Integer.MAX_VALUE;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0 && cnt[i][j] == total) {
ans = Math.min(ans, dist[i][j]);
}
}
}
return ans == Integer.MAX_VALUE ? -1 : ans;
}
}
|
317 |
Shortest Distance from All Buildings
|
Hard
|
<p>You are given an <code>m x n</code> grid <code>grid</code> of values <code>0</code>, <code>1</code>, or <code>2</code>, where:</p>
<ul>
<li>each <code>0</code> marks <strong>an empty land</strong> that you can pass by freely,</li>
<li>each <code>1</code> marks <strong>a building</strong> that you cannot pass through, and</li>
<li>each <code>2</code> marks <strong>an obstacle</strong> that you cannot pass through.</li>
</ul>
<p>You want to build a house on an empty land that reaches all buildings in the <strong>shortest total travel</strong> distance. You can only move up, down, left, and right.</p>
<p>Return <em>the <strong>shortest travel distance</strong> for such a house</em>. If it is not possible to build such a house according to the above rules, return <code>-1</code>.</p>
<p>The <strong>total travel distance</strong> is the sum of the distances between the houses of the friends and the meeting point.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0317.Shortest%20Distance%20from%20All%20Buildings/images/buildings-grid.jpg" style="width: 413px; height: 253px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2).
The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal.
So return 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,0]]
<strong>Output:</strong> 1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1]]
<strong>Output:</strong> -1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>grid[i][j]</code> is either <code>0</code>, <code>1</code>, or <code>2</code>.</li>
<li>There will be <strong>at least one</strong> building in the <code>grid</code>.</li>
</ul>
|
Breadth-First Search; Array; Matrix
|
Python
|
class Solution:
def shortestDistance(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
q = deque()
total = 0
cnt = [[0] * n for _ in range(m)]
dist = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
total += 1
q.append((i, j))
d = 0
vis = set()
while q:
d += 1
for _ in range(len(q)):
r, c = q.popleft()
for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
x, y = r + a, c + b
if (
0 <= x < m
and 0 <= y < n
and grid[x][y] == 0
and (x, y) not in vis
):
cnt[x][y] += 1
dist[x][y] += d
q.append((x, y))
vis.add((x, y))
ans = inf
for i in range(m):
for j in range(n):
if grid[i][j] == 0 and cnt[i][j] == total:
ans = min(ans, dist[i][j])
return -1 if ans == inf else ans
|
318 |
Maximum Product of Word Lengths
|
Medium
|
<p>Given a string array <code>words</code>, return <em>the maximum value of</em> <code>length(word[i]) * length(word[j])</code> <em>where the two words do not share common letters</em>. If no such two words exist, return <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["abcw","baz","foo","bar","xtfn","abcdef"]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The two words can be "abcw", "xtfn".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","ab","abc","d","cd","bcd","abcd"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The two words can be "ab", "cd".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aa","aaa","aaaa"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> No such pair of words.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 1000</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Bit Manipulation; Array; String
|
C++
|
class Solution {
public:
int maxProduct(vector<string>& words) {
int n = words.size();
int mask[n];
memset(mask, 0, sizeof(mask));
int ans = 0;
for (int i = 0; i < n; ++i) {
for (char& c : words[i]) {
mask[i] |= 1 << (c - 'a');
}
for (int j = 0; j < i; ++j) {
if ((mask[i] & mask[j]) == 0) {
ans = max(ans, (int) (words[i].size() * words[j].size()));
}
}
}
return ans;
}
};
|
318 |
Maximum Product of Word Lengths
|
Medium
|
<p>Given a string array <code>words</code>, return <em>the maximum value of</em> <code>length(word[i]) * length(word[j])</code> <em>where the two words do not share common letters</em>. If no such two words exist, return <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["abcw","baz","foo","bar","xtfn","abcdef"]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The two words can be "abcw", "xtfn".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","ab","abc","d","cd","bcd","abcd"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The two words can be "ab", "cd".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aa","aaa","aaaa"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> No such pair of words.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 1000</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Bit Manipulation; Array; String
|
Go
|
func maxProduct(words []string) (ans int) {
n := len(words)
mask := make([]int, n)
for i, s := range words {
for _, c := range s {
mask[i] |= 1 << (c - 'a')
}
for j, t := range words[:i] {
if mask[i]&mask[j] == 0 {
ans = max(ans, len(s)*len(t))
}
}
}
return
}
|
318 |
Maximum Product of Word Lengths
|
Medium
|
<p>Given a string array <code>words</code>, return <em>the maximum value of</em> <code>length(word[i]) * length(word[j])</code> <em>where the two words do not share common letters</em>. If no such two words exist, return <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["abcw","baz","foo","bar","xtfn","abcdef"]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The two words can be "abcw", "xtfn".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","ab","abc","d","cd","bcd","abcd"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The two words can be "ab", "cd".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aa","aaa","aaaa"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> No such pair of words.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 1000</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Bit Manipulation; Array; String
|
Java
|
class Solution {
public int maxProduct(String[] words) {
int n = words.length;
int[] mask = new int[n];
int ans = 0;
for (int i = 0; i < n; ++i) {
for (char c : words[i].toCharArray()) {
mask[i] |= 1 << (c - 'a');
}
for (int j = 0; j < i; ++j) {
if ((mask[i] & mask[j]) == 0) {
ans = Math.max(ans, words[i].length() * words[j].length());
}
}
}
return ans;
}
}
|
318 |
Maximum Product of Word Lengths
|
Medium
|
<p>Given a string array <code>words</code>, return <em>the maximum value of</em> <code>length(word[i]) * length(word[j])</code> <em>where the two words do not share common letters</em>. If no such two words exist, return <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["abcw","baz","foo","bar","xtfn","abcdef"]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The two words can be "abcw", "xtfn".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","ab","abc","d","cd","bcd","abcd"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The two words can be "ab", "cd".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aa","aaa","aaaa"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> No such pair of words.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 1000</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Bit Manipulation; Array; String
|
Python
|
class Solution:
def maxProduct(self, words: List[str]) -> int:
mask = [0] * len(words)
ans = 0
for i, s in enumerate(words):
for c in s:
mask[i] |= 1 << (ord(c) - ord("a"))
for j, t in enumerate(words[:i]):
if (mask[i] & mask[j]) == 0:
ans = max(ans, len(s) * len(t))
return ans
|
318 |
Maximum Product of Word Lengths
|
Medium
|
<p>Given a string array <code>words</code>, return <em>the maximum value of</em> <code>length(word[i]) * length(word[j])</code> <em>where the two words do not share common letters</em>. If no such two words exist, return <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["abcw","baz","foo","bar","xtfn","abcdef"]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The two words can be "abcw", "xtfn".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","ab","abc","d","cd","bcd","abcd"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The two words can be "ab", "cd".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aa","aaa","aaaa"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> No such pair of words.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 1000</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Bit Manipulation; Array; String
|
TypeScript
|
function maxProduct(words: string[]): number {
const n = words.length;
const mask: number[] = Array(n).fill(0);
let ans = 0;
for (let i = 0; i < n; ++i) {
for (const c of words[i]) {
mask[i] |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0));
}
for (let j = 0; j < i; ++j) {
if ((mask[i] & mask[j]) === 0) {
ans = Math.max(ans, words[i].length * words[j].length);
}
}
}
return ans;
}
|
319 |
Bulb Switcher
|
Medium
|
<p>There are <code>n</code> bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.</p>
<p>On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the <code>i<sup>th</sup></code> round, you toggle every <code>i</code> bulb. For the <code>n<sup>th</sup></code> round, you only toggle the last bulb.</p>
<p>Return <em>the number of bulbs that are on after <code>n</code> rounds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0319.Bulb%20Switcher/images/bulb.jpg" style="width: 421px; height: 321px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong> At first, the three bulbs are [off, off, off].
After the first round, the three bulbs are [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 0
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 10<sup>9</sup></code></li>
</ul>
|
Brainteaser; Math
|
C++
|
class Solution {
public:
int bulbSwitch(int n) {
return (int) sqrt(n);
}
};
|
319 |
Bulb Switcher
|
Medium
|
<p>There are <code>n</code> bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.</p>
<p>On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the <code>i<sup>th</sup></code> round, you toggle every <code>i</code> bulb. For the <code>n<sup>th</sup></code> round, you only toggle the last bulb.</p>
<p>Return <em>the number of bulbs that are on after <code>n</code> rounds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0319.Bulb%20Switcher/images/bulb.jpg" style="width: 421px; height: 321px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong> At first, the three bulbs are [off, off, off].
After the first round, the three bulbs are [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 0
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 10<sup>9</sup></code></li>
</ul>
|
Brainteaser; Math
|
Go
|
func bulbSwitch(n int) int {
return int(math.Sqrt(float64(n)))
}
|
319 |
Bulb Switcher
|
Medium
|
<p>There are <code>n</code> bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.</p>
<p>On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the <code>i<sup>th</sup></code> round, you toggle every <code>i</code> bulb. For the <code>n<sup>th</sup></code> round, you only toggle the last bulb.</p>
<p>Return <em>the number of bulbs that are on after <code>n</code> rounds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0319.Bulb%20Switcher/images/bulb.jpg" style="width: 421px; height: 321px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong> At first, the three bulbs are [off, off, off].
After the first round, the three bulbs are [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 0
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 10<sup>9</sup></code></li>
</ul>
|
Brainteaser; Math
|
Java
|
class Solution {
public int bulbSwitch(int n) {
return (int) Math.sqrt(n);
}
}
|
319 |
Bulb Switcher
|
Medium
|
<p>There are <code>n</code> bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.</p>
<p>On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the <code>i<sup>th</sup></code> round, you toggle every <code>i</code> bulb. For the <code>n<sup>th</sup></code> round, you only toggle the last bulb.</p>
<p>Return <em>the number of bulbs that are on after <code>n</code> rounds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0319.Bulb%20Switcher/images/bulb.jpg" style="width: 421px; height: 321px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong> At first, the three bulbs are [off, off, off].
After the first round, the three bulbs are [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 0
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 10<sup>9</sup></code></li>
</ul>
|
Brainteaser; Math
|
Python
|
class Solution:
def bulbSwitch(self, n: int) -> int:
return int(sqrt(n))
|
319 |
Bulb Switcher
|
Medium
|
<p>There are <code>n</code> bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.</p>
<p>On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the <code>i<sup>th</sup></code> round, you toggle every <code>i</code> bulb. For the <code>n<sup>th</sup></code> round, you only toggle the last bulb.</p>
<p>Return <em>the number of bulbs that are on after <code>n</code> rounds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0319.Bulb%20Switcher/images/bulb.jpg" style="width: 421px; height: 321px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong> At first, the three bulbs are [off, off, off].
After the first round, the three bulbs are [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 0
<strong>Output:</strong> 0
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 10<sup>9</sup></code></li>
</ul>
|
Brainteaser; Math
|
TypeScript
|
function bulbSwitch(n: number): number {
return Math.floor(Math.sqrt(n));
}
|
320 |
Generalized Abbreviation
|
Medium
|
<p>A word's <strong>generalized abbreviation</strong> can be constructed by taking any number of <strong>non-overlapping</strong> and <strong>non-adjacent</strong> <span data-keyword="substring-nonempty">substrings</span> and replacing them with their respective lengths.</p>
<ul>
<li>For example, <code>"abcde"</code> can be abbreviated into:
<ul>
<li><code>"a3e"</code> (<code>"bcd"</code> turned into <code>"3"</code>)</li>
<li><code>"1bcd1"</code> (<code>"a"</code> and <code>"e"</code> both turned into <code>"1"</code>)</li>
<li><code>"5"</code> (<code>"abcde"</code> turned into <code>"5"</code>)</li>
<li><code>"abcde"</code> (no substrings replaced)</li>
</ul>
</li>
<li>However, these abbreviations are <strong>invalid</strong>:
<ul>
<li><code>"23"</code> (<code>"ab"</code> turned into <code>"2"</code> and <code>"cde"</code> turned into <code>"3"</code>) is invalid as the substrings chosen are adjacent.</li>
<li><code>"22de"</code> (<code>"ab"</code> turned into <code>"2"</code> and <code>"bc"</code> turned into <code>"2"</code>) is invalid as the substring chosen overlap.</li>
</ul>
</li>
</ul>
<p>Given a string <code>word</code>, return <em>a list of all the possible <strong>generalized abbreviations</strong> of</em> <code>word</code>. Return the answer in <strong>any order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> word = "word"
<strong>Output:</strong> ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> word = "a"
<strong>Output:</strong> ["1","a"]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 15</code></li>
<li><code>word</code> consists of only lowercase English letters.</li>
</ul>
|
Bit Manipulation; String; Backtracking
|
C++
|
class Solution {
public:
vector<string> generateAbbreviations(string word) {
int n = word.size();
function<vector<string>(int)> dfs = [&](int i) -> vector<string> {
if (i >= n) {
return {""};
}
vector<string> ans;
for (auto& s : dfs(i + 1)) {
string p(1, word[i]);
ans.emplace_back(p + s);
}
for (int j = i + 1; j <= n; ++j) {
for (auto& s : dfs(j + 1)) {
string p = j < n ? string(1, word[j]) : "";
ans.emplace_back(to_string(j - i) + p + s);
}
}
return ans;
};
return dfs(0);
}
};
|
320 |
Generalized Abbreviation
|
Medium
|
<p>A word's <strong>generalized abbreviation</strong> can be constructed by taking any number of <strong>non-overlapping</strong> and <strong>non-adjacent</strong> <span data-keyword="substring-nonempty">substrings</span> and replacing them with their respective lengths.</p>
<ul>
<li>For example, <code>"abcde"</code> can be abbreviated into:
<ul>
<li><code>"a3e"</code> (<code>"bcd"</code> turned into <code>"3"</code>)</li>
<li><code>"1bcd1"</code> (<code>"a"</code> and <code>"e"</code> both turned into <code>"1"</code>)</li>
<li><code>"5"</code> (<code>"abcde"</code> turned into <code>"5"</code>)</li>
<li><code>"abcde"</code> (no substrings replaced)</li>
</ul>
</li>
<li>However, these abbreviations are <strong>invalid</strong>:
<ul>
<li><code>"23"</code> (<code>"ab"</code> turned into <code>"2"</code> and <code>"cde"</code> turned into <code>"3"</code>) is invalid as the substrings chosen are adjacent.</li>
<li><code>"22de"</code> (<code>"ab"</code> turned into <code>"2"</code> and <code>"bc"</code> turned into <code>"2"</code>) is invalid as the substring chosen overlap.</li>
</ul>
</li>
</ul>
<p>Given a string <code>word</code>, return <em>a list of all the possible <strong>generalized abbreviations</strong> of</em> <code>word</code>. Return the answer in <strong>any order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> word = "word"
<strong>Output:</strong> ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> word = "a"
<strong>Output:</strong> ["1","a"]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 15</code></li>
<li><code>word</code> consists of only lowercase English letters.</li>
</ul>
|
Bit Manipulation; String; Backtracking
|
Go
|
func generateAbbreviations(word string) []string {
n := len(word)
var dfs func(int) []string
dfs = func(i int) []string {
if i >= n {
return []string{""}
}
ans := []string{}
for _, s := range dfs(i + 1) {
ans = append(ans, word[i:i+1]+s)
}
for j := i + 1; j <= n; j++ {
for _, s := range dfs(j + 1) {
p := ""
if j < n {
p = word[j : j+1]
}
ans = append(ans, strconv.Itoa(j-i)+p+s)
}
}
return ans
}
return dfs(0)
}
|
320 |
Generalized Abbreviation
|
Medium
|
<p>A word's <strong>generalized abbreviation</strong> can be constructed by taking any number of <strong>non-overlapping</strong> and <strong>non-adjacent</strong> <span data-keyword="substring-nonempty">substrings</span> and replacing them with their respective lengths.</p>
<ul>
<li>For example, <code>"abcde"</code> can be abbreviated into:
<ul>
<li><code>"a3e"</code> (<code>"bcd"</code> turned into <code>"3"</code>)</li>
<li><code>"1bcd1"</code> (<code>"a"</code> and <code>"e"</code> both turned into <code>"1"</code>)</li>
<li><code>"5"</code> (<code>"abcde"</code> turned into <code>"5"</code>)</li>
<li><code>"abcde"</code> (no substrings replaced)</li>
</ul>
</li>
<li>However, these abbreviations are <strong>invalid</strong>:
<ul>
<li><code>"23"</code> (<code>"ab"</code> turned into <code>"2"</code> and <code>"cde"</code> turned into <code>"3"</code>) is invalid as the substrings chosen are adjacent.</li>
<li><code>"22de"</code> (<code>"ab"</code> turned into <code>"2"</code> and <code>"bc"</code> turned into <code>"2"</code>) is invalid as the substring chosen overlap.</li>
</ul>
</li>
</ul>
<p>Given a string <code>word</code>, return <em>a list of all the possible <strong>generalized abbreviations</strong> of</em> <code>word</code>. Return the answer in <strong>any order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> word = "word"
<strong>Output:</strong> ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> word = "a"
<strong>Output:</strong> ["1","a"]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 15</code></li>
<li><code>word</code> consists of only lowercase English letters.</li>
</ul>
|
Bit Manipulation; String; Backtracking
|
Java
|
class Solution {
private String word;
private int n;
public List<String> generateAbbreviations(String word) {
this.word = word;
n = word.length();
return dfs(0);
}
private List<String> dfs(int i) {
if (i >= n) {
return List.of("");
}
List<String> ans = new ArrayList<>();
for (String s : dfs(i + 1)) {
ans.add(String.valueOf(word.charAt(i)) + s);
}
for (int j = i + 1; j <= n; ++j) {
for (String s : dfs(j + 1)) {
ans.add((j - i) + "" + (j < n ? String.valueOf(word.charAt(j)) : "") + s);
}
}
return ans;
}
}
|
320 |
Generalized Abbreviation
|
Medium
|
<p>A word's <strong>generalized abbreviation</strong> can be constructed by taking any number of <strong>non-overlapping</strong> and <strong>non-adjacent</strong> <span data-keyword="substring-nonempty">substrings</span> and replacing them with their respective lengths.</p>
<ul>
<li>For example, <code>"abcde"</code> can be abbreviated into:
<ul>
<li><code>"a3e"</code> (<code>"bcd"</code> turned into <code>"3"</code>)</li>
<li><code>"1bcd1"</code> (<code>"a"</code> and <code>"e"</code> both turned into <code>"1"</code>)</li>
<li><code>"5"</code> (<code>"abcde"</code> turned into <code>"5"</code>)</li>
<li><code>"abcde"</code> (no substrings replaced)</li>
</ul>
</li>
<li>However, these abbreviations are <strong>invalid</strong>:
<ul>
<li><code>"23"</code> (<code>"ab"</code> turned into <code>"2"</code> and <code>"cde"</code> turned into <code>"3"</code>) is invalid as the substrings chosen are adjacent.</li>
<li><code>"22de"</code> (<code>"ab"</code> turned into <code>"2"</code> and <code>"bc"</code> turned into <code>"2"</code>) is invalid as the substring chosen overlap.</li>
</ul>
</li>
</ul>
<p>Given a string <code>word</code>, return <em>a list of all the possible <strong>generalized abbreviations</strong> of</em> <code>word</code>. Return the answer in <strong>any order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> word = "word"
<strong>Output:</strong> ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> word = "a"
<strong>Output:</strong> ["1","a"]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 15</code></li>
<li><code>word</code> consists of only lowercase English letters.</li>
</ul>
|
Bit Manipulation; String; Backtracking
|
Python
|
class Solution:
def generateAbbreviations(self, word: str) -> List[str]:
def dfs(i: int) -> List[str]:
if i >= n:
return [""]
ans = [word[i] + s for s in dfs(i + 1)]
for j in range(i + 1, n + 1):
for s in dfs(j + 1):
ans.append(str(j - i) + (word[j] if j < n else "") + s)
return ans
n = len(word)
return dfs(0)
|
320 |
Generalized Abbreviation
|
Medium
|
<p>A word's <strong>generalized abbreviation</strong> can be constructed by taking any number of <strong>non-overlapping</strong> and <strong>non-adjacent</strong> <span data-keyword="substring-nonempty">substrings</span> and replacing them with their respective lengths.</p>
<ul>
<li>For example, <code>"abcde"</code> can be abbreviated into:
<ul>
<li><code>"a3e"</code> (<code>"bcd"</code> turned into <code>"3"</code>)</li>
<li><code>"1bcd1"</code> (<code>"a"</code> and <code>"e"</code> both turned into <code>"1"</code>)</li>
<li><code>"5"</code> (<code>"abcde"</code> turned into <code>"5"</code>)</li>
<li><code>"abcde"</code> (no substrings replaced)</li>
</ul>
</li>
<li>However, these abbreviations are <strong>invalid</strong>:
<ul>
<li><code>"23"</code> (<code>"ab"</code> turned into <code>"2"</code> and <code>"cde"</code> turned into <code>"3"</code>) is invalid as the substrings chosen are adjacent.</li>
<li><code>"22de"</code> (<code>"ab"</code> turned into <code>"2"</code> and <code>"bc"</code> turned into <code>"2"</code>) is invalid as the substring chosen overlap.</li>
</ul>
</li>
</ul>
<p>Given a string <code>word</code>, return <em>a list of all the possible <strong>generalized abbreviations</strong> of</em> <code>word</code>. Return the answer in <strong>any order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> word = "word"
<strong>Output:</strong> ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> word = "a"
<strong>Output:</strong> ["1","a"]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 15</code></li>
<li><code>word</code> consists of only lowercase English letters.</li>
</ul>
|
Bit Manipulation; String; Backtracking
|
TypeScript
|
function generateAbbreviations(word: string): string[] {
const n = word.length;
const dfs = (i: number): string[] => {
if (i >= n) {
return [''];
}
const ans: string[] = [];
for (const s of dfs(i + 1)) {
ans.push(word[i] + s);
}
for (let j = i + 1; j <= n; ++j) {
for (const s of dfs(j + 1)) {
ans.push((j - i).toString() + (j < n ? word[j] : '') + s);
}
}
return ans;
};
return dfs(0);
}
|
321 |
Create Maximum Number
|
Hard
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>m</code> and <code>n</code> respectively. <code>nums1</code> and <code>nums2</code> represent the digits of two numbers. You are also given an integer <code>k</code>.</p>
<p>Create the maximum number of length <code>k <= m + n</code> from digits of the two numbers. The relative order of the digits from the same array must be preserved.</p>
<p>Return an array of the <code>k</code> digits representing the answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
<strong>Output:</strong> [9,8,6,5,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [6,7], nums2 = [6,0,4], k = 5
<strong>Output:</strong> [6,7,6,0,4]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,9], nums2 = [8,9], k = 3
<strong>Output:</strong> [9,8,9]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == nums1.length</code></li>
<li><code>n == nums2.length</code></li>
<li><code>1 <= m, n <= 500</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 9</code></li>
<li><code>1 <= k <= m + n</code></li>
<li><code>nums1</code> and <code>nums2</code> do not have leading zeros.</li>
</ul>
|
Stack; Greedy; Array; Two Pointers; Monotonic Stack
|
C++
|
class Solution {
public:
vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
auto f = [](vector<int>& nums, int k) {
int n = nums.size();
vector<int> stk(k);
int top = -1;
int remain = n - k;
for (int x : nums) {
while (top >= 0 && stk[top] < x && remain > 0) {
--top;
--remain;
}
if (top + 1 < k) {
stk[++top] = x;
} else {
--remain;
}
}
return stk;
};
function<bool(vector<int>&, vector<int>&, int, int)> compare = [&](vector<int>& nums1, vector<int>& nums2, int i, int j) -> bool {
if (i >= nums1.size()) {
return false;
}
if (j >= nums2.size()) {
return true;
}
if (nums1[i] > nums2[j]) {
return true;
}
if (nums1[i] < nums2[j]) {
return false;
}
return compare(nums1, nums2, i + 1, j + 1);
};
auto merge = [&](vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size(), n = nums2.size();
int i = 0, j = 0;
vector<int> ans(m + n);
for (int k = 0; k < m + n; ++k) {
if (compare(nums1, nums2, i, j)) {
ans[k] = nums1[i++];
} else {
ans[k] = nums2[j++];
}
}
return ans;
};
int m = nums1.size(), n = nums2.size();
int l = max(0, k - n), r = min(k, m);
vector<int> ans(k);
for (int x = l; x <= r; ++x) {
vector<int> arr1 = f(nums1, x);
vector<int> arr2 = f(nums2, k - x);
vector<int> arr = merge(arr1, arr2);
if (ans < arr) {
ans = move(arr);
}
}
return ans;
}
};
|
321 |
Create Maximum Number
|
Hard
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>m</code> and <code>n</code> respectively. <code>nums1</code> and <code>nums2</code> represent the digits of two numbers. You are also given an integer <code>k</code>.</p>
<p>Create the maximum number of length <code>k <= m + n</code> from digits of the two numbers. The relative order of the digits from the same array must be preserved.</p>
<p>Return an array of the <code>k</code> digits representing the answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
<strong>Output:</strong> [9,8,6,5,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [6,7], nums2 = [6,0,4], k = 5
<strong>Output:</strong> [6,7,6,0,4]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,9], nums2 = [8,9], k = 3
<strong>Output:</strong> [9,8,9]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == nums1.length</code></li>
<li><code>n == nums2.length</code></li>
<li><code>1 <= m, n <= 500</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 9</code></li>
<li><code>1 <= k <= m + n</code></li>
<li><code>nums1</code> and <code>nums2</code> do not have leading zeros.</li>
</ul>
|
Stack; Greedy; Array; Two Pointers; Monotonic Stack
|
Go
|
func maxNumber(nums1 []int, nums2 []int, k int) []int {
m, n := len(nums1), len(nums2)
l, r := max(0, k-n), min(k, m)
f := func(nums []int, k int) []int {
n := len(nums)
stk := make([]int, k)
top := -1
remain := n - k
for _, x := range nums {
for top >= 0 && stk[top] < x && remain > 0 {
top--
remain--
}
if top+1 < k {
top++
stk[top] = x
} else {
remain--
}
}
return stk
}
var compare func(nums1, nums2 []int, i, j int) bool
compare = func(nums1, nums2 []int, i, j int) bool {
if i >= len(nums1) {
return false
}
if j >= len(nums2) {
return true
}
if nums1[i] > nums2[j] {
return true
}
if nums1[i] < nums2[j] {
return false
}
return compare(nums1, nums2, i+1, j+1)
}
merge := func(nums1, nums2 []int) []int {
m, n := len(nums1), len(nums2)
ans := make([]int, m+n)
i, j := 0, 0
for k := range ans {
if compare(nums1, nums2, i, j) {
ans[k] = nums1[i]
i++
} else {
ans[k] = nums2[j]
j++
}
}
return ans
}
ans := make([]int, k)
for x := l; x <= r; x++ {
arr1 := f(nums1, x)
arr2 := f(nums2, k-x)
arr := merge(arr1, arr2)
if compare(arr, ans, 0, 0) {
ans = arr
}
}
return ans
}
|
321 |
Create Maximum Number
|
Hard
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>m</code> and <code>n</code> respectively. <code>nums1</code> and <code>nums2</code> represent the digits of two numbers. You are also given an integer <code>k</code>.</p>
<p>Create the maximum number of length <code>k <= m + n</code> from digits of the two numbers. The relative order of the digits from the same array must be preserved.</p>
<p>Return an array of the <code>k</code> digits representing the answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
<strong>Output:</strong> [9,8,6,5,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [6,7], nums2 = [6,0,4], k = 5
<strong>Output:</strong> [6,7,6,0,4]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,9], nums2 = [8,9], k = 3
<strong>Output:</strong> [9,8,9]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == nums1.length</code></li>
<li><code>n == nums2.length</code></li>
<li><code>1 <= m, n <= 500</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 9</code></li>
<li><code>1 <= k <= m + n</code></li>
<li><code>nums1</code> and <code>nums2</code> do not have leading zeros.</li>
</ul>
|
Stack; Greedy; Array; Two Pointers; Monotonic Stack
|
Java
|
class Solution {
public int[] maxNumber(int[] nums1, int[] nums2, int k) {
int m = nums1.length, n = nums2.length;
int l = Math.max(0, k - n), r = Math.min(k, m);
int[] ans = new int[k];
for (int x = l; x <= r; ++x) {
int[] arr1 = f(nums1, x);
int[] arr2 = f(nums2, k - x);
int[] arr = merge(arr1, arr2);
if (compare(arr, ans, 0, 0)) {
ans = arr;
}
}
return ans;
}
private int[] f(int[] nums, int k) {
int n = nums.length;
int[] stk = new int[k];
int top = -1;
int remain = n - k;
for (int x : nums) {
while (top >= 0 && stk[top] < x && remain > 0) {
--top;
--remain;
}
if (top + 1 < k) {
stk[++top] = x;
} else {
--remain;
}
}
return stk;
}
private int[] merge(int[] nums1, int[] nums2) {
int m = nums1.length, n = nums2.length;
int i = 0, j = 0;
int[] ans = new int[m + n];
for (int k = 0; k < m + n; ++k) {
if (compare(nums1, nums2, i, j)) {
ans[k] = nums1[i++];
} else {
ans[k] = nums2[j++];
}
}
return ans;
}
private boolean compare(int[] nums1, int[] nums2, int i, int j) {
if (i >= nums1.length) {
return false;
}
if (j >= nums2.length) {
return true;
}
if (nums1[i] > nums2[j]) {
return true;
}
if (nums1[i] < nums2[j]) {
return false;
}
return compare(nums1, nums2, i + 1, j + 1);
}
}
|
321 |
Create Maximum Number
|
Hard
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>m</code> and <code>n</code> respectively. <code>nums1</code> and <code>nums2</code> represent the digits of two numbers. You are also given an integer <code>k</code>.</p>
<p>Create the maximum number of length <code>k <= m + n</code> from digits of the two numbers. The relative order of the digits from the same array must be preserved.</p>
<p>Return an array of the <code>k</code> digits representing the answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
<strong>Output:</strong> [9,8,6,5,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [6,7], nums2 = [6,0,4], k = 5
<strong>Output:</strong> [6,7,6,0,4]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,9], nums2 = [8,9], k = 3
<strong>Output:</strong> [9,8,9]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == nums1.length</code></li>
<li><code>n == nums2.length</code></li>
<li><code>1 <= m, n <= 500</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 9</code></li>
<li><code>1 <= k <= m + n</code></li>
<li><code>nums1</code> and <code>nums2</code> do not have leading zeros.</li>
</ul>
|
Stack; Greedy; Array; Two Pointers; Monotonic Stack
|
Python
|
class Solution:
def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:
def f(nums: List[int], k: int) -> List[int]:
n = len(nums)
stk = [0] * k
top = -1
remain = n - k
for x in nums:
while top >= 0 and stk[top] < x and remain > 0:
top -= 1
remain -= 1
if top + 1 < k:
top += 1
stk[top] = x
else:
remain -= 1
return stk
def compare(nums1: List[int], nums2: List[int], i: int, j: int) -> bool:
if i >= len(nums1):
return False
if j >= len(nums2):
return True
if nums1[i] > nums2[j]:
return True
if nums1[i] < nums2[j]:
return False
return compare(nums1, nums2, i + 1, j + 1)
def merge(nums1: List[int], nums2: List[int]) -> List[int]:
m, n = len(nums1), len(nums2)
i = j = 0
ans = [0] * (m + n)
for k in range(m + n):
if compare(nums1, nums2, i, j):
ans[k] = nums1[i]
i += 1
else:
ans[k] = nums2[j]
j += 1
return ans
m, n = len(nums1), len(nums2)
l, r = max(0, k - n), min(k, m)
ans = [0] * k
for x in range(l, r + 1):
arr1 = f(nums1, x)
arr2 = f(nums2, k - x)
arr = merge(arr1, arr2)
if ans < arr:
ans = arr
return ans
|
321 |
Create Maximum Number
|
Hard
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>m</code> and <code>n</code> respectively. <code>nums1</code> and <code>nums2</code> represent the digits of two numbers. You are also given an integer <code>k</code>.</p>
<p>Create the maximum number of length <code>k <= m + n</code> from digits of the two numbers. The relative order of the digits from the same array must be preserved.</p>
<p>Return an array of the <code>k</code> digits representing the answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
<strong>Output:</strong> [9,8,6,5,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [6,7], nums2 = [6,0,4], k = 5
<strong>Output:</strong> [6,7,6,0,4]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,9], nums2 = [8,9], k = 3
<strong>Output:</strong> [9,8,9]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == nums1.length</code></li>
<li><code>n == nums2.length</code></li>
<li><code>1 <= m, n <= 500</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 9</code></li>
<li><code>1 <= k <= m + n</code></li>
<li><code>nums1</code> and <code>nums2</code> do not have leading zeros.</li>
</ul>
|
Stack; Greedy; Array; Two Pointers; Monotonic Stack
|
TypeScript
|
function maxNumber(nums1: number[], nums2: number[], k: number): number[] {
const m = nums1.length;
const n = nums2.length;
const l = Math.max(0, k - n);
const r = Math.min(k, m);
let ans: number[] = Array(k).fill(0);
for (let x = l; x <= r; ++x) {
const arr1 = f(nums1, x);
const arr2 = f(nums2, k - x);
const arr = merge(arr1, arr2);
if (compare(arr, ans, 0, 0)) {
ans = arr;
}
}
return ans;
}
function f(nums: number[], k: number): number[] {
const n = nums.length;
const stk: number[] = Array(k).fill(0);
let top = -1;
let remain = n - k;
for (const x of nums) {
while (top >= 0 && stk[top] < x && remain > 0) {
--top;
--remain;
}
if (top + 1 < k) {
stk[++top] = x;
} else {
--remain;
}
}
return stk;
}
function compare(nums1: number[], nums2: number[], i: number, j: number): boolean {
if (i >= nums1.length) {
return false;
}
if (j >= nums2.length) {
return true;
}
if (nums1[i] > nums2[j]) {
return true;
}
if (nums1[i] < nums2[j]) {
return false;
}
return compare(nums1, nums2, i + 1, j + 1);
}
function merge(nums1: number[], nums2: number[]): number[] {
const m = nums1.length;
const n = nums2.length;
const ans: number[] = Array(m + n).fill(0);
let i = 0;
let j = 0;
for (let k = 0; k < m + n; ++k) {
if (compare(nums1, nums2, i, j)) {
ans[k] = nums1[i++];
} else {
ans[k] = nums2[j++];
}
}
return ans;
}
|
322 |
Coin Change
|
Medium
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>
<p>Return <em>the fewest number of coins that you need to make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>-1</code>.</p>
<p>You may assume that you have an infinite number of each kind of coin.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> coins = [1,2,5], amount = 11
<strong>Output:</strong> 3
<strong>Explanation:</strong> 11 = 5 + 5 + 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> coins = [2], amount = 3
<strong>Output:</strong> -1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> coins = [1], amount = 0
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 12</code></li>
<li><code>1 <= coins[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>0 <= amount <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Array; Dynamic Programming
|
C++
|
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int m = coins.size(), n = amount;
int f[m + 1][n + 1];
memset(f, 0x3f, sizeof(f));
f[0][0] = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (j >= coins[i - 1]) {
f[i][j] = min(f[i][j], f[i][j - coins[i - 1]] + 1);
}
}
}
return f[m][n] > n ? -1 : f[m][n];
}
};
|
322 |
Coin Change
|
Medium
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>
<p>Return <em>the fewest number of coins that you need to make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>-1</code>.</p>
<p>You may assume that you have an infinite number of each kind of coin.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> coins = [1,2,5], amount = 11
<strong>Output:</strong> 3
<strong>Explanation:</strong> 11 = 5 + 5 + 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> coins = [2], amount = 3
<strong>Output:</strong> -1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> coins = [1], amount = 0
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 12</code></li>
<li><code>1 <= coins[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>0 <= amount <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Array; Dynamic Programming
|
Go
|
func coinChange(coins []int, amount int) int {
m, n := len(coins), amount
f := make([][]int, m+1)
const inf = 1 << 30
for i := range f {
f[i] = make([]int, n+1)
for j := range f[i] {
f[i][j] = inf
}
}
f[0][0] = 0
for i := 1; i <= m; i++ {
for j := 0; j <= n; j++ {
f[i][j] = f[i-1][j]
if j >= coins[i-1] {
f[i][j] = min(f[i][j], f[i][j-coins[i-1]]+1)
}
}
}
if f[m][n] > n {
return -1
}
return f[m][n]
}
|
322 |
Coin Change
|
Medium
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>
<p>Return <em>the fewest number of coins that you need to make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>-1</code>.</p>
<p>You may assume that you have an infinite number of each kind of coin.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> coins = [1,2,5], amount = 11
<strong>Output:</strong> 3
<strong>Explanation:</strong> 11 = 5 + 5 + 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> coins = [2], amount = 3
<strong>Output:</strong> -1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> coins = [1], amount = 0
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 12</code></li>
<li><code>1 <= coins[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>0 <= amount <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Array; Dynamic Programming
|
Java
|
class Solution {
public int coinChange(int[] coins, int amount) {
final int inf = 1 << 30;
int m = coins.length;
int n = amount;
int[][] f = new int[m + 1][n + 1];
for (var g : f) {
Arrays.fill(g, inf);
}
f[0][0] = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (j >= coins[i - 1]) {
f[i][j] = Math.min(f[i][j], f[i][j - coins[i - 1]] + 1);
}
}
}
return f[m][n] >= inf ? -1 : f[m][n];
}
}
|
322 |
Coin Change
|
Medium
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>
<p>Return <em>the fewest number of coins that you need to make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>-1</code>.</p>
<p>You may assume that you have an infinite number of each kind of coin.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> coins = [1,2,5], amount = 11
<strong>Output:</strong> 3
<strong>Explanation:</strong> 11 = 5 + 5 + 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> coins = [2], amount = 3
<strong>Output:</strong> -1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> coins = [1], amount = 0
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 12</code></li>
<li><code>1 <= coins[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>0 <= amount <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Array; Dynamic Programming
|
JavaScript
|
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function (coins, amount) {
const m = coins.length;
const n = amount;
const f = Array(m + 1)
.fill(0)
.map(() => Array(n + 1).fill(1 << 30));
f[0][0] = 0;
for (let i = 1; i <= m; ++i) {
for (let j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (j >= coins[i - 1]) {
f[i][j] = Math.min(f[i][j], f[i][j - coins[i - 1]] + 1);
}
}
}
return f[m][n] > n ? -1 : f[m][n];
};
|
322 |
Coin Change
|
Medium
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>
<p>Return <em>the fewest number of coins that you need to make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>-1</code>.</p>
<p>You may assume that you have an infinite number of each kind of coin.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> coins = [1,2,5], amount = 11
<strong>Output:</strong> 3
<strong>Explanation:</strong> 11 = 5 + 5 + 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> coins = [2], amount = 3
<strong>Output:</strong> -1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> coins = [1], amount = 0
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 12</code></li>
<li><code>1 <= coins[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>0 <= amount <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Array; Dynamic Programming
|
Python
|
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
m, n = len(coins), amount
f = [[inf] * (n + 1) for _ in range(m + 1)]
f[0][0] = 0
for i, x in enumerate(coins, 1):
for j in range(n + 1):
f[i][j] = f[i - 1][j]
if j >= x:
f[i][j] = min(f[i][j], f[i][j - x] + 1)
return -1 if f[m][n] >= inf else f[m][n]
|
322 |
Coin Change
|
Medium
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>
<p>Return <em>the fewest number of coins that you need to make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>-1</code>.</p>
<p>You may assume that you have an infinite number of each kind of coin.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> coins = [1,2,5], amount = 11
<strong>Output:</strong> 3
<strong>Explanation:</strong> 11 = 5 + 5 + 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> coins = [2], amount = 3
<strong>Output:</strong> -1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> coins = [1], amount = 0
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 12</code></li>
<li><code>1 <= coins[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>0 <= amount <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Array; Dynamic Programming
|
Rust
|
impl Solution {
pub fn coin_change(coins: Vec<i32>, amount: i32) -> i32 {
let n = amount as usize;
let mut f = vec![n + 1; n + 1];
f[0] = 0;
for &x in &coins {
for j in x as usize..=n {
f[j] = f[j].min(f[j - (x as usize)] + 1);
}
}
if f[n] > n {
-1
} else {
f[n] as i32
}
}
}
|
322 |
Coin Change
|
Medium
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>
<p>Return <em>the fewest number of coins that you need to make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>-1</code>.</p>
<p>You may assume that you have an infinite number of each kind of coin.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> coins = [1,2,5], amount = 11
<strong>Output:</strong> 3
<strong>Explanation:</strong> 11 = 5 + 5 + 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> coins = [2], amount = 3
<strong>Output:</strong> -1
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> coins = [1], amount = 0
<strong>Output:</strong> 0
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 12</code></li>
<li><code>1 <= coins[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>0 <= amount <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Array; Dynamic Programming
|
TypeScript
|
function coinChange(coins: number[], amount: number): number {
const m = coins.length;
const n = amount;
const f: number[][] = Array(m + 1)
.fill(0)
.map(() => Array(n + 1).fill(1 << 30));
f[0][0] = 0;
for (let i = 1; i <= m; ++i) {
for (let j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (j >= coins[i - 1]) {
f[i][j] = Math.min(f[i][j], f[i][j - coins[i - 1]] + 1);
}
}
}
return f[m][n] > n ? -1 : f[m][n];
}
|
323 |
Number of Connected Components in an Undirected Graph
|
Medium
|
<p>You have a graph of <code>n</code> nodes. You are given an integer <code>n</code> and an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p>
<p>Return <em>the number of connected components in the graph</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn1-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[3,4]]
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn2-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2000</code></li>
<li><code>1 <= edges.length <= 5000</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>There are no repeated edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph
|
C++
|
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
vector<int> g[n];
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
g[b].push_back(a);
}
vector<bool> vis(n);
function<int(int)> dfs = [&](int i) {
if (vis[i]) {
return 0;
}
vis[i] = true;
for (int j : g[i]) {
dfs(j);
}
return 1;
};
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += dfs(i);
}
return ans;
}
};
|
323 |
Number of Connected Components in an Undirected Graph
|
Medium
|
<p>You have a graph of <code>n</code> nodes. You are given an integer <code>n</code> and an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p>
<p>Return <em>the number of connected components in the graph</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn1-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[3,4]]
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn2-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2000</code></li>
<li><code>1 <= edges.length <= 5000</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>There are no repeated edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph
|
Go
|
func countComponents(n int, edges [][]int) (ans int) {
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
vis := make([]bool, n)
var dfs func(int) int
dfs = func(i int) int {
if vis[i] {
return 0
}
vis[i] = true
for _, j := range g[i] {
dfs(j)
}
return 1
}
for i := range g {
ans += dfs(i)
}
return
}
|
323 |
Number of Connected Components in an Undirected Graph
|
Medium
|
<p>You have a graph of <code>n</code> nodes. You are given an integer <code>n</code> and an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p>
<p>Return <em>the number of connected components in the graph</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn1-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[3,4]]
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn2-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2000</code></li>
<li><code>1 <= edges.length <= 5000</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>There are no repeated edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph
|
Java
|
class Solution {
private List<Integer>[] g;
private boolean[] vis;
public int countComponents(int n, int[][] edges) {
g = new List[n];
vis = new boolean[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += dfs(i);
}
return ans;
}
private int dfs(int i) {
if (vis[i]) {
return 0;
}
vis[i] = true;
for (int j : g[i]) {
dfs(j);
}
return 1;
}
}
|
323 |
Number of Connected Components in an Undirected Graph
|
Medium
|
<p>You have a graph of <code>n</code> nodes. You are given an integer <code>n</code> and an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p>
<p>Return <em>the number of connected components in the graph</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn1-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[3,4]]
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn2-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2000</code></li>
<li><code>1 <= edges.length <= 5000</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>There are no repeated edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph
|
JavaScript
|
/**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/
var countComponents = function (n, edges) {
const g = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
const vis = Array(n).fill(false);
const dfs = i => {
if (vis[i]) {
return 0;
}
vis[i] = true;
for (const j of g[i]) {
dfs(j);
}
return 1;
};
return g.reduce((acc, _, i) => acc + dfs(i), 0);
};
|
323 |
Number of Connected Components in an Undirected Graph
|
Medium
|
<p>You have a graph of <code>n</code> nodes. You are given an integer <code>n</code> and an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p>
<p>Return <em>the number of connected components in the graph</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn1-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[3,4]]
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn2-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2000</code></li>
<li><code>1 <= edges.length <= 5000</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>There are no repeated edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph
|
Python
|
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
def dfs(i: int) -> int:
if i in vis:
return 0
vis.add(i)
for j in g[i]:
dfs(j)
return 1
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
vis = set()
return sum(dfs(i) for i in range(n))
|
323 |
Number of Connected Components in an Undirected Graph
|
Medium
|
<p>You have a graph of <code>n</code> nodes. You are given an integer <code>n</code> and an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p>
<p>Return <em>the number of connected components in the graph</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn1-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[3,4]]
<strong>Output:</strong> 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn2-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2000</code></li>
<li><code>1 <= edges.length <= 5000</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>There are no repeated edges.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph
|
TypeScript
|
function countComponents(n: number, edges: number[][]): number {
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
const vis: boolean[] = Array(n).fill(false);
const dfs = (i: number): number => {
if (vis[i]) {
return 0;
}
vis[i] = true;
for (const j of g[i]) {
dfs(j);
}
return 1;
};
return g.reduce((acc, _, i) => acc + dfs(i), 0);
}
|
324 |
Wiggle Sort II
|
Medium
|
<p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] < nums[1] > nums[2] < nums[3]...</code>.</p>
<p>You may assume the input array always has a valid answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,1,1,6,4]
<strong>Output:</strong> [1,6,1,5,1,4]
<strong>Explanation:</strong> [1,4,1,5,1,6] is also accepted.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,2,3,1]
<strong>Output:</strong> [2,3,1,3,1,2]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 5000</code></li>
<li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li>
</ul>
<p> </p>
<strong>Follow Up:</strong> Can you do it in <code>O(n)</code> time and/or <strong>in-place</strong> with <code>O(1)</code> extra space?
|
Greedy; Array; Divide and Conquer; Quickselect; Sorting
|
C++
|
class Solution {
public:
void wiggleSort(vector<int>& nums) {
vector<int> arr = nums;
sort(arr.begin(), arr.end());
int n = nums.size();
int i = (n - 1) >> 1, j = n - 1;
for (int k = 0; k < n; ++k) {
if (k % 2 == 0)
nums[k] = arr[i--];
else
nums[k] = arr[j--];
}
}
};
|
324 |
Wiggle Sort II
|
Medium
|
<p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] < nums[1] > nums[2] < nums[3]...</code>.</p>
<p>You may assume the input array always has a valid answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,1,1,6,4]
<strong>Output:</strong> [1,6,1,5,1,4]
<strong>Explanation:</strong> [1,4,1,5,1,6] is also accepted.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,2,3,1]
<strong>Output:</strong> [2,3,1,3,1,2]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 5000</code></li>
<li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li>
</ul>
<p> </p>
<strong>Follow Up:</strong> Can you do it in <code>O(n)</code> time and/or <strong>in-place</strong> with <code>O(1)</code> extra space?
|
Greedy; Array; Divide and Conquer; Quickselect; Sorting
|
Go
|
func wiggleSort(nums []int) {
n := len(nums)
arr := make([]int, n)
copy(arr, nums)
sort.Ints(arr)
i, j := (n-1)>>1, n-1
for k := 0; k < n; k++ {
if k%2 == 0 {
nums[k] = arr[i]
i--
} else {
nums[k] = arr[j]
j--
}
}
}
|
324 |
Wiggle Sort II
|
Medium
|
<p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] < nums[1] > nums[2] < nums[3]...</code>.</p>
<p>You may assume the input array always has a valid answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,1,1,6,4]
<strong>Output:</strong> [1,6,1,5,1,4]
<strong>Explanation:</strong> [1,4,1,5,1,6] is also accepted.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,2,3,1]
<strong>Output:</strong> [2,3,1,3,1,2]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 5000</code></li>
<li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li>
</ul>
<p> </p>
<strong>Follow Up:</strong> Can you do it in <code>O(n)</code> time and/or <strong>in-place</strong> with <code>O(1)</code> extra space?
|
Greedy; Array; Divide and Conquer; Quickselect; Sorting
|
Java
|
class Solution {
public void wiggleSort(int[] nums) {
int[] arr = nums.clone();
Arrays.sort(arr);
int n = nums.length;
int i = (n - 1) >> 1, j = n - 1;
for (int k = 0; k < n; ++k) {
if (k % 2 == 0) {
nums[k] = arr[i--];
} else {
nums[k] = arr[j--];
}
}
}
}
|
324 |
Wiggle Sort II
|
Medium
|
<p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] < nums[1] > nums[2] < nums[3]...</code>.</p>
<p>You may assume the input array always has a valid answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,1,1,6,4]
<strong>Output:</strong> [1,6,1,5,1,4]
<strong>Explanation:</strong> [1,4,1,5,1,6] is also accepted.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,2,3,1]
<strong>Output:</strong> [2,3,1,3,1,2]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 5000</code></li>
<li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li>
</ul>
<p> </p>
<strong>Follow Up:</strong> Can you do it in <code>O(n)</code> time and/or <strong>in-place</strong> with <code>O(1)</code> extra space?
|
Greedy; Array; Divide and Conquer; Quickselect; Sorting
|
JavaScript
|
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var wiggleSort = function (nums) {
let bucket = new Array(5001).fill(0);
for (const v of nums) {
bucket[v]++;
}
const n = nums.length;
let j = 5000;
for (let i = 1; i < n; i += 2) {
while (bucket[j] == 0) {
--j;
}
nums[i] = j;
--bucket[j];
}
for (let i = 0; i < n; i += 2) {
while (bucket[j] == 0) {
--j;
}
nums[i] = j;
--bucket[j];
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.