id
int64 1
3.71k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
|---|---|---|---|---|---|---|
657
|
Robot Return to Origin
|
Easy
|
<p>There is a robot starting at the position <code>(0, 0)</code>, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot <strong>ends up at </strong><code>(0, 0)</code> after it completes its moves.</p>
<p>You are given a string <code>moves</code> that represents the move sequence of the robot where <code>moves[i]</code> represents its <code>i<sup>th</sup></code> move. Valid moves are <code>'R'</code> (right), <code>'L'</code> (left), <code>'U'</code> (up), and <code>'D'</code> (down).</p>
<p>Return <code>true</code><em> if the robot returns to the origin after it finishes all of its moves, or </em><code>false</code><em> otherwise</em>.</p>
<p><strong>Note</strong>: The way that the robot is "facing" is irrelevant. <code>'R'</code> will always make the robot move to the right once, <code>'L'</code> will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> moves = "UD"
<strong>Output:</strong> true
<strong>Explanation</strong>: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> moves = "LL"
<strong>Output:</strong> false
<strong>Explanation</strong>: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= moves.length <= 2 * 10<sup>4</sup></code></li>
<li><code>moves</code> only contains the characters <code>'U'</code>, <code>'D'</code>, <code>'L'</code> and <code>'R'</code>.</li>
</ul>
|
String; Simulation
|
C++
|
class Solution {
public:
bool judgeCircle(string moves) {
int x = 0, y = 0;
for (char c : moves) {
switch (c) {
case 'U': y++; break;
case 'D': y--; break;
case 'L': x--; break;
case 'R': x++; break;
}
}
return x == 0 && y == 0;
}
};
|
657
|
Robot Return to Origin
|
Easy
|
<p>There is a robot starting at the position <code>(0, 0)</code>, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot <strong>ends up at </strong><code>(0, 0)</code> after it completes its moves.</p>
<p>You are given a string <code>moves</code> that represents the move sequence of the robot where <code>moves[i]</code> represents its <code>i<sup>th</sup></code> move. Valid moves are <code>'R'</code> (right), <code>'L'</code> (left), <code>'U'</code> (up), and <code>'D'</code> (down).</p>
<p>Return <code>true</code><em> if the robot returns to the origin after it finishes all of its moves, or </em><code>false</code><em> otherwise</em>.</p>
<p><strong>Note</strong>: The way that the robot is "facing" is irrelevant. <code>'R'</code> will always make the robot move to the right once, <code>'L'</code> will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> moves = "UD"
<strong>Output:</strong> true
<strong>Explanation</strong>: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> moves = "LL"
<strong>Output:</strong> false
<strong>Explanation</strong>: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= moves.length <= 2 * 10<sup>4</sup></code></li>
<li><code>moves</code> only contains the characters <code>'U'</code>, <code>'D'</code>, <code>'L'</code> and <code>'R'</code>.</li>
</ul>
|
String; Simulation
|
Go
|
func judgeCircle(moves string) bool {
x, y := 0, 0
for _, c := range moves {
switch c {
case 'U':
y++
case 'D':
y--
case 'L':
x--
case 'R':
x++
}
}
return x == 0 && y == 0
}
|
657
|
Robot Return to Origin
|
Easy
|
<p>There is a robot starting at the position <code>(0, 0)</code>, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot <strong>ends up at </strong><code>(0, 0)</code> after it completes its moves.</p>
<p>You are given a string <code>moves</code> that represents the move sequence of the robot where <code>moves[i]</code> represents its <code>i<sup>th</sup></code> move. Valid moves are <code>'R'</code> (right), <code>'L'</code> (left), <code>'U'</code> (up), and <code>'D'</code> (down).</p>
<p>Return <code>true</code><em> if the robot returns to the origin after it finishes all of its moves, or </em><code>false</code><em> otherwise</em>.</p>
<p><strong>Note</strong>: The way that the robot is "facing" is irrelevant. <code>'R'</code> will always make the robot move to the right once, <code>'L'</code> will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> moves = "UD"
<strong>Output:</strong> true
<strong>Explanation</strong>: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> moves = "LL"
<strong>Output:</strong> false
<strong>Explanation</strong>: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= moves.length <= 2 * 10<sup>4</sup></code></li>
<li><code>moves</code> only contains the characters <code>'U'</code>, <code>'D'</code>, <code>'L'</code> and <code>'R'</code>.</li>
</ul>
|
String; Simulation
|
Java
|
class Solution {
public boolean judgeCircle(String moves) {
int x = 0, y = 0;
for (char c : moves.toCharArray()) {
switch (c) {
case 'U' -> y++;
case 'D' -> y--;
case 'L' -> x--;
case 'R' -> x++;
}
}
return x == 0 && y == 0;
}
}
|
657
|
Robot Return to Origin
|
Easy
|
<p>There is a robot starting at the position <code>(0, 0)</code>, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot <strong>ends up at </strong><code>(0, 0)</code> after it completes its moves.</p>
<p>You are given a string <code>moves</code> that represents the move sequence of the robot where <code>moves[i]</code> represents its <code>i<sup>th</sup></code> move. Valid moves are <code>'R'</code> (right), <code>'L'</code> (left), <code>'U'</code> (up), and <code>'D'</code> (down).</p>
<p>Return <code>true</code><em> if the robot returns to the origin after it finishes all of its moves, or </em><code>false</code><em> otherwise</em>.</p>
<p><strong>Note</strong>: The way that the robot is "facing" is irrelevant. <code>'R'</code> will always make the robot move to the right once, <code>'L'</code> will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> moves = "UD"
<strong>Output:</strong> true
<strong>Explanation</strong>: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> moves = "LL"
<strong>Output:</strong> false
<strong>Explanation</strong>: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= moves.length <= 2 * 10<sup>4</sup></code></li>
<li><code>moves</code> only contains the characters <code>'U'</code>, <code>'D'</code>, <code>'L'</code> and <code>'R'</code>.</li>
</ul>
|
String; Simulation
|
JavaScript
|
/**
* @param {string} moves
* @return {boolean}
*/
var judgeCircle = function (moves) {
let [x, y] = [0, 0];
for (const c of moves) {
if (c === 'U') {
y++;
} else if (c === 'D') {
y--;
} else if (c === 'L') {
x--;
} else {
x++;
}
}
return x === 0 && y === 0;
};
|
657
|
Robot Return to Origin
|
Easy
|
<p>There is a robot starting at the position <code>(0, 0)</code>, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot <strong>ends up at </strong><code>(0, 0)</code> after it completes its moves.</p>
<p>You are given a string <code>moves</code> that represents the move sequence of the robot where <code>moves[i]</code> represents its <code>i<sup>th</sup></code> move. Valid moves are <code>'R'</code> (right), <code>'L'</code> (left), <code>'U'</code> (up), and <code>'D'</code> (down).</p>
<p>Return <code>true</code><em> if the robot returns to the origin after it finishes all of its moves, or </em><code>false</code><em> otherwise</em>.</p>
<p><strong>Note</strong>: The way that the robot is "facing" is irrelevant. <code>'R'</code> will always make the robot move to the right once, <code>'L'</code> will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> moves = "UD"
<strong>Output:</strong> true
<strong>Explanation</strong>: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> moves = "LL"
<strong>Output:</strong> false
<strong>Explanation</strong>: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= moves.length <= 2 * 10<sup>4</sup></code></li>
<li><code>moves</code> only contains the characters <code>'U'</code>, <code>'D'</code>, <code>'L'</code> and <code>'R'</code>.</li>
</ul>
|
String; Simulation
|
Python
|
class Solution:
def judgeCircle(self, moves: str) -> bool:
x = y = 0
for c in moves:
match c:
case "U":
y += 1
case "D":
y -= 1
case "L":
x -= 1
case "R":
x += 1
return x == 0 and y == 0
|
657
|
Robot Return to Origin
|
Easy
|
<p>There is a robot starting at the position <code>(0, 0)</code>, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot <strong>ends up at </strong><code>(0, 0)</code> after it completes its moves.</p>
<p>You are given a string <code>moves</code> that represents the move sequence of the robot where <code>moves[i]</code> represents its <code>i<sup>th</sup></code> move. Valid moves are <code>'R'</code> (right), <code>'L'</code> (left), <code>'U'</code> (up), and <code>'D'</code> (down).</p>
<p>Return <code>true</code><em> if the robot returns to the origin after it finishes all of its moves, or </em><code>false</code><em> otherwise</em>.</p>
<p><strong>Note</strong>: The way that the robot is "facing" is irrelevant. <code>'R'</code> will always make the robot move to the right once, <code>'L'</code> will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> moves = "UD"
<strong>Output:</strong> true
<strong>Explanation</strong>: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> moves = "LL"
<strong>Output:</strong> false
<strong>Explanation</strong>: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= moves.length <= 2 * 10<sup>4</sup></code></li>
<li><code>moves</code> only contains the characters <code>'U'</code>, <code>'D'</code>, <code>'L'</code> and <code>'R'</code>.</li>
</ul>
|
String; Simulation
|
TypeScript
|
function judgeCircle(moves: string): boolean {
let [x, y] = [0, 0];
for (const c of moves) {
if (c === 'U') {
y++;
} else if (c === 'D') {
y--;
} else if (c === 'L') {
x--;
} else {
x++;
}
}
return x === 0 && y === 0;
}
|
658
|
Find K Closest Elements
|
Medium
|
<p>Given a <strong>sorted</strong> integer array <code>arr</code>, two integers <code>k</code> and <code>x</code>, return the <code>k</code> closest integers to <code>x</code> in the array. The result should also be sorted in ascending order.</p>
<p>An integer <code>a</code> is closer to <code>x</code> than an integer <code>b</code> if:</p>
<ul>
<li><code>|a - x| < |b - x|</code>, or</li>
<li><code>|a - x| == |b - x|</code> and <code>a < b</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,2,3,4,5], k = 4, x = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,1,2,3,4,5], k = 4, x = -1</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,2,3]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= arr.length</code></li>
<li><code>1 <= arr.length <= 10<sup>4</sup></code></li>
<li><code>arr</code> is sorted in <strong>ascending</strong> order.</li>
<li><code>-10<sup>4</sup> <= arr[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting; Sliding Window; Heap (Priority Queue)
|
C++
|
int target;
class Solution {
public:
static bool cmp(int& a, int& b) {
int v = abs(a - target) - abs(b - target);
return v == 0 ? a < b : v < 0;
}
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
target = x;
sort(arr.begin(), arr.end(), cmp);
vector<int> ans(arr.begin(), arr.begin() + k);
sort(ans.begin(), ans.end());
return ans;
}
};
|
658
|
Find K Closest Elements
|
Medium
|
<p>Given a <strong>sorted</strong> integer array <code>arr</code>, two integers <code>k</code> and <code>x</code>, return the <code>k</code> closest integers to <code>x</code> in the array. The result should also be sorted in ascending order.</p>
<p>An integer <code>a</code> is closer to <code>x</code> than an integer <code>b</code> if:</p>
<ul>
<li><code>|a - x| < |b - x|</code>, or</li>
<li><code>|a - x| == |b - x|</code> and <code>a < b</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,2,3,4,5], k = 4, x = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,1,2,3,4,5], k = 4, x = -1</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,2,3]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= arr.length</code></li>
<li><code>1 <= arr.length <= 10<sup>4</sup></code></li>
<li><code>arr</code> is sorted in <strong>ascending</strong> order.</li>
<li><code>-10<sup>4</sup> <= arr[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting; Sliding Window; Heap (Priority Queue)
|
Go
|
func findClosestElements(arr []int, k int, x int) []int {
sort.Slice(arr, func(i, j int) bool {
v := abs(arr[i]-x) - abs(arr[j]-x)
if v == 0 {
return arr[i] < arr[j]
}
return v < 0
})
ans := arr[:k]
sort.Ints(ans)
return ans
}
func abs(x int) int {
if x >= 0 {
return x
}
return -x
}
|
658
|
Find K Closest Elements
|
Medium
|
<p>Given a <strong>sorted</strong> integer array <code>arr</code>, two integers <code>k</code> and <code>x</code>, return the <code>k</code> closest integers to <code>x</code> in the array. The result should also be sorted in ascending order.</p>
<p>An integer <code>a</code> is closer to <code>x</code> than an integer <code>b</code> if:</p>
<ul>
<li><code>|a - x| < |b - x|</code>, or</li>
<li><code>|a - x| == |b - x|</code> and <code>a < b</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,2,3,4,5], k = 4, x = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,1,2,3,4,5], k = 4, x = -1</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,2,3]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= arr.length</code></li>
<li><code>1 <= arr.length <= 10<sup>4</sup></code></li>
<li><code>arr</code> is sorted in <strong>ascending</strong> order.</li>
<li><code>-10<sup>4</sup> <= arr[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting; Sliding Window; Heap (Priority Queue)
|
Java
|
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> ans = Arrays.stream(arr)
.boxed()
.sorted((a, b) -> {
int v = Math.abs(a - x) - Math.abs(b - x);
return v == 0 ? a - b : v;
})
.collect(Collectors.toList());
ans = ans.subList(0, k);
Collections.sort(ans);
return ans;
}
}
|
658
|
Find K Closest Elements
|
Medium
|
<p>Given a <strong>sorted</strong> integer array <code>arr</code>, two integers <code>k</code> and <code>x</code>, return the <code>k</code> closest integers to <code>x</code> in the array. The result should also be sorted in ascending order.</p>
<p>An integer <code>a</code> is closer to <code>x</code> than an integer <code>b</code> if:</p>
<ul>
<li><code>|a - x| < |b - x|</code>, or</li>
<li><code>|a - x| == |b - x|</code> and <code>a < b</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,2,3,4,5], k = 4, x = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,1,2,3,4,5], k = 4, x = -1</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,2,3]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= arr.length</code></li>
<li><code>1 <= arr.length <= 10<sup>4</sup></code></li>
<li><code>arr</code> is sorted in <strong>ascending</strong> order.</li>
<li><code>-10<sup>4</sup> <= arr[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting; Sliding Window; Heap (Priority Queue)
|
Python
|
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
arr.sort(key=lambda v: abs(v - x))
return sorted(arr[:k])
|
658
|
Find K Closest Elements
|
Medium
|
<p>Given a <strong>sorted</strong> integer array <code>arr</code>, two integers <code>k</code> and <code>x</code>, return the <code>k</code> closest integers to <code>x</code> in the array. The result should also be sorted in ascending order.</p>
<p>An integer <code>a</code> is closer to <code>x</code> than an integer <code>b</code> if:</p>
<ul>
<li><code>|a - x| < |b - x|</code>, or</li>
<li><code>|a - x| == |b - x|</code> and <code>a < b</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,2,3,4,5], k = 4, x = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,1,2,3,4,5], k = 4, x = -1</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,2,3]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= arr.length</code></li>
<li><code>1 <= arr.length <= 10<sup>4</sup></code></li>
<li><code>arr</code> is sorted in <strong>ascending</strong> order.</li>
<li><code>-10<sup>4</sup> <= arr[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting; Sliding Window; Heap (Priority Queue)
|
Rust
|
impl Solution {
pub fn find_closest_elements(arr: Vec<i32>, k: i32, x: i32) -> Vec<i32> {
let n = arr.len();
let mut l = 0;
let mut r = n;
while r - l != (k as usize) {
if x - arr[l] <= arr[r - 1] - x {
r -= 1;
} else {
l += 1;
}
}
arr[l..r].to_vec()
}
}
|
658
|
Find K Closest Elements
|
Medium
|
<p>Given a <strong>sorted</strong> integer array <code>arr</code>, two integers <code>k</code> and <code>x</code>, return the <code>k</code> closest integers to <code>x</code> in the array. The result should also be sorted in ascending order.</p>
<p>An integer <code>a</code> is closer to <code>x</code> than an integer <code>b</code> if:</p>
<ul>
<li><code>|a - x| < |b - x|</code>, or</li>
<li><code>|a - x| == |b - x|</code> and <code>a < b</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,2,3,4,5], k = 4, x = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">arr = [1,1,2,3,4,5], k = 4, x = -1</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,2,3]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= arr.length</code></li>
<li><code>1 <= arr.length <= 10<sup>4</sup></code></li>
<li><code>arr</code> is sorted in <strong>ascending</strong> order.</li>
<li><code>-10<sup>4</sup> <= arr[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting; Sliding Window; Heap (Priority Queue)
|
TypeScript
|
function findClosestElements(arr: number[], k: number, x: number): number[] {
let l = 0;
let r = arr.length;
while (r - l > k) {
if (x - arr[l] <= arr[r - 1] - x) {
--r;
} else {
++l;
}
}
return arr.slice(l, r);
}
|
659
|
Split Array into Consecutive Subsequences
|
Medium
|
<p>You are given an integer array <code>nums</code> that is <strong>sorted in non-decreasing order</strong>.</p>
<p>Determine if it is possible to split <code>nums</code> into <strong>one or more subsequences</strong> such that <strong>both</strong> of the following conditions are true:</p>
<ul>
<li>Each subsequence is a <strong>consecutive increasing sequence</strong> (i.e. each integer is <strong>exactly one</strong> more than the previous integer).</li>
<li>All subsequences have a length of <code>3</code><strong> or more</strong>.</li>
</ul>
<p>Return <code>true</code><em> if you can split </em><code>nums</code><em> according to the above conditions, or </em><code>false</code><em> otherwise</em>.</p>
<p>A <strong>subsequence</strong> of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., <code>[1,3,5]</code> is a subsequence of <code>[<u>1</u>,2,<u>3</u>,4,<u>5</u>]</code> while <code>[1,3,2]</code> is not).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,3,4,5]
<strong>Output:</strong> true
<strong>Explanation:</strong> nums can be split into the following subsequences:
[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,4,5] --> 1, 2, 3
[1,2,3,<strong><u>3</u></strong>,<strong><u>4</u></strong>,<strong><u>5</u></strong>] --> 3, 4, 5
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,3,4,4,5,5]
<strong>Output:</strong> true
<strong>Explanation:</strong> nums can be split into the following subsequences:
[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,<strong><u>4</u></strong>,4,<strong><u>5</u></strong>,5] --> 1, 2, 3, 4, 5
[1,2,3,<strong><u>3</u></strong>,4,<strong><u>4</u></strong>,5,<strong><u>5</u></strong>] --> 3, 4, 5
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,4,5]
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Greedy; Array; Hash Table; Heap (Priority Queue)
|
C++
|
class Solution {
public:
bool isPossible(vector<int>& nums) {
unordered_map<int, priority_queue<int, vector<int>, greater<int>>> d;
for (int v : nums) {
if (d.count(v - 1)) {
auto& q = d[v - 1];
d[v].push(q.top() + 1);
q.pop();
if (q.empty()) {
d.erase(v - 1);
}
} else {
d[v].push(1);
}
}
for (auto& [_, v] : d) {
if (v.top() < 3) {
return false;
}
}
return true;
}
};
|
659
|
Split Array into Consecutive Subsequences
|
Medium
|
<p>You are given an integer array <code>nums</code> that is <strong>sorted in non-decreasing order</strong>.</p>
<p>Determine if it is possible to split <code>nums</code> into <strong>one or more subsequences</strong> such that <strong>both</strong> of the following conditions are true:</p>
<ul>
<li>Each subsequence is a <strong>consecutive increasing sequence</strong> (i.e. each integer is <strong>exactly one</strong> more than the previous integer).</li>
<li>All subsequences have a length of <code>3</code><strong> or more</strong>.</li>
</ul>
<p>Return <code>true</code><em> if you can split </em><code>nums</code><em> according to the above conditions, or </em><code>false</code><em> otherwise</em>.</p>
<p>A <strong>subsequence</strong> of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., <code>[1,3,5]</code> is a subsequence of <code>[<u>1</u>,2,<u>3</u>,4,<u>5</u>]</code> while <code>[1,3,2]</code> is not).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,3,4,5]
<strong>Output:</strong> true
<strong>Explanation:</strong> nums can be split into the following subsequences:
[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,4,5] --> 1, 2, 3
[1,2,3,<strong><u>3</u></strong>,<strong><u>4</u></strong>,<strong><u>5</u></strong>] --> 3, 4, 5
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,3,4,4,5,5]
<strong>Output:</strong> true
<strong>Explanation:</strong> nums can be split into the following subsequences:
[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,<strong><u>4</u></strong>,4,<strong><u>5</u></strong>,5] --> 1, 2, 3, 4, 5
[1,2,3,<strong><u>3</u></strong>,4,<strong><u>4</u></strong>,5,<strong><u>5</u></strong>] --> 3, 4, 5
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,4,5]
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Greedy; Array; Hash Table; Heap (Priority Queue)
|
Go
|
func isPossible(nums []int) bool {
d := map[int]*hp{}
for _, v := range nums {
if d[v] == nil {
d[v] = new(hp)
}
if h := d[v-1]; h != nil {
heap.Push(d[v], heap.Pop(h).(int)+1)
if h.Len() == 0 {
delete(d, v-1)
}
} else {
heap.Push(d[v], 1)
}
}
for _, q := range d {
if q.IntSlice[0] < 3 {
return false
}
}
return true
}
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
}
|
659
|
Split Array into Consecutive Subsequences
|
Medium
|
<p>You are given an integer array <code>nums</code> that is <strong>sorted in non-decreasing order</strong>.</p>
<p>Determine if it is possible to split <code>nums</code> into <strong>one or more subsequences</strong> such that <strong>both</strong> of the following conditions are true:</p>
<ul>
<li>Each subsequence is a <strong>consecutive increasing sequence</strong> (i.e. each integer is <strong>exactly one</strong> more than the previous integer).</li>
<li>All subsequences have a length of <code>3</code><strong> or more</strong>.</li>
</ul>
<p>Return <code>true</code><em> if you can split </em><code>nums</code><em> according to the above conditions, or </em><code>false</code><em> otherwise</em>.</p>
<p>A <strong>subsequence</strong> of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., <code>[1,3,5]</code> is a subsequence of <code>[<u>1</u>,2,<u>3</u>,4,<u>5</u>]</code> while <code>[1,3,2]</code> is not).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,3,4,5]
<strong>Output:</strong> true
<strong>Explanation:</strong> nums can be split into the following subsequences:
[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,4,5] --> 1, 2, 3
[1,2,3,<strong><u>3</u></strong>,<strong><u>4</u></strong>,<strong><u>5</u></strong>] --> 3, 4, 5
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,3,4,4,5,5]
<strong>Output:</strong> true
<strong>Explanation:</strong> nums can be split into the following subsequences:
[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,<strong><u>4</u></strong>,4,<strong><u>5</u></strong>,5] --> 1, 2, 3, 4, 5
[1,2,3,<strong><u>3</u></strong>,4,<strong><u>4</u></strong>,5,<strong><u>5</u></strong>] --> 3, 4, 5
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,4,5]
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Greedy; Array; Hash Table; Heap (Priority Queue)
|
Java
|
class Solution {
public boolean isPossible(int[] nums) {
Map<Integer, PriorityQueue<Integer>> d = new HashMap<>();
for (int v : nums) {
if (d.containsKey(v - 1)) {
var q = d.get(v - 1);
d.computeIfAbsent(v, k -> new PriorityQueue<>()).offer(q.poll() + 1);
if (q.isEmpty()) {
d.remove(v - 1);
}
} else {
d.computeIfAbsent(v, k -> new PriorityQueue<>()).offer(1);
}
}
for (var v : d.values()) {
if (v.peek() < 3) {
return false;
}
}
return true;
}
}
|
659
|
Split Array into Consecutive Subsequences
|
Medium
|
<p>You are given an integer array <code>nums</code> that is <strong>sorted in non-decreasing order</strong>.</p>
<p>Determine if it is possible to split <code>nums</code> into <strong>one or more subsequences</strong> such that <strong>both</strong> of the following conditions are true:</p>
<ul>
<li>Each subsequence is a <strong>consecutive increasing sequence</strong> (i.e. each integer is <strong>exactly one</strong> more than the previous integer).</li>
<li>All subsequences have a length of <code>3</code><strong> or more</strong>.</li>
</ul>
<p>Return <code>true</code><em> if you can split </em><code>nums</code><em> according to the above conditions, or </em><code>false</code><em> otherwise</em>.</p>
<p>A <strong>subsequence</strong> of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., <code>[1,3,5]</code> is a subsequence of <code>[<u>1</u>,2,<u>3</u>,4,<u>5</u>]</code> while <code>[1,3,2]</code> is not).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,3,4,5]
<strong>Output:</strong> true
<strong>Explanation:</strong> nums can be split into the following subsequences:
[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,4,5] --> 1, 2, 3
[1,2,3,<strong><u>3</u></strong>,<strong><u>4</u></strong>,<strong><u>5</u></strong>] --> 3, 4, 5
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,3,4,4,5,5]
<strong>Output:</strong> true
<strong>Explanation:</strong> nums can be split into the following subsequences:
[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,<strong><u>4</u></strong>,4,<strong><u>5</u></strong>,5] --> 1, 2, 3, 4, 5
[1,2,3,<strong><u>3</u></strong>,4,<strong><u>4</u></strong>,5,<strong><u>5</u></strong>] --> 3, 4, 5
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,4,5]
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Greedy; Array; Hash Table; Heap (Priority Queue)
|
Python
|
class Solution:
def isPossible(self, nums: List[int]) -> bool:
d = defaultdict(list)
for v in nums:
if h := d[v - 1]:
heappush(d[v], heappop(h) + 1)
else:
heappush(d[v], 1)
return all(not v or v and v[0] > 2 for v in d.values())
|
661
|
Image Smoother
|
Easy
|
<p>An <strong>image smoother</strong> is a filter of the size <code>3 x 3</code> that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smoother-grid.jpg" style="width: 493px; height: 493px;" />
<p>Given an <code>m x n</code> integer matrix <code>img</code> representing the grayscale of an image, return <em>the image after applying the smoother on each cell of it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[1,1,1],[1,0,1],[1,1,1]]
<strong>Output:</strong> [[0,0,0],[0,0,0],[0,0,0]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth2-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[100,200,100],[200,50,200],[100,200,100]]
<strong>Output:</strong> [[137,141,137],[141,138,141],[137,141,137]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == img.length</code></li>
<li><code>n == img[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= img[i][j] <= 255</code></li>
</ul>
|
Array; Matrix
|
C++
|
class Solution {
public:
vector<vector<int>> imageSmoother(vector<vector<int>>& img) {
int m = img.size(), n = img[0].size();
vector<vector<int>> ans(m, vector<int>(n));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int s = 0, cnt = 0;
for (int x = i - 1; x <= i + 1; ++x) {
for (int y = j - 1; y <= j + 1; ++y) {
if (x < 0 || x >= m || y < 0 || y >= n) {
continue;
}
++cnt;
s += img[x][y];
}
}
ans[i][j] = s / cnt;
}
}
return ans;
}
};
|
661
|
Image Smoother
|
Easy
|
<p>An <strong>image smoother</strong> is a filter of the size <code>3 x 3</code> that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smoother-grid.jpg" style="width: 493px; height: 493px;" />
<p>Given an <code>m x n</code> integer matrix <code>img</code> representing the grayscale of an image, return <em>the image after applying the smoother on each cell of it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[1,1,1],[1,0,1],[1,1,1]]
<strong>Output:</strong> [[0,0,0],[0,0,0],[0,0,0]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth2-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[100,200,100],[200,50,200],[100,200,100]]
<strong>Output:</strong> [[137,141,137],[141,138,141],[137,141,137]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == img.length</code></li>
<li><code>n == img[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= img[i][j] <= 255</code></li>
</ul>
|
Array; Matrix
|
Go
|
func imageSmoother(img [][]int) [][]int {
m, n := len(img), len(img[0])
ans := make([][]int, m)
for i, row := range img {
ans[i] = make([]int, n)
for j := range row {
s, cnt := 0, 0
for x := i - 1; x <= i+1; x++ {
for y := j - 1; y <= j+1; y++ {
if x >= 0 && x < m && y >= 0 && y < n {
cnt++
s += img[x][y]
}
}
}
ans[i][j] = s / cnt
}
}
return ans
}
|
661
|
Image Smoother
|
Easy
|
<p>An <strong>image smoother</strong> is a filter of the size <code>3 x 3</code> that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smoother-grid.jpg" style="width: 493px; height: 493px;" />
<p>Given an <code>m x n</code> integer matrix <code>img</code> representing the grayscale of an image, return <em>the image after applying the smoother on each cell of it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[1,1,1],[1,0,1],[1,1,1]]
<strong>Output:</strong> [[0,0,0],[0,0,0],[0,0,0]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth2-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[100,200,100],[200,50,200],[100,200,100]]
<strong>Output:</strong> [[137,141,137],[141,138,141],[137,141,137]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == img.length</code></li>
<li><code>n == img[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= img[i][j] <= 255</code></li>
</ul>
|
Array; Matrix
|
Java
|
class Solution {
public int[][] imageSmoother(int[][] img) {
int m = img.length;
int n = img[0].length;
int[][] ans = new int[m][n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int s = 0;
int cnt = 0;
for (int x = i - 1; x <= i + 1; ++x) {
for (int y = j - 1; y <= j + 1; ++y) {
if (x >= 0 && x < m && y >= 0 && y < n) {
++cnt;
s += img[x][y];
}
}
}
ans[i][j] = s / cnt;
}
}
return ans;
}
}
|
661
|
Image Smoother
|
Easy
|
<p>An <strong>image smoother</strong> is a filter of the size <code>3 x 3</code> that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smoother-grid.jpg" style="width: 493px; height: 493px;" />
<p>Given an <code>m x n</code> integer matrix <code>img</code> representing the grayscale of an image, return <em>the image after applying the smoother on each cell of it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[1,1,1],[1,0,1],[1,1,1]]
<strong>Output:</strong> [[0,0,0],[0,0,0],[0,0,0]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth2-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[100,200,100],[200,50,200],[100,200,100]]
<strong>Output:</strong> [[137,141,137],[141,138,141],[137,141,137]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == img.length</code></li>
<li><code>n == img[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= img[i][j] <= 255</code></li>
</ul>
|
Array; Matrix
|
Python
|
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
m, n = len(img), len(img[0])
ans = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
s = cnt = 0
for x in range(i - 1, i + 2):
for y in range(j - 1, j + 2):
if 0 <= x < m and 0 <= y < n:
cnt += 1
s += img[x][y]
ans[i][j] = s // cnt
return ans
|
661
|
Image Smoother
|
Easy
|
<p>An <strong>image smoother</strong> is a filter of the size <code>3 x 3</code> that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smoother-grid.jpg" style="width: 493px; height: 493px;" />
<p>Given an <code>m x n</code> integer matrix <code>img</code> representing the grayscale of an image, return <em>the image after applying the smoother on each cell of it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[1,1,1],[1,0,1],[1,1,1]]
<strong>Output:</strong> [[0,0,0],[0,0,0],[0,0,0]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth2-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[100,200,100],[200,50,200],[100,200,100]]
<strong>Output:</strong> [[137,141,137],[141,138,141],[137,141,137]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == img.length</code></li>
<li><code>n == img[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= img[i][j] <= 255</code></li>
</ul>
|
Array; Matrix
|
Rust
|
impl Solution {
pub fn image_smoother(img: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let m = img.len();
let n = img[0].len();
let mut ans = vec![vec![0; n]; m];
for i in 0..m {
for j in 0..n {
let mut s = 0;
let mut cnt = 0;
for x in i.saturating_sub(1)..=(i + 1).min(m - 1) {
for y in j.saturating_sub(1)..=(j + 1).min(n - 1) {
s += img[x][y];
cnt += 1;
}
}
ans[i][j] = s / cnt;
}
}
ans
}
}
|
661
|
Image Smoother
|
Easy
|
<p>An <strong>image smoother</strong> is a filter of the size <code>3 x 3</code> that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smoother-grid.jpg" style="width: 493px; height: 493px;" />
<p>Given an <code>m x n</code> integer matrix <code>img</code> representing the grayscale of an image, return <em>the image after applying the smoother on each cell of it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[1,1,1],[1,0,1],[1,1,1]]
<strong>Output:</strong> [[0,0,0],[0,0,0],[0,0,0]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0661.Image%20Smoother/images/smooth2-grid.jpg" style="width: 613px; height: 253px;" />
<pre>
<strong>Input:</strong> img = [[100,200,100],[200,50,200],[100,200,100]]
<strong>Output:</strong> [[137,141,137],[141,138,141],[137,141,137]]
<strong>Explanation:</strong>
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == img.length</code></li>
<li><code>n == img[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= img[i][j] <= 255</code></li>
</ul>
|
Array; Matrix
|
TypeScript
|
function imageSmoother(img: number[][]): number[][] {
const m = img.length;
const n = img[0].length;
const ans: number[][] = Array.from({ length: m }, () => Array(n).fill(0));
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
let s = 0;
let cnt = 0;
for (let x = i - 1; x <= i + 1; ++x) {
for (let y = j - 1; y <= j + 1; ++y) {
if (x >= 0 && x < m && y >= 0 && y < n) {
++cnt;
s += img[x][y];
}
}
}
ans[i][j] = Math.floor(s / cnt);
}
}
return ans;
}
|
662
|
Maximum Width of Binary Tree
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <em>the <strong>maximum width</strong> of the given tree</em>.</p>
<p>The <strong>maximum width</strong> of a tree is the maximum <strong>width</strong> among all levels.</p>
<p>The <strong>width</strong> of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.</p>
<p>It is <strong>guaranteed</strong> that the answer will in the range of a <strong>32-bit</strong> signed integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/width1-tree.jpg" style="width: 359px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5,3,null,9]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The maximum width exists in the third level with length 4 (5,3,null,9).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/maximum-width-of-binary-tree-v3.jpg" style="width: 442px; height: 422px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5,null,null,9,6,null,7]
<strong>Output:</strong> 7
<strong>Explanation:</strong> The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/width3-tree.jpg" style="width: 289px; height: 299px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The maximum width exists in the second level with length 2 (3,2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 3000]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search; Binary Tree
|
C++
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
queue<pair<TreeNode*, int>> q;
q.push({root, 1});
int ans = 0;
while (!q.empty()) {
ans = max(ans, q.back().second - q.front().second + 1);
int i = q.front().second;
for (int n = q.size(); n; --n) {
auto p = q.front();
q.pop();
root = p.first;
int j = p.second;
if (root->left) q.push({root->left, (j << 1) - (i << 1)});
if (root->right) q.push({root->right, (j << 1 | 1) - (i << 1)});
}
}
return ans;
}
};
|
662
|
Maximum Width of Binary Tree
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <em>the <strong>maximum width</strong> of the given tree</em>.</p>
<p>The <strong>maximum width</strong> of a tree is the maximum <strong>width</strong> among all levels.</p>
<p>The <strong>width</strong> of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.</p>
<p>It is <strong>guaranteed</strong> that the answer will in the range of a <strong>32-bit</strong> signed integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/width1-tree.jpg" style="width: 359px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5,3,null,9]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The maximum width exists in the third level with length 4 (5,3,null,9).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/maximum-width-of-binary-tree-v3.jpg" style="width: 442px; height: 422px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5,null,null,9,6,null,7]
<strong>Output:</strong> 7
<strong>Explanation:</strong> The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/width3-tree.jpg" style="width: 289px; height: 299px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The maximum width exists in the second level with length 2 (3,2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 3000]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search; Binary Tree
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func widthOfBinaryTree(root *TreeNode) int {
q := []pair{{root, 1}}
ans := 0
for len(q) > 0 {
ans = max(ans, q[len(q)-1].i-q[0].i+1)
for n := len(q); n > 0; n-- {
p := q[0]
q = q[1:]
root = p.node
if root.Left != nil {
q = append(q, pair{root.Left, p.i << 1})
}
if root.Right != nil {
q = append(q, pair{root.Right, p.i<<1 | 1})
}
}
}
return ans
}
type pair struct {
node *TreeNode
i int
}
|
662
|
Maximum Width of Binary Tree
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <em>the <strong>maximum width</strong> of the given tree</em>.</p>
<p>The <strong>maximum width</strong> of a tree is the maximum <strong>width</strong> among all levels.</p>
<p>The <strong>width</strong> of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.</p>
<p>It is <strong>guaranteed</strong> that the answer will in the range of a <strong>32-bit</strong> signed integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/width1-tree.jpg" style="width: 359px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5,3,null,9]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The maximum width exists in the third level with length 4 (5,3,null,9).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/maximum-width-of-binary-tree-v3.jpg" style="width: 442px; height: 422px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5,null,null,9,6,null,7]
<strong>Output:</strong> 7
<strong>Explanation:</strong> The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/width3-tree.jpg" style="width: 289px; height: 299px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The maximum width exists in the second level with length 2 (3,2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 3000]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search; Binary Tree
|
Java
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int widthOfBinaryTree(TreeNode root) {
Deque<Pair<TreeNode, Integer>> q = new ArrayDeque<>();
q.offer(new Pair<>(root, 1));
int ans = 0;
while (!q.isEmpty()) {
ans = Math.max(ans, q.peekLast().getValue() - q.peekFirst().getValue() + 1);
for (int n = q.size(); n > 0; --n) {
var p = q.pollFirst();
root = p.getKey();
int i = p.getValue();
if (root.left != null) {
q.offer(new Pair<>(root.left, i << 1));
}
if (root.right != null) {
q.offer(new Pair<>(root.right, i << 1 | 1));
}
}
}
return ans;
}
}
|
662
|
Maximum Width of Binary Tree
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <em>the <strong>maximum width</strong> of the given tree</em>.</p>
<p>The <strong>maximum width</strong> of a tree is the maximum <strong>width</strong> among all levels.</p>
<p>The <strong>width</strong> of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.</p>
<p>It is <strong>guaranteed</strong> that the answer will in the range of a <strong>32-bit</strong> signed integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/width1-tree.jpg" style="width: 359px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5,3,null,9]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The maximum width exists in the third level with length 4 (5,3,null,9).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/maximum-width-of-binary-tree-v3.jpg" style="width: 442px; height: 422px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5,null,null,9,6,null,7]
<strong>Output:</strong> 7
<strong>Explanation:</strong> The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/images/width3-tree.jpg" style="width: 289px; height: 299px;" />
<pre>
<strong>Input:</strong> root = [1,3,2,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The maximum width exists in the second level with length 2 (3,2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 3000]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search; Binary Tree
|
Python
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
ans = 0
q = deque([(root, 1)])
while q:
ans = max(ans, q[-1][1] - q[0][1] + 1)
for _ in range(len(q)):
root, i = q.popleft()
if root.left:
q.append((root.left, i << 1))
if root.right:
q.append((root.right, i << 1 | 1))
return ans
|
663
|
Equal Tree Partition
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <code>true</code><em> if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0663.Equal%20Tree%20Partition/images/split1-tree.jpg" style="width: 500px; height: 204px;" />
<pre>
<strong>Input:</strong> root = [5,10,10,null,null,2,3]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0663.Equal%20Tree%20Partition/images/split2-tree.jpg" style="width: 277px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [1,2,10,null,null,2,20]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
C++
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> seen;
bool checkEqualTree(TreeNode* root) {
int s = sum(root);
if (s % 2 != 0) return false;
seen.pop_back();
return count(seen.begin(), seen.end(), s / 2);
}
int sum(TreeNode* root) {
if (!root) return 0;
int l = sum(root->left), r = sum(root->right);
int s = l + r + root->val;
seen.push_back(s);
return s;
}
};
|
663
|
Equal Tree Partition
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <code>true</code><em> if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0663.Equal%20Tree%20Partition/images/split1-tree.jpg" style="width: 500px; height: 204px;" />
<pre>
<strong>Input:</strong> root = [5,10,10,null,null,2,3]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0663.Equal%20Tree%20Partition/images/split2-tree.jpg" style="width: 277px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [1,2,10,null,null,2,20]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func checkEqualTree(root *TreeNode) bool {
var seen []int
var sum func(root *TreeNode) int
sum = func(root *TreeNode) int {
if root == nil {
return 0
}
l, r := sum(root.Left), sum(root.Right)
s := l + r + root.Val
seen = append(seen, s)
return s
}
s := sum(root)
if s%2 != 0 {
return false
}
seen = seen[:len(seen)-1]
for _, v := range seen {
if v == s/2 {
return true
}
}
return false
}
|
663
|
Equal Tree Partition
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <code>true</code><em> if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0663.Equal%20Tree%20Partition/images/split1-tree.jpg" style="width: 500px; height: 204px;" />
<pre>
<strong>Input:</strong> root = [5,10,10,null,null,2,3]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0663.Equal%20Tree%20Partition/images/split2-tree.jpg" style="width: 277px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [1,2,10,null,null,2,20]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
Java
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private List<Integer> seen;
public boolean checkEqualTree(TreeNode root) {
seen = new ArrayList<>();
int s = sum(root);
if (s % 2 != 0) {
return false;
}
seen.remove(seen.size() - 1);
return seen.contains(s / 2);
}
private int sum(TreeNode root) {
if (root == null) {
return 0;
}
int l = sum(root.left);
int r = sum(root.right);
int s = l + r + root.val;
seen.add(s);
return s;
}
}
|
663
|
Equal Tree Partition
|
Medium
|
<p>Given the <code>root</code> of a binary tree, return <code>true</code><em> if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0663.Equal%20Tree%20Partition/images/split1-tree.jpg" style="width: 500px; height: 204px;" />
<pre>
<strong>Input:</strong> root = [5,10,10,null,null,2,3]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0663.Equal%20Tree%20Partition/images/split2-tree.jpg" style="width: 277px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [1,2,10,null,null,2,20]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
Python
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def checkEqualTree(self, root: TreeNode) -> bool:
def sum(root):
if root is None:
return 0
l, r = sum(root.left), sum(root.right)
seen.append(l + r + root.val)
return seen[-1]
seen = []
s = sum(root)
if s % 2 == 1:
return False
seen.pop()
return s // 2 in seen
|
664
|
Strange Printer
|
Hard
|
<p>There is a strange printer with the following two special properties:</p>
<ul>
<li>The printer can only print a sequence of <strong>the same character</strong> each time.</li>
<li>At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.</li>
</ul>
<p>Given a string <code>s</code>, return <em>the minimum number of turns the printer needed to print it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaabbb"
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print "aaa" first and then print "bbb".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
C++
|
class Solution {
public:
int strangePrinter(string s) {
int n = s.size();
int f[n][n];
memset(f, 0x3f, sizeof(f));
for (int i = n - 1; ~i; --i) {
f[i][i] = 1;
for (int j = i + 1; j < n; ++j) {
if (s[i] == s[j]) {
f[i][j] = f[i][j - 1];
} else {
for (int k = i; k < j; ++k) {
f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j]);
}
}
}
}
return f[0][n - 1];
}
};
|
664
|
Strange Printer
|
Hard
|
<p>There is a strange printer with the following two special properties:</p>
<ul>
<li>The printer can only print a sequence of <strong>the same character</strong> each time.</li>
<li>At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.</li>
</ul>
<p>Given a string <code>s</code>, return <em>the minimum number of turns the printer needed to print it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaabbb"
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print "aaa" first and then print "bbb".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Go
|
func strangePrinter(s string) int {
n := len(s)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n)
for j := range f[i] {
f[i][j] = 1 << 30
}
}
for i := n - 1; i >= 0; i-- {
f[i][i] = 1
for j := i + 1; j < n; j++ {
if s[i] == s[j] {
f[i][j] = f[i][j-1]
} else {
for k := i; k < j; k++ {
f[i][j] = min(f[i][j], f[i][k]+f[k+1][j])
}
}
}
}
return f[0][n-1]
}
|
664
|
Strange Printer
|
Hard
|
<p>There is a strange printer with the following two special properties:</p>
<ul>
<li>The printer can only print a sequence of <strong>the same character</strong> each time.</li>
<li>At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.</li>
</ul>
<p>Given a string <code>s</code>, return <em>the minimum number of turns the printer needed to print it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaabbb"
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print "aaa" first and then print "bbb".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Java
|
class Solution {
public int strangePrinter(String s) {
final int inf = 1 << 30;
int n = s.length();
int[][] f = new int[n][n];
for (var g : f) {
Arrays.fill(g, inf);
}
for (int i = n - 1; i >= 0; --i) {
f[i][i] = 1;
for (int j = i + 1; j < n; ++j) {
if (s.charAt(i) == s.charAt(j)) {
f[i][j] = f[i][j - 1];
} else {
for (int k = i; k < j; ++k) {
f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j]);
}
}
}
}
return f[0][n - 1];
}
}
|
664
|
Strange Printer
|
Hard
|
<p>There is a strange printer with the following two special properties:</p>
<ul>
<li>The printer can only print a sequence of <strong>the same character</strong> each time.</li>
<li>At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.</li>
</ul>
<p>Given a string <code>s</code>, return <em>the minimum number of turns the printer needed to print it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaabbb"
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print "aaa" first and then print "bbb".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Python
|
class Solution:
def strangePrinter(self, s: str) -> int:
n = len(s)
f = [[inf] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
f[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
f[i][j] = f[i][j - 1]
else:
for k in range(i, j):
f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j])
return f[0][-1]
|
664
|
Strange Printer
|
Hard
|
<p>There is a strange printer with the following two special properties:</p>
<ul>
<li>The printer can only print a sequence of <strong>the same character</strong> each time.</li>
<li>At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.</li>
</ul>
<p>Given a string <code>s</code>, return <em>the minimum number of turns the printer needed to print it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaabbb"
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print "aaa" first and then print "bbb".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
TypeScript
|
function strangePrinter(s: string): number {
const n = s.length;
const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(1 << 30));
for (let i = n - 1; i >= 0; --i) {
f[i][i] = 1;
for (let j = i + 1; j < n; ++j) {
if (s[i] === s[j]) {
f[i][j] = f[i][j - 1];
} else {
for (let k = i; k < j; ++k) {
f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j]);
}
}
}
}
return f[0][n - 1];
}
|
665
|
Non-decreasing Array
|
Medium
|
<p>Given an array <code>nums</code> with <code>n</code> integers, your task is to check if it could become non-decreasing by modifying <strong>at most one element</strong>.</p>
<p>We define an array is non-decreasing if <code>nums[i] <= nums[i + 1]</code> holds for every <code>i</code> (<strong>0-based</strong>) such that (<code>0 <= i <= n - 2</code>).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,2,3]
<strong>Output:</strong> true
<strong>Explanation:</strong> You could modify the first 4 to 1 to get a non-decreasing array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,2,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot get a non-decreasing array by modifying at most one element.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
bool checkPossibility(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n - 1; ++i) {
int a = nums[i], b = nums[i + 1];
if (a > b) {
nums[i] = b;
if (is_sorted(nums.begin(), nums.end())) {
return true;
}
nums[i] = a;
nums[i + 1] = a;
return is_sorted(nums.begin(), nums.end());
}
}
return true;
}
};
|
665
|
Non-decreasing Array
|
Medium
|
<p>Given an array <code>nums</code> with <code>n</code> integers, your task is to check if it could become non-decreasing by modifying <strong>at most one element</strong>.</p>
<p>We define an array is non-decreasing if <code>nums[i] <= nums[i + 1]</code> holds for every <code>i</code> (<strong>0-based</strong>) such that (<code>0 <= i <= n - 2</code>).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,2,3]
<strong>Output:</strong> true
<strong>Explanation:</strong> You could modify the first 4 to 1 to get a non-decreasing array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,2,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot get a non-decreasing array by modifying at most one element.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Go
|
func checkPossibility(nums []int) bool {
isSorted := func(nums []int) bool {
for i, b := range nums[1:] {
if nums[i] > b {
return false
}
}
return true
}
for i := 0; i < len(nums)-1; i++ {
a, b := nums[i], nums[i+1]
if a > b {
nums[i] = b
if isSorted(nums) {
return true
}
nums[i] = a
nums[i+1] = a
return isSorted(nums)
}
}
return true
}
|
665
|
Non-decreasing Array
|
Medium
|
<p>Given an array <code>nums</code> with <code>n</code> integers, your task is to check if it could become non-decreasing by modifying <strong>at most one element</strong>.</p>
<p>We define an array is non-decreasing if <code>nums[i] <= nums[i + 1]</code> holds for every <code>i</code> (<strong>0-based</strong>) such that (<code>0 <= i <= n - 2</code>).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,2,3]
<strong>Output:</strong> true
<strong>Explanation:</strong> You could modify the first 4 to 1 to get a non-decreasing array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,2,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot get a non-decreasing array by modifying at most one element.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Java
|
class Solution {
public boolean checkPossibility(int[] nums) {
for (int i = 0; i < nums.length - 1; ++i) {
int a = nums[i], b = nums[i + 1];
if (a > b) {
nums[i] = b;
if (isSorted(nums)) {
return true;
}
nums[i] = a;
nums[i + 1] = a;
return isSorted(nums);
}
}
return true;
}
private boolean isSorted(int[] nums) {
for (int i = 0; i < nums.length - 1; ++i) {
if (nums[i] > nums[i + 1]) {
return false;
}
}
return true;
}
}
|
665
|
Non-decreasing Array
|
Medium
|
<p>Given an array <code>nums</code> with <code>n</code> integers, your task is to check if it could become non-decreasing by modifying <strong>at most one element</strong>.</p>
<p>We define an array is non-decreasing if <code>nums[i] <= nums[i + 1]</code> holds for every <code>i</code> (<strong>0-based</strong>) such that (<code>0 <= i <= n - 2</code>).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,2,3]
<strong>Output:</strong> true
<strong>Explanation:</strong> You could modify the first 4 to 1 to get a non-decreasing array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,2,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot get a non-decreasing array by modifying at most one element.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Python
|
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
def is_sorted(nums: List[int]) -> bool:
return all(a <= b for a, b in pairwise(nums))
n = len(nums)
for i in range(n - 1):
a, b = nums[i], nums[i + 1]
if a > b:
nums[i] = b
if is_sorted(nums):
return True
nums[i] = nums[i + 1] = a
return is_sorted(nums)
return True
|
665
|
Non-decreasing Array
|
Medium
|
<p>Given an array <code>nums</code> with <code>n</code> integers, your task is to check if it could become non-decreasing by modifying <strong>at most one element</strong>.</p>
<p>We define an array is non-decreasing if <code>nums[i] <= nums[i + 1]</code> holds for every <code>i</code> (<strong>0-based</strong>) such that (<code>0 <= i <= n - 2</code>).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,2,3]
<strong>Output:</strong> true
<strong>Explanation:</strong> You could modify the first 4 to 1 to get a non-decreasing array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,2,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot get a non-decreasing array by modifying at most one element.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
TypeScript
|
function checkPossibility(nums: number[]): boolean {
const isSorted = (nums: number[]) => {
for (let i = 0; i < nums.length - 1; ++i) {
if (nums[i] > nums[i + 1]) {
return false;
}
}
return true;
};
for (let i = 0; i < nums.length - 1; ++i) {
const a = nums[i],
b = nums[i + 1];
if (a > b) {
nums[i] = b;
if (isSorted(nums)) {
return true;
}
nums[i] = a;
nums[i + 1] = a;
return isSorted(nums);
}
}
return true;
}
|
666
|
Path Sum IV
|
Medium
|
<p>If the depth of a tree is smaller than <code>5</code>, then this tree can be represented by an array of three-digit integers. You are given an <strong>ascending </strong>array <code>nums</code> consisting of three-digit integers representing a binary tree with a depth smaller than <code>5</code>, where for each integer:</p>
<ul>
<li>The hundreds digit represents the depth <code>d</code> of this node, where <code>1 <= d <= 4</code>.</li>
<li>The tens digit represents the position <code>p</code> of this node within its level, where <code>1 <= p <= 8</code>, corresponding to its position in a <strong>full binary tree</strong>.</li>
<li>The units digit represents the value <code>v</code> of this node, where <code>0 <= v <= 9</code>.</li>
</ul>
<p>Return the <strong>sum</strong> of <strong>all paths</strong> from the <strong>root</strong> towards the <strong>leaves</strong>.</p>
<p>It is <strong>guaranteed</strong> that the given array represents a valid connected binary tree.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0666.Path%20Sum%20IV/images/pathsum4-1-tree.jpg" style="width: 212px; height: 183px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [113,215,221]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The tree that the list represents is shown.<br />
The path sum is (3 + 5) + (3 + 1) = 12.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0666.Path%20Sum%20IV/images/pathsum4-2-tree.jpg" style="width: 132px; height: 183px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [113,221]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The tree that the list represents is shown. <br />
The path sum is (3 + 1) = 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 15</code></li>
<li><code>110 <= nums[i] <= 489</code></li>
<li><code>nums</code> represents a valid binary tree with depth less than <code>5</code>.</li>
<li><code>nums</code> is sorted in ascending order.</li>
</ul>
|
Tree; Depth-First Search; Array; Hash Table; Binary Tree
|
C++
|
class Solution {
public:
int ans;
unordered_map<int, int> mp;
int pathSum(vector<int>& nums) {
ans = 0;
mp.clear();
for (int num : nums) mp[num / 10] = num % 10;
dfs(11, 0);
return ans;
}
void dfs(int node, int t) {
if (!mp.count(node)) return;
t += mp[node];
int d = node / 10, p = node % 10;
int l = (d + 1) * 10 + (p * 2) - 1;
int r = l + 1;
if (!mp.count(l) && !mp.count(r)) {
ans += t;
return;
}
dfs(l, t);
dfs(r, t);
}
};
|
666
|
Path Sum IV
|
Medium
|
<p>If the depth of a tree is smaller than <code>5</code>, then this tree can be represented by an array of three-digit integers. You are given an <strong>ascending </strong>array <code>nums</code> consisting of three-digit integers representing a binary tree with a depth smaller than <code>5</code>, where for each integer:</p>
<ul>
<li>The hundreds digit represents the depth <code>d</code> of this node, where <code>1 <= d <= 4</code>.</li>
<li>The tens digit represents the position <code>p</code> of this node within its level, where <code>1 <= p <= 8</code>, corresponding to its position in a <strong>full binary tree</strong>.</li>
<li>The units digit represents the value <code>v</code> of this node, where <code>0 <= v <= 9</code>.</li>
</ul>
<p>Return the <strong>sum</strong> of <strong>all paths</strong> from the <strong>root</strong> towards the <strong>leaves</strong>.</p>
<p>It is <strong>guaranteed</strong> that the given array represents a valid connected binary tree.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0666.Path%20Sum%20IV/images/pathsum4-1-tree.jpg" style="width: 212px; height: 183px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [113,215,221]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The tree that the list represents is shown.<br />
The path sum is (3 + 5) + (3 + 1) = 12.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0666.Path%20Sum%20IV/images/pathsum4-2-tree.jpg" style="width: 132px; height: 183px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [113,221]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The tree that the list represents is shown. <br />
The path sum is (3 + 1) = 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 15</code></li>
<li><code>110 <= nums[i] <= 489</code></li>
<li><code>nums</code> represents a valid binary tree with depth less than <code>5</code>.</li>
<li><code>nums</code> is sorted in ascending order.</li>
</ul>
|
Tree; Depth-First Search; Array; Hash Table; Binary Tree
|
Go
|
func pathSum(nums []int) int {
ans := 0
mp := make(map[int]int)
for _, num := range nums {
mp[num/10] = num % 10
}
var dfs func(node, t int)
dfs = func(node, t int) {
if v, ok := mp[node]; ok {
t += v
d, p := node/10, node%10
l := (d+1)*10 + (p * 2) - 1
r := l + 1
if _, ok1 := mp[l]; !ok1 {
if _, ok2 := mp[r]; !ok2 {
ans += t
return
}
}
dfs(l, t)
dfs(r, t)
}
}
dfs(11, 0)
return ans
}
|
666
|
Path Sum IV
|
Medium
|
<p>If the depth of a tree is smaller than <code>5</code>, then this tree can be represented by an array of three-digit integers. You are given an <strong>ascending </strong>array <code>nums</code> consisting of three-digit integers representing a binary tree with a depth smaller than <code>5</code>, where for each integer:</p>
<ul>
<li>The hundreds digit represents the depth <code>d</code> of this node, where <code>1 <= d <= 4</code>.</li>
<li>The tens digit represents the position <code>p</code> of this node within its level, where <code>1 <= p <= 8</code>, corresponding to its position in a <strong>full binary tree</strong>.</li>
<li>The units digit represents the value <code>v</code> of this node, where <code>0 <= v <= 9</code>.</li>
</ul>
<p>Return the <strong>sum</strong> of <strong>all paths</strong> from the <strong>root</strong> towards the <strong>leaves</strong>.</p>
<p>It is <strong>guaranteed</strong> that the given array represents a valid connected binary tree.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0666.Path%20Sum%20IV/images/pathsum4-1-tree.jpg" style="width: 212px; height: 183px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [113,215,221]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The tree that the list represents is shown.<br />
The path sum is (3 + 5) + (3 + 1) = 12.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0666.Path%20Sum%20IV/images/pathsum4-2-tree.jpg" style="width: 132px; height: 183px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [113,221]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The tree that the list represents is shown. <br />
The path sum is (3 + 1) = 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 15</code></li>
<li><code>110 <= nums[i] <= 489</code></li>
<li><code>nums</code> represents a valid binary tree with depth less than <code>5</code>.</li>
<li><code>nums</code> is sorted in ascending order.</li>
</ul>
|
Tree; Depth-First Search; Array; Hash Table; Binary Tree
|
Java
|
class Solution {
private int ans;
private Map<Integer, Integer> mp;
public int pathSum(int[] nums) {
ans = 0;
mp = new HashMap<>(nums.length);
for (int num : nums) {
mp.put(num / 10, num % 10);
}
dfs(11, 0);
return ans;
}
private void dfs(int node, int t) {
if (!mp.containsKey(node)) {
return;
}
t += mp.get(node);
int d = node / 10, p = node % 10;
int l = (d + 1) * 10 + (p * 2) - 1;
int r = l + 1;
if (!mp.containsKey(l) && !mp.containsKey(r)) {
ans += t;
return;
}
dfs(l, t);
dfs(r, t);
}
}
|
666
|
Path Sum IV
|
Medium
|
<p>If the depth of a tree is smaller than <code>5</code>, then this tree can be represented by an array of three-digit integers. You are given an <strong>ascending </strong>array <code>nums</code> consisting of three-digit integers representing a binary tree with a depth smaller than <code>5</code>, where for each integer:</p>
<ul>
<li>The hundreds digit represents the depth <code>d</code> of this node, where <code>1 <= d <= 4</code>.</li>
<li>The tens digit represents the position <code>p</code> of this node within its level, where <code>1 <= p <= 8</code>, corresponding to its position in a <strong>full binary tree</strong>.</li>
<li>The units digit represents the value <code>v</code> of this node, where <code>0 <= v <= 9</code>.</li>
</ul>
<p>Return the <strong>sum</strong> of <strong>all paths</strong> from the <strong>root</strong> towards the <strong>leaves</strong>.</p>
<p>It is <strong>guaranteed</strong> that the given array represents a valid connected binary tree.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0666.Path%20Sum%20IV/images/pathsum4-1-tree.jpg" style="width: 212px; height: 183px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [113,215,221]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The tree that the list represents is shown.<br />
The path sum is (3 + 5) + (3 + 1) = 12.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0666.Path%20Sum%20IV/images/pathsum4-2-tree.jpg" style="width: 132px; height: 183px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [113,221]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The tree that the list represents is shown. <br />
The path sum is (3 + 1) = 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 15</code></li>
<li><code>110 <= nums[i] <= 489</code></li>
<li><code>nums</code> represents a valid binary tree with depth less than <code>5</code>.</li>
<li><code>nums</code> is sorted in ascending order.</li>
</ul>
|
Tree; Depth-First Search; Array; Hash Table; Binary Tree
|
Python
|
class Solution:
def pathSum(self, nums: List[int]) -> int:
def dfs(node, t):
if node not in mp:
return
t += mp[node]
d, p = divmod(node, 10)
l = (d + 1) * 10 + (p * 2) - 1
r = l + 1
nonlocal ans
if l not in mp and r not in mp:
ans += t
return
dfs(l, t)
dfs(r, t)
ans = 0
mp = {num // 10: num % 10 for num in nums}
dfs(11, 0)
return ans
|
667
|
Beautiful Arrangement II
|
Medium
|
<p>Given two integers <code>n</code> and <code>k</code>, construct a list <code>answer</code> that contains <code>n</code> different positive integers ranging from <code>1</code> to <code>n</code> and obeys the following requirement:</p>
<ul>
<li>Suppose this list is <code>answer = [a<sub>1</sub>, a<sub>2</sub>, a<sub>3</sub>, ... , a<sub>n</sub>]</code>, then the list <code>[|a<sub>1</sub> - a<sub>2</sub>|, |a<sub>2</sub> - a<sub>3</sub>|, |a<sub>3</sub> - a<sub>4</sub>|, ... , |a<sub>n-1</sub> - a<sub>n</sub>|]</code> has exactly <code>k</code> distinct integers.</li>
</ul>
<p>Return <em>the list</em> <code>answer</code>. If there multiple valid answers, return <strong>any of them</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> [1,2,3]
Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 2
<strong>Output:</strong> [1,3,2]
Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k < n <= 10<sup>4</sup></code></li>
</ul>
|
Array; Math
|
C++
|
class Solution {
public:
vector<int> constructArray(int n, int k) {
int l = 1, r = n;
vector<int> ans(n);
for (int i = 0; i < k; ++i) {
ans[i] = i % 2 == 0 ? l++ : r--;
}
for (int i = k; i < n; ++i) {
ans[i] = k % 2 == 0 ? r-- : l++;
}
return ans;
}
};
|
667
|
Beautiful Arrangement II
|
Medium
|
<p>Given two integers <code>n</code> and <code>k</code>, construct a list <code>answer</code> that contains <code>n</code> different positive integers ranging from <code>1</code> to <code>n</code> and obeys the following requirement:</p>
<ul>
<li>Suppose this list is <code>answer = [a<sub>1</sub>, a<sub>2</sub>, a<sub>3</sub>, ... , a<sub>n</sub>]</code>, then the list <code>[|a<sub>1</sub> - a<sub>2</sub>|, |a<sub>2</sub> - a<sub>3</sub>|, |a<sub>3</sub> - a<sub>4</sub>|, ... , |a<sub>n-1</sub> - a<sub>n</sub>|]</code> has exactly <code>k</code> distinct integers.</li>
</ul>
<p>Return <em>the list</em> <code>answer</code>. If there multiple valid answers, return <strong>any of them</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> [1,2,3]
Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 2
<strong>Output:</strong> [1,3,2]
Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k < n <= 10<sup>4</sup></code></li>
</ul>
|
Array; Math
|
Go
|
func constructArray(n int, k int) []int {
l, r := 1, n
ans := make([]int, n)
for i := 0; i < k; i++ {
if i%2 == 0 {
ans[i] = l
l++
} else {
ans[i] = r
r--
}
}
for i := k; i < n; i++ {
if k%2 == 0 {
ans[i] = r
r--
} else {
ans[i] = l
l++
}
}
return ans
}
|
667
|
Beautiful Arrangement II
|
Medium
|
<p>Given two integers <code>n</code> and <code>k</code>, construct a list <code>answer</code> that contains <code>n</code> different positive integers ranging from <code>1</code> to <code>n</code> and obeys the following requirement:</p>
<ul>
<li>Suppose this list is <code>answer = [a<sub>1</sub>, a<sub>2</sub>, a<sub>3</sub>, ... , a<sub>n</sub>]</code>, then the list <code>[|a<sub>1</sub> - a<sub>2</sub>|, |a<sub>2</sub> - a<sub>3</sub>|, |a<sub>3</sub> - a<sub>4</sub>|, ... , |a<sub>n-1</sub> - a<sub>n</sub>|]</code> has exactly <code>k</code> distinct integers.</li>
</ul>
<p>Return <em>the list</em> <code>answer</code>. If there multiple valid answers, return <strong>any of them</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> [1,2,3]
Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 2
<strong>Output:</strong> [1,3,2]
Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k < n <= 10<sup>4</sup></code></li>
</ul>
|
Array; Math
|
Java
|
class Solution {
public int[] constructArray(int n, int k) {
int l = 1, r = n;
int[] ans = new int[n];
for (int i = 0; i < k; ++i) {
ans[i] = i % 2 == 0 ? l++ : r--;
}
for (int i = k; i < n; ++i) {
ans[i] = k % 2 == 0 ? r-- : l++;
}
return ans;
}
}
|
667
|
Beautiful Arrangement II
|
Medium
|
<p>Given two integers <code>n</code> and <code>k</code>, construct a list <code>answer</code> that contains <code>n</code> different positive integers ranging from <code>1</code> to <code>n</code> and obeys the following requirement:</p>
<ul>
<li>Suppose this list is <code>answer = [a<sub>1</sub>, a<sub>2</sub>, a<sub>3</sub>, ... , a<sub>n</sub>]</code>, then the list <code>[|a<sub>1</sub> - a<sub>2</sub>|, |a<sub>2</sub> - a<sub>3</sub>|, |a<sub>3</sub> - a<sub>4</sub>|, ... , |a<sub>n-1</sub> - a<sub>n</sub>|]</code> has exactly <code>k</code> distinct integers.</li>
</ul>
<p>Return <em>the list</em> <code>answer</code>. If there multiple valid answers, return <strong>any of them</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> [1,2,3]
Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 2
<strong>Output:</strong> [1,3,2]
Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k < n <= 10<sup>4</sup></code></li>
</ul>
|
Array; Math
|
Python
|
class Solution:
def constructArray(self, n: int, k: int) -> List[int]:
l, r = 1, n
ans = []
for i in range(k):
if i % 2 == 0:
ans.append(l)
l += 1
else:
ans.append(r)
r -= 1
for i in range(k, n):
if k % 2 == 0:
ans.append(r)
r -= 1
else:
ans.append(l)
l += 1
return ans
|
667
|
Beautiful Arrangement II
|
Medium
|
<p>Given two integers <code>n</code> and <code>k</code>, construct a list <code>answer</code> that contains <code>n</code> different positive integers ranging from <code>1</code> to <code>n</code> and obeys the following requirement:</p>
<ul>
<li>Suppose this list is <code>answer = [a<sub>1</sub>, a<sub>2</sub>, a<sub>3</sub>, ... , a<sub>n</sub>]</code>, then the list <code>[|a<sub>1</sub> - a<sub>2</sub>|, |a<sub>2</sub> - a<sub>3</sub>|, |a<sub>3</sub> - a<sub>4</sub>|, ... , |a<sub>n-1</sub> - a<sub>n</sub>|]</code> has exactly <code>k</code> distinct integers.</li>
</ul>
<p>Return <em>the list</em> <code>answer</code>. If there multiple valid answers, return <strong>any of them</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> [1,2,3]
Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, k = 2
<strong>Output:</strong> [1,3,2]
Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k < n <= 10<sup>4</sup></code></li>
</ul>
|
Array; Math
|
TypeScript
|
function constructArray(n: number, k: number): number[] {
let l = 1;
let r = n;
const ans = new Array(n);
for (let i = 0; i < k; ++i) {
ans[i] = i % 2 == 0 ? l++ : r--;
}
for (let i = k; i < n; ++i) {
ans[i] = k % 2 == 0 ? r-- : l++;
}
return ans;
}
|
668
|
Kth Smallest Number in Multiplication Table
|
Hard
|
<p>Nearly everyone has used the <a href="https://en.wikipedia.org/wiki/Multiplication_table" target="_blank">Multiplication Table</a>. The multiplication table of size <code>m x n</code> is an integer matrix <code>mat</code> where <code>mat[i][j] == i * j</code> (<strong>1-indexed</strong>).</p>
<p>Given three integers <code>m</code>, <code>n</code>, and <code>k</code>, return <em>the </em><code>k<sup>th</sup></code><em> smallest element in the </em><code>m x n</code><em> multiplication table</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0668.Kth%20Smallest%20Number%20in%20Multiplication%20Table/images/multtable1-grid.jpg" style="width: 500px; height: 254px;" />
<pre>
<strong>Input:</strong> m = 3, n = 3, k = 5
<strong>Output:</strong> 3
<strong>Explanation:</strong> The 5<sup>th</sup> smallest number is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0668.Kth%20Smallest%20Number%20in%20Multiplication%20Table/images/multtable2-grid.jpg" style="width: 493px; height: 293px;" />
<pre>
<strong>Input:</strong> m = 2, n = 3, k = 6
<strong>Output:</strong> 6
<strong>Explanation:</strong> The 6<sup>th</sup> smallest number is 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= m * n</code></li>
</ul>
|
Math; Binary Search
|
C++
|
class Solution {
public:
int findKthNumber(int m, int n, int k) {
int left = 1, right = m * n;
while (left < right) {
int mid = (left + right) >> 1;
int cnt = 0;
for (int i = 1; i <= m; ++i) cnt += min(mid / i, n);
if (cnt >= k)
right = mid;
else
left = mid + 1;
}
return left;
}
};
|
668
|
Kth Smallest Number in Multiplication Table
|
Hard
|
<p>Nearly everyone has used the <a href="https://en.wikipedia.org/wiki/Multiplication_table" target="_blank">Multiplication Table</a>. The multiplication table of size <code>m x n</code> is an integer matrix <code>mat</code> where <code>mat[i][j] == i * j</code> (<strong>1-indexed</strong>).</p>
<p>Given three integers <code>m</code>, <code>n</code>, and <code>k</code>, return <em>the </em><code>k<sup>th</sup></code><em> smallest element in the </em><code>m x n</code><em> multiplication table</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0668.Kth%20Smallest%20Number%20in%20Multiplication%20Table/images/multtable1-grid.jpg" style="width: 500px; height: 254px;" />
<pre>
<strong>Input:</strong> m = 3, n = 3, k = 5
<strong>Output:</strong> 3
<strong>Explanation:</strong> The 5<sup>th</sup> smallest number is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0668.Kth%20Smallest%20Number%20in%20Multiplication%20Table/images/multtable2-grid.jpg" style="width: 493px; height: 293px;" />
<pre>
<strong>Input:</strong> m = 2, n = 3, k = 6
<strong>Output:</strong> 6
<strong>Explanation:</strong> The 6<sup>th</sup> smallest number is 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= m * n</code></li>
</ul>
|
Math; Binary Search
|
Go
|
func findKthNumber(m int, n int, k int) int {
left, right := 1, m*n
for left < right {
mid := (left + right) >> 1
cnt := 0
for i := 1; i <= m; i++ {
cnt += min(mid/i, n)
}
if cnt >= k {
right = mid
} else {
left = mid + 1
}
}
return left
}
|
668
|
Kth Smallest Number in Multiplication Table
|
Hard
|
<p>Nearly everyone has used the <a href="https://en.wikipedia.org/wiki/Multiplication_table" target="_blank">Multiplication Table</a>. The multiplication table of size <code>m x n</code> is an integer matrix <code>mat</code> where <code>mat[i][j] == i * j</code> (<strong>1-indexed</strong>).</p>
<p>Given three integers <code>m</code>, <code>n</code>, and <code>k</code>, return <em>the </em><code>k<sup>th</sup></code><em> smallest element in the </em><code>m x n</code><em> multiplication table</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0668.Kth%20Smallest%20Number%20in%20Multiplication%20Table/images/multtable1-grid.jpg" style="width: 500px; height: 254px;" />
<pre>
<strong>Input:</strong> m = 3, n = 3, k = 5
<strong>Output:</strong> 3
<strong>Explanation:</strong> The 5<sup>th</sup> smallest number is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0668.Kth%20Smallest%20Number%20in%20Multiplication%20Table/images/multtable2-grid.jpg" style="width: 493px; height: 293px;" />
<pre>
<strong>Input:</strong> m = 2, n = 3, k = 6
<strong>Output:</strong> 6
<strong>Explanation:</strong> The 6<sup>th</sup> smallest number is 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= m * n</code></li>
</ul>
|
Math; Binary Search
|
Java
|
class Solution {
public int findKthNumber(int m, int n, int k) {
int left = 1, right = m * n;
while (left < right) {
int mid = (left + right) >>> 1;
int cnt = 0;
for (int i = 1; i <= m; ++i) {
cnt += Math.min(mid / i, n);
}
if (cnt >= k) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
|
668
|
Kth Smallest Number in Multiplication Table
|
Hard
|
<p>Nearly everyone has used the <a href="https://en.wikipedia.org/wiki/Multiplication_table" target="_blank">Multiplication Table</a>. The multiplication table of size <code>m x n</code> is an integer matrix <code>mat</code> where <code>mat[i][j] == i * j</code> (<strong>1-indexed</strong>).</p>
<p>Given three integers <code>m</code>, <code>n</code>, and <code>k</code>, return <em>the </em><code>k<sup>th</sup></code><em> smallest element in the </em><code>m x n</code><em> multiplication table</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0668.Kth%20Smallest%20Number%20in%20Multiplication%20Table/images/multtable1-grid.jpg" style="width: 500px; height: 254px;" />
<pre>
<strong>Input:</strong> m = 3, n = 3, k = 5
<strong>Output:</strong> 3
<strong>Explanation:</strong> The 5<sup>th</sup> smallest number is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0668.Kth%20Smallest%20Number%20in%20Multiplication%20Table/images/multtable2-grid.jpg" style="width: 493px; height: 293px;" />
<pre>
<strong>Input:</strong> m = 2, n = 3, k = 6
<strong>Output:</strong> 6
<strong>Explanation:</strong> The 6<sup>th</sup> smallest number is 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= m * n</code></li>
</ul>
|
Math; Binary Search
|
Python
|
class Solution:
def findKthNumber(self, m: int, n: int, k: int) -> int:
left, right = 1, m * n
while left < right:
mid = (left + right) >> 1
cnt = 0
for i in range(1, m + 1):
cnt += min(mid // i, n)
if cnt >= k:
right = mid
else:
left = mid + 1
return left
|
669
|
Trim a Binary Search Tree
|
Medium
|
<p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a <strong>unique answer</strong>.</p>
<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim1.jpg" style="width: 450px; height: 126px;" />
<pre>
<strong>Input:</strong> root = [1,0,2], low = 1, high = 2
<strong>Output:</strong> [1,null,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim2.jpg" style="width: 450px; height: 277px;" />
<pre>
<strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3
<strong>Output:</strong> [3,2,null,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>0 <= Node.val <= 10<sup>4</sup></code></li>
<li>The value of each node in the tree is <strong>unique</strong>.</li>
<li><code>root</code> is guaranteed to be a valid binary search tree.</li>
<li><code>0 <= low <= high <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Search Tree; Binary Tree
|
C
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* trimBST(struct TreeNode* root, int low, int high) {
if (!root) {
return root;
}
if (root->val < low) {
return trimBST(root->right, low, high);
}
if (root->val > high) {
return trimBST(root->left, low, high);
}
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
|
669
|
Trim a Binary Search Tree
|
Medium
|
<p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a <strong>unique answer</strong>.</p>
<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim1.jpg" style="width: 450px; height: 126px;" />
<pre>
<strong>Input:</strong> root = [1,0,2], low = 1, high = 2
<strong>Output:</strong> [1,null,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim2.jpg" style="width: 450px; height: 277px;" />
<pre>
<strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3
<strong>Output:</strong> [3,2,null,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>0 <= Node.val <= 10<sup>4</sup></code></li>
<li>The value of each node in the tree is <strong>unique</strong>.</li>
<li><code>root</code> is guaranteed to be a valid binary search tree.</li>
<li><code>0 <= low <= high <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Search Tree; Binary Tree
|
C++
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (!root) return root;
if (root->val > high) return trimBST(root->left, low, high);
if (root->val < low) return trimBST(root->right, low, high);
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};
|
669
|
Trim a Binary Search Tree
|
Medium
|
<p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a <strong>unique answer</strong>.</p>
<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim1.jpg" style="width: 450px; height: 126px;" />
<pre>
<strong>Input:</strong> root = [1,0,2], low = 1, high = 2
<strong>Output:</strong> [1,null,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim2.jpg" style="width: 450px; height: 277px;" />
<pre>
<strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3
<strong>Output:</strong> [3,2,null,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>0 <= Node.val <= 10<sup>4</sup></code></li>
<li>The value of each node in the tree is <strong>unique</strong>.</li>
<li><code>root</code> is guaranteed to be a valid binary search tree.</li>
<li><code>0 <= low <= high <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Search Tree; Binary Tree
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func trimBST(root *TreeNode, low int, high int) *TreeNode {
if root == nil {
return root
}
if root.Val > high {
return trimBST(root.Left, low, high)
}
if root.Val < low {
return trimBST(root.Right, low, high)
}
root.Left = trimBST(root.Left, low, high)
root.Right = trimBST(root.Right, low, high)
return root
}
|
669
|
Trim a Binary Search Tree
|
Medium
|
<p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a <strong>unique answer</strong>.</p>
<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim1.jpg" style="width: 450px; height: 126px;" />
<pre>
<strong>Input:</strong> root = [1,0,2], low = 1, high = 2
<strong>Output:</strong> [1,null,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim2.jpg" style="width: 450px; height: 277px;" />
<pre>
<strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3
<strong>Output:</strong> [3,2,null,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>0 <= Node.val <= 10<sup>4</sup></code></li>
<li>The value of each node in the tree is <strong>unique</strong>.</li>
<li><code>root</code> is guaranteed to be a valid binary search tree.</li>
<li><code>0 <= low <= high <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Search Tree; Binary Tree
|
Java
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return root;
}
if (root.val > high) {
return trimBST(root.left, low, high);
}
if (root.val < low) {
return trimBST(root.right, low, high);
}
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
|
669
|
Trim a Binary Search Tree
|
Medium
|
<p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a <strong>unique answer</strong>.</p>
<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim1.jpg" style="width: 450px; height: 126px;" />
<pre>
<strong>Input:</strong> root = [1,0,2], low = 1, high = 2
<strong>Output:</strong> [1,null,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim2.jpg" style="width: 450px; height: 277px;" />
<pre>
<strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3
<strong>Output:</strong> [3,2,null,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>0 <= Node.val <= 10<sup>4</sup></code></li>
<li>The value of each node in the tree is <strong>unique</strong>.</li>
<li><code>root</code> is guaranteed to be a valid binary search tree.</li>
<li><code>0 <= low <= high <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Search Tree; Binary Tree
|
JavaScript
|
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} low
* @param {number} high
* @return {TreeNode}
*/
var trimBST = function (root, low, high) {
function dfs(root) {
if (!root) {
return root;
}
if (root.val < low) {
return dfs(root.right);
}
if (root.val > high) {
return dfs(root.left);
}
root.left = dfs(root.left);
root.right = dfs(root.right);
return root;
}
return dfs(root);
};
|
669
|
Trim a Binary Search Tree
|
Medium
|
<p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a <strong>unique answer</strong>.</p>
<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim1.jpg" style="width: 450px; height: 126px;" />
<pre>
<strong>Input:</strong> root = [1,0,2], low = 1, high = 2
<strong>Output:</strong> [1,null,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim2.jpg" style="width: 450px; height: 277px;" />
<pre>
<strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3
<strong>Output:</strong> [3,2,null,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>0 <= Node.val <= 10<sup>4</sup></code></li>
<li>The value of each node in the tree is <strong>unique</strong>.</li>
<li><code>root</code> is guaranteed to be a valid binary search tree.</li>
<li><code>0 <= low <= high <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Search Tree; Binary Tree
|
Python
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def trimBST(
self, root: Optional[TreeNode], low: int, high: int
) -> Optional[TreeNode]:
def dfs(root):
if root is None:
return root
if root.val > high:
return dfs(root.left)
if root.val < low:
return dfs(root.right)
root.left = dfs(root.left)
root.right = dfs(root.right)
return root
return dfs(root)
|
669
|
Trim a Binary Search Tree
|
Medium
|
<p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a <strong>unique answer</strong>.</p>
<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim1.jpg" style="width: 450px; height: 126px;" />
<pre>
<strong>Input:</strong> root = [1,0,2], low = 1, high = 2
<strong>Output:</strong> [1,null,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim2.jpg" style="width: 450px; height: 277px;" />
<pre>
<strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3
<strong>Output:</strong> [3,2,null,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>0 <= Node.val <= 10<sup>4</sup></code></li>
<li>The value of each node in the tree is <strong>unique</strong>.</li>
<li><code>root</code> is guaranteed to be a valid binary search tree.</li>
<li><code>0 <= low <= high <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Search Tree; Binary Tree
|
Rust
|
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn trim_bst(
mut root: Option<Rc<RefCell<TreeNode>>>,
low: i32,
high: i32,
) -> Option<Rc<RefCell<TreeNode>>> {
if root.is_none() {
return root;
}
{
let mut node = root.as_mut().unwrap().borrow_mut();
if node.val < low {
return Self::trim_bst(node.right.take(), low, high);
}
if node.val > high {
return Self::trim_bst(node.left.take(), low, high);
}
node.left = Self::trim_bst(node.left.take(), low, high);
node.right = Self::trim_bst(node.right.take(), low, high);
}
root
}
}
|
669
|
Trim a Binary Search Tree
|
Medium
|
<p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a <strong>unique answer</strong>.</p>
<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim1.jpg" style="width: 450px; height: 126px;" />
<pre>
<strong>Input:</strong> root = [1,0,2], low = 1, high = 2
<strong>Output:</strong> [1,null,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/images/trim2.jpg" style="width: 450px; height: 277px;" />
<pre>
<strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3
<strong>Output:</strong> [3,2,null,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
<li><code>0 <= Node.val <= 10<sup>4</sup></code></li>
<li>The value of each node in the tree is <strong>unique</strong>.</li>
<li><code>root</code> is guaranteed to be a valid binary search tree.</li>
<li><code>0 <= low <= high <= 10<sup>4</sup></code></li>
</ul>
|
Tree; Depth-First Search; Binary Search Tree; Binary Tree
|
TypeScript
|
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {
const dfs = (root: TreeNode | null) => {
if (root == null) {
return root;
}
const { val, left, right } = root;
if (val < low || val > high) {
return dfs(left) || dfs(right);
}
root.left = dfs(left);
root.right = dfs(right);
return root;
};
return dfs(root);
}
|
670
|
Maximum Swap
|
Medium
|
<p>You are given an integer <code>num</code>. You can swap two digits at most once to get the maximum valued number.</p>
<p>Return <em>the maximum valued number you can get</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 2736
<strong>Output:</strong> 7236
<strong>Explanation:</strong> Swap the number 2 and the number 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 9973
<strong>Output:</strong> 9973
<strong>Explanation:</strong> No swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= num <= 10<sup>8</sup></code></li>
</ul>
|
Greedy; Math
|
C++
|
class Solution {
public:
int maximumSwap(int num) {
string s = to_string(num);
int n = s.size();
vector<int> d(n);
iota(d.begin(), d.end(), 0);
for (int i = n - 2; ~i; --i) {
if (s[i] <= s[d[i + 1]]) {
d[i] = d[i + 1];
}
}
for (int i = 0; i < n; ++i) {
int j = d[i];
if (s[i] < s[j]) {
swap(s[i], s[j]);
break;
}
}
return stoi(s);
}
};
|
670
|
Maximum Swap
|
Medium
|
<p>You are given an integer <code>num</code>. You can swap two digits at most once to get the maximum valued number.</p>
<p>Return <em>the maximum valued number you can get</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 2736
<strong>Output:</strong> 7236
<strong>Explanation:</strong> Swap the number 2 and the number 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 9973
<strong>Output:</strong> 9973
<strong>Explanation:</strong> No swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= num <= 10<sup>8</sup></code></li>
</ul>
|
Greedy; Math
|
Go
|
func maximumSwap(num int) int {
s := []byte(strconv.Itoa(num))
n := len(s)
d := make([]int, n)
for i := range d {
d[i] = i
}
for i := n - 2; i >= 0; i-- {
if s[i] <= s[d[i+1]] {
d[i] = d[i+1]
}
}
for i, j := range d {
if s[i] < s[j] {
s[i], s[j] = s[j], s[i]
break
}
}
ans, _ := strconv.Atoi(string(s))
return ans
}
|
670
|
Maximum Swap
|
Medium
|
<p>You are given an integer <code>num</code>. You can swap two digits at most once to get the maximum valued number.</p>
<p>Return <em>the maximum valued number you can get</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 2736
<strong>Output:</strong> 7236
<strong>Explanation:</strong> Swap the number 2 and the number 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 9973
<strong>Output:</strong> 9973
<strong>Explanation:</strong> No swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= num <= 10<sup>8</sup></code></li>
</ul>
|
Greedy; Math
|
Java
|
class Solution {
public int maximumSwap(int num) {
char[] s = String.valueOf(num).toCharArray();
int n = s.length;
int[] d = new int[n];
for (int i = 0; i < n; ++i) {
d[i] = i;
}
for (int i = n - 2; i >= 0; --i) {
if (s[i] <= s[d[i + 1]]) {
d[i] = d[i + 1];
}
}
for (int i = 0; i < n; ++i) {
int j = d[i];
if (s[i] < s[j]) {
char t = s[i];
s[i] = s[j];
s[j] = t;
break;
}
}
return Integer.parseInt(String.valueOf(s));
}
}
|
670
|
Maximum Swap
|
Medium
|
<p>You are given an integer <code>num</code>. You can swap two digits at most once to get the maximum valued number.</p>
<p>Return <em>the maximum valued number you can get</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 2736
<strong>Output:</strong> 7236
<strong>Explanation:</strong> Swap the number 2 and the number 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 9973
<strong>Output:</strong> 9973
<strong>Explanation:</strong> No swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= num <= 10<sup>8</sup></code></li>
</ul>
|
Greedy; Math
|
Python
|
class Solution:
def maximumSwap(self, num: int) -> int:
s = list(str(num))
n = len(s)
d = list(range(n))
for i in range(n - 2, -1, -1):
if s[i] <= s[d[i + 1]]:
d[i] = d[i + 1]
for i, j in enumerate(d):
if s[i] < s[j]:
s[i], s[j] = s[j], s[i]
break
return int(''.join(s))
|
670
|
Maximum Swap
|
Medium
|
<p>You are given an integer <code>num</code>. You can swap two digits at most once to get the maximum valued number.</p>
<p>Return <em>the maximum valued number you can get</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 2736
<strong>Output:</strong> 7236
<strong>Explanation:</strong> Swap the number 2 and the number 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 9973
<strong>Output:</strong> 9973
<strong>Explanation:</strong> No swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= num <= 10<sup>8</sup></code></li>
</ul>
|
Greedy; Math
|
Rust
|
impl Solution {
pub fn maximum_swap(mut num: i32) -> i32 {
let mut list = {
let mut res = Vec::new();
while num != 0 {
res.push(num % 10);
num /= 10;
}
res
};
let n = list.len();
let idx = {
let mut i = 0;
(0..n)
.map(|j| {
if list[j] > list[i] {
i = j;
}
i
})
.collect::<Vec<usize>>()
};
for i in (0..n).rev() {
if list[i] != list[idx[i]] {
list.swap(i, idx[i]);
break;
}
}
let mut res = 0;
for i in list.iter().rev() {
res = res * 10 + i;
}
res
}
}
|
670
|
Maximum Swap
|
Medium
|
<p>You are given an integer <code>num</code>. You can swap two digits at most once to get the maximum valued number.</p>
<p>Return <em>the maximum valued number you can get</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 2736
<strong>Output:</strong> 7236
<strong>Explanation:</strong> Swap the number 2 and the number 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 9973
<strong>Output:</strong> 9973
<strong>Explanation:</strong> No swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= num <= 10<sup>8</sup></code></li>
</ul>
|
Greedy; Math
|
TypeScript
|
function maximumSwap(num: number): number {
const list = new Array();
while (num !== 0) {
list.push(num % 10);
num = Math.floor(num / 10);
}
const n = list.length;
const idx = new Array();
for (let i = 0, j = 0; i < n; i++) {
if (list[i] > list[j]) {
j = i;
}
idx.push(j);
}
for (let i = n - 1; i >= 0; i--) {
if (list[idx[i]] !== list[i]) {
[list[idx[i]], list[i]] = [list[i], list[idx[i]]];
break;
}
}
let res = 0;
for (let i = n - 1; i >= 0; i--) {
res = res * 10 + list[i];
}
return res;
}
|
671
|
Second Minimum Node In a Binary Tree
|
Easy
|
<p>Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly <code>two</code> or <code>zero</code> sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property <code>root.val = min(root.left.val, root.right.val)</code> always holds.</p>
<p>Given such a binary tree, you need to output the <b>second minimum</b> value in the set made of all the nodes' value in the whole tree.</p>
<p>If no such second minimum value exists, output -1 instead.</p>
<p> </p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/images/smbt1.jpg" style="width: 431px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [2,2,5,null,null,5,7]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The smallest value is 2, the second smallest value is 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/images/smbt2.jpg" style="width: 321px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [2,2,2]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The smallest value is 2, but there isn't any second smallest value.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 25]</code>.</li>
<li><code>1 <= Node.val <= 2<sup>31</sup> - 1</code></li>
<li><code>root.val == min(root.left.val, root.right.val)</code> for each internal node of the tree.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
C++
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int ans = -1;
int findSecondMinimumValue(TreeNode* root) {
dfs(root, root->val);
return ans;
}
void dfs(TreeNode* root, int val) {
if (!root) return;
dfs(root->left, val);
dfs(root->right, val);
if (root->val > val) ans = ans == -1 ? root->val : min(ans, root->val);
}
};
|
671
|
Second Minimum Node In a Binary Tree
|
Easy
|
<p>Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly <code>two</code> or <code>zero</code> sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property <code>root.val = min(root.left.val, root.right.val)</code> always holds.</p>
<p>Given such a binary tree, you need to output the <b>second minimum</b> value in the set made of all the nodes' value in the whole tree.</p>
<p>If no such second minimum value exists, output -1 instead.</p>
<p> </p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/images/smbt1.jpg" style="width: 431px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [2,2,5,null,null,5,7]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The smallest value is 2, the second smallest value is 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/images/smbt2.jpg" style="width: 321px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [2,2,2]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The smallest value is 2, but there isn't any second smallest value.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 25]</code>.</li>
<li><code>1 <= Node.val <= 2<sup>31</sup> - 1</code></li>
<li><code>root.val == min(root.left.val, root.right.val)</code> for each internal node of the tree.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findSecondMinimumValue(root *TreeNode) int {
ans, v := -1, root.Val
var dfs func(*TreeNode)
dfs = func(root *TreeNode) {
if root == nil {
return
}
dfs(root.Left)
dfs(root.Right)
if root.Val > v {
if ans == -1 || ans > root.Val {
ans = root.Val
}
}
}
dfs(root)
return ans
}
|
671
|
Second Minimum Node In a Binary Tree
|
Easy
|
<p>Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly <code>two</code> or <code>zero</code> sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property <code>root.val = min(root.left.val, root.right.val)</code> always holds.</p>
<p>Given such a binary tree, you need to output the <b>second minimum</b> value in the set made of all the nodes' value in the whole tree.</p>
<p>If no such second minimum value exists, output -1 instead.</p>
<p> </p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/images/smbt1.jpg" style="width: 431px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [2,2,5,null,null,5,7]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The smallest value is 2, the second smallest value is 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/images/smbt2.jpg" style="width: 321px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [2,2,2]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The smallest value is 2, but there isn't any second smallest value.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 25]</code>.</li>
<li><code>1 <= Node.val <= 2<sup>31</sup> - 1</code></li>
<li><code>root.val == min(root.left.val, root.right.val)</code> for each internal node of the tree.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
Java
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int ans = -1;
public int findSecondMinimumValue(TreeNode root) {
dfs(root, root.val);
return ans;
}
private void dfs(TreeNode root, int val) {
if (root != null) {
dfs(root.left, val);
dfs(root.right, val);
if (root.val > val) {
ans = ans == -1 ? root.val : Math.min(ans, root.val);
}
}
}
}
|
671
|
Second Minimum Node In a Binary Tree
|
Easy
|
<p>Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly <code>two</code> or <code>zero</code> sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property <code>root.val = min(root.left.val, root.right.val)</code> always holds.</p>
<p>Given such a binary tree, you need to output the <b>second minimum</b> value in the set made of all the nodes' value in the whole tree.</p>
<p>If no such second minimum value exists, output -1 instead.</p>
<p> </p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/images/smbt1.jpg" style="width: 431px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [2,2,5,null,null,5,7]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The smallest value is 2, the second smallest value is 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/images/smbt2.jpg" style="width: 321px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [2,2,2]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The smallest value is 2, but there isn't any second smallest value.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 25]</code>.</li>
<li><code>1 <= Node.val <= 2<sup>31</sup> - 1</code></li>
<li><code>root.val == min(root.left.val, root.right.val)</code> for each internal node of the tree.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
JavaScript
|
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var findSecondMinimumValue = function (root) {
let ans = -1;
const v = root.val;
function dfs(root) {
if (!root) {
return;
}
dfs(root.left);
dfs(root.right);
if (root.val > v) {
if (ans == -1 || ans > root.val) {
ans = root.val;
}
}
}
dfs(root);
return ans;
};
|
671
|
Second Minimum Node In a Binary Tree
|
Easy
|
<p>Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly <code>two</code> or <code>zero</code> sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property <code>root.val = min(root.left.val, root.right.val)</code> always holds.</p>
<p>Given such a binary tree, you need to output the <b>second minimum</b> value in the set made of all the nodes' value in the whole tree.</p>
<p>If no such second minimum value exists, output -1 instead.</p>
<p> </p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/images/smbt1.jpg" style="width: 431px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [2,2,5,null,null,5,7]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The smallest value is 2, the second smallest value is 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/images/smbt2.jpg" style="width: 321px; height: 182px;" />
<pre>
<strong>Input:</strong> root = [2,2,2]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The smallest value is 2, but there isn't any second smallest value.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 25]</code>.</li>
<li><code>1 <= Node.val <= 2<sup>31</sup> - 1</code></li>
<li><code>root.val == min(root.left.val, root.right.val)</code> for each internal node of the tree.</li>
</ul>
|
Tree; Depth-First Search; Binary Tree
|
Python
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if root:
dfs(root.left)
dfs(root.right)
nonlocal ans, v
if root.val > v:
ans = root.val if ans == -1 else min(ans, root.val)
ans, v = -1, root.val
dfs(root)
return ans
|
672
|
Bulb Switcher II
|
Medium
|
<p>There is a room with <code>n</code> bulbs labeled from <code>1</code> to <code>n</code> that all are turned on initially, and <strong>four buttons</strong> on the wall. Each of the four buttons has a different functionality where:</p>
<ul>
<li><strong>Button 1:</strong> Flips the status of all the bulbs.</li>
<li><strong>Button 2:</strong> Flips the status of all the bulbs with even labels (i.e., <code>2, 4, ...</code>).</li>
<li><strong>Button 3:</strong> Flips the status of all the bulbs with odd labels (i.e., <code>1, 3, ...</code>).</li>
<li><strong>Button 4:</strong> Flips the status of all the bulbs with a label <code>j = 3k + 1</code> where <code>k = 0, 1, 2, ...</code> (i.e., <code>1, 4, 7, 10, ...</code>).</li>
</ul>
<p>You must make <strong>exactly</strong> <code>presses</code> button presses in total. For each press, you may pick <strong>any</strong> of the four buttons to press.</p>
<p>Given the two integers <code>n</code> and <code>presses</code>, return <em>the number of <strong>different possible statuses</strong> after performing all </em><code>presses</code><em> button presses</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 1, presses = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> Status can be:
- [off] by pressing button 1
- [on] by pressing button 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2, presses = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> Status can be:
- [off, off] by pressing button 1
- [on, off] by pressing button 2
- [off, on] by pressing button 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 3, presses = 1
<strong>Output:</strong> 4
<strong>Explanation:</strong> Status can be:
- [off, off, off] by pressing button 1
- [off, on, off] by pressing button 2
- [on, off, on] by pressing button 3
- [off, on, on] by pressing button 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
<li><code>0 <= presses <= 1000</code></li>
</ul>
|
Bit Manipulation; Depth-First Search; Breadth-First Search; Math
|
C++
|
class Solution {
public:
int flipLights(int n, int presses) {
n = min(n, 6);
vector<int> ops = {0b111111, 0b010101, 0b101010, 0b100100};
unordered_set<int> vis;
for (int mask = 0; mask < 1 << 4; ++mask) {
int cnt = __builtin_popcount(mask);
if (cnt > presses || cnt % 2 != presses % 2) continue;
int t = 0;
for (int i = 0; i < 4; ++i) {
if (mask >> i & 1) {
t ^= ops[i];
}
}
t &= (1 << 6) - 1;
t >>= (6 - n);
vis.insert(t);
}
return vis.size();
}
};
|
672
|
Bulb Switcher II
|
Medium
|
<p>There is a room with <code>n</code> bulbs labeled from <code>1</code> to <code>n</code> that all are turned on initially, and <strong>four buttons</strong> on the wall. Each of the four buttons has a different functionality where:</p>
<ul>
<li><strong>Button 1:</strong> Flips the status of all the bulbs.</li>
<li><strong>Button 2:</strong> Flips the status of all the bulbs with even labels (i.e., <code>2, 4, ...</code>).</li>
<li><strong>Button 3:</strong> Flips the status of all the bulbs with odd labels (i.e., <code>1, 3, ...</code>).</li>
<li><strong>Button 4:</strong> Flips the status of all the bulbs with a label <code>j = 3k + 1</code> where <code>k = 0, 1, 2, ...</code> (i.e., <code>1, 4, 7, 10, ...</code>).</li>
</ul>
<p>You must make <strong>exactly</strong> <code>presses</code> button presses in total. For each press, you may pick <strong>any</strong> of the four buttons to press.</p>
<p>Given the two integers <code>n</code> and <code>presses</code>, return <em>the number of <strong>different possible statuses</strong> after performing all </em><code>presses</code><em> button presses</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 1, presses = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> Status can be:
- [off] by pressing button 1
- [on] by pressing button 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2, presses = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> Status can be:
- [off, off] by pressing button 1
- [on, off] by pressing button 2
- [off, on] by pressing button 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 3, presses = 1
<strong>Output:</strong> 4
<strong>Explanation:</strong> Status can be:
- [off, off, off] by pressing button 1
- [off, on, off] by pressing button 2
- [on, off, on] by pressing button 3
- [off, on, on] by pressing button 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
<li><code>0 <= presses <= 1000</code></li>
</ul>
|
Bit Manipulation; Depth-First Search; Breadth-First Search; Math
|
Go
|
func flipLights(n int, presses int) int {
if n > 6 {
n = 6
}
ops := []int{0b111111, 0b010101, 0b101010, 0b100100}
vis := map[int]bool{}
for mask := 0; mask < 1<<4; mask++ {
cnt := bits.OnesCount(uint(mask))
if cnt <= presses && cnt%2 == presses%2 {
t := 0
for i, op := range ops {
if mask>>i&1 == 1 {
t ^= op
}
}
t &= 1<<6 - 1
t >>= (6 - n)
vis[t] = true
}
}
return len(vis)
}
|
672
|
Bulb Switcher II
|
Medium
|
<p>There is a room with <code>n</code> bulbs labeled from <code>1</code> to <code>n</code> that all are turned on initially, and <strong>four buttons</strong> on the wall. Each of the four buttons has a different functionality where:</p>
<ul>
<li><strong>Button 1:</strong> Flips the status of all the bulbs.</li>
<li><strong>Button 2:</strong> Flips the status of all the bulbs with even labels (i.e., <code>2, 4, ...</code>).</li>
<li><strong>Button 3:</strong> Flips the status of all the bulbs with odd labels (i.e., <code>1, 3, ...</code>).</li>
<li><strong>Button 4:</strong> Flips the status of all the bulbs with a label <code>j = 3k + 1</code> where <code>k = 0, 1, 2, ...</code> (i.e., <code>1, 4, 7, 10, ...</code>).</li>
</ul>
<p>You must make <strong>exactly</strong> <code>presses</code> button presses in total. For each press, you may pick <strong>any</strong> of the four buttons to press.</p>
<p>Given the two integers <code>n</code> and <code>presses</code>, return <em>the number of <strong>different possible statuses</strong> after performing all </em><code>presses</code><em> button presses</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 1, presses = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> Status can be:
- [off] by pressing button 1
- [on] by pressing button 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2, presses = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> Status can be:
- [off, off] by pressing button 1
- [on, off] by pressing button 2
- [off, on] by pressing button 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 3, presses = 1
<strong>Output:</strong> 4
<strong>Explanation:</strong> Status can be:
- [off, off, off] by pressing button 1
- [off, on, off] by pressing button 2
- [on, off, on] by pressing button 3
- [off, on, on] by pressing button 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
<li><code>0 <= presses <= 1000</code></li>
</ul>
|
Bit Manipulation; Depth-First Search; Breadth-First Search; Math
|
Java
|
class Solution {
public int flipLights(int n, int presses) {
int[] ops = new int[] {0b111111, 0b010101, 0b101010, 0b100100};
Set<Integer> vis = new HashSet<>();
n = Math.min(n, 6);
for (int mask = 0; mask < 1 << 4; ++mask) {
int cnt = Integer.bitCount(mask);
if (cnt <= presses && cnt % 2 == presses % 2) {
int t = 0;
for (int i = 0; i < 4; ++i) {
if (((mask >> i) & 1) == 1) {
t ^= ops[i];
}
}
t &= ((1 << 6) - 1);
t >>= (6 - n);
vis.add(t);
}
}
return vis.size();
}
}
|
672
|
Bulb Switcher II
|
Medium
|
<p>There is a room with <code>n</code> bulbs labeled from <code>1</code> to <code>n</code> that all are turned on initially, and <strong>four buttons</strong> on the wall. Each of the four buttons has a different functionality where:</p>
<ul>
<li><strong>Button 1:</strong> Flips the status of all the bulbs.</li>
<li><strong>Button 2:</strong> Flips the status of all the bulbs with even labels (i.e., <code>2, 4, ...</code>).</li>
<li><strong>Button 3:</strong> Flips the status of all the bulbs with odd labels (i.e., <code>1, 3, ...</code>).</li>
<li><strong>Button 4:</strong> Flips the status of all the bulbs with a label <code>j = 3k + 1</code> where <code>k = 0, 1, 2, ...</code> (i.e., <code>1, 4, 7, 10, ...</code>).</li>
</ul>
<p>You must make <strong>exactly</strong> <code>presses</code> button presses in total. For each press, you may pick <strong>any</strong> of the four buttons to press.</p>
<p>Given the two integers <code>n</code> and <code>presses</code>, return <em>the number of <strong>different possible statuses</strong> after performing all </em><code>presses</code><em> button presses</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 1, presses = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> Status can be:
- [off] by pressing button 1
- [on] by pressing button 2
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2, presses = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> Status can be:
- [off, off] by pressing button 1
- [on, off] by pressing button 2
- [off, on] by pressing button 3
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 3, presses = 1
<strong>Output:</strong> 4
<strong>Explanation:</strong> Status can be:
- [off, off, off] by pressing button 1
- [off, on, off] by pressing button 2
- [on, off, on] by pressing button 3
- [off, on, on] by pressing button 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
<li><code>0 <= presses <= 1000</code></li>
</ul>
|
Bit Manipulation; Depth-First Search; Breadth-First Search; Math
|
Python
|
class Solution:
def flipLights(self, n: int, presses: int) -> int:
ops = (0b111111, 0b010101, 0b101010, 0b100100)
n = min(n, 6)
vis = set()
for mask in range(1 << 4):
cnt = mask.bit_count()
if cnt <= presses and cnt % 2 == presses % 2:
t = 0
for i, op in enumerate(ops):
if (mask >> i) & 1:
t ^= op
t &= (1 << 6) - 1
t >>= 6 - n
vis.add(t)
return len(vis)
|
673
|
Number of Longest Increasing Subsequence
|
Medium
|
<p>Given an integer array <code>nums</code>, return <em>the number of longest increasing subsequences.</em></p>
<p><strong>Notice</strong> that the sequence has to be <strong>strictly</strong> increasing.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
<li>The answer is guaranteed to fit inside a 32-bit integer.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Dynamic Programming
|
C++
|
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
int n = nums.size();
int mx = 0, ans = 0;
vector<int> f(n, 1);
vector<int> cnt(n, 1);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) {
if (f[i] < f[j] + 1) {
f[i] = f[j] + 1;
cnt[i] = cnt[j];
} else if (f[i] == f[j] + 1) {
cnt[i] += cnt[j];
}
}
}
if (mx < f[i]) {
mx = f[i];
ans = cnt[i];
} else if (mx == f[i]) {
ans += cnt[i];
}
}
return ans;
}
};
|
673
|
Number of Longest Increasing Subsequence
|
Medium
|
<p>Given an integer array <code>nums</code>, return <em>the number of longest increasing subsequences.</em></p>
<p><strong>Notice</strong> that the sequence has to be <strong>strictly</strong> increasing.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
<li>The answer is guaranteed to fit inside a 32-bit integer.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Dynamic Programming
|
Go
|
func findNumberOfLIS(nums []int) (ans int) {
n, mx := len(nums), 0
f := make([]int, n)
cnt := make([]int, n)
for i, x := range nums {
for j, y := range nums[:i] {
if y < x {
if f[i] < f[j]+1 {
f[i] = f[j] + 1
cnt[i] = cnt[j]
} else if f[i] == f[j]+1 {
cnt[i] += cnt[j]
}
}
}
if mx < f[i] {
mx = f[i]
ans = cnt[i]
} else if mx == f[i] {
ans += cnt[i]
}
}
return
}
|
673
|
Number of Longest Increasing Subsequence
|
Medium
|
<p>Given an integer array <code>nums</code>, return <em>the number of longest increasing subsequences.</em></p>
<p><strong>Notice</strong> that the sequence has to be <strong>strictly</strong> increasing.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
<li>The answer is guaranteed to fit inside a 32-bit integer.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Dynamic Programming
|
Java
|
class Solution {
public int findNumberOfLIS(int[] nums) {
int n = nums.length;
int[] f = new int[n];
int[] cnt = new int[n];
int mx = 0, ans = 0;
for (int i = 0; i < n; ++i) {
f[i] = 1;
cnt[i] = 1;
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) {
if (f[i] < f[j] + 1) {
f[i] = f[j] + 1;
cnt[i] = cnt[j];
} else if (f[i] == f[j] + 1) {
cnt[i] += cnt[j];
}
}
}
if (mx < f[i]) {
mx = f[i];
ans = cnt[i];
} else if (mx == f[i]) {
ans += cnt[i];
}
}
return ans;
}
}
|
673
|
Number of Longest Increasing Subsequence
|
Medium
|
<p>Given an integer array <code>nums</code>, return <em>the number of longest increasing subsequences.</em></p>
<p><strong>Notice</strong> that the sequence has to be <strong>strictly</strong> increasing.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
<li>The answer is guaranteed to fit inside a 32-bit integer.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Dynamic Programming
|
Python
|
class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
n = len(nums)
f = [1] * n
cnt = [1] * n
mx = 0
for i in range(n):
for j in range(i):
if nums[j] < nums[i]:
if f[i] < f[j] + 1:
f[i] = f[j] + 1
cnt[i] = cnt[j]
elif f[i] == f[j] + 1:
cnt[i] += cnt[j]
if mx < f[i]:
mx = f[i]
ans = cnt[i]
elif mx == f[i]:
ans += cnt[i]
return ans
|
673
|
Number of Longest Increasing Subsequence
|
Medium
|
<p>Given an integer array <code>nums</code>, return <em>the number of longest increasing subsequences.</em></p>
<p><strong>Notice</strong> that the sequence has to be <strong>strictly</strong> increasing.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
<li>The answer is guaranteed to fit inside a 32-bit integer.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Dynamic Programming
|
Rust
|
impl Solution {
pub fn find_number_of_lis(nums: Vec<i32>) -> i32 {
let n = nums.len();
let mut ans = 0;
let mut mx = 0;
let mut f = vec![1; n];
let mut cnt = vec![1; n];
for i in 0..n {
for j in 0..i {
if nums[j] < nums[i] {
if f[i] < f[j] + 1 {
f[i] = f[j] + 1;
cnt[i] = cnt[j];
} else if f[i] == f[j] + 1 {
cnt[i] += cnt[j];
}
}
}
if mx < f[i] {
mx = f[i];
ans = cnt[i];
} else if mx == f[i] {
ans += cnt[i];
}
}
ans
}
}
|
673
|
Number of Longest Increasing Subsequence
|
Medium
|
<p>Given an integer array <code>nums</code>, return <em>the number of longest increasing subsequences.</em></p>
<p><strong>Notice</strong> that the sequence has to be <strong>strictly</strong> increasing.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
<li>The answer is guaranteed to fit inside a 32-bit integer.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Dynamic Programming
|
TypeScript
|
function findNumberOfLIS(nums: number[]): number {
const n = nums.length;
let [ans, mx] = [0, 0];
const f: number[] = Array(n).fill(1);
const cnt: number[] = Array(n).fill(1);
for (let i = 0; i < n; ++i) {
for (let j = 0; j < i; ++j) {
if (nums[j] < nums[i]) {
if (f[i] < f[j] + 1) {
f[i] = f[j] + 1;
cnt[i] = cnt[j];
} else if (f[i] === f[j] + 1) {
cnt[i] += cnt[j];
}
}
}
if (mx < f[i]) {
mx = f[i];
ans = cnt[i];
} else if (mx === f[i]) {
ans += cnt[i];
}
}
return ans;
}
|
674
|
Longest Continuous Increasing Subsequence
|
Easy
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest <strong>continuous increasing subsequence</strong> (i.e. subarray)</em>. The subsequence must be <strong>strictly</strong> increasing.</p>
<p>A <strong>continuous increasing subsequence</strong> is defined by two indices <code>l</code> and <code>r</code> (<code>l < r</code>) such that it is <code>[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]</code> and for each <code>l <= i < r</code>, <code>nums[i] < nums[i + 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
int ans = 1;
for (int i = 1, cnt = 1; i < nums.size(); ++i) {
if (nums[i - 1] < nums[i]) {
ans = max(ans, ++cnt);
} else {
cnt = 1;
}
}
return ans;
}
};
|
674
|
Longest Continuous Increasing Subsequence
|
Easy
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest <strong>continuous increasing subsequence</strong> (i.e. subarray)</em>. The subsequence must be <strong>strictly</strong> increasing.</p>
<p>A <strong>continuous increasing subsequence</strong> is defined by two indices <code>l</code> and <code>r</code> (<code>l < r</code>) such that it is <code>[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]</code> and for each <code>l <= i < r</code>, <code>nums[i] < nums[i + 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array
|
Go
|
func findLengthOfLCIS(nums []int) int {
ans, cnt := 1, 1
for i, x := range nums[1:] {
if nums[i] < x {
cnt++
ans = max(ans, cnt)
} else {
cnt = 1
}
}
return ans
}
|
674
|
Longest Continuous Increasing Subsequence
|
Easy
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest <strong>continuous increasing subsequence</strong> (i.e. subarray)</em>. The subsequence must be <strong>strictly</strong> increasing.</p>
<p>A <strong>continuous increasing subsequence</strong> is defined by two indices <code>l</code> and <code>r</code> (<code>l < r</code>) such that it is <code>[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]</code> and for each <code>l <= i < r</code>, <code>nums[i] < nums[i + 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array
|
Java
|
class Solution {
public int findLengthOfLCIS(int[] nums) {
int ans = 1;
for (int i = 1, cnt = 1; i < nums.length; ++i) {
if (nums[i - 1] < nums[i]) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 1;
}
}
return ans;
}
}
|
674
|
Longest Continuous Increasing Subsequence
|
Easy
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest <strong>continuous increasing subsequence</strong> (i.e. subarray)</em>. The subsequence must be <strong>strictly</strong> increasing.</p>
<p>A <strong>continuous increasing subsequence</strong> is defined by two indices <code>l</code> and <code>r</code> (<code>l < r</code>) such that it is <code>[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]</code> and for each <code>l <= i < r</code>, <code>nums[i] < nums[i + 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array
|
PHP
|
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function findLengthOfLCIS($nums) {
$ans = 1;
$cnt = 1;
for ($i = 1; $i < count($nums); ++$i) {
if ($nums[$i - 1] < $nums[$i]) {
$ans = max($ans, ++$cnt);
} else {
$cnt = 1;
}
}
return $ans;
}
}
|
674
|
Longest Continuous Increasing Subsequence
|
Easy
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest <strong>continuous increasing subsequence</strong> (i.e. subarray)</em>. The subsequence must be <strong>strictly</strong> increasing.</p>
<p>A <strong>continuous increasing subsequence</strong> is defined by two indices <code>l</code> and <code>r</code> (<code>l < r</code>) such that it is <code>[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]</code> and for each <code>l <= i < r</code>, <code>nums[i] < nums[i + 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array
|
Python
|
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
ans = cnt = 1
for i, x in enumerate(nums[1:]):
if nums[i] < x:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 1
return ans
|
674
|
Longest Continuous Increasing Subsequence
|
Easy
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest <strong>continuous increasing subsequence</strong> (i.e. subarray)</em>. The subsequence must be <strong>strictly</strong> increasing.</p>
<p>A <strong>continuous increasing subsequence</strong> is defined by two indices <code>l</code> and <code>r</code> (<code>l < r</code>) such that it is <code>[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]</code> and for each <code>l <= i < r</code>, <code>nums[i] < nums[i + 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array
|
Rust
|
impl Solution {
pub fn find_length_of_lcis(nums: Vec<i32>) -> i32 {
let mut ans = 1;
let mut cnt = 1;
for i in 1..nums.len() {
if nums[i - 1] < nums[i] {
ans = ans.max(cnt + 1);
cnt += 1;
} else {
cnt = 1;
}
}
ans
}
}
|
674
|
Longest Continuous Increasing Subsequence
|
Easy
|
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest <strong>continuous increasing subsequence</strong> (i.e. subarray)</em>. The subsequence must be <strong>strictly</strong> increasing.</p>
<p>A <strong>continuous increasing subsequence</strong> is defined by two indices <code>l</code> and <code>r</code> (<code>l < r</code>) such that it is <code>[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]</code> and for each <code>l <= i < r</code>, <code>nums[i] < nums[i + 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,4,7]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,2,2,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array
|
TypeScript
|
function findLengthOfLCIS(nums: number[]): number {
let [ans, cnt] = [1, 1];
for (let i = 1; i < nums.length; ++i) {
if (nums[i - 1] < nums[i]) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 1;
}
}
return ans;
}
|
675
|
Cut Off Trees for Golf Event
|
Hard
|
<p>You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an <code>m x n</code> matrix. In this matrix:</p>
<ul>
<li><code>0</code> means the cell cannot be walked through.</li>
<li><code>1</code> represents an empty cell that can be walked through.</li>
<li>A number greater than <code>1</code> represents a tree in a cell that can be walked through, and this number is the tree's height.</li>
</ul>
<p>In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.</p>
<p>You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes <code>1</code> (an empty cell).</p>
<p>Starting from the point <code>(0, 0)</code>, return <em>the minimum steps you need to walk to cut off all the trees</em>. If you cannot cut off all the trees, return <code>-1</code>.</p>
<p><strong>Note:</strong> The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/images/trees1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,4],[7,6,5]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/images/trees2.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,0],[7,6,5]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The trees in the bottom row cannot be accessed as the middle row is blocked.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> forest = [[2,3,4],[0,0,5],[8,7,6]]
<strong>Output:</strong> 6
<b>Explanation:</b> You can follow the same path as Example 1 to cut off all the trees.
Note that you can cut off the first tree at (0, 0) before making any steps.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == forest.length</code></li>
<li><code>n == forest[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= forest[i][j] <= 10<sup>9</sup></code></li>
<li>Heights of all trees are <strong>distinct</strong>.</li>
</ul>
|
Breadth-First Search; Array; Matrix; Heap (Priority Queue)
|
C++
|
class Solution {
public:
int m;
int n;
vector<int> dist;
int cutOffTree(vector<vector<int>>& forest) {
m = forest.size();
n = forest[0].size();
dist.resize(3600);
vector<pair<int, int>> trees;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (forest[i][j] > 1)
trees.push_back({forest[i][j], i * n + j});
sort(trees.begin(), trees.end());
int ans = 0;
int start = 0;
for (auto& tree : trees) {
int end = tree.second;
int t = bfs(start, end, forest);
if (t == -1) return -1;
ans += t;
start = end;
}
return ans;
}
int bfs(int start, int end, vector<vector<int>>& forest) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
q.push({f(start, end), start});
fill(dist.begin(), dist.end(), INT_MAX);
dist[start] = 0;
vector<int> dirs = {-1, 0, 1, 0, -1};
while (!q.empty()) {
int state = q.top().second;
q.pop();
if (state == end) return dist[state];
for (int k = 0; k < 4; ++k) {
int x = state / n + dirs[k], y = state % n + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && forest[x][y] && dist[x * n + y] > dist[state] + 1) {
dist[x * n + y] = dist[state] + 1;
q.push({dist[x * n + y] + f(x * n + y, end), x * n + y});
}
}
}
return -1;
}
int f(int start, int end) {
int a = start / n, b = start % n;
int c = end / n, d = end % n;
return abs(a - c) + abs(b - d);
}
};
|
675
|
Cut Off Trees for Golf Event
|
Hard
|
<p>You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an <code>m x n</code> matrix. In this matrix:</p>
<ul>
<li><code>0</code> means the cell cannot be walked through.</li>
<li><code>1</code> represents an empty cell that can be walked through.</li>
<li>A number greater than <code>1</code> represents a tree in a cell that can be walked through, and this number is the tree's height.</li>
</ul>
<p>In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.</p>
<p>You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes <code>1</code> (an empty cell).</p>
<p>Starting from the point <code>(0, 0)</code>, return <em>the minimum steps you need to walk to cut off all the trees</em>. If you cannot cut off all the trees, return <code>-1</code>.</p>
<p><strong>Note:</strong> The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/images/trees1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,4],[7,6,5]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/images/trees2.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,0],[7,6,5]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The trees in the bottom row cannot be accessed as the middle row is blocked.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> forest = [[2,3,4],[0,0,5],[8,7,6]]
<strong>Output:</strong> 6
<b>Explanation:</b> You can follow the same path as Example 1 to cut off all the trees.
Note that you can cut off the first tree at (0, 0) before making any steps.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == forest.length</code></li>
<li><code>n == forest[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= forest[i][j] <= 10<sup>9</sup></code></li>
<li>Heights of all trees are <strong>distinct</strong>.</li>
</ul>
|
Breadth-First Search; Array; Matrix; Heap (Priority Queue)
|
Go
|
var dirs = [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
type tree struct {
height int
pos int
}
func cutOffTree(forest [][]int) int {
row, col := len(forest), len(forest[0])
bfs := func(start, end int) int {
q := []int{start}
vis := make(map[int]bool)
vis[start] = true
step := 0
for n := len(q); n > 0; n = len(q) {
for i := 0; i < n; i++ {
state := q[0]
q = q[1:]
if state == end {
return step
}
for k := 0; k < 4; k++ {
x, y := state/col+dirs[k][0], state%col+dirs[k][1]
nxt := x*col + y
if x >= 0 && x < row && y >= 0 && y < col && forest[x][y] != 0 && !vis[nxt] {
q = append(q, nxt)
vis[nxt] = true
}
}
}
step++
}
return -1
}
var trees []tree
for i := 0; i < row; i++ {
for j := 0; j < col; j++ {
if forest[i][j] > 1 {
trees = append(trees, tree{forest[i][j], i*col + j})
}
}
}
sort.Slice(trees, func(i, j int) bool {
return trees[i].height < trees[j].height
})
ans, start := 0, 0
for _, t := range trees {
end := t.pos
step := bfs(start, end)
if step == -1 {
return -1
}
ans += step
start = end
}
return ans
}
|
675
|
Cut Off Trees for Golf Event
|
Hard
|
<p>You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an <code>m x n</code> matrix. In this matrix:</p>
<ul>
<li><code>0</code> means the cell cannot be walked through.</li>
<li><code>1</code> represents an empty cell that can be walked through.</li>
<li>A number greater than <code>1</code> represents a tree in a cell that can be walked through, and this number is the tree's height.</li>
</ul>
<p>In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.</p>
<p>You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes <code>1</code> (an empty cell).</p>
<p>Starting from the point <code>(0, 0)</code>, return <em>the minimum steps you need to walk to cut off all the trees</em>. If you cannot cut off all the trees, return <code>-1</code>.</p>
<p><strong>Note:</strong> The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/images/trees1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,4],[7,6,5]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/images/trees2.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,0],[7,6,5]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The trees in the bottom row cannot be accessed as the middle row is blocked.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> forest = [[2,3,4],[0,0,5],[8,7,6]]
<strong>Output:</strong> 6
<b>Explanation:</b> You can follow the same path as Example 1 to cut off all the trees.
Note that you can cut off the first tree at (0, 0) before making any steps.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == forest.length</code></li>
<li><code>n == forest[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= forest[i][j] <= 10<sup>9</sup></code></li>
<li>Heights of all trees are <strong>distinct</strong>.</li>
</ul>
|
Breadth-First Search; Array; Matrix; Heap (Priority Queue)
|
Java
|
class Solution {
private int[] dist = new int[3600];
private List<List<Integer>> forest;
private int m;
private int n;
public int cutOffTree(List<List<Integer>> forest) {
this.forest = forest;
m = forest.size();
n = forest.get(0).size();
List<int[]> trees = new ArrayList<>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (forest.get(i).get(j) > 1) {
trees.add(new int[] {forest.get(i).get(j), i * n + j});
}
}
}
trees.sort(Comparator.comparingInt(a -> a[0]));
int ans = 0;
int start = 0;
for (int[] tree : trees) {
int end = tree[1];
int t = bfs(start, end);
if (t == -1) {
return -1;
}
ans += t;
start = end;
}
return ans;
}
private int bfs(int start, int end) {
PriorityQueue<int[]> q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
q.offer(new int[] {f(start, end), start});
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
int[] dirs = {-1, 0, 1, 0, -1};
while (!q.isEmpty()) {
int state = q.poll()[1];
if (state == end) {
return dist[state];
}
for (int k = 0; k < 4; ++k) {
int x = state / n + dirs[k];
int y = state % n + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && forest.get(x).get(y) > 0) {
if (dist[x * n + y] > dist[state] + 1) {
dist[x * n + y] = dist[state] + 1;
q.offer(new int[] {dist[x * n + y] + f(x * n + y, end), x * n + y});
}
}
}
}
return -1;
}
private int f(int start, int end) {
int a = start / n;
int b = start % n;
int c = end / n;
int d = end % n;
return Math.abs(a - c) + Math.abs(b - d);
}
}
|
675
|
Cut Off Trees for Golf Event
|
Hard
|
<p>You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an <code>m x n</code> matrix. In this matrix:</p>
<ul>
<li><code>0</code> means the cell cannot be walked through.</li>
<li><code>1</code> represents an empty cell that can be walked through.</li>
<li>A number greater than <code>1</code> represents a tree in a cell that can be walked through, and this number is the tree's height.</li>
</ul>
<p>In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.</p>
<p>You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes <code>1</code> (an empty cell).</p>
<p>Starting from the point <code>(0, 0)</code>, return <em>the minimum steps you need to walk to cut off all the trees</em>. If you cannot cut off all the trees, return <code>-1</code>.</p>
<p><strong>Note:</strong> The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/images/trees1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,4],[7,6,5]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/images/trees2.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,0],[7,6,5]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The trees in the bottom row cannot be accessed as the middle row is blocked.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> forest = [[2,3,4],[0,0,5],[8,7,6]]
<strong>Output:</strong> 6
<b>Explanation:</b> You can follow the same path as Example 1 to cut off all the trees.
Note that you can cut off the first tree at (0, 0) before making any steps.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == forest.length</code></li>
<li><code>n == forest[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= forest[i][j] <= 10<sup>9</sup></code></li>
<li>Heights of all trees are <strong>distinct</strong>.</li>
</ul>
|
Breadth-First Search; Array; Matrix; Heap (Priority Queue)
|
Python
|
class Solution:
def cutOffTree(self, forest: List[List[int]]) -> int:
def f(i, j, x, y):
return abs(i - x) + abs(j - y)
def bfs(i, j, x, y):
q = [(f(i, j, x, y), i, j)]
dist = {i * n + j: 0}
while q:
_, i, j = heappop(q)
step = dist[i * n + j]
if (i, j) == (x, y):
return step
for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]:
c, d = i + a, j + b
if 0 <= c < m and 0 <= d < n and forest[c][d] > 0:
if c * n + d not in dist or dist[c * n + d] > step + 1:
dist[c * n + d] = step + 1
heappush(q, (dist[c * n + d] + f(c, d, x, y), c, d))
return -1
m, n = len(forest), len(forest[0])
trees = [
(forest[i][j], i, j) for i in range(m) for j in range(n) if forest[i][j] > 1
]
trees.sort()
i = j = 0
ans = 0
for _, x, y in trees:
t = bfs(i, j, x, y)
if t == -1:
return -1
ans += t
i, j = x, y
return ans
|
675
|
Cut Off Trees for Golf Event
|
Hard
|
<p>You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an <code>m x n</code> matrix. In this matrix:</p>
<ul>
<li><code>0</code> means the cell cannot be walked through.</li>
<li><code>1</code> represents an empty cell that can be walked through.</li>
<li>A number greater than <code>1</code> represents a tree in a cell that can be walked through, and this number is the tree's height.</li>
</ul>
<p>In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.</p>
<p>You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes <code>1</code> (an empty cell).</p>
<p>Starting from the point <code>(0, 0)</code>, return <em>the minimum steps you need to walk to cut off all the trees</em>. If you cannot cut off all the trees, return <code>-1</code>.</p>
<p><strong>Note:</strong> The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/images/trees1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,4],[7,6,5]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/images/trees2.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,0],[7,6,5]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The trees in the bottom row cannot be accessed as the middle row is blocked.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> forest = [[2,3,4],[0,0,5],[8,7,6]]
<strong>Output:</strong> 6
<b>Explanation:</b> You can follow the same path as Example 1 to cut off all the trees.
Note that you can cut off the first tree at (0, 0) before making any steps.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == forest.length</code></li>
<li><code>n == forest[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= forest[i][j] <= 10<sup>9</sup></code></li>
<li>Heights of all trees are <strong>distinct</strong>.</li>
</ul>
|
Breadth-First Search; Array; Matrix; Heap (Priority Queue)
|
Rust
|
use std::collections::HashSet;
use std::collections::VecDeque;
const DIRS: [[i32; 2]; 4] = [[-1, 0], [1, 0], [0, -1], [0, 1]];
impl Solution {
pub fn cut_off_tree(forest: Vec<Vec<i32>>) -> i32 {
let (row, col) = (forest.len() as i32, forest[0].len() as i32);
let bfs = |start: i32, end: i32| -> i32 {
let mut queue = VecDeque::new();
let mut vis = HashSet::new();
queue.push_back(start);
vis.insert(start);
let mut step = 0;
while !queue.is_empty() {
let n = queue.len();
for _ in 0..n {
let state = queue.pop_front().unwrap();
if state == end {
return step;
}
for k in 0..4 {
let x = state / col + DIRS[k][0];
let y = (state % col) + DIRS[k][1];
let nxt = x * col + y;
if x >= 0
&& x < row
&& y >= 0
&& y < col
&& forest[x as usize][y as usize] != 0
&& !vis.contains(&nxt)
{
queue.push_back(nxt);
vis.insert(nxt);
}
}
}
step += 1;
}
-1
};
let mut trees = Vec::new();
for i in 0..row {
for j in 0..col {
let height = forest[i as usize][j as usize];
if height > 1 {
trees.push((height, i * col + j));
}
}
}
trees.sort();
let (mut ans, mut start) = (0, 0);
for t in &trees {
let end = t.1;
let step = bfs(start, end);
if step == -1 {
return -1;
}
ans += step;
start = end;
}
ans
}
}
|
676
|
Implement Magic Dictionary
|
Medium
|
<p>Design a data structure that is initialized with a list of <strong>different</strong> words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.</p>
<p>Implement the <code>MagicDictionary</code> class:</p>
<ul>
<li><code>MagicDictionary()</code> Initializes the object.</li>
<li><code>void buildDict(String[] dictionary)</code> Sets the data structure with an array of distinct strings <code>dictionary</code>.</li>
<li><code>bool search(String searchWord)</code> Returns <code>true</code> if you can change <strong>exactly one character</strong> in <code>searchWord</code> to match any string in the data structure, otherwise returns <code>false</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
<strong>Output</strong>
[null, null, false, true, false, false]
<strong>Explanation</strong>
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dictionary.length <= 100</code></li>
<li><code>1 <= dictionary[i].length <= 100</code></li>
<li><code>dictionary[i]</code> consists of only lower-case English letters.</li>
<li>All the strings in <code>dictionary</code> are <strong>distinct</strong>.</li>
<li><code>1 <= searchWord.length <= 100</code></li>
<li><code>searchWord</code> consists of only lower-case English letters.</li>
<li><code>buildDict</code> will be called only once before <code>search</code>.</li>
<li>At most <code>100</code> calls will be made to <code>search</code>.</li>
</ul>
|
Depth-First Search; Design; Trie; Hash Table; String
|
C++
|
class Trie {
private:
Trie* children[26];
bool isEnd = false;
public:
Trie() {
fill(begin(children), end(children), nullptr);
}
void insert(const string& w) {
Trie* node = this;
for (char c : w) {
int i = c - 'a';
if (!node->children[i]) {
node->children[i] = new Trie();
}
node = node->children[i];
}
node->isEnd = true;
}
bool search(const string& w) {
function<bool(int, Trie*, int)> dfs = [&](int i, Trie* node, int diff) {
if (i >= w.size()) {
return diff == 1 && node->isEnd;
}
int j = w[i] - 'a';
if (node->children[j] && dfs(i + 1, node->children[j], diff)) {
return true;
}
if (diff == 0) {
for (int k = 0; k < 26; ++k) {
if (k != j && node->children[k]) {
if (dfs(i + 1, node->children[k], 1)) {
return true;
}
}
}
}
return false;
};
return dfs(0, this, 0);
}
};
class MagicDictionary {
public:
MagicDictionary() {
trie = new Trie();
}
void buildDict(vector<string> dictionary) {
for (auto& w : dictionary) {
trie->insert(w);
}
}
bool search(string searchWord) {
return trie->search(searchWord);
}
private:
Trie* trie;
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary* obj = new MagicDictionary();
* obj->buildDict(dictionary);
* bool param_2 = obj->search(searchWord);
*/
|
676
|
Implement Magic Dictionary
|
Medium
|
<p>Design a data structure that is initialized with a list of <strong>different</strong> words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.</p>
<p>Implement the <code>MagicDictionary</code> class:</p>
<ul>
<li><code>MagicDictionary()</code> Initializes the object.</li>
<li><code>void buildDict(String[] dictionary)</code> Sets the data structure with an array of distinct strings <code>dictionary</code>.</li>
<li><code>bool search(String searchWord)</code> Returns <code>true</code> if you can change <strong>exactly one character</strong> in <code>searchWord</code> to match any string in the data structure, otherwise returns <code>false</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
<strong>Output</strong>
[null, null, false, true, false, false]
<strong>Explanation</strong>
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dictionary.length <= 100</code></li>
<li><code>1 <= dictionary[i].length <= 100</code></li>
<li><code>dictionary[i]</code> consists of only lower-case English letters.</li>
<li>All the strings in <code>dictionary</code> are <strong>distinct</strong>.</li>
<li><code>1 <= searchWord.length <= 100</code></li>
<li><code>searchWord</code> consists of only lower-case English letters.</li>
<li><code>buildDict</code> will be called only once before <code>search</code>.</li>
<li>At most <code>100</code> calls will be made to <code>search</code>.</li>
</ul>
|
Depth-First Search; Design; Trie; Hash Table; String
|
Go
|
type Trie struct {
children [26]*Trie
isEnd bool
}
func NewTrie() *Trie {
return &Trie{}
}
func (t *Trie) Insert(w string) {
node := t
for _, c := range w {
i := c - 'a'
if node.children[i] == nil {
node.children[i] = NewTrie()
}
node = node.children[i]
}
node.isEnd = true
}
func (t *Trie) Search(w string) bool {
var dfs func(int, *Trie, int) bool
dfs = func(i int, node *Trie, diff int) bool {
if i >= len(w) {
return diff == 1 && node.isEnd
}
j := int(w[i] - 'a')
if node.children[j] != nil && dfs(i+1, node.children[j], diff) {
return true
}
if diff == 0 {
for k := 0; k < 26; k++ {
if k != j && node.children[k] != nil && dfs(i+1, node.children[k], 1) {
return true
}
}
}
return false
}
return dfs(0, t, 0)
}
type MagicDictionary struct {
trie *Trie
}
func Constructor() MagicDictionary {
return MagicDictionary{trie: NewTrie()}
}
func (md *MagicDictionary) BuildDict(dictionary []string) {
for _, w := range dictionary {
md.trie.Insert(w)
}
}
func (md *MagicDictionary) Search(searchWord string) bool {
return md.trie.Search(searchWord)
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* obj := Constructor();
* obj.BuildDict(dictionary);
* param_2 := obj.Search(searchWord);
*/
|
676
|
Implement Magic Dictionary
|
Medium
|
<p>Design a data structure that is initialized with a list of <strong>different</strong> words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.</p>
<p>Implement the <code>MagicDictionary</code> class:</p>
<ul>
<li><code>MagicDictionary()</code> Initializes the object.</li>
<li><code>void buildDict(String[] dictionary)</code> Sets the data structure with an array of distinct strings <code>dictionary</code>.</li>
<li><code>bool search(String searchWord)</code> Returns <code>true</code> if you can change <strong>exactly one character</strong> in <code>searchWord</code> to match any string in the data structure, otherwise returns <code>false</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
<strong>Output</strong>
[null, null, false, true, false, false]
<strong>Explanation</strong>
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dictionary.length <= 100</code></li>
<li><code>1 <= dictionary[i].length <= 100</code></li>
<li><code>dictionary[i]</code> consists of only lower-case English letters.</li>
<li>All the strings in <code>dictionary</code> are <strong>distinct</strong>.</li>
<li><code>1 <= searchWord.length <= 100</code></li>
<li><code>searchWord</code> consists of only lower-case English letters.</li>
<li><code>buildDict</code> will be called only once before <code>search</code>.</li>
<li>At most <code>100</code> calls will be made to <code>search</code>.</li>
</ul>
|
Depth-First Search; Design; Trie; Hash Table; String
|
Java
|
class Trie {
private Trie[] children = new Trie[26];
private boolean isEnd;
public void insert(String w) {
Trie node = this;
for (char c : w.toCharArray()) {
int i = c - 'a';
if (node.children[i] == null) {
node.children[i] = new Trie();
}
node = node.children[i];
}
node.isEnd = true;
}
public boolean search(String w) {
return dfs(w, 0, this, 0);
}
private boolean dfs(String w, int i, Trie node, int diff) {
if (i == w.length()) {
return diff == 1 && node.isEnd;
}
int j = w.charAt(i) - 'a';
if (node.children[j] != null) {
if (dfs(w, i + 1, node.children[j], diff)) {
return true;
}
}
if (diff == 0) {
for (int k = 0; k < 26; k++) {
if (k != j && node.children[k] != null) {
if (dfs(w, i + 1, node.children[k], 1)) {
return true;
}
}
}
}
return false;
}
}
class MagicDictionary {
private Trie trie = new Trie();
public MagicDictionary() {
}
public void buildDict(String[] dictionary) {
for (String w : dictionary) {
trie.insert(w);
}
}
public boolean search(String searchWord) {
return trie.search(searchWord);
}
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dictionary);
* boolean param_2 = obj.search(searchWord);
*/
|
676
|
Implement Magic Dictionary
|
Medium
|
<p>Design a data structure that is initialized with a list of <strong>different</strong> words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.</p>
<p>Implement the <code>MagicDictionary</code> class:</p>
<ul>
<li><code>MagicDictionary()</code> Initializes the object.</li>
<li><code>void buildDict(String[] dictionary)</code> Sets the data structure with an array of distinct strings <code>dictionary</code>.</li>
<li><code>bool search(String searchWord)</code> Returns <code>true</code> if you can change <strong>exactly one character</strong> in <code>searchWord</code> to match any string in the data structure, otherwise returns <code>false</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
<strong>Output</strong>
[null, null, false, true, false, false]
<strong>Explanation</strong>
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dictionary.length <= 100</code></li>
<li><code>1 <= dictionary[i].length <= 100</code></li>
<li><code>dictionary[i]</code> consists of only lower-case English letters.</li>
<li>All the strings in <code>dictionary</code> are <strong>distinct</strong>.</li>
<li><code>1 <= searchWord.length <= 100</code></li>
<li><code>searchWord</code> consists of only lower-case English letters.</li>
<li><code>buildDict</code> will be called only once before <code>search</code>.</li>
<li>At most <code>100</code> calls will be made to <code>search</code>.</li>
</ul>
|
Depth-First Search; Design; Trie; Hash Table; String
|
Python
|
class Trie:
__slots__ = ["children", "is_end"]
def __init__(self):
self.children = {}
self.is_end = False
def insert(self, w: str) -> None:
node = self
for c in w:
if c not in node.children:
node.children[c] = Trie()
node = node.children[c]
node.is_end = True
def search(self, w: str) -> bool:
def dfs(i: int, node: Trie, diff: int) -> bool:
if i == len(w):
return diff == 1 and node.is_end
if w[i] in node.children and dfs(i + 1, node.children[w[i]], diff):
return True
return diff == 0 and any(
dfs(i + 1, node.children[c], 1) for c in node.children if c != w[i]
)
return dfs(0, self, 0)
class MagicDictionary:
def __init__(self):
self.trie = Trie()
def buildDict(self, dictionary: List[str]) -> None:
for w in dictionary:
self.trie.insert(w)
def search(self, searchWord: str) -> bool:
return self.trie.search(searchWord)
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dictionary)
# param_2 = obj.search(searchWord)
|
676
|
Implement Magic Dictionary
|
Medium
|
<p>Design a data structure that is initialized with a list of <strong>different</strong> words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.</p>
<p>Implement the <code>MagicDictionary</code> class:</p>
<ul>
<li><code>MagicDictionary()</code> Initializes the object.</li>
<li><code>void buildDict(String[] dictionary)</code> Sets the data structure with an array of distinct strings <code>dictionary</code>.</li>
<li><code>bool search(String searchWord)</code> Returns <code>true</code> if you can change <strong>exactly one character</strong> in <code>searchWord</code> to match any string in the data structure, otherwise returns <code>false</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
<strong>Output</strong>
[null, null, false, true, false, false]
<strong>Explanation</strong>
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dictionary.length <= 100</code></li>
<li><code>1 <= dictionary[i].length <= 100</code></li>
<li><code>dictionary[i]</code> consists of only lower-case English letters.</li>
<li>All the strings in <code>dictionary</code> are <strong>distinct</strong>.</li>
<li><code>1 <= searchWord.length <= 100</code></li>
<li><code>searchWord</code> consists of only lower-case English letters.</li>
<li><code>buildDict</code> will be called only once before <code>search</code>.</li>
<li>At most <code>100</code> calls will be made to <code>search</code>.</li>
</ul>
|
Depth-First Search; Design; Trie; Hash Table; String
|
Rust
|
struct Trie {
children: [Option<Box<Trie>>; 26],
is_end: bool,
}
impl Trie {
fn new() -> Self {
Trie {
children: Default::default(),
is_end: false,
}
}
fn insert(&mut self, w: &str) {
let mut node = self;
for c in w.chars() {
let i = (c as usize) - ('a' as usize);
if node.children[i].is_none() {
node.children[i] = Some(Box::new(Trie::new()));
}
node = node.children[i].as_mut().unwrap();
}
node.is_end = true;
}
fn search(&self, w: &str) -> bool {
self.dfs(w, 0, 0)
}
fn dfs(&self, w: &str, i: usize, diff: usize) -> bool {
if i == w.len() {
return diff == 1 && self.is_end;
}
let j = (w.chars().nth(i).unwrap() as usize) - ('a' as usize);
if let Some(child) = &self.children[j] {
if child.dfs(w, i + 1, diff) {
return true;
}
}
if diff == 0 {
for k in 0..26 {
if k != j {
if let Some(child) = &self.children[k] {
if child.dfs(w, i + 1, 1) {
return true;
}
}
}
}
}
false
}
}
struct MagicDictionary {
trie: Trie,
}
impl MagicDictionary {
fn new() -> Self {
MagicDictionary { trie: Trie::new() }
}
fn build_dict(&mut self, dictionary: Vec<String>) {
for w in dictionary {
self.trie.insert(&w);
}
}
fn search(&self, search_word: String) -> bool {
self.trie.search(&search_word)
}
}
|
676
|
Implement Magic Dictionary
|
Medium
|
<p>Design a data structure that is initialized with a list of <strong>different</strong> words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.</p>
<p>Implement the <code>MagicDictionary</code> class:</p>
<ul>
<li><code>MagicDictionary()</code> Initializes the object.</li>
<li><code>void buildDict(String[] dictionary)</code> Sets the data structure with an array of distinct strings <code>dictionary</code>.</li>
<li><code>bool search(String searchWord)</code> Returns <code>true</code> if you can change <strong>exactly one character</strong> in <code>searchWord</code> to match any string in the data structure, otherwise returns <code>false</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
<strong>Output</strong>
[null, null, false, true, false, false]
<strong>Explanation</strong>
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dictionary.length <= 100</code></li>
<li><code>1 <= dictionary[i].length <= 100</code></li>
<li><code>dictionary[i]</code> consists of only lower-case English letters.</li>
<li>All the strings in <code>dictionary</code> are <strong>distinct</strong>.</li>
<li><code>1 <= searchWord.length <= 100</code></li>
<li><code>searchWord</code> consists of only lower-case English letters.</li>
<li><code>buildDict</code> will be called only once before <code>search</code>.</li>
<li>At most <code>100</code> calls will be made to <code>search</code>.</li>
</ul>
|
Depth-First Search; Design; Trie; Hash Table; String
|
TypeScript
|
class Trie {
private children: Trie[] = Array(26).fill(null);
private isEnd: boolean = false;
constructor() {}
insert(w: string): void {
let node: Trie = this;
for (const c of w) {
const i: number = c.charCodeAt(0) - 'a'.charCodeAt(0);
if (!node.children[i]) {
node.children[i] = new Trie();
}
node = node.children[i];
}
node.isEnd = true;
}
search(w: string): boolean {
const dfs = (i: number, node: Trie, diff: number): boolean => {
if (i >= w.length) {
return diff === 1 && node.isEnd;
}
const j: number = w.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.children[j] && dfs(i + 1, node.children[j], diff)) {
return true;
}
if (diff === 0) {
for (let k = 0; k < 26; k++) {
if (k !== j && node.children[k] && dfs(i + 1, node.children[k], 1)) {
return true;
}
}
}
return false;
};
return dfs(0, this, 0);
}
}
class MagicDictionary {
private trie: Trie;
constructor() {
this.trie = new Trie();
}
buildDict(dictionary: string[]): void {
for (const w of dictionary) {
this.trie.insert(w);
}
}
search(searchWord: string): boolean {
return this.trie.search(searchWord);
}
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* var obj = new MagicDictionary()
* obj.buildDict(dictionary)
* var param_2 = obj.search(searchWord)
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.