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
|
|---|---|---|---|---|---|---|
477
|
Total Hamming Distance
|
Medium
|
<p>The <a href="https://en.wikipedia.org/wiki/Hamming_distance" target="_blank">Hamming distance</a> between two integers is the number of positions at which the corresponding bits are different.</p>
<p>Given an integer array <code>nums</code>, return <em>the sum of <strong>Hamming distances</strong> between all the pairs of the integers in</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,2]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,4]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The answer for the given input will fit in a <strong>32-bit</strong> integer.</li>
</ul>
|
Bit Manipulation; Array; Math
|
Rust
|
impl Solution {
pub fn total_hamming_distance(nums: Vec<i32>) -> i32 {
let mut ans = 0;
for i in 0..32 {
let mut a = 0;
for &x in nums.iter() {
a += (x >> i) & 1;
}
let b = (nums.len() as i32) - a;
ans += a * b;
}
ans
}
}
|
477
|
Total Hamming Distance
|
Medium
|
<p>The <a href="https://en.wikipedia.org/wiki/Hamming_distance" target="_blank">Hamming distance</a> between two integers is the number of positions at which the corresponding bits are different.</p>
<p>Given an integer array <code>nums</code>, return <em>the sum of <strong>Hamming distances</strong> between all the pairs of the integers in</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,2]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,4]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The answer for the given input will fit in a <strong>32-bit</strong> integer.</li>
</ul>
|
Bit Manipulation; Array; Math
|
TypeScript
|
function totalHammingDistance(nums: number[]): number {
let ans = 0;
for (let i = 0; i < 32; ++i) {
const a = nums.filter(x => (x >> i) & 1).length;
const b = nums.length - a;
ans += a * b;
}
return ans;
}
|
478
|
Generate Random Point in a Circle
|
Medium
|
<p>Given the radius and the position of the center of a circle, implement the function <code>randPoint</code> which generates a uniform random point inside the circle.</p>
<p>Implement the <code>Solution</code> class:</p>
<ul>
<li><code>Solution(double radius, double x_center, double y_center)</code> initializes the object with the radius of the circle <code>radius</code> and the position of the center <code>(x_center, y_center)</code>.</li>
<li><code>randPoint()</code> returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array <code>[x, y]</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["Solution", "randPoint", "randPoint", "randPoint"]
[[1.0, 0.0, 0.0], [], [], []]
<strong>Output</strong>
[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]
<strong>Explanation</strong>
Solution solution = new Solution(1.0, 0.0, 0.0);
solution.randPoint(); // return [-0.02493, -0.38077]
solution.randPoint(); // return [0.82314, 0.38945]
solution.randPoint(); // return [0.36572, 0.17248]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 < radius <= 10<sup>8</sup></code></li>
<li><code>-10<sup>7</sup> <= x_center, y_center <= 10<sup>7</sup></code></li>
<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>randPoint</code>.</li>
</ul>
|
Geometry; Math; Rejection Sampling; Randomized
|
Python
|
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self) -> List[float]:
length = math.sqrt(random.uniform(0, self.radius**2))
degree = random.uniform(0, 1) * 2 * math.pi
x = self.x_center + length * math.cos(degree)
y = self.y_center + length * math.sin(degree)
return [x, y]
|
479
|
Largest Palindrome Product
|
Hard
|
<p>Given an integer n, return <em>the <strong>largest palindromic integer</strong> that can be represented as the product of two <code>n</code>-digits integers</em>. Since the answer can be very large, return it <strong>modulo</strong> <code>1337</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 9
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 8</code></li>
</ul>
|
Math; Enumeration
|
C++
|
class Solution {
public:
int largestPalindrome(int n) {
int mx = pow(10, n) - 1;
for (int a = mx; a > mx / 10; --a) {
int b = a;
long x = a;
while (b) {
x = x * 10 + b % 10;
b /= 10;
}
for (long t = mx; t * t >= x; --t)
if (x % t == 0)
return x % 1337;
}
return 9;
}
};
|
479
|
Largest Palindrome Product
|
Hard
|
<p>Given an integer n, return <em>the <strong>largest palindromic integer</strong> that can be represented as the product of two <code>n</code>-digits integers</em>. Since the answer can be very large, return it <strong>modulo</strong> <code>1337</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 9
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 8</code></li>
</ul>
|
Math; Enumeration
|
Go
|
func largestPalindrome(n int) int {
mx := int(math.Pow10(n)) - 1
for a := mx; a > mx/10; a-- {
x := a
for b := a; b != 0; b /= 10 {
x = x*10 + b%10
}
for t := mx; t*t >= x; t-- {
if x%t == 0 {
return x % 1337
}
}
}
return 9
}
|
479
|
Largest Palindrome Product
|
Hard
|
<p>Given an integer n, return <em>the <strong>largest palindromic integer</strong> that can be represented as the product of two <code>n</code>-digits integers</em>. Since the answer can be very large, return it <strong>modulo</strong> <code>1337</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 9
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 8</code></li>
</ul>
|
Math; Enumeration
|
Java
|
class Solution {
public int largestPalindrome(int n) {
int mx = (int) Math.pow(10, n) - 1;
for (int a = mx; a > mx / 10; --a) {
int b = a;
long x = a;
while (b != 0) {
x = x * 10 + b % 10;
b /= 10;
}
for (long t = mx; t * t >= x; --t) {
if (x % t == 0) {
return (int) (x % 1337);
}
}
}
return 9;
}
}
|
479
|
Largest Palindrome Product
|
Hard
|
<p>Given an integer n, return <em>the <strong>largest palindromic integer</strong> that can be represented as the product of two <code>n</code>-digits integers</em>. Since the answer can be very large, return it <strong>modulo</strong> <code>1337</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 9
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 8</code></li>
</ul>
|
Math; Enumeration
|
Python
|
class Solution:
def largestPalindrome(self, n: int) -> int:
mx = 10**n - 1
for a in range(mx, mx // 10, -1):
b = x = a
while b:
x = x * 10 + b % 10
b //= 10
t = mx
while t * t >= x:
if x % t == 0:
return x % 1337
t -= 1
return 9
|
480
|
Sliding Window Median
|
Hard
|
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.</p>
<ul>
<li>For examples, if <code>arr = [2,<u>3</u>,4]</code>, the median is <code>3</code>.</li>
<li>For examples, if <code>arr = [1,<u>2,3</u>,4]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li>
</ul>
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. There is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>
<p>Return <em>the median array for each window in the original array</em>. Answers within <code>10<sup>-5</sup></code> of the actual value will be accepted.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3
<strong>Output:</strong> [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
<strong>Explanation:</strong>
Window position Median
--------------- -----
[<strong>1 3 -1</strong>] -3 5 3 6 7 1
1 [<strong>3 -1 -3</strong>] 5 3 6 7 -1
1 3 [<strong>-1 -3 5</strong>] 3 6 7 -1
1 3 -1 [<strong>-3 5 3</strong>] 6 7 3
1 3 -1 -3 [<strong>5 3 6</strong>] 7 5
1 3 -1 -3 5 [<strong>3 6 7</strong>] 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,2,3,1,4,2], k = 3
<strong>Output:</strong> [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Array; Hash Table; Sliding Window; Heap (Priority Queue)
|
C++
|
class MedianFinder {
public:
MedianFinder(int k) {
this->k = k;
}
void addNum(int num) {
if (small.empty() || num <= small.top()) {
small.push(num);
++smallSize;
} else {
large.push(num);
++largeSize;
}
reblance();
}
void removeNum(int num) {
++delayed[num];
if (num <= small.top()) {
--smallSize;
if (num == small.top()) {
prune(small);
}
} else {
--largeSize;
if (num == large.top()) {
prune(large);
}
}
reblance();
}
double findMedian() {
return k & 1 ? small.top() : ((double) small.top() + large.top()) / 2.0;
}
private:
priority_queue<int> small;
priority_queue<int, vector<int>, greater<int>> large;
unordered_map<int, int> delayed;
int smallSize = 0;
int largeSize = 0;
int k;
template <typename T>
void prune(T& pq) {
while (!pq.empty() && delayed[pq.top()]) {
if (--delayed[pq.top()] == 0) {
delayed.erase(pq.top());
}
pq.pop();
}
}
void reblance() {
if (smallSize > largeSize + 1) {
large.push(small.top());
small.pop();
--smallSize;
++largeSize;
prune(small);
} else if (smallSize < largeSize) {
small.push(large.top());
large.pop();
++smallSize;
--largeSize;
prune(large);
}
}
};
class Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
MedianFinder finder(k);
for (int i = 0; i < k; ++i) {
finder.addNum(nums[i]);
}
vector<double> ans = {finder.findMedian()};
for (int i = k; i < nums.size(); ++i) {
finder.addNum(nums[i]);
finder.removeNum(nums[i - k]);
ans.push_back(finder.findMedian());
}
return ans;
}
};
|
480
|
Sliding Window Median
|
Hard
|
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.</p>
<ul>
<li>For examples, if <code>arr = [2,<u>3</u>,4]</code>, the median is <code>3</code>.</li>
<li>For examples, if <code>arr = [1,<u>2,3</u>,4]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li>
</ul>
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. There is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>
<p>Return <em>the median array for each window in the original array</em>. Answers within <code>10<sup>-5</sup></code> of the actual value will be accepted.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3
<strong>Output:</strong> [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
<strong>Explanation:</strong>
Window position Median
--------------- -----
[<strong>1 3 -1</strong>] -3 5 3 6 7 1
1 [<strong>3 -1 -3</strong>] 5 3 6 7 -1
1 3 [<strong>-1 -3 5</strong>] 3 6 7 -1
1 3 -1 [<strong>-3 5 3</strong>] 6 7 3
1 3 -1 -3 [<strong>5 3 6</strong>] 7 5
1 3 -1 -3 5 [<strong>3 6 7</strong>] 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,2,3,1,4,2], k = 3
<strong>Output:</strong> [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Array; Hash Table; Sliding Window; Heap (Priority Queue)
|
Go
|
type MedianFinder struct {
small hp
large hp
delayed map[int]int
smallSize, largeSize int
k int
}
func Constructor(k int) MedianFinder {
return MedianFinder{hp{}, hp{}, map[int]int{}, 0, 0, k}
}
func (this *MedianFinder) AddNum(num int) {
if this.small.Len() == 0 || num <= -this.small.IntSlice[0] {
heap.Push(&this.small, -num)
this.smallSize++
} else {
heap.Push(&this.large, num)
this.largeSize++
}
this.rebalance()
}
func (this *MedianFinder) FindMedian() float64 {
if this.k&1 == 1 {
return float64(-this.small.IntSlice[0])
}
return float64(-this.small.IntSlice[0]+this.large.IntSlice[0]) / 2
}
func (this *MedianFinder) removeNum(num int) {
this.delayed[num]++
if num <= -this.small.IntSlice[0] {
this.smallSize--
if num == -this.small.IntSlice[0] {
this.prune(&this.small)
}
} else {
this.largeSize--
if num == this.large.IntSlice[0] {
this.prune(&this.large)
}
}
this.rebalance()
}
func (this *MedianFinder) prune(pq *hp) {
sign := 1
if pq == &this.small {
sign = -1
}
for pq.Len() > 0 && this.delayed[sign*pq.IntSlice[0]] > 0 {
this.delayed[sign*pq.IntSlice[0]]--
if this.delayed[sign*pq.IntSlice[0]] == 0 {
delete(this.delayed, sign*pq.IntSlice[0])
}
heap.Pop(pq)
}
}
func (this *MedianFinder) rebalance() {
if this.smallSize > this.largeSize+1 {
heap.Push(&this.large, -heap.Pop(&this.small).(int))
this.smallSize--
this.largeSize++
this.prune(&this.small)
} else if this.smallSize < this.largeSize {
heap.Push(&this.small, -heap.Pop(&this.large).(int))
this.smallSize++
this.largeSize--
this.prune(&this.large)
}
}
func medianSlidingWindow(nums []int, k int) []float64 {
finder := Constructor(k)
for _, num := range nums[:k] {
finder.AddNum(num)
}
ans := []float64{finder.FindMedian()}
for i := k; i < len(nums); i++ {
finder.AddNum(nums[i])
finder.removeNum(nums[i-k])
ans = append(ans, finder.FindMedian())
}
return ans
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
|
480
|
Sliding Window Median
|
Hard
|
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.</p>
<ul>
<li>For examples, if <code>arr = [2,<u>3</u>,4]</code>, the median is <code>3</code>.</li>
<li>For examples, if <code>arr = [1,<u>2,3</u>,4]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li>
</ul>
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. There is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>
<p>Return <em>the median array for each window in the original array</em>. Answers within <code>10<sup>-5</sup></code> of the actual value will be accepted.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3
<strong>Output:</strong> [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
<strong>Explanation:</strong>
Window position Median
--------------- -----
[<strong>1 3 -1</strong>] -3 5 3 6 7 1
1 [<strong>3 -1 -3</strong>] 5 3 6 7 -1
1 3 [<strong>-1 -3 5</strong>] 3 6 7 -1
1 3 -1 [<strong>-3 5 3</strong>] 6 7 3
1 3 -1 -3 [<strong>5 3 6</strong>] 7 5
1 3 -1 -3 5 [<strong>3 6 7</strong>] 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,2,3,1,4,2], k = 3
<strong>Output:</strong> [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Array; Hash Table; Sliding Window; Heap (Priority Queue)
|
Java
|
class MedianFinder {
private PriorityQueue<Integer> small = new PriorityQueue<>(Comparator.reverseOrder());
private PriorityQueue<Integer> large = new PriorityQueue<>();
private Map<Integer, Integer> delayed = new HashMap<>();
private int smallSize;
private int largeSize;
private int k;
public MedianFinder(int k) {
this.k = k;
}
public void addNum(int num) {
if (small.isEmpty() || num <= small.peek()) {
small.offer(num);
++smallSize;
} else {
large.offer(num);
++largeSize;
}
rebalance();
}
public double findMedian() {
return (k & 1) == 1 ? small.peek() : ((double) small.peek() + large.peek()) / 2;
}
public void removeNum(int num) {
delayed.merge(num, 1, Integer::sum);
if (num <= small.peek()) {
--smallSize;
if (num == small.peek()) {
prune(small);
}
} else {
--largeSize;
if (num == large.peek()) {
prune(large);
}
}
rebalance();
}
private void prune(PriorityQueue<Integer> pq) {
while (!pq.isEmpty() && delayed.containsKey(pq.peek())) {
if (delayed.merge(pq.peek(), -1, Integer::sum) == 0) {
delayed.remove(pq.peek());
}
pq.poll();
}
}
private void rebalance() {
if (smallSize > largeSize + 1) {
large.offer(small.poll());
--smallSize;
++largeSize;
prune(small);
} else if (smallSize < largeSize) {
small.offer(large.poll());
--largeSize;
++smallSize;
prune(large);
}
}
}
class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
MedianFinder finder = new MedianFinder(k);
for (int i = 0; i < k; ++i) {
finder.addNum(nums[i]);
}
int n = nums.length;
double[] ans = new double[n - k + 1];
ans[0] = finder.findMedian();
for (int i = k; i < n; ++i) {
finder.addNum(nums[i]);
finder.removeNum(nums[i - k]);
ans[i - k + 1] = finder.findMedian();
}
return ans;
}
}
|
480
|
Sliding Window Median
|
Hard
|
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.</p>
<ul>
<li>For examples, if <code>arr = [2,<u>3</u>,4]</code>, the median is <code>3</code>.</li>
<li>For examples, if <code>arr = [1,<u>2,3</u>,4]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li>
</ul>
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. There is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>
<p>Return <em>the median array for each window in the original array</em>. Answers within <code>10<sup>-5</sup></code> of the actual value will be accepted.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3
<strong>Output:</strong> [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
<strong>Explanation:</strong>
Window position Median
--------------- -----
[<strong>1 3 -1</strong>] -3 5 3 6 7 1
1 [<strong>3 -1 -3</strong>] 5 3 6 7 -1
1 3 [<strong>-1 -3 5</strong>] 3 6 7 -1
1 3 -1 [<strong>-3 5 3</strong>] 6 7 3
1 3 -1 -3 [<strong>5 3 6</strong>] 7 5
1 3 -1 -3 5 [<strong>3 6 7</strong>] 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,2,3,1,4,2], k = 3
<strong>Output:</strong> [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Array; Hash Table; Sliding Window; Heap (Priority Queue)
|
Python
|
class MedianFinder:
def __init__(self, k: int):
self.k = k
self.small = []
self.large = []
self.delayed = defaultdict(int)
self.small_size = 0
self.large_size = 0
def add_num(self, num: int):
if not self.small or num <= -self.small[0]:
heappush(self.small, -num)
self.small_size += 1
else:
heappush(self.large, num)
self.large_size += 1
self.rebalance()
def find_median(self) -> float:
return -self.small[0] if self.k & 1 else (-self.small[0] + self.large[0]) / 2
def remove_num(self, num: int):
self.delayed[num] += 1
if num <= -self.small[0]:
self.small_size -= 1
if num == -self.small[0]:
self.prune(self.small)
else:
self.large_size -= 1
if num == self.large[0]:
self.prune(self.large)
self.rebalance()
def prune(self, pq: List[int]):
sign = -1 if pq is self.small else 1
while pq and sign * pq[0] in self.delayed:
self.delayed[sign * pq[0]] -= 1
if self.delayed[sign * pq[0]] == 0:
self.delayed.pop(sign * pq[0])
heappop(pq)
def rebalance(self):
if self.small_size > self.large_size + 1:
heappush(self.large, -heappop(self.small))
self.small_size -= 1
self.large_size += 1
self.prune(self.small)
elif self.small_size < self.large_size:
heappush(self.small, -heappop(self.large))
self.large_size -= 1
self.small_size += 1
self.prune(self.large)
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
finder = MedianFinder(k)
for x in nums[:k]:
finder.add_num(x)
ans = [finder.find_median()]
for i in range(k, len(nums)):
finder.add_num(nums[i])
finder.remove_num(nums[i - k])
ans.append(finder.find_median())
return ans
|
481
|
Magical String
|
Medium
|
<p>A magical string <code>s</code> consists of only <code>'1'</code> and <code>'2'</code> and obeys the following rules:</p>
<ul>
<li>The string s is magical because concatenating the number of contiguous occurrences of characters <code>'1'</code> and <code>'2'</code> generates the string <code>s</code> itself.</li>
</ul>
<p>The first few elements of <code>s</code> is <code>s = "1221121221221121122……"</code>. If we group the consecutive <code>1</code>'s and <code>2</code>'s in <code>s</code>, it will be <code>"1 22 11 2 1 22 1 22 11 2 11 22 ......"</code> and the occurrences of <code>1</code>'s or <code>2</code>'s in each group are <code>"1 2 2 1 1 2 1 2 2 1 2 2 ......"</code>. You can see that the occurrence sequence is <code>s</code> itself.</p>
<p>Given an integer <code>n</code>, return the number of <code>1</code>'s in the first <code>n</code> number in the magical string <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Two Pointers; String
|
C++
|
class Solution {
public:
int magicalString(int n) {
vector<int> s = {1, 2, 2};
for (int i = 2; s.size() < n; ++i) {
int pre = s.back();
int cur = 3 - pre;
for (int j = 0; j < s[i]; ++j) {
s.emplace_back(cur);
}
}
return count(s.begin(), s.begin() + n, 1);
}
};
|
481
|
Magical String
|
Medium
|
<p>A magical string <code>s</code> consists of only <code>'1'</code> and <code>'2'</code> and obeys the following rules:</p>
<ul>
<li>The string s is magical because concatenating the number of contiguous occurrences of characters <code>'1'</code> and <code>'2'</code> generates the string <code>s</code> itself.</li>
</ul>
<p>The first few elements of <code>s</code> is <code>s = "1221121221221121122……"</code>. If we group the consecutive <code>1</code>'s and <code>2</code>'s in <code>s</code>, it will be <code>"1 22 11 2 1 22 1 22 11 2 11 22 ......"</code> and the occurrences of <code>1</code>'s or <code>2</code>'s in each group are <code>"1 2 2 1 1 2 1 2 2 1 2 2 ......"</code>. You can see that the occurrence sequence is <code>s</code> itself.</p>
<p>Given an integer <code>n</code>, return the number of <code>1</code>'s in the first <code>n</code> number in the magical string <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Two Pointers; String
|
Go
|
func magicalString(n int) (ans int) {
s := []int{1, 2, 2}
for i := 2; len(s) < n; i++ {
pre := s[len(s)-1]
cur := 3 - pre
for j := 0; j < s[i]; j++ {
s = append(s, cur)
}
}
for _, c := range s[:n] {
if c == 1 {
ans++
}
}
return
}
|
481
|
Magical String
|
Medium
|
<p>A magical string <code>s</code> consists of only <code>'1'</code> and <code>'2'</code> and obeys the following rules:</p>
<ul>
<li>The string s is magical because concatenating the number of contiguous occurrences of characters <code>'1'</code> and <code>'2'</code> generates the string <code>s</code> itself.</li>
</ul>
<p>The first few elements of <code>s</code> is <code>s = "1221121221221121122……"</code>. If we group the consecutive <code>1</code>'s and <code>2</code>'s in <code>s</code>, it will be <code>"1 22 11 2 1 22 1 22 11 2 11 22 ......"</code> and the occurrences of <code>1</code>'s or <code>2</code>'s in each group are <code>"1 2 2 1 1 2 1 2 2 1 2 2 ......"</code>. You can see that the occurrence sequence is <code>s</code> itself.</p>
<p>Given an integer <code>n</code>, return the number of <code>1</code>'s in the first <code>n</code> number in the magical string <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Two Pointers; String
|
Java
|
class Solution {
public int magicalString(int n) {
List<Integer> s = new ArrayList<>(List.of(1, 2, 2));
for (int i = 2; s.size() < n; ++i) {
int pre = s.get(s.size() - 1);
int cur = 3 - pre;
for (int j = 0; j < s.get(i); ++j) {
s.add(cur);
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
if (s.get(i) == 1) {
++ans;
}
}
return ans;
}
}
|
481
|
Magical String
|
Medium
|
<p>A magical string <code>s</code> consists of only <code>'1'</code> and <code>'2'</code> and obeys the following rules:</p>
<ul>
<li>The string s is magical because concatenating the number of contiguous occurrences of characters <code>'1'</code> and <code>'2'</code> generates the string <code>s</code> itself.</li>
</ul>
<p>The first few elements of <code>s</code> is <code>s = "1221121221221121122……"</code>. If we group the consecutive <code>1</code>'s and <code>2</code>'s in <code>s</code>, it will be <code>"1 22 11 2 1 22 1 22 11 2 11 22 ......"</code> and the occurrences of <code>1</code>'s or <code>2</code>'s in each group are <code>"1 2 2 1 1 2 1 2 2 1 2 2 ......"</code>. You can see that the occurrence sequence is <code>s</code> itself.</p>
<p>Given an integer <code>n</code>, return the number of <code>1</code>'s in the first <code>n</code> number in the magical string <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Two Pointers; String
|
Python
|
class Solution:
def magicalString(self, n: int) -> int:
s = [1, 2, 2]
i = 2
while len(s) < n:
pre = s[-1]
cur = 3 - pre
s += [cur] * s[i]
i += 1
return s[:n].count(1)
|
481
|
Magical String
|
Medium
|
<p>A magical string <code>s</code> consists of only <code>'1'</code> and <code>'2'</code> and obeys the following rules:</p>
<ul>
<li>The string s is magical because concatenating the number of contiguous occurrences of characters <code>'1'</code> and <code>'2'</code> generates the string <code>s</code> itself.</li>
</ul>
<p>The first few elements of <code>s</code> is <code>s = "1221121221221121122……"</code>. If we group the consecutive <code>1</code>'s and <code>2</code>'s in <code>s</code>, it will be <code>"1 22 11 2 1 22 1 22 11 2 11 22 ......"</code> and the occurrences of <code>1</code>'s or <code>2</code>'s in each group are <code>"1 2 2 1 1 2 1 2 2 1 2 2 ......"</code>. You can see that the occurrence sequence is <code>s</code> itself.</p>
<p>Given an integer <code>n</code>, return the number of <code>1</code>'s in the first <code>n</code> number in the magical string <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Two Pointers; String
|
Rust
|
impl Solution {
pub fn magical_string(n: i32) -> i32 {
let mut s = vec![1, 2, 2];
let mut i = 2;
while s.len() < n as usize {
let pre = s[s.len() - 1];
let cur = 3 - pre;
for _ in 0..s[i] {
s.push(cur);
}
i += 1;
}
s.iter().take(n as usize).filter(|&&x| x == 1).count() as i32
}
}
|
481
|
Magical String
|
Medium
|
<p>A magical string <code>s</code> consists of only <code>'1'</code> and <code>'2'</code> and obeys the following rules:</p>
<ul>
<li>The string s is magical because concatenating the number of contiguous occurrences of characters <code>'1'</code> and <code>'2'</code> generates the string <code>s</code> itself.</li>
</ul>
<p>The first few elements of <code>s</code> is <code>s = "1221121221221121122……"</code>. If we group the consecutive <code>1</code>'s and <code>2</code>'s in <code>s</code>, it will be <code>"1 22 11 2 1 22 1 22 11 2 11 22 ......"</code> and the occurrences of <code>1</code>'s or <code>2</code>'s in each group are <code>"1 2 2 1 1 2 1 2 2 1 2 2 ......"</code>. You can see that the occurrence sequence is <code>s</code> itself.</p>
<p>Given an integer <code>n</code>, return the number of <code>1</code>'s in the first <code>n</code> number in the magical string <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Two Pointers; String
|
TypeScript
|
function magicalString(n: number): number {
const s: number[] = [1, 2, 2];
for (let i = 2; s.length < n; ++i) {
let pre = s[s.length - 1];
let cur = 3 - pre;
for (let j = 0; j < s[i]; ++j) {
s.push(cur);
}
}
return s.slice(0, n).filter(x => x === 1).length;
}
|
482
|
License Key Formatting
|
Easy
|
<p>You are given a license key represented as a string <code>s</code> that consists of only alphanumeric characters and dashes. The string is separated into <code>n + 1</code> groups by <code>n</code> dashes. You are also given an integer <code>k</code>.</p>
<p>We want to reformat the string <code>s</code> such that each group contains exactly <code>k</code> characters, except for the first group, which could be shorter than <code>k</code> but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.</p>
<p>Return <em>the reformatted license key</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "5F3Z-2e-9-w", k = 4
<strong>Output:</strong> "5F3Z-2E9W"
<strong>Explanation:</strong> The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "2-5g-3-J", k = 2
<strong>Output:</strong> "2-5G-3J"
<strong>Explanation:</strong> The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of English letters, digits, and dashes <code>'-'</code>.</li>
<li><code>1 <= k <= 10<sup>4</sup></code></li>
</ul>
|
String
|
C++
|
class Solution {
public:
string licenseKeyFormatting(string s, int k) {
int n = s.length();
int cnt = (n - count(s.begin(), s.end(), '-')) % k;
if (cnt == 0) {
cnt = k;
}
string ans;
for (int i = 0; i < n; ++i) {
char c = s[i];
if (c == '-') {
continue;
}
ans += toupper(c);
if (--cnt == 0) {
cnt = k;
if (i != n - 1) {
ans += '-';
}
}
}
if (!ans.empty() && ans.back() == '-') {
ans.pop_back();
}
return ans;
}
};
|
482
|
License Key Formatting
|
Easy
|
<p>You are given a license key represented as a string <code>s</code> that consists of only alphanumeric characters and dashes. The string is separated into <code>n + 1</code> groups by <code>n</code> dashes. You are also given an integer <code>k</code>.</p>
<p>We want to reformat the string <code>s</code> such that each group contains exactly <code>k</code> characters, except for the first group, which could be shorter than <code>k</code> but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.</p>
<p>Return <em>the reformatted license key</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "5F3Z-2e-9-w", k = 4
<strong>Output:</strong> "5F3Z-2E9W"
<strong>Explanation:</strong> The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "2-5g-3-J", k = 2
<strong>Output:</strong> "2-5G-3J"
<strong>Explanation:</strong> The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of English letters, digits, and dashes <code>'-'</code>.</li>
<li><code>1 <= k <= 10<sup>4</sup></code></li>
</ul>
|
String
|
Go
|
func licenseKeyFormatting(s string, k int) string {
n := len(s)
cnt := (n - strings.Count(s, "-")) % k
if cnt == 0 {
cnt = k
}
var ans strings.Builder
for i := 0; i < n; i++ {
c := s[i]
if c == '-' {
continue
}
if cnt == 0 {
cnt = k
ans.WriteByte('-')
}
ans.WriteRune(unicode.ToUpper(rune(c)))
cnt--
}
return ans.String()
}
|
482
|
License Key Formatting
|
Easy
|
<p>You are given a license key represented as a string <code>s</code> that consists of only alphanumeric characters and dashes. The string is separated into <code>n + 1</code> groups by <code>n</code> dashes. You are also given an integer <code>k</code>.</p>
<p>We want to reformat the string <code>s</code> such that each group contains exactly <code>k</code> characters, except for the first group, which could be shorter than <code>k</code> but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.</p>
<p>Return <em>the reformatted license key</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "5F3Z-2e-9-w", k = 4
<strong>Output:</strong> "5F3Z-2E9W"
<strong>Explanation:</strong> The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "2-5g-3-J", k = 2
<strong>Output:</strong> "2-5G-3J"
<strong>Explanation:</strong> The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of English letters, digits, and dashes <code>'-'</code>.</li>
<li><code>1 <= k <= 10<sup>4</sup></code></li>
</ul>
|
String
|
Java
|
class Solution {
public String licenseKeyFormatting(String s, int k) {
int n = s.length();
int cnt = (int) (n - s.chars().filter(ch -> ch == '-').count()) % k;
if (cnt == 0) {
cnt = k;
}
StringBuilder ans = new StringBuilder();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c == '-') {
continue;
}
ans.append(Character.toUpperCase(c));
--cnt;
if (cnt == 0) {
cnt = k;
if (i != n - 1) {
ans.append('-');
}
}
}
if (ans.length() > 0 && ans.charAt(ans.length() - 1) == '-') {
ans.deleteCharAt(ans.length() - 1);
}
return ans.toString();
}
}
|
482
|
License Key Formatting
|
Easy
|
<p>You are given a license key represented as a string <code>s</code> that consists of only alphanumeric characters and dashes. The string is separated into <code>n + 1</code> groups by <code>n</code> dashes. You are also given an integer <code>k</code>.</p>
<p>We want to reformat the string <code>s</code> such that each group contains exactly <code>k</code> characters, except for the first group, which could be shorter than <code>k</code> but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.</p>
<p>Return <em>the reformatted license key</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "5F3Z-2e-9-w", k = 4
<strong>Output:</strong> "5F3Z-2E9W"
<strong>Explanation:</strong> The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "2-5g-3-J", k = 2
<strong>Output:</strong> "2-5G-3J"
<strong>Explanation:</strong> The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of English letters, digits, and dashes <code>'-'</code>.</li>
<li><code>1 <= k <= 10<sup>4</sup></code></li>
</ul>
|
String
|
Python
|
class Solution:
def licenseKeyFormatting(self, s: str, k: int) -> str:
n = len(s)
cnt = (n - s.count("-")) % k or k
ans = []
for i, c in enumerate(s):
if c == "-":
continue
ans.append(c.upper())
cnt -= 1
if cnt == 0:
cnt = k
if i != n - 1:
ans.append("-")
return "".join(ans).rstrip("-")
|
482
|
License Key Formatting
|
Easy
|
<p>You are given a license key represented as a string <code>s</code> that consists of only alphanumeric characters and dashes. The string is separated into <code>n + 1</code> groups by <code>n</code> dashes. You are also given an integer <code>k</code>.</p>
<p>We want to reformat the string <code>s</code> such that each group contains exactly <code>k</code> characters, except for the first group, which could be shorter than <code>k</code> but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.</p>
<p>Return <em>the reformatted license key</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "5F3Z-2e-9-w", k = 4
<strong>Output:</strong> "5F3Z-2E9W"
<strong>Explanation:</strong> The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "2-5g-3-J", k = 2
<strong>Output:</strong> "2-5G-3J"
<strong>Explanation:</strong> The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of English letters, digits, and dashes <code>'-'</code>.</li>
<li><code>1 <= k <= 10<sup>4</sup></code></li>
</ul>
|
String
|
TypeScript
|
function licenseKeyFormatting(s: string, k: number): string {
const n = s.length;
let cnt = (n - (s.match(/-/g) || []).length) % k || k;
const ans: string[] = [];
for (let i = 0; i < n; i++) {
const c = s[i];
if (c === '-') {
continue;
}
ans.push(c.toUpperCase());
if (--cnt === 0) {
cnt = k;
if (i !== n - 1) {
ans.push('-');
}
}
}
while (ans.at(-1) === '-') {
ans.pop();
}
return ans.join('');
}
|
483
|
Smallest Good Base
|
Hard
|
<p>Given an integer <code>n</code> represented as a string, return <em>the smallest <strong>good base</strong> of</em> <code>n</code>.</p>
<p>We call <code>k >= 2</code> a <strong>good base</strong> of <code>n</code>, if all digits of <code>n</code> base <code>k</code> are <code>1</code>'s.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = "13"
<strong>Output:</strong> "3"
<strong>Explanation:</strong> 13 base 3 is 111.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = "4681"
<strong>Output:</strong> "8"
<strong>Explanation:</strong> 4681 base 8 is 11111.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = "1000000000000000000"
<strong>Output:</strong> "999999999999999999"
<strong>Explanation:</strong> 1000000000000000000 base 999999999999999999 is 11.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n</code> is an integer in the range <code>[3, 10<sup>18</sup>]</code>.</li>
<li><code>n</code> does not contain any leading zeros.</li>
</ul>
|
Math; Binary Search
|
C++
|
class Solution {
public:
string smallestGoodBase(string n) {
long v = stol(n);
int mx = floor(log(v) / log(2));
for (int m = mx; m > 1; --m) {
int k = pow(v, 1.0 / m);
long mul = 1, s = 1;
for (int i = 0; i < m; ++i) {
mul *= k;
s += mul;
}
if (s == v) {
return to_string(k);
}
}
return to_string(v - 1);
}
};
|
483
|
Smallest Good Base
|
Hard
|
<p>Given an integer <code>n</code> represented as a string, return <em>the smallest <strong>good base</strong> of</em> <code>n</code>.</p>
<p>We call <code>k >= 2</code> a <strong>good base</strong> of <code>n</code>, if all digits of <code>n</code> base <code>k</code> are <code>1</code>'s.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = "13"
<strong>Output:</strong> "3"
<strong>Explanation:</strong> 13 base 3 is 111.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = "4681"
<strong>Output:</strong> "8"
<strong>Explanation:</strong> 4681 base 8 is 11111.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = "1000000000000000000"
<strong>Output:</strong> "999999999999999999"
<strong>Explanation:</strong> 1000000000000000000 base 999999999999999999 is 11.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n</code> is an integer in the range <code>[3, 10<sup>18</sup>]</code>.</li>
<li><code>n</code> does not contain any leading zeros.</li>
</ul>
|
Math; Binary Search
|
Java
|
class Solution {
public String smallestGoodBase(String n) {
long num = Long.parseLong(n);
for (int len = 63; len >= 2; --len) {
long radix = getRadix(len, num);
if (radix != -1) {
return String.valueOf(radix);
}
}
return String.valueOf(num - 1);
}
private long getRadix(int len, long num) {
long l = 2, r = num - 1;
while (l < r) {
long mid = l + r >>> 1;
if (calc(mid, len) >= num)
r = mid;
else
l = mid + 1;
}
return calc(r, len) == num ? r : -1;
}
private long calc(long radix, int len) {
long p = 1;
long sum = 0;
for (int i = 0; i < len; ++i) {
if (Long.MAX_VALUE - sum < p) {
return Long.MAX_VALUE;
}
sum += p;
if (Long.MAX_VALUE / p < radix) {
p = Long.MAX_VALUE;
} else {
p *= radix;
}
}
return sum;
}
}
|
483
|
Smallest Good Base
|
Hard
|
<p>Given an integer <code>n</code> represented as a string, return <em>the smallest <strong>good base</strong> of</em> <code>n</code>.</p>
<p>We call <code>k >= 2</code> a <strong>good base</strong> of <code>n</code>, if all digits of <code>n</code> base <code>k</code> are <code>1</code>'s.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = "13"
<strong>Output:</strong> "3"
<strong>Explanation:</strong> 13 base 3 is 111.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = "4681"
<strong>Output:</strong> "8"
<strong>Explanation:</strong> 4681 base 8 is 11111.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = "1000000000000000000"
<strong>Output:</strong> "999999999999999999"
<strong>Explanation:</strong> 1000000000000000000 base 999999999999999999 is 11.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n</code> is an integer in the range <code>[3, 10<sup>18</sup>]</code>.</li>
<li><code>n</code> does not contain any leading zeros.</li>
</ul>
|
Math; Binary Search
|
Python
|
class Solution:
def smallestGoodBase(self, n: str) -> str:
def cal(k, m):
p = s = 1
for i in range(m):
p *= k
s += p
return s
num = int(n)
for m in range(63, 1, -1):
l, r = 2, num - 1
while l < r:
mid = (l + r) >> 1
if cal(mid, m) >= num:
r = mid
else:
l = mid + 1
if cal(l, m) == num:
return str(l)
return str(num - 1)
|
484
|
Find Permutation
|
Medium
|
<p>A permutation <code>perm</code> of <code>n</code> integers of all the integers in the range <code>[1, n]</code> can be represented as a string <code>s</code> of length <code>n - 1</code> where:</p>
<ul>
<li><code>s[i] == 'I'</code> if <code>perm[i] < perm[i + 1]</code>, and</li>
<li><code>s[i] == 'D'</code> if <code>perm[i] > perm[i + 1]</code>.</li>
</ul>
<p>Given a string <code>s</code>, reconstruct the lexicographically smallest permutation <code>perm</code> and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "I"
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong> [1,2] is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "DI"
<strong>Output:</strong> [2,1,3]
<strong>Explanation:</strong> Both [2,1,3] and [3,1,2] can be represented as "DI", but since we want to find the smallest lexicographical permutation, you should return [2,1,3]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'I'</code> or <code>'D'</code>.</li>
</ul>
|
Stack; Greedy; Array; String
|
C++
|
class Solution {
public:
vector<int> findPermutation(string s) {
int n = s.size();
vector<int> ans(n + 1);
iota(ans.begin(), ans.end(), 1);
int i = 0;
while (i < n) {
int j = i;
while (j < n && s[j] == 'D') {
++j;
}
reverse(ans.begin() + i, ans.begin() + j + 1);
i = max(i + 1, j);
}
return ans;
}
};
|
484
|
Find Permutation
|
Medium
|
<p>A permutation <code>perm</code> of <code>n</code> integers of all the integers in the range <code>[1, n]</code> can be represented as a string <code>s</code> of length <code>n - 1</code> where:</p>
<ul>
<li><code>s[i] == 'I'</code> if <code>perm[i] < perm[i + 1]</code>, and</li>
<li><code>s[i] == 'D'</code> if <code>perm[i] > perm[i + 1]</code>.</li>
</ul>
<p>Given a string <code>s</code>, reconstruct the lexicographically smallest permutation <code>perm</code> and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "I"
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong> [1,2] is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "DI"
<strong>Output:</strong> [2,1,3]
<strong>Explanation:</strong> Both [2,1,3] and [3,1,2] can be represented as "DI", but since we want to find the smallest lexicographical permutation, you should return [2,1,3]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'I'</code> or <code>'D'</code>.</li>
</ul>
|
Stack; Greedy; Array; String
|
Go
|
func findPermutation(s string) []int {
n := len(s)
ans := make([]int, n+1)
for i := range ans {
ans[i] = i + 1
}
i := 0
for i < n {
j := i
for ; j < n && s[j] == 'D'; j++ {
}
reverse(ans, i, j)
i = max(i+1, j)
}
return ans
}
func reverse(arr []int, i, j int) {
for ; i < j; i, j = i+1, j-1 {
arr[i], arr[j] = arr[j], arr[i]
}
}
|
484
|
Find Permutation
|
Medium
|
<p>A permutation <code>perm</code> of <code>n</code> integers of all the integers in the range <code>[1, n]</code> can be represented as a string <code>s</code> of length <code>n - 1</code> where:</p>
<ul>
<li><code>s[i] == 'I'</code> if <code>perm[i] < perm[i + 1]</code>, and</li>
<li><code>s[i] == 'D'</code> if <code>perm[i] > perm[i + 1]</code>.</li>
</ul>
<p>Given a string <code>s</code>, reconstruct the lexicographically smallest permutation <code>perm</code> and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "I"
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong> [1,2] is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "DI"
<strong>Output:</strong> [2,1,3]
<strong>Explanation:</strong> Both [2,1,3] and [3,1,2] can be represented as "DI", but since we want to find the smallest lexicographical permutation, you should return [2,1,3]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'I'</code> or <code>'D'</code>.</li>
</ul>
|
Stack; Greedy; Array; String
|
Java
|
class Solution {
public int[] findPermutation(String s) {
int n = s.length();
int[] ans = new int[n + 1];
for (int i = 0; i < n + 1; ++i) {
ans[i] = i + 1;
}
int i = 0;
while (i < n) {
int j = i;
while (j < n && s.charAt(j) == 'D') {
++j;
}
reverse(ans, i, j);
i = Math.max(i + 1, j);
}
return ans;
}
private void reverse(int[] arr, int i, int j) {
for (; i < j; ++i, --j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
|
484
|
Find Permutation
|
Medium
|
<p>A permutation <code>perm</code> of <code>n</code> integers of all the integers in the range <code>[1, n]</code> can be represented as a string <code>s</code> of length <code>n - 1</code> where:</p>
<ul>
<li><code>s[i] == 'I'</code> if <code>perm[i] < perm[i + 1]</code>, and</li>
<li><code>s[i] == 'D'</code> if <code>perm[i] > perm[i + 1]</code>.</li>
</ul>
<p>Given a string <code>s</code>, reconstruct the lexicographically smallest permutation <code>perm</code> and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "I"
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong> [1,2] is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "DI"
<strong>Output:</strong> [2,1,3]
<strong>Explanation:</strong> Both [2,1,3] and [3,1,2] can be represented as "DI", but since we want to find the smallest lexicographical permutation, you should return [2,1,3]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'I'</code> or <code>'D'</code>.</li>
</ul>
|
Stack; Greedy; Array; String
|
Python
|
class Solution:
def findPermutation(self, s: str) -> List[int]:
n = len(s)
ans = list(range(1, n + 2))
i = 0
while i < n:
j = i
while j < n and s[j] == 'D':
j += 1
ans[i : j + 1] = ans[i : j + 1][::-1]
i = max(i + 1, j)
return ans
|
485
|
Max Consecutive Ones
|
Easy
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,0,1,1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int ans = 0, cnt = 0;
for (int x : nums) {
if (x) {
ans = max(ans, ++cnt);
} else {
cnt = 0;
}
}
return ans;
}
};
|
485
|
Max Consecutive Ones
|
Easy
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,0,1,1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array
|
Go
|
func findMaxConsecutiveOnes(nums []int) (ans int) {
cnt := 0
for _, x := range nums {
if x == 1 {
cnt++
ans = max(ans, cnt)
} else {
cnt = 0
}
}
return
}
|
485
|
Max Consecutive Ones
|
Easy
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,0,1,1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array
|
Java
|
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int ans = 0, cnt = 0;
for (int x : nums) {
if (x == 1) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 0;
}
}
return ans;
}
}
|
485
|
Max Consecutive Ones
|
Easy
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,0,1,1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array
|
JavaScript
|
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxConsecutiveOnes = function (nums) {
let [ans, cnt] = [0, 0];
for (const x of nums) {
if (x) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 0;
}
}
return ans;
};
|
485
|
Max Consecutive Ones
|
Easy
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,0,1,1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array
|
PHP
|
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function findMaxConsecutiveOnes($nums) {
$ans = $cnt = 0;
foreach ($nums as $x) {
if ($x == 1) {
$cnt += 1;
$ans = max($ans, $cnt);
} else {
$cnt = 0;
}
}
return $ans;
}
}
|
485
|
Max Consecutive Ones
|
Easy
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,0,1,1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array
|
Python
|
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
ans = cnt = 0
for x in nums:
if x:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans
|
485
|
Max Consecutive Ones
|
Easy
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,0,1,1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array
|
Rust
|
impl Solution {
pub fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
let mut ans = 0;
let mut cnt = 0;
for &x in nums.iter() {
if x == 1 {
cnt += 1;
ans = ans.max(cnt);
} else {
cnt = 0;
}
}
ans
}
}
|
485
|
Max Consecutive Ones
|
Easy
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,0,1,1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array
|
TypeScript
|
function findMaxConsecutiveOnes(nums: number[]): number {
let [ans, cnt] = [0, 0];
for (const x of nums) {
if (x) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 0;
}
}
return ans;
}
|
486
|
Predict the Winner
|
Medium
|
<p>You are given an integer array <code>nums</code>. Two players are playing a game with this array: player 1 and player 2.</p>
<p>Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of <code>0</code>. At each turn, the player takes one of the numbers from either end of the array (i.e., <code>nums[0]</code> or <code>nums[nums.length - 1]</code>) which reduces the size of the array by <code>1</code>. The player adds the chosen number to their score. The game ends when there are no more elements in the array.</p>
<p>Return <code>true</code> if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return <code>true</code>. You may assume that both players are playing optimally.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,233,7]
<strong>Output:</strong> true
<strong>Explanation:</strong> Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 10<sup>7</sup></code></li>
</ul>
|
Recursion; Array; Math; Dynamic Programming; Game Theory
|
C++
|
class Solution {
public:
bool predictTheWinner(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> f(n, vector<int>(n));
auto dfs = [&](this auto&& dfs, int i, int j) -> int {
if (i > j) {
return 0;
}
if (f[i][j]) {
return f[i][j];
}
return f[i][j] = max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1));
};
return dfs(0, n - 1) >= 0;
}
};
|
486
|
Predict the Winner
|
Medium
|
<p>You are given an integer array <code>nums</code>. Two players are playing a game with this array: player 1 and player 2.</p>
<p>Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of <code>0</code>. At each turn, the player takes one of the numbers from either end of the array (i.e., <code>nums[0]</code> or <code>nums[nums.length - 1]</code>) which reduces the size of the array by <code>1</code>. The player adds the chosen number to their score. The game ends when there are no more elements in the array.</p>
<p>Return <code>true</code> if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return <code>true</code>. You may assume that both players are playing optimally.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,233,7]
<strong>Output:</strong> true
<strong>Explanation:</strong> Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 10<sup>7</sup></code></li>
</ul>
|
Recursion; Array; Math; Dynamic Programming; Game Theory
|
Go
|
func predictTheWinner(nums []int) bool {
n := len(nums)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n)
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
if i > j {
return 0
}
if f[i][j] == 0 {
f[i][j] = max(nums[i]-dfs(i+1, j), nums[j]-dfs(i, j-1))
}
return f[i][j]
}
return dfs(0, n-1) >= 0
}
|
486
|
Predict the Winner
|
Medium
|
<p>You are given an integer array <code>nums</code>. Two players are playing a game with this array: player 1 and player 2.</p>
<p>Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of <code>0</code>. At each turn, the player takes one of the numbers from either end of the array (i.e., <code>nums[0]</code> or <code>nums[nums.length - 1]</code>) which reduces the size of the array by <code>1</code>. The player adds the chosen number to their score. The game ends when there are no more elements in the array.</p>
<p>Return <code>true</code> if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return <code>true</code>. You may assume that both players are playing optimally.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,233,7]
<strong>Output:</strong> true
<strong>Explanation:</strong> Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 10<sup>7</sup></code></li>
</ul>
|
Recursion; Array; Math; Dynamic Programming; Game Theory
|
Java
|
class Solution {
private int[] nums;
private int[][] f;
public boolean predictTheWinner(int[] nums) {
this.nums = nums;
int n = nums.length;
f = new int[n][n];
return dfs(0, n - 1) >= 0;
}
private int dfs(int i, int j) {
if (i > j) {
return 0;
}
if (f[i][j] != 0) {
return f[i][j];
}
return f[i][j] = Math.max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1));
}
}
|
486
|
Predict the Winner
|
Medium
|
<p>You are given an integer array <code>nums</code>. Two players are playing a game with this array: player 1 and player 2.</p>
<p>Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of <code>0</code>. At each turn, the player takes one of the numbers from either end of the array (i.e., <code>nums[0]</code> or <code>nums[nums.length - 1]</code>) which reduces the size of the array by <code>1</code>. The player adds the chosen number to their score. The game ends when there are no more elements in the array.</p>
<p>Return <code>true</code> if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return <code>true</code>. You may assume that both players are playing optimally.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,233,7]
<strong>Output:</strong> true
<strong>Explanation:</strong> Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 10<sup>7</sup></code></li>
</ul>
|
Recursion; Array; Math; Dynamic Programming; Game Theory
|
Python
|
class Solution:
def predictTheWinner(self, nums: List[int]) -> bool:
@cache
def dfs(i: int, j: int) -> int:
if i > j:
return 0
return max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1))
return dfs(0, len(nums) - 1) >= 0
|
486
|
Predict the Winner
|
Medium
|
<p>You are given an integer array <code>nums</code>. Two players are playing a game with this array: player 1 and player 2.</p>
<p>Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of <code>0</code>. At each turn, the player takes one of the numbers from either end of the array (i.e., <code>nums[0]</code> or <code>nums[nums.length - 1]</code>) which reduces the size of the array by <code>1</code>. The player adds the chosen number to their score. The game ends when there are no more elements in the array.</p>
<p>Return <code>true</code> if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return <code>true</code>. You may assume that both players are playing optimally.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,233,7]
<strong>Output:</strong> true
<strong>Explanation:</strong> Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 10<sup>7</sup></code></li>
</ul>
|
Recursion; Array; Math; Dynamic Programming; Game Theory
|
Rust
|
impl Solution {
pub fn predict_the_winner(nums: Vec<i32>) -> bool {
let n = nums.len();
let mut f = vec![vec![0; n]; n];
Self::dfs(&nums, &mut f, 0, n - 1) >= 0
}
fn dfs(nums: &Vec<i32>, f: &mut Vec<Vec<i32>>, i: usize, j: usize) -> i32 {
if i == j {
return nums[i] as i32;
}
if f[i][j] != 0 {
return f[i][j];
}
f[i][j] = std::cmp::max(
nums[i] - Self::dfs(nums, f, i + 1, j),
nums[j] - Self::dfs(nums, f, i, j - 1),
);
f[i][j]
}
}
|
486
|
Predict the Winner
|
Medium
|
<p>You are given an integer array <code>nums</code>. Two players are playing a game with this array: player 1 and player 2.</p>
<p>Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of <code>0</code>. At each turn, the player takes one of the numbers from either end of the array (i.e., <code>nums[0]</code> or <code>nums[nums.length - 1]</code>) which reduces the size of the array by <code>1</code>. The player adds the chosen number to their score. The game ends when there are no more elements in the array.</p>
<p>Return <code>true</code> if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return <code>true</code>. You may assume that both players are playing optimally.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,5,233,7]
<strong>Output:</strong> true
<strong>Explanation:</strong> Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 10<sup>7</sup></code></li>
</ul>
|
Recursion; Array; Math; Dynamic Programming; Game Theory
|
TypeScript
|
function predictTheWinner(nums: number[]): boolean {
const n = nums.length;
const f: number[][] = Array.from({ length: n }, () => Array(n).fill(0));
const dfs = (i: number, j: number): number => {
if (i > j) {
return 0;
}
if (f[i][j] === 0) {
f[i][j] = Math.max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1));
}
return f[i][j];
};
return dfs(0, n - 1) >= 0;
}
|
487
|
Max Consecutive Ones II
|
Medium
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array if you can flip at most one</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?</p>
|
Array; Dynamic Programming; Sliding Window
|
C++
|
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int l = 0, cnt = 0;
for (int x : nums) {
cnt += x ^ 1;
if (cnt > 1) {
cnt -= nums[l++] ^ 1;
}
}
return nums.size() - l;
}
};
|
487
|
Max Consecutive Ones II
|
Medium
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array if you can flip at most one</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?</p>
|
Array; Dynamic Programming; Sliding Window
|
Go
|
func findMaxConsecutiveOnes(nums []int) int {
l, cnt := 0, 0
for _, x := range nums {
cnt += x ^ 1
if cnt > 1 {
cnt -= nums[l] ^ 1
l++
}
}
return len(nums) - l
}
|
487
|
Max Consecutive Ones II
|
Medium
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array if you can flip at most one</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?</p>
|
Array; Dynamic Programming; Sliding Window
|
Java
|
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int l = 0, cnt = 0;
for (int x : nums) {
cnt += x ^ 1;
if (cnt > 1) {
cnt -= nums[l++] ^ 1;
}
}
return nums.length - l;
}
}
|
487
|
Max Consecutive Ones II
|
Medium
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array if you can flip at most one</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?</p>
|
Array; Dynamic Programming; Sliding Window
|
JavaScript
|
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxConsecutiveOnes = function (nums) {
let [l, cnt] = [0, 0];
for (const x of nums) {
cnt += x ^ 1;
if (cnt > 1) {
cnt -= nums[l++] ^ 1;
}
}
return nums.length - l;
};
|
487
|
Max Consecutive Ones II
|
Medium
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array if you can flip at most one</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?</p>
|
Array; Dynamic Programming; Sliding Window
|
Python
|
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
l = cnt = 0
for x in nums:
cnt += x ^ 1
if cnt > 1:
cnt -= nums[l] ^ 1
l += 1
return len(nums) - l
|
487
|
Max Consecutive Ones II
|
Medium
|
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array if you can flip at most one</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,0,1,1,0,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
The max number of consecutive ones is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?</p>
|
Array; Dynamic Programming; Sliding Window
|
TypeScript
|
function findMaxConsecutiveOnes(nums: number[]): number {
let [l, cnt] = [0, 0];
for (const x of nums) {
cnt += x ^ 1;
if (cnt > 1) {
cnt -= nums[l++] ^ 1;
}
}
return nums.length - l;
}
|
488
|
Zuma Game
|
Hard
|
<p>You are playing a variation of the game Zuma.</p>
<p>In this variation of Zuma, there is a <strong>single row</strong> of colored balls on a board, where each ball can be colored red <code>'R'</code>, yellow <code>'Y'</code>, blue <code>'B'</code>, green <code>'G'</code>, or white <code>'W'</code>. You also have several colored balls in your hand.</p>
<p>Your goal is to <strong>clear all</strong> of the balls from the board. On each turn:</p>
<ul>
<li>Pick <strong>any</strong> ball from your hand and insert it in between two balls in the row or on either end of the row.</li>
<li>If there is a group of <strong>three or more consecutive balls</strong> of the <strong>same color</strong>, remove the group of balls from the board.
<ul>
<li>If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.</li>
</ul>
</li>
<li>If there are no more balls on the board, then you win the game.</li>
<li>Repeat this process until you either win or do not have any more balls in your hand.</li>
</ul>
<p>Given a string <code>board</code>, representing the row of balls on the board, and a string <code>hand</code>, representing the balls in your hand, return <em>the <strong>minimum</strong> number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return </em><code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> board = "WRRBBW", hand = "RB"
<strong>Output:</strong> -1
<strong>Explanation:</strong> It is impossible to clear all the balls. The best you can do is:
- Insert 'R' so the board becomes WRR<u>R</u>BBW. W<u>RRR</u>BBW -> WBBW.
- Insert 'B' so the board becomes WBB<u>B</u>W. W<u>BBB</u>W -> WW.
There are still balls remaining on the board, and you are out of balls to insert.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> board = "WWRRBBWW", hand = "WRBRW"
<strong>Output:</strong> 2
<strong>Explanation:</strong> To make the board empty:
- Insert 'R' so the board becomes WWRR<u>R</u>BBWW. WW<u>RRR</u>BBWW -> WWBBWW.
- Insert 'B' so the board becomes WWBB<u>B</u>WW. WW<u>BBB</u>WW -> <u>WWWW</u> -> empty.
2 balls from your hand were needed to clear the board.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> board = "G", hand = "GGGGG"
<strong>Output:</strong> 2
<strong>Explanation:</strong> To make the board empty:
- Insert 'G' so the board becomes G<u>G</u>.
- Insert 'G' so the board becomes GG<u>G</u>. <u>GGG</u> -> empty.
2 balls from your hand were needed to clear the board.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= board.length <= 16</code></li>
<li><code>1 <= hand.length <= 5</code></li>
<li><code>board</code> and <code>hand</code> consist of the characters <code>'R'</code>, <code>'Y'</code>, <code>'B'</code>, <code>'G'</code>, and <code>'W'</code>.</li>
<li>The initial row of balls on the board will <strong>not</strong> have any groups of three or more consecutive balls of the same color.</li>
</ul>
|
Stack; Breadth-First Search; Memoization; String; Dynamic Programming
|
Java
|
class Solution {
public int findMinStep(String board, String hand) {
final Zuma zuma = Zuma.create(board, hand);
final HashSet<Long> visited = new HashSet<>();
final ArrayList<Zuma> init = new ArrayList<>();
visited.add(zuma.board());
init.add(zuma);
return bfs(init, 0, visited);
}
private int bfs(ArrayList<Zuma> curr, int k, HashSet<Long> visited) {
if (curr.isEmpty()) {
return -1;
}
final ArrayList<Zuma> next = new ArrayList<>();
for (Zuma zuma : curr) {
ArrayList<Zuma> neib = zuma.getNextLevel(k, visited);
if (neib == null) {
return k + 1;
}
next.addAll(neib);
}
return bfs(next, k + 1, visited);
}
}
record Zuma(long board, long hand) {
public static Zuma create(String boardStr, String handStr) {
return new Zuma(Zuma.encode(boardStr, false), Zuma.encode(handStr, true));
}
public ArrayList<Zuma> getNextLevel(int depth, HashSet<Long> visited) {
final ArrayList<Zuma> next = new ArrayList<>();
final ArrayList<long[]> handList = this.buildHandList();
final long[] boardList = new long[32];
final int size = this.buildBoardList(boardList);
for (long[] pair : handList) {
for (int i = 0; i < size; ++i) {
final long rawBoard = pruningCheck(boardList[i], pair[0], i * 3, depth);
if (rawBoard == -1) {
continue;
}
final long nextBoard = updateBoard(rawBoard);
if (nextBoard == 0) {
return null;
}
if (pair[1] == 0 || visited.contains(nextBoard)) {
continue;
}
visited.add(nextBoard);
next.add(new Zuma(nextBoard, pair[1]));
}
}
return next;
}
private long pruningCheck(long insBoard, long ball, int pos, int depth) {
final long L = (insBoard >> (pos + 3)) & 0x7;
final long R = (insBoard >> (pos - 3)) & 0x7;
if (depth == 0 && (ball != R) && (L != R) || depth > 0 && (ball != R)) {
return -1;
}
return insBoard | (ball << pos);
}
private long updateBoard(long board) {
long stack = 0;
for (int i = 0; i < 64; i += 3) {
final long curr = (board >> i) & 0x7;
final long top = (stack) &0x7;
// pop (if possible)
if ((top > 0) && (curr != top) && (stack & 0x3F) == ((stack >> 3) & 0x3F)) {
stack >>= 9;
if ((stack & 0x7) == top) stack >>= 3;
}
if (curr == 0) {
// done
break;
}
// push and continue
stack = (stack << 3) | curr;
}
return stack;
}
private ArrayList<long[]> buildHandList() {
final ArrayList<long[]> handList = new ArrayList<>();
long prevBall = 0;
long ballMask = 0;
for (int i = 0; i < 16; i += 3) {
final long currBall = (this.hand >> i) & 0x7;
if (currBall == 0) {
break;
}
if (currBall != prevBall) {
prevBall = currBall;
handList.add(
new long[] {currBall, ((this.hand >> 3) & ~ballMask) | (this.hand & ballMask)});
}
ballMask = (ballMask << 3) | 0x7;
}
return handList;
}
private int buildBoardList(long[] buffer) {
int ptr = 0;
long ballMask = 0x7;
long insBoard = this.board << 3;
buffer[ptr++] = insBoard;
while (true) {
final long currBall = this.board & ballMask;
if (currBall == 0) {
break;
}
ballMask <<= 3;
insBoard = (insBoard | currBall) & ~ballMask;
buffer[ptr++] = insBoard;
}
return ptr;
}
private static long encode(String stateStr, boolean sortFlag) {
final char[] stateChars = stateStr.toCharArray();
if (sortFlag) {
Arrays.sort(stateChars);
}
long stateBits = 0;
for (char ch : stateChars) {
stateBits = (stateBits << 3) | Zuma.encode(ch);
}
return stateBits;
}
private static long encode(char ch) {
return switch (ch) {
case 'R' -> 0x1;
case 'G' -> 0x2;
case 'B' -> 0x3;
case 'W' -> 0x4;
case 'Y' -> 0x5;
case ' ' -> 0x0;
default ->
throw new IllegalArgumentException("Invalid char: " + ch);
};
}
}
|
488
|
Zuma Game
|
Hard
|
<p>You are playing a variation of the game Zuma.</p>
<p>In this variation of Zuma, there is a <strong>single row</strong> of colored balls on a board, where each ball can be colored red <code>'R'</code>, yellow <code>'Y'</code>, blue <code>'B'</code>, green <code>'G'</code>, or white <code>'W'</code>. You also have several colored balls in your hand.</p>
<p>Your goal is to <strong>clear all</strong> of the balls from the board. On each turn:</p>
<ul>
<li>Pick <strong>any</strong> ball from your hand and insert it in between two balls in the row or on either end of the row.</li>
<li>If there is a group of <strong>three or more consecutive balls</strong> of the <strong>same color</strong>, remove the group of balls from the board.
<ul>
<li>If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.</li>
</ul>
</li>
<li>If there are no more balls on the board, then you win the game.</li>
<li>Repeat this process until you either win or do not have any more balls in your hand.</li>
</ul>
<p>Given a string <code>board</code>, representing the row of balls on the board, and a string <code>hand</code>, representing the balls in your hand, return <em>the <strong>minimum</strong> number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return </em><code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> board = "WRRBBW", hand = "RB"
<strong>Output:</strong> -1
<strong>Explanation:</strong> It is impossible to clear all the balls. The best you can do is:
- Insert 'R' so the board becomes WRR<u>R</u>BBW. W<u>RRR</u>BBW -> WBBW.
- Insert 'B' so the board becomes WBB<u>B</u>W. W<u>BBB</u>W -> WW.
There are still balls remaining on the board, and you are out of balls to insert.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> board = "WWRRBBWW", hand = "WRBRW"
<strong>Output:</strong> 2
<strong>Explanation:</strong> To make the board empty:
- Insert 'R' so the board becomes WWRR<u>R</u>BBWW. WW<u>RRR</u>BBWW -> WWBBWW.
- Insert 'B' so the board becomes WWBB<u>B</u>WW. WW<u>BBB</u>WW -> <u>WWWW</u> -> empty.
2 balls from your hand were needed to clear the board.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> board = "G", hand = "GGGGG"
<strong>Output:</strong> 2
<strong>Explanation:</strong> To make the board empty:
- Insert 'G' so the board becomes G<u>G</u>.
- Insert 'G' so the board becomes GG<u>G</u>. <u>GGG</u> -> empty.
2 balls from your hand were needed to clear the board.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= board.length <= 16</code></li>
<li><code>1 <= hand.length <= 5</code></li>
<li><code>board</code> and <code>hand</code> consist of the characters <code>'R'</code>, <code>'Y'</code>, <code>'B'</code>, <code>'G'</code>, and <code>'W'</code>.</li>
<li>The initial row of balls on the board will <strong>not</strong> have any groups of three or more consecutive balls of the same color.</li>
</ul>
|
Stack; Breadth-First Search; Memoization; String; Dynamic Programming
|
Python
|
class Solution:
def findMinStep(self, board: str, hand: str) -> int:
def remove(s):
while len(s):
next = re.sub(r'B{3,}|G{3,}|R{3,}|W{3,}|Y{3,}', '', s)
if len(next) == len(s):
break
s = next
return s
visited = set()
q = deque([(board, hand)])
while q:
state, balls = q.popleft()
if not state:
return len(hand) - len(balls)
for ball in set(balls):
b = balls.replace(ball, '', 1)
for i in range(1, len(state) + 1):
s = state[:i] + ball + state[i:]
s = remove(s)
if s not in visited:
visited.add(s)
q.append((s, b))
return -1
|
489
|
Robot Room Cleaner
|
Hard
|
<p>You are controlling a robot that is located somewhere in a room. The room is modeled as an <code>m x n</code> binary grid where <code>0</code> represents a wall and <code>1</code> represents an empty slot.</p>
<p>The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API <code>Robot</code>.</p>
<p>You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is <code>90</code> degrees.</p>
<p>When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.</p>
<p>Design an algorithm to clean the entire room using the following APIs:</p>
<pre>
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
</pre>
<p><strong>Note</strong> that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.</p>
<p> </p>
<p><strong>Custom testing:</strong></p>
<p>The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0489.Robot%20Room%20Cleaner/images/lc-grid.jpg" style="width: 500px; height: 314px;" />
<pre>
<strong>Input:</strong> room = [[1,1,1,1,1,0,1,1],[1,1,1,1,1,0,1,1],[1,0,1,1,1,1,1,1],[0,0,0,1,0,0,0,0],[1,1,1,1,1,1,1,1]], row = 1, col = 3
<strong>Output:</strong> Robot cleaned all rooms.
<strong>Explanation:</strong> All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> room = [[1]], row = 0, col = 0
<strong>Output:</strong> Robot cleaned all rooms.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == room.length</code></li>
<li><code>n == room[i].length</code></li>
<li><code>1 <= m <= 100</code></li>
<li><code>1 <= n <= 200</code></li>
<li><code>room[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= row < m</code></li>
<li><code>0 <= col < n</code></li>
<li><code>room[row][col] == 1</code></li>
<li>All the empty cells can be visited from the starting position.</li>
</ul>
|
Backtracking; Interactive
|
C++
|
/**
* // This is the robot's control interface.
* // You should not implement it, or speculate about its implementation
* class Robot {
* public:
* // Returns true if the cell in front is open and robot moves into the cell.
* // Returns false if the cell in front is blocked and robot stays in the current cell.
* bool move();
*
* // Robot will stay in the same cell after calling turnLeft/turnRight.
* // Each turn will be 90 degrees.
* void turnLeft();
* void turnRight();
*
* // Clean the current cell.
* void clean();
* };
*/
class Solution {
public:
void cleanRoom(Robot& robot) {
int dirs[5] = {-1, 0, 1, 0, -1};
set<pair<int, int>> vis;
function<void(int, int, int)> dfs = [&](int i, int j, int d) {
robot.clean();
vis.insert({i, j});
for (int k = 0; k < 4; ++k) {
int nd = (d + k) % 4;
int x = i + dirs[nd], y = j + dirs[nd + 1];
if (!vis.count({x, y}) && robot.move()) {
dfs(x, y, nd);
robot.turnRight();
robot.turnRight();
robot.move();
robot.turnRight();
robot.turnRight();
}
robot.turnRight();
}
};
dfs(0, 0, 0);
}
};
|
489
|
Robot Room Cleaner
|
Hard
|
<p>You are controlling a robot that is located somewhere in a room. The room is modeled as an <code>m x n</code> binary grid where <code>0</code> represents a wall and <code>1</code> represents an empty slot.</p>
<p>The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API <code>Robot</code>.</p>
<p>You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is <code>90</code> degrees.</p>
<p>When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.</p>
<p>Design an algorithm to clean the entire room using the following APIs:</p>
<pre>
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
</pre>
<p><strong>Note</strong> that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.</p>
<p> </p>
<p><strong>Custom testing:</strong></p>
<p>The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0489.Robot%20Room%20Cleaner/images/lc-grid.jpg" style="width: 500px; height: 314px;" />
<pre>
<strong>Input:</strong> room = [[1,1,1,1,1,0,1,1],[1,1,1,1,1,0,1,1],[1,0,1,1,1,1,1,1],[0,0,0,1,0,0,0,0],[1,1,1,1,1,1,1,1]], row = 1, col = 3
<strong>Output:</strong> Robot cleaned all rooms.
<strong>Explanation:</strong> All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> room = [[1]], row = 0, col = 0
<strong>Output:</strong> Robot cleaned all rooms.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == room.length</code></li>
<li><code>n == room[i].length</code></li>
<li><code>1 <= m <= 100</code></li>
<li><code>1 <= n <= 200</code></li>
<li><code>room[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= row < m</code></li>
<li><code>0 <= col < n</code></li>
<li><code>room[row][col] == 1</code></li>
<li>All the empty cells can be visited from the starting position.</li>
</ul>
|
Backtracking; Interactive
|
Go
|
/**
* // This is the robot's control interface.
* // You should not implement it, or speculate about its implementation
* type Robot struct {
* }
*
* // Returns true if the cell in front is open and robot moves into the cell.
* // Returns false if the cell in front is blocked and robot stays in the current cell.
* func (robot *Robot) Move() bool {}
*
* // Robot will stay in the same cell after calling TurnLeft/TurnRight.
* // Each turn will be 90 degrees.
* func (robot *Robot) TurnLeft() {}
* func (robot *Robot) TurnRight() {}
*
* // Clean the current cell.
* func (robot *Robot) Clean() {}
*/
func cleanRoom(robot *Robot) {
vis := map[[2]int]bool{}
dirs := [5]int{-1, 0, 1, 0, -1}
var dfs func(int, int, int)
dfs = func(i, j, d int) {
vis[[2]int{i, j}] = true
robot.Clean()
for k := 0; k < 4; k++ {
nd := (d + k) % 4
x, y := i+dirs[nd], j+dirs[nd+1]
if !vis[[2]int{x, y}] && robot.Move() {
dfs(x, y, nd)
robot.TurnRight()
robot.TurnRight()
robot.Move()
robot.TurnRight()
robot.TurnRight()
}
robot.TurnRight()
}
}
dfs(0, 0, 0)
}
|
489
|
Robot Room Cleaner
|
Hard
|
<p>You are controlling a robot that is located somewhere in a room. The room is modeled as an <code>m x n</code> binary grid where <code>0</code> represents a wall and <code>1</code> represents an empty slot.</p>
<p>The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API <code>Robot</code>.</p>
<p>You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is <code>90</code> degrees.</p>
<p>When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.</p>
<p>Design an algorithm to clean the entire room using the following APIs:</p>
<pre>
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
</pre>
<p><strong>Note</strong> that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.</p>
<p> </p>
<p><strong>Custom testing:</strong></p>
<p>The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0489.Robot%20Room%20Cleaner/images/lc-grid.jpg" style="width: 500px; height: 314px;" />
<pre>
<strong>Input:</strong> room = [[1,1,1,1,1,0,1,1],[1,1,1,1,1,0,1,1],[1,0,1,1,1,1,1,1],[0,0,0,1,0,0,0,0],[1,1,1,1,1,1,1,1]], row = 1, col = 3
<strong>Output:</strong> Robot cleaned all rooms.
<strong>Explanation:</strong> All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> room = [[1]], row = 0, col = 0
<strong>Output:</strong> Robot cleaned all rooms.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == room.length</code></li>
<li><code>n == room[i].length</code></li>
<li><code>1 <= m <= 100</code></li>
<li><code>1 <= n <= 200</code></li>
<li><code>room[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= row < m</code></li>
<li><code>0 <= col < n</code></li>
<li><code>room[row][col] == 1</code></li>
<li>All the empty cells can be visited from the starting position.</li>
</ul>
|
Backtracking; Interactive
|
Java
|
/**
* // This is the robot's control interface.
* // You should not implement it, or speculate about its implementation
* interface Robot {
* // Returns true if the cell in front is open and robot moves into the cell.
* // Returns false if the cell in front is blocked and robot stays in the current cell.
* public boolean move();
*
* // Robot will stay in the same cell after calling turnLeft/turnRight.
* // Each turn will be 90 degrees.
* public void turnLeft();
* public void turnRight();
*
* // Clean the current cell.
* public void clean();
* }
*/
class Solution {
private int[] dirs = {-1, 0, 1, 0, -1};
private Set<List<Integer>> vis = new HashSet<>();
private Robot robot;
public void cleanRoom(Robot robot) {
this.robot = robot;
dfs(0, 0, 0);
}
private void dfs(int i, int j, int d) {
robot.clean();
vis.add(List.of(i, j));
for (int k = 0; k < 4; ++k) {
int nd = (d + k) % 4;
int x = i + dirs[nd], y = j + dirs[nd + 1];
if (!vis.contains(List.of(x, y)) && robot.move()) {
dfs(x, y, nd);
robot.turnRight();
robot.turnRight();
robot.move();
robot.turnRight();
robot.turnRight();
}
robot.turnRight();
}
}
}
|
489
|
Robot Room Cleaner
|
Hard
|
<p>You are controlling a robot that is located somewhere in a room. The room is modeled as an <code>m x n</code> binary grid where <code>0</code> represents a wall and <code>1</code> represents an empty slot.</p>
<p>The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API <code>Robot</code>.</p>
<p>You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is <code>90</code> degrees.</p>
<p>When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.</p>
<p>Design an algorithm to clean the entire room using the following APIs:</p>
<pre>
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
</pre>
<p><strong>Note</strong> that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.</p>
<p> </p>
<p><strong>Custom testing:</strong></p>
<p>The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0489.Robot%20Room%20Cleaner/images/lc-grid.jpg" style="width: 500px; height: 314px;" />
<pre>
<strong>Input:</strong> room = [[1,1,1,1,1,0,1,1],[1,1,1,1,1,0,1,1],[1,0,1,1,1,1,1,1],[0,0,0,1,0,0,0,0],[1,1,1,1,1,1,1,1]], row = 1, col = 3
<strong>Output:</strong> Robot cleaned all rooms.
<strong>Explanation:</strong> All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> room = [[1]], row = 0, col = 0
<strong>Output:</strong> Robot cleaned all rooms.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == room.length</code></li>
<li><code>n == room[i].length</code></li>
<li><code>1 <= m <= 100</code></li>
<li><code>1 <= n <= 200</code></li>
<li><code>room[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= row < m</code></li>
<li><code>0 <= col < n</code></li>
<li><code>room[row][col] == 1</code></li>
<li>All the empty cells can be visited from the starting position.</li>
</ul>
|
Backtracking; Interactive
|
Python
|
# """
# This is the robot's control interface.
# You should not implement it, or speculate about its implementation
# """
# class Robot:
# def move(self):
# """
# Returns true if the cell in front is open and robot moves into the cell.
# Returns false if the cell in front is blocked and robot stays in the current cell.
# :rtype bool
# """
#
# def turnLeft(self):
# """
# Robot will stay in the same cell after calling turnLeft/turnRight.
# Each turn will be 90 degrees.
# :rtype void
# """
#
# def turnRight(self):
# """
# Robot will stay in the same cell after calling turnLeft/turnRight.
# Each turn will be 90 degrees.
# :rtype void
# """
#
# def clean(self):
# """
# Clean the current cell.
# :rtype void
# """
class Solution:
def cleanRoom(self, robot):
"""
:type robot: Robot
:rtype: None
"""
def dfs(i, j, d):
vis.add((i, j))
robot.clean()
for k in range(4):
nd = (d + k) % 4
x, y = i + dirs[nd], j + dirs[nd + 1]
if (x, y) not in vis and robot.move():
dfs(x, y, nd)
robot.turnRight()
robot.turnRight()
robot.move()
robot.turnRight()
robot.turnRight()
robot.turnRight()
dirs = (-1, 0, 1, 0, -1)
vis = set()
dfs(0, 0, 0)
|
489
|
Robot Room Cleaner
|
Hard
|
<p>You are controlling a robot that is located somewhere in a room. The room is modeled as an <code>m x n</code> binary grid where <code>0</code> represents a wall and <code>1</code> represents an empty slot.</p>
<p>The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API <code>Robot</code>.</p>
<p>You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is <code>90</code> degrees.</p>
<p>When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.</p>
<p>Design an algorithm to clean the entire room using the following APIs:</p>
<pre>
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
</pre>
<p><strong>Note</strong> that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.</p>
<p> </p>
<p><strong>Custom testing:</strong></p>
<p>The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0489.Robot%20Room%20Cleaner/images/lc-grid.jpg" style="width: 500px; height: 314px;" />
<pre>
<strong>Input:</strong> room = [[1,1,1,1,1,0,1,1],[1,1,1,1,1,0,1,1],[1,0,1,1,1,1,1,1],[0,0,0,1,0,0,0,0],[1,1,1,1,1,1,1,1]], row = 1, col = 3
<strong>Output:</strong> Robot cleaned all rooms.
<strong>Explanation:</strong> All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> room = [[1]], row = 0, col = 0
<strong>Output:</strong> Robot cleaned all rooms.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == room.length</code></li>
<li><code>n == room[i].length</code></li>
<li><code>1 <= m <= 100</code></li>
<li><code>1 <= n <= 200</code></li>
<li><code>room[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li><code>0 <= row < m</code></li>
<li><code>0 <= col < n</code></li>
<li><code>room[row][col] == 1</code></li>
<li>All the empty cells can be visited from the starting position.</li>
</ul>
|
Backtracking; Interactive
|
TypeScript
|
/**
* class Robot {
* // Returns true if the cell in front is open and robot moves into the cell.
* // Returns false if the cell in front is blocked and robot stays in the current cell.
* move(): boolean {}
*
* // Robot will stay in the same cell after calling turnLeft/turnRight.
* // Each turn will be 90 degrees.
* turnRight() {}
*
* // Robot will stay in the same cell after calling turnLeft/turnRight.
* // Each turn will be 90 degrees.
* turnLeft() {}
*
* // Clean the current cell.
* clean(): {}
* }
*/
function cleanRoom(robot: Robot) {
const dirs = [-1, 0, 1, 0, -1];
const vis = new Set<string>();
const dfs = (i: number, j: number, d: number) => {
vis.add(`${i}-${j}`);
robot.clean();
for (let k = 0; k < 4; ++k) {
const nd = (d + k) % 4;
const [x, y] = [i + dirs[nd], j + dirs[nd + 1]];
if (!vis.has(`${x}-${y}`) && robot.move()) {
dfs(x, y, nd);
robot.turnRight();
robot.turnRight();
robot.move();
robot.turnRight();
robot.turnRight();
}
robot.turnRight();
}
};
dfs(0, 0, 0);
}
|
490
|
The Maze
|
Medium
|
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.</p>
<p>Given the <code>m x n</code> <code>maze</code>, the ball's <code>start</code> position and the <code>destination</code>, where <code>start = [start<sub>row</sub>, start<sub>col</sub>]</code> and <code>destination = [destination<sub>row</sub>, destination<sub>col</sub>]</code>, return <code>true</code> if the ball can stop at the destination, otherwise return <code>false</code>.</p>
<p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0490.The%20Maze/images/maze1-1-grid.jpg" style="width: 573px; height: 573px;" />
<pre>
<strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One possible way is : left -> down -> left -> down -> right -> down -> right.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0490.The%20Maze/images/maze1-2-grid.jpg" style="width: 573px; height: 573px;" />
<pre>
<strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == maze.length</code></li>
<li><code>n == maze[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li>
<li><code>start.length == 2</code></li>
<li><code>destination.length == 2</code></li>
<li><code>0 <= start<sub>row</sub>, destination<sub>row</sub> < m</code></li>
<li><code>0 <= start<sub>col</sub>, destination<sub>col</sub> < n</code></li>
<li>Both the ball and the destination exist in an empty space, and they will not be in the same position initially.</li>
<li>The maze contains <strong>at least 2 empty spaces</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix
|
C++
|
class Solution {
public:
vector<vector<int>> maze;
vector<vector<bool>> vis;
vector<int> d;
int m;
int n;
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
m = maze.size();
n = maze[0].size();
d = destination;
vis.resize(m, vector<bool>(n, false));
this->maze = maze;
dfs(start[0], start[1]);
return vis[d[0]][d[1]];
}
void dfs(int i, int j) {
if (vis[i][j]) return;
vis[i][j] = true;
if (i == d[0] && j == d[1]) return;
vector<int> dirs = {-1, 0, 1, 0, -1};
for (int k = 0; k < 4; ++k) {
int x = i, y = j;
int a = dirs[k], b = dirs[k + 1];
while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) {
x += a;
y += b;
}
dfs(x, y);
}
}
};
|
490
|
The Maze
|
Medium
|
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.</p>
<p>Given the <code>m x n</code> <code>maze</code>, the ball's <code>start</code> position and the <code>destination</code>, where <code>start = [start<sub>row</sub>, start<sub>col</sub>]</code> and <code>destination = [destination<sub>row</sub>, destination<sub>col</sub>]</code>, return <code>true</code> if the ball can stop at the destination, otherwise return <code>false</code>.</p>
<p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0490.The%20Maze/images/maze1-1-grid.jpg" style="width: 573px; height: 573px;" />
<pre>
<strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One possible way is : left -> down -> left -> down -> right -> down -> right.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0490.The%20Maze/images/maze1-2-grid.jpg" style="width: 573px; height: 573px;" />
<pre>
<strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == maze.length</code></li>
<li><code>n == maze[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li>
<li><code>start.length == 2</code></li>
<li><code>destination.length == 2</code></li>
<li><code>0 <= start<sub>row</sub>, destination<sub>row</sub> < m</code></li>
<li><code>0 <= start<sub>col</sub>, destination<sub>col</sub> < n</code></li>
<li>Both the ball and the destination exist in an empty space, and they will not be in the same position initially.</li>
<li>The maze contains <strong>at least 2 empty spaces</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix
|
Go
|
func hasPath(maze [][]int, start []int, destination []int) bool {
m, n := len(maze), len(maze[0])
vis := make([][]bool, m)
for i := range vis {
vis[i] = make([]bool, n)
}
var dfs func(i, j int)
dfs = func(i, j int) {
if vis[i][j] {
return
}
vis[i][j] = true
if i == destination[0] && j == destination[1] {
return
}
dirs := []int{-1, 0, 1, 0, -1}
for k := 0; k < 4; k++ {
x, y := i, j
a, b := dirs[k], dirs[k+1]
for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 {
x += a
y += b
}
dfs(x, y)
}
}
dfs(start[0], start[1])
return vis[destination[0]][destination[1]]
}
|
490
|
The Maze
|
Medium
|
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.</p>
<p>Given the <code>m x n</code> <code>maze</code>, the ball's <code>start</code> position and the <code>destination</code>, where <code>start = [start<sub>row</sub>, start<sub>col</sub>]</code> and <code>destination = [destination<sub>row</sub>, destination<sub>col</sub>]</code>, return <code>true</code> if the ball can stop at the destination, otherwise return <code>false</code>.</p>
<p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0490.The%20Maze/images/maze1-1-grid.jpg" style="width: 573px; height: 573px;" />
<pre>
<strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One possible way is : left -> down -> left -> down -> right -> down -> right.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0490.The%20Maze/images/maze1-2-grid.jpg" style="width: 573px; height: 573px;" />
<pre>
<strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == maze.length</code></li>
<li><code>n == maze[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li>
<li><code>start.length == 2</code></li>
<li><code>destination.length == 2</code></li>
<li><code>0 <= start<sub>row</sub>, destination<sub>row</sub> < m</code></li>
<li><code>0 <= start<sub>col</sub>, destination<sub>col</sub> < n</code></li>
<li>Both the ball and the destination exist in an empty space, and they will not be in the same position initially.</li>
<li>The maze contains <strong>at least 2 empty spaces</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix
|
Java
|
class Solution {
private boolean[][] vis;
private int[][] maze;
private int[] d;
private int m;
private int n;
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
m = maze.length;
n = maze[0].length;
d = destination;
this.maze = maze;
vis = new boolean[m][n];
dfs(start[0], start[1]);
return vis[d[0]][d[1]];
}
private void dfs(int i, int j) {
if (vis[i][j]) {
return;
}
vis[i][j] = true;
if (i == d[0] && j == d[1]) {
return;
}
int[] dirs = {-1, 0, 1, 0, -1};
for (int k = 0; k < 4; ++k) {
int x = i, y = j;
int a = dirs[k], b = dirs[k + 1];
while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) {
x += a;
y += b;
}
dfs(x, y);
}
}
}
|
490
|
The Maze
|
Medium
|
<p>There is a ball in a <code>maze</code> with empty spaces (represented as <code>0</code>) and walls (represented as <code>1</code>). The ball can go through the empty spaces by rolling <strong>up, down, left or right</strong>, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.</p>
<p>Given the <code>m x n</code> <code>maze</code>, the ball's <code>start</code> position and the <code>destination</code>, where <code>start = [start<sub>row</sub>, start<sub>col</sub>]</code> and <code>destination = [destination<sub>row</sub>, destination<sub>col</sub>]</code>, return <code>true</code> if the ball can stop at the destination, otherwise return <code>false</code>.</p>
<p>You may assume that <strong>the borders of the maze are all walls</strong> (see examples).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0490.The%20Maze/images/maze1-1-grid.jpg" style="width: 573px; height: 573px;" />
<pre>
<strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One possible way is : left -> down -> left -> down -> right -> down -> right.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0490.The%20Maze/images/maze1-2-grid.jpg" style="width: 573px; height: 573px;" />
<pre>
<strong>Input:</strong> maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == maze.length</code></li>
<li><code>n == maze[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>maze[i][j]</code> is <code>0</code> or <code>1</code>.</li>
<li><code>start.length == 2</code></li>
<li><code>destination.length == 2</code></li>
<li><code>0 <= start<sub>row</sub>, destination<sub>row</sub> < m</code></li>
<li><code>0 <= start<sub>col</sub>, destination<sub>col</sub> < n</code></li>
<li>Both the ball and the destination exist in an empty space, and they will not be in the same position initially.</li>
<li>The maze contains <strong>at least 2 empty spaces</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix
|
Python
|
class Solution:
def hasPath(
self, maze: List[List[int]], start: List[int], destination: List[int]
) -> bool:
def dfs(i, j):
if vis[i][j]:
return
vis[i][j] = True
if [i, j] == destination:
return
for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]:
x, y = i, j
while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0:
x, y = x + a, y + b
dfs(x, y)
m, n = len(maze), len(maze[0])
vis = [[False] * n for _ in range(m)]
dfs(start[0], start[1])
return vis[destination[0]][destination[1]]
|
491
|
Non-decreasing Subsequences
|
Medium
|
<p>Given an integer array <code>nums</code>, return <em>all the different possible non-decreasing subsequences of the given array with at least two elements</em>. You may return the answer in <strong>any order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,6,7,7]
<strong>Output:</strong> [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,4,3,2,1]
<strong>Output:</strong> [[4,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 15</code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Array; Hash Table; Backtracking
|
C++
|
class Solution {
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> t;
dfs(0, -1000, t, nums, ans);
return ans;
}
void dfs(int u, int last, vector<int>& t, vector<int>& nums, vector<vector<int>>& ans) {
if (u == nums.size()) {
if (t.size() > 1) ans.push_back(t);
return;
}
if (nums[u] >= last) {
t.push_back(nums[u]);
dfs(u + 1, nums[u], t, nums, ans);
t.pop_back();
}
if (nums[u] != last) dfs(u + 1, last, t, nums, ans);
}
};
|
491
|
Non-decreasing Subsequences
|
Medium
|
<p>Given an integer array <code>nums</code>, return <em>all the different possible non-decreasing subsequences of the given array with at least two elements</em>. You may return the answer in <strong>any order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,6,7,7]
<strong>Output:</strong> [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,4,3,2,1]
<strong>Output:</strong> [[4,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 15</code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Array; Hash Table; Backtracking
|
Go
|
func findSubsequences(nums []int) [][]int {
var ans [][]int
var dfs func(u, last int, t []int)
dfs = func(u, last int, t []int) {
if u == len(nums) {
if len(t) > 1 {
ans = append(ans, slices.Clone(t))
}
return
}
if nums[u] >= last {
t = append(t, nums[u])
dfs(u+1, nums[u], t)
t = t[:len(t)-1]
}
if nums[u] != last {
dfs(u+1, last, t)
}
}
var t []int
dfs(0, -1000, t)
return ans
}
|
491
|
Non-decreasing Subsequences
|
Medium
|
<p>Given an integer array <code>nums</code>, return <em>all the different possible non-decreasing subsequences of the given array with at least two elements</em>. You may return the answer in <strong>any order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,6,7,7]
<strong>Output:</strong> [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,4,3,2,1]
<strong>Output:</strong> [[4,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 15</code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Array; Hash Table; Backtracking
|
Java
|
class Solution {
private int[] nums;
private List<List<Integer>> ans;
public List<List<Integer>> findSubsequences(int[] nums) {
this.nums = nums;
ans = new ArrayList<>();
dfs(0, -1000, new ArrayList<>());
return ans;
}
private void dfs(int u, int last, List<Integer> t) {
if (u == nums.length) {
if (t.size() > 1) {
ans.add(new ArrayList<>(t));
}
return;
}
if (nums[u] >= last) {
t.add(nums[u]);
dfs(u + 1, nums[u], t);
t.remove(t.size() - 1);
}
if (nums[u] != last) {
dfs(u + 1, last, t);
}
}
}
|
491
|
Non-decreasing Subsequences
|
Medium
|
<p>Given an integer array <code>nums</code>, return <em>all the different possible non-decreasing subsequences of the given array with at least two elements</em>. You may return the answer in <strong>any order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,6,7,7]
<strong>Output:</strong> [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,4,3,2,1]
<strong>Output:</strong> [[4,4]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 15</code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Array; Hash Table; Backtracking
|
Python
|
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
def dfs(u, last, t):
if u == len(nums):
if len(t) > 1:
ans.append(t[:])
return
if nums[u] >= last:
t.append(nums[u])
dfs(u + 1, nums[u], t)
t.pop()
if nums[u] != last:
dfs(u + 1, last, t)
ans = []
dfs(0, -1000, [])
return ans
|
492
|
Construct the Rectangle
|
Easy
|
<p>A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:</p>
<ol>
<li>The area of the rectangular web page you designed must equal to the given target area.</li>
<li>The width <code>W</code> should not be larger than the length <code>L</code>, which means <code>L >= W</code>.</li>
<li>The difference between length <code>L</code> and width <code>W</code> should be as small as possible.</li>
</ol>
<p>Return <em>an array <code>[L, W]</code> where <code>L</code> and <code>W</code> are the length and width of the web page you designed in sequence.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> area = 4
<strong>Output:</strong> [2,2]
<strong>Explanation:</strong> The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> area = 37
<strong>Output:</strong> [37,1]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> area = 122122
<strong>Output:</strong> [427,286]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= area <= 10<sup>7</sup></code></li>
</ul>
|
Math
|
C++
|
class Solution {
public:
vector<int> constructRectangle(int area) {
int w = sqrt(1.0 * area);
while (area % w != 0) --w;
return {area / w, w};
}
};
|
492
|
Construct the Rectangle
|
Easy
|
<p>A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:</p>
<ol>
<li>The area of the rectangular web page you designed must equal to the given target area.</li>
<li>The width <code>W</code> should not be larger than the length <code>L</code>, which means <code>L >= W</code>.</li>
<li>The difference between length <code>L</code> and width <code>W</code> should be as small as possible.</li>
</ol>
<p>Return <em>an array <code>[L, W]</code> where <code>L</code> and <code>W</code> are the length and width of the web page you designed in sequence.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> area = 4
<strong>Output:</strong> [2,2]
<strong>Explanation:</strong> The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> area = 37
<strong>Output:</strong> [37,1]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> area = 122122
<strong>Output:</strong> [427,286]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= area <= 10<sup>7</sup></code></li>
</ul>
|
Math
|
Go
|
func constructRectangle(area int) []int {
w := int(math.Sqrt(float64(area)))
for area%w != 0 {
w--
}
return []int{area / w, w}
}
|
492
|
Construct the Rectangle
|
Easy
|
<p>A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:</p>
<ol>
<li>The area of the rectangular web page you designed must equal to the given target area.</li>
<li>The width <code>W</code> should not be larger than the length <code>L</code>, which means <code>L >= W</code>.</li>
<li>The difference between length <code>L</code> and width <code>W</code> should be as small as possible.</li>
</ol>
<p>Return <em>an array <code>[L, W]</code> where <code>L</code> and <code>W</code> are the length and width of the web page you designed in sequence.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> area = 4
<strong>Output:</strong> [2,2]
<strong>Explanation:</strong> The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> area = 37
<strong>Output:</strong> [37,1]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> area = 122122
<strong>Output:</strong> [427,286]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= area <= 10<sup>7</sup></code></li>
</ul>
|
Math
|
Java
|
class Solution {
public int[] constructRectangle(int area) {
int w = (int) Math.sqrt(area);
while (area % w != 0) {
--w;
}
return new int[] {area / w, w};
}
}
|
492
|
Construct the Rectangle
|
Easy
|
<p>A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:</p>
<ol>
<li>The area of the rectangular web page you designed must equal to the given target area.</li>
<li>The width <code>W</code> should not be larger than the length <code>L</code>, which means <code>L >= W</code>.</li>
<li>The difference between length <code>L</code> and width <code>W</code> should be as small as possible.</li>
</ol>
<p>Return <em>an array <code>[L, W]</code> where <code>L</code> and <code>W</code> are the length and width of the web page you designed in sequence.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> area = 4
<strong>Output:</strong> [2,2]
<strong>Explanation:</strong> The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> area = 37
<strong>Output:</strong> [37,1]
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> area = 122122
<strong>Output:</strong> [427,286]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= area <= 10<sup>7</sup></code></li>
</ul>
|
Math
|
Python
|
class Solution:
def constructRectangle(self, area: int) -> List[int]:
w = int(sqrt(area))
while area % w != 0:
w -= 1
return [area // w, w]
|
493
|
Reverse Pairs
|
Hard
|
<p>Given an integer array <code>nums</code>, return <em>the number of <strong>reverse pairs</strong> in the array</em>.</p>
<p>A <strong>reverse pair</strong> is a pair <code>(i, j)</code> where:</p>
<ul>
<li><code>0 <= i < j < nums.length</code> and</li>
<li><code>nums[i] > 2 * nums[j]</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,3,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The reverse pairs are:
(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,3,5,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The reverse pairs are:
(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1
(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
C++
|
class Solution {
public:
int reversePairs(vector<int>& nums) {
int n = nums.size();
int t[n];
function<int(int, int)> mergeSort = [&](int l, int r) -> int {
if (l >= r) {
return 0;
}
int mid = (l + r) >> 1;
int ans = mergeSort(l, mid) + mergeSort(mid + 1, r);
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r) {
if (nums[i] <= nums[j] * 2LL) {
++i;
} else {
ans += mid - i + 1;
++j;
}
}
i = l;
j = mid + 1;
while (i <= mid && j <= r) {
if (nums[i] <= nums[j]) {
t[k++] = nums[i++];
} else {
t[k++] = nums[j++];
}
}
while (i <= mid) {
t[k++] = nums[i++];
}
while (j <= r) {
t[k++] = nums[j++];
}
for (i = l; i <= r; ++i) {
nums[i] = t[i - l];
}
return ans;
};
return mergeSort(0, n - 1);
}
};
|
493
|
Reverse Pairs
|
Hard
|
<p>Given an integer array <code>nums</code>, return <em>the number of <strong>reverse pairs</strong> in the array</em>.</p>
<p>A <strong>reverse pair</strong> is a pair <code>(i, j)</code> where:</p>
<ul>
<li><code>0 <= i < j < nums.length</code> and</li>
<li><code>nums[i] > 2 * nums[j]</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,3,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The reverse pairs are:
(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,3,5,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The reverse pairs are:
(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1
(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
Go
|
func reversePairs(nums []int) int {
n := len(nums)
t := make([]int, n)
var mergeSort func(l, r int) int
mergeSort = func(l, r int) int {
if l >= r {
return 0
}
mid := (l + r) >> 1
ans := mergeSort(l, mid) + mergeSort(mid+1, r)
i, j, k := l, mid+1, 0
for i <= mid && j <= r {
if nums[i] <= nums[j]*2 {
i++
} else {
ans += mid - i + 1
j++
}
}
i, j = l, mid+1
for i <= mid && j <= r {
if nums[i] <= nums[j] {
t[k] = nums[i]
k, i = k+1, i+1
} else {
t[k] = nums[j]
k, j = k+1, j+1
}
}
for ; i <= mid; i, k = i+1, k+1 {
t[k] = nums[i]
}
for ; j <= r; j, k = j+1, k+1 {
t[k] = nums[j]
}
for i = l; i <= r; i++ {
nums[i] = t[i-l]
}
return ans
}
return mergeSort(0, n-1)
}
|
493
|
Reverse Pairs
|
Hard
|
<p>Given an integer array <code>nums</code>, return <em>the number of <strong>reverse pairs</strong> in the array</em>.</p>
<p>A <strong>reverse pair</strong> is a pair <code>(i, j)</code> where:</p>
<ul>
<li><code>0 <= i < j < nums.length</code> and</li>
<li><code>nums[i] > 2 * nums[j]</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,3,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The reverse pairs are:
(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,3,5,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The reverse pairs are:
(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1
(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
Java
|
class Solution {
private int[] nums;
private int[] t;
public int reversePairs(int[] nums) {
this.nums = nums;
int n = nums.length;
this.t = new int[n];
return mergeSort(0, n - 1);
}
private int mergeSort(int l, int r) {
if (l >= r) {
return 0;
}
int mid = (l + r) >> 1;
int ans = mergeSort(l, mid) + mergeSort(mid + 1, r);
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r) {
if (nums[i] <= nums[j] * 2L) {
++i;
} else {
ans += mid - i + 1;
++j;
}
}
i = l;
j = mid + 1;
while (i <= mid && j <= r) {
if (nums[i] <= nums[j]) {
t[k++] = nums[i++];
} else {
t[k++] = nums[j++];
}
}
while (i <= mid) {
t[k++] = nums[i++];
}
while (j <= r) {
t[k++] = nums[j++];
}
for (i = l; i <= r; ++i) {
nums[i] = t[i - l];
}
return ans;
}
}
|
493
|
Reverse Pairs
|
Hard
|
<p>Given an integer array <code>nums</code>, return <em>the number of <strong>reverse pairs</strong> in the array</em>.</p>
<p>A <strong>reverse pair</strong> is a pair <code>(i, j)</code> where:</p>
<ul>
<li><code>0 <= i < j < nums.length</code> and</li>
<li><code>nums[i] > 2 * nums[j]</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,3,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The reverse pairs are:
(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,3,5,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The reverse pairs are:
(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1
(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
Python
|
class Solution:
def reversePairs(self, nums: List[int]) -> int:
def merge_sort(l, r):
if l >= r:
return 0
mid = (l + r) >> 1
ans = merge_sort(l, mid) + merge_sort(mid + 1, r)
t = []
i, j = l, mid + 1
while i <= mid and j <= r:
if nums[i] <= 2 * nums[j]:
i += 1
else:
ans += mid - i + 1
j += 1
i, j = l, mid + 1
while i <= mid and j <= r:
if nums[i] <= nums[j]:
t.append(nums[i])
i += 1
else:
t.append(nums[j])
j += 1
t.extend(nums[i : mid + 1])
t.extend(nums[j : r + 1])
nums[l : r + 1] = t
return ans
return merge_sort(0, len(nums) - 1)
|
494
|
Target Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>
<p>You want to build an <strong>expression</strong> out of nums by adding one of the symbols <code>'+'</code> and <code>'-'</code> before each integer in nums and then concatenate all the integers.</p>
<ul>
<li>For example, if <code>nums = [2, 1]</code>, you can add a <code>'+'</code> before <code>2</code> and a <code>'-'</code> before <code>1</code> and concatenate them to build the expression <code>"+2-1"</code>.</li>
</ul>
<p>Return the number of different <strong>expressions</strong> that you can build, which evaluates to <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], target = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], target = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 1000</code></li>
<li><code>0 <= sum(nums[i]) <= 1000</code></li>
<li><code>-1000 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming; Backtracking
|
C++
|
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int s = accumulate(nums.begin(), nums.end(), 0);
if (s < target || (s - target) % 2) {
return 0;
}
int m = nums.size();
int n = (s - target) / 2;
int f[m + 1][n + 1];
memset(f, 0, sizeof(f));
f[0][0] = 1;
for (int i = 1; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (j >= nums[i - 1]) {
f[i][j] += f[i - 1][j - nums[i - 1]];
}
}
}
return f[m][n];
}
};
|
494
|
Target Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>
<p>You want to build an <strong>expression</strong> out of nums by adding one of the symbols <code>'+'</code> and <code>'-'</code> before each integer in nums and then concatenate all the integers.</p>
<ul>
<li>For example, if <code>nums = [2, 1]</code>, you can add a <code>'+'</code> before <code>2</code> and a <code>'-'</code> before <code>1</code> and concatenate them to build the expression <code>"+2-1"</code>.</li>
</ul>
<p>Return the number of different <strong>expressions</strong> that you can build, which evaluates to <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], target = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], target = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 1000</code></li>
<li><code>0 <= sum(nums[i]) <= 1000</code></li>
<li><code>-1000 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming; Backtracking
|
Go
|
func findTargetSumWays(nums []int, target int) int {
s := 0
for _, x := range nums {
s += x
}
if s < target || (s-target)%2 != 0 {
return 0
}
m, n := len(nums), (s-target)/2
f := make([][]int, m+1)
for i := range f {
f[i] = make([]int, n+1)
}
f[0][0] = 1
for i := 1; i <= m; i++ {
for j := 0; j <= n; j++ {
f[i][j] = f[i-1][j]
if j >= nums[i-1] {
f[i][j] += f[i-1][j-nums[i-1]]
}
}
}
return f[m][n]
}
|
494
|
Target Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>
<p>You want to build an <strong>expression</strong> out of nums by adding one of the symbols <code>'+'</code> and <code>'-'</code> before each integer in nums and then concatenate all the integers.</p>
<ul>
<li>For example, if <code>nums = [2, 1]</code>, you can add a <code>'+'</code> before <code>2</code> and a <code>'-'</code> before <code>1</code> and concatenate them to build the expression <code>"+2-1"</code>.</li>
</ul>
<p>Return the number of different <strong>expressions</strong> that you can build, which evaluates to <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], target = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], target = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 1000</code></li>
<li><code>0 <= sum(nums[i]) <= 1000</code></li>
<li><code>-1000 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming; Backtracking
|
Java
|
class Solution {
public int findTargetSumWays(int[] nums, int target) {
int s = Arrays.stream(nums).sum();
if (s < target || (s - target) % 2 != 0) {
return 0;
}
int m = nums.length;
int n = (s - target) / 2;
int[][] f = new int[m + 1][n + 1];
f[0][0] = 1;
for (int i = 1; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (j >= nums[i - 1]) {
f[i][j] += f[i - 1][j - nums[i - 1]];
}
}
}
return f[m][n];
}
}
|
494
|
Target Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>
<p>You want to build an <strong>expression</strong> out of nums by adding one of the symbols <code>'+'</code> and <code>'-'</code> before each integer in nums and then concatenate all the integers.</p>
<ul>
<li>For example, if <code>nums = [2, 1]</code>, you can add a <code>'+'</code> before <code>2</code> and a <code>'-'</code> before <code>1</code> and concatenate them to build the expression <code>"+2-1"</code>.</li>
</ul>
<p>Return the number of different <strong>expressions</strong> that you can build, which evaluates to <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], target = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], target = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 1000</code></li>
<li><code>0 <= sum(nums[i]) <= 1000</code></li>
<li><code>-1000 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming; Backtracking
|
JavaScript
|
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var findTargetSumWays = function (nums, target) {
const s = nums.reduce((a, b) => a + b, 0);
if (s < target || (s - target) % 2) {
return 0;
}
const [m, n] = [nums.length, ((s - target) / 2) | 0];
const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
f[0][0] = 1;
for (let i = 1; i <= m; i++) {
for (let j = 0; j <= n; j++) {
f[i][j] = f[i - 1][j];
if (j >= nums[i - 1]) {
f[i][j] += f[i - 1][j - nums[i - 1]];
}
}
}
return f[m][n];
};
|
494
|
Target Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>
<p>You want to build an <strong>expression</strong> out of nums by adding one of the symbols <code>'+'</code> and <code>'-'</code> before each integer in nums and then concatenate all the integers.</p>
<ul>
<li>For example, if <code>nums = [2, 1]</code>, you can add a <code>'+'</code> before <code>2</code> and a <code>'-'</code> before <code>1</code> and concatenate them to build the expression <code>"+2-1"</code>.</li>
</ul>
<p>Return the number of different <strong>expressions</strong> that you can build, which evaluates to <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], target = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], target = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 1000</code></li>
<li><code>0 <= sum(nums[i]) <= 1000</code></li>
<li><code>-1000 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming; Backtracking
|
Python
|
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
s = sum(nums)
if s < target or (s - target) % 2:
return 0
m, n = len(nums), (s - target) // 2
f = [[0] * (n + 1) for _ in range(m + 1)]
f[0][0] = 1
for i, x in enumerate(nums, 1):
for j in range(n + 1):
f[i][j] = f[i - 1][j]
if j >= x:
f[i][j] += f[i - 1][j - x]
return f[m][n]
|
494
|
Target Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>
<p>You want to build an <strong>expression</strong> out of nums by adding one of the symbols <code>'+'</code> and <code>'-'</code> before each integer in nums and then concatenate all the integers.</p>
<ul>
<li>For example, if <code>nums = [2, 1]</code>, you can add a <code>'+'</code> before <code>2</code> and a <code>'-'</code> before <code>1</code> and concatenate them to build the expression <code>"+2-1"</code>.</li>
</ul>
<p>Return the number of different <strong>expressions</strong> that you can build, which evaluates to <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], target = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], target = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 1000</code></li>
<li><code>0 <= sum(nums[i]) <= 1000</code></li>
<li><code>-1000 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming; Backtracking
|
Rust
|
impl Solution {
pub fn find_target_sum_ways(nums: Vec<i32>, target: i32) -> i32 {
let s: i32 = nums.iter().sum();
if s < target || (s - target) % 2 != 0 {
return 0;
}
let m = nums.len();
let n = ((s - target) / 2) as usize;
let mut f = vec![vec![0; n + 1]; m + 1];
f[0][0] = 1;
for i in 1..=m {
for j in 0..=n {
f[i][j] = f[i - 1][j];
if j as i32 >= nums[i - 1] {
f[i][j] += f[i - 1][j - nums[i - 1] as usize];
}
}
}
f[m][n]
}
}
|
494
|
Target Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>
<p>You want to build an <strong>expression</strong> out of nums by adding one of the symbols <code>'+'</code> and <code>'-'</code> before each integer in nums and then concatenate all the integers.</p>
<ul>
<li>For example, if <code>nums = [2, 1]</code>, you can add a <code>'+'</code> before <code>2</code> and a <code>'-'</code> before <code>1</code> and concatenate them to build the expression <code>"+2-1"</code>.</li>
</ul>
<p>Return the number of different <strong>expressions</strong> that you can build, which evaluates to <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], target = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], target = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 1000</code></li>
<li><code>0 <= sum(nums[i]) <= 1000</code></li>
<li><code>-1000 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming; Backtracking
|
TypeScript
|
function findTargetSumWays(nums: number[], target: number): number {
const s = nums.reduce((a, b) => a + b, 0);
if (s < target || (s - target) % 2) {
return 0;
}
const [m, n] = [nums.length, ((s - target) / 2) | 0];
const f: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
f[0][0] = 1;
for (let i = 1; i <= m; i++) {
for (let j = 0; j <= n; j++) {
f[i][j] = f[i - 1][j];
if (j >= nums[i - 1]) {
f[i][j] += f[i - 1][j - nums[i - 1]];
}
}
}
return f[m][n];
}
|
495
|
Teemo Attacking
|
Easy
|
<p>Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly <code>duration</code> seconds. More formally, an attack at second <code>t</code> will mean Ashe is poisoned during the <strong>inclusive</strong> time interval <code>[t, t + duration - 1]</code>. If Teemo attacks again <strong>before</strong> the poison effect ends, the timer for it is <strong>reset</strong>, and the poison effect will end <code>duration</code> seconds after the new attack.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>timeSeries</code>, where <code>timeSeries[i]</code> denotes that Teemo attacks Ashe at second <code>timeSeries[i]</code>, and an integer <code>duration</code>.</p>
<p>Return <em>the <strong>total</strong> number of seconds that Ashe is poisoned</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,4], duration = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,2], duration = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= timeSeries.length <= 10<sup>4</sup></code></li>
<li><code>0 <= timeSeries[i], duration <= 10<sup>7</sup></code></li>
<li><code>timeSeries</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Simulation
|
C++
|
class Solution {
public:
int findPoisonedDuration(vector<int>& timeSeries, int duration) {
int ans = duration;
int n = timeSeries.size();
for (int i = 1; i < n; ++i) {
ans += min(duration, timeSeries[i] - timeSeries[i - 1]);
}
return ans;
}
};
|
495
|
Teemo Attacking
|
Easy
|
<p>Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly <code>duration</code> seconds. More formally, an attack at second <code>t</code> will mean Ashe is poisoned during the <strong>inclusive</strong> time interval <code>[t, t + duration - 1]</code>. If Teemo attacks again <strong>before</strong> the poison effect ends, the timer for it is <strong>reset</strong>, and the poison effect will end <code>duration</code> seconds after the new attack.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>timeSeries</code>, where <code>timeSeries[i]</code> denotes that Teemo attacks Ashe at second <code>timeSeries[i]</code>, and an integer <code>duration</code>.</p>
<p>Return <em>the <strong>total</strong> number of seconds that Ashe is poisoned</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,4], duration = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,2], duration = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= timeSeries.length <= 10<sup>4</sup></code></li>
<li><code>0 <= timeSeries[i], duration <= 10<sup>7</sup></code></li>
<li><code>timeSeries</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Simulation
|
C#
|
public class Solution {
public int FindPoisonedDuration(int[] timeSeries, int duration) {
int ans = duration;
int n = timeSeries.Length;
for (int i = 1; i < n; ++i) {
ans += Math.Min(duration, timeSeries[i] - timeSeries[i - 1]);
}
return ans;
}
}
|
495
|
Teemo Attacking
|
Easy
|
<p>Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly <code>duration</code> seconds. More formally, an attack at second <code>t</code> will mean Ashe is poisoned during the <strong>inclusive</strong> time interval <code>[t, t + duration - 1]</code>. If Teemo attacks again <strong>before</strong> the poison effect ends, the timer for it is <strong>reset</strong>, and the poison effect will end <code>duration</code> seconds after the new attack.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>timeSeries</code>, where <code>timeSeries[i]</code> denotes that Teemo attacks Ashe at second <code>timeSeries[i]</code>, and an integer <code>duration</code>.</p>
<p>Return <em>the <strong>total</strong> number of seconds that Ashe is poisoned</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,4], duration = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,2], duration = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= timeSeries.length <= 10<sup>4</sup></code></li>
<li><code>0 <= timeSeries[i], duration <= 10<sup>7</sup></code></li>
<li><code>timeSeries</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Simulation
|
Go
|
func findPoisonedDuration(timeSeries []int, duration int) (ans int) {
ans = duration
for i, x := range timeSeries[1:] {
ans += min(duration, x-timeSeries[i])
}
return
}
|
495
|
Teemo Attacking
|
Easy
|
<p>Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly <code>duration</code> seconds. More formally, an attack at second <code>t</code> will mean Ashe is poisoned during the <strong>inclusive</strong> time interval <code>[t, t + duration - 1]</code>. If Teemo attacks again <strong>before</strong> the poison effect ends, the timer for it is <strong>reset</strong>, and the poison effect will end <code>duration</code> seconds after the new attack.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>timeSeries</code>, where <code>timeSeries[i]</code> denotes that Teemo attacks Ashe at second <code>timeSeries[i]</code>, and an integer <code>duration</code>.</p>
<p>Return <em>the <strong>total</strong> number of seconds that Ashe is poisoned</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,4], duration = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,2], duration = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= timeSeries.length <= 10<sup>4</sup></code></li>
<li><code>0 <= timeSeries[i], duration <= 10<sup>7</sup></code></li>
<li><code>timeSeries</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Simulation
|
Java
|
class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
int n = timeSeries.length;
int ans = duration;
for (int i = 1; i < n; ++i) {
ans += Math.min(duration, timeSeries[i] - timeSeries[i - 1]);
}
return ans;
}
}
|
495
|
Teemo Attacking
|
Easy
|
<p>Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly <code>duration</code> seconds. More formally, an attack at second <code>t</code> will mean Ashe is poisoned during the <strong>inclusive</strong> time interval <code>[t, t + duration - 1]</code>. If Teemo attacks again <strong>before</strong> the poison effect ends, the timer for it is <strong>reset</strong>, and the poison effect will end <code>duration</code> seconds after the new attack.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>timeSeries</code>, where <code>timeSeries[i]</code> denotes that Teemo attacks Ashe at second <code>timeSeries[i]</code>, and an integer <code>duration</code>.</p>
<p>Return <em>the <strong>total</strong> number of seconds that Ashe is poisoned</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,4], duration = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,2], duration = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= timeSeries.length <= 10<sup>4</sup></code></li>
<li><code>0 <= timeSeries[i], duration <= 10<sup>7</sup></code></li>
<li><code>timeSeries</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Simulation
|
Python
|
class Solution:
def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
ans = duration
for a, b in pairwise(timeSeries):
ans += min(duration, b - a)
return ans
|
495
|
Teemo Attacking
|
Easy
|
<p>Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly <code>duration</code> seconds. More formally, an attack at second <code>t</code> will mean Ashe is poisoned during the <strong>inclusive</strong> time interval <code>[t, t + duration - 1]</code>. If Teemo attacks again <strong>before</strong> the poison effect ends, the timer for it is <strong>reset</strong>, and the poison effect will end <code>duration</code> seconds after the new attack.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>timeSeries</code>, where <code>timeSeries[i]</code> denotes that Teemo attacks Ashe at second <code>timeSeries[i]</code>, and an integer <code>duration</code>.</p>
<p>Return <em>the <strong>total</strong> number of seconds that Ashe is poisoned</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,4], duration = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> timeSeries = [1,2], duration = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= timeSeries.length <= 10<sup>4</sup></code></li>
<li><code>0 <= timeSeries[i], duration <= 10<sup>7</sup></code></li>
<li><code>timeSeries</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Simulation
|
TypeScript
|
function findPoisonedDuration(timeSeries: number[], duration: number): number {
const n = timeSeries.length;
let ans = duration;
for (let i = 1; i < n; ++i) {
ans += Math.min(duration, timeSeries[i] - timeSeries[i - 1]);
}
return ans;
}
|
496
|
Next Greater Element I
|
Easy
|
<p>The <strong>next greater element</strong> of some element <code>x</code> in an array is the <strong>first greater</strong> element that is <strong>to the right</strong> of <code>x</code> in the same array.</p>
<p>You are given two <strong>distinct 0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, where <code>nums1</code> is a subset of <code>nums2</code>.</p>
<p>For each <code>0 <= i < nums1.length</code>, find the index <code>j</code> such that <code>nums1[i] == nums2[j]</code> and determine the <strong>next greater element</strong> of <code>nums2[j]</code> in <code>nums2</code>. If there is no next greater element, then the answer for this query is <code>-1</code>.</p>
<p>Return <em>an array </em><code>ans</code><em> of length </em><code>nums1.length</code><em> such that </em><code>ans[i]</code><em> is the <strong>next greater element</strong> as described above.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]
<strong>Output:</strong> [-1,3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,<u>4</u>,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [<u>1</u>,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,<u>2</u>]. There is no next greater element, so the answer is -1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,4], nums2 = [1,2,3,4]
<strong>Output:</strong> [3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,<u>2</u>,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,<u>4</u>]. There is no next greater element, so the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length <= nums2.length <= 1000</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>4</sup></code></li>
<li>All integers in <code>nums1</code> and <code>nums2</code> are <strong>unique</strong>.</li>
<li>All the integers of <code>nums1</code> also appear in <code>nums2</code>.</li>
</ul>
<p> </p>
<strong>Follow up:</strong> Could you find an <code>O(nums1.length + nums2.length)</code> solution?
|
Stack; Array; Hash Table; Monotonic Stack
|
C++
|
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
stack<int> stk;
unordered_map<int, int> d;
ranges::reverse(nums2);
for (int x : nums2) {
while (!stk.empty() && stk.top() < x) {
stk.pop();
}
if (!stk.empty()) {
d[x] = stk.top();
}
stk.push(x);
}
vector<int> ans;
for (int x : nums1) {
ans.push_back(d.contains(x) ? d[x] : -1);
}
return ans;
}
};
|
496
|
Next Greater Element I
|
Easy
|
<p>The <strong>next greater element</strong> of some element <code>x</code> in an array is the <strong>first greater</strong> element that is <strong>to the right</strong> of <code>x</code> in the same array.</p>
<p>You are given two <strong>distinct 0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, where <code>nums1</code> is a subset of <code>nums2</code>.</p>
<p>For each <code>0 <= i < nums1.length</code>, find the index <code>j</code> such that <code>nums1[i] == nums2[j]</code> and determine the <strong>next greater element</strong> of <code>nums2[j]</code> in <code>nums2</code>. If there is no next greater element, then the answer for this query is <code>-1</code>.</p>
<p>Return <em>an array </em><code>ans</code><em> of length </em><code>nums1.length</code><em> such that </em><code>ans[i]</code><em> is the <strong>next greater element</strong> as described above.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]
<strong>Output:</strong> [-1,3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,<u>4</u>,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [<u>1</u>,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,<u>2</u>]. There is no next greater element, so the answer is -1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,4], nums2 = [1,2,3,4]
<strong>Output:</strong> [3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,<u>2</u>,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,<u>4</u>]. There is no next greater element, so the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length <= nums2.length <= 1000</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>4</sup></code></li>
<li>All integers in <code>nums1</code> and <code>nums2</code> are <strong>unique</strong>.</li>
<li>All the integers of <code>nums1</code> also appear in <code>nums2</code>.</li>
</ul>
<p> </p>
<strong>Follow up:</strong> Could you find an <code>O(nums1.length + nums2.length)</code> solution?
|
Stack; Array; Hash Table; Monotonic Stack
|
Go
|
func nextGreaterElement(nums1 []int, nums2 []int) (ans []int) {
stk := []int{}
d := map[int]int{}
for i := len(nums2) - 1; i >= 0; i-- {
x := nums2[i]
for len(stk) > 0 && stk[len(stk)-1] < x {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
d[x] = stk[len(stk)-1]
}
stk = append(stk, x)
}
for _, x := range nums1 {
if v, ok := d[x]; ok {
ans = append(ans, v)
} else {
ans = append(ans, -1)
}
}
return
}
|
496
|
Next Greater Element I
|
Easy
|
<p>The <strong>next greater element</strong> of some element <code>x</code> in an array is the <strong>first greater</strong> element that is <strong>to the right</strong> of <code>x</code> in the same array.</p>
<p>You are given two <strong>distinct 0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, where <code>nums1</code> is a subset of <code>nums2</code>.</p>
<p>For each <code>0 <= i < nums1.length</code>, find the index <code>j</code> such that <code>nums1[i] == nums2[j]</code> and determine the <strong>next greater element</strong> of <code>nums2[j]</code> in <code>nums2</code>. If there is no next greater element, then the answer for this query is <code>-1</code>.</p>
<p>Return <em>an array </em><code>ans</code><em> of length </em><code>nums1.length</code><em> such that </em><code>ans[i]</code><em> is the <strong>next greater element</strong> as described above.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]
<strong>Output:</strong> [-1,3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,<u>4</u>,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [<u>1</u>,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,<u>2</u>]. There is no next greater element, so the answer is -1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,4], nums2 = [1,2,3,4]
<strong>Output:</strong> [3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,<u>2</u>,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,<u>4</u>]. There is no next greater element, so the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length <= nums2.length <= 1000</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>4</sup></code></li>
<li>All integers in <code>nums1</code> and <code>nums2</code> are <strong>unique</strong>.</li>
<li>All the integers of <code>nums1</code> also appear in <code>nums2</code>.</li>
</ul>
<p> </p>
<strong>Follow up:</strong> Could you find an <code>O(nums1.length + nums2.length)</code> solution?
|
Stack; Array; Hash Table; Monotonic Stack
|
Java
|
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Deque<Integer> stk = new ArrayDeque<>();
int m = nums1.length, n = nums2.length;
Map<Integer, Integer> d = new HashMap(n);
for (int i = n - 1; i >= 0; --i) {
int x = nums2[i];
while (!stk.isEmpty() && stk.peek() < x) {
stk.pop();
}
if (!stk.isEmpty()) {
d.put(x, stk.peek());
}
stk.push(x);
}
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
ans[i] = d.getOrDefault(nums1[i], -1);
}
return ans;
}
}
|
496
|
Next Greater Element I
|
Easy
|
<p>The <strong>next greater element</strong> of some element <code>x</code> in an array is the <strong>first greater</strong> element that is <strong>to the right</strong> of <code>x</code> in the same array.</p>
<p>You are given two <strong>distinct 0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, where <code>nums1</code> is a subset of <code>nums2</code>.</p>
<p>For each <code>0 <= i < nums1.length</code>, find the index <code>j</code> such that <code>nums1[i] == nums2[j]</code> and determine the <strong>next greater element</strong> of <code>nums2[j]</code> in <code>nums2</code>. If there is no next greater element, then the answer for this query is <code>-1</code>.</p>
<p>Return <em>an array </em><code>ans</code><em> of length </em><code>nums1.length</code><em> such that </em><code>ans[i]</code><em> is the <strong>next greater element</strong> as described above.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]
<strong>Output:</strong> [-1,3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,<u>4</u>,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [<u>1</u>,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,<u>2</u>]. There is no next greater element, so the answer is -1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,4], nums2 = [1,2,3,4]
<strong>Output:</strong> [3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,<u>2</u>,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,<u>4</u>]. There is no next greater element, so the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length <= nums2.length <= 1000</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>4</sup></code></li>
<li>All integers in <code>nums1</code> and <code>nums2</code> are <strong>unique</strong>.</li>
<li>All the integers of <code>nums1</code> also appear in <code>nums2</code>.</li>
</ul>
<p> </p>
<strong>Follow up:</strong> Could you find an <code>O(nums1.length + nums2.length)</code> solution?
|
Stack; Array; Hash Table; Monotonic Stack
|
JavaScript
|
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var nextGreaterElement = function (nums1, nums2) {
const stk = [];
const d = {};
for (const x of nums2.reverse()) {
while (stk.length && stk.at(-1) < x) {
stk.pop();
}
d[x] = stk.length ? stk.at(-1) : -1;
stk.push(x);
}
return nums1.map(x => d[x]);
};
|
496
|
Next Greater Element I
|
Easy
|
<p>The <strong>next greater element</strong> of some element <code>x</code> in an array is the <strong>first greater</strong> element that is <strong>to the right</strong> of <code>x</code> in the same array.</p>
<p>You are given two <strong>distinct 0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, where <code>nums1</code> is a subset of <code>nums2</code>.</p>
<p>For each <code>0 <= i < nums1.length</code>, find the index <code>j</code> such that <code>nums1[i] == nums2[j]</code> and determine the <strong>next greater element</strong> of <code>nums2[j]</code> in <code>nums2</code>. If there is no next greater element, then the answer for this query is <code>-1</code>.</p>
<p>Return <em>an array </em><code>ans</code><em> of length </em><code>nums1.length</code><em> such that </em><code>ans[i]</code><em> is the <strong>next greater element</strong> as described above.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]
<strong>Output:</strong> [-1,3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,<u>4</u>,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [<u>1</u>,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,<u>2</u>]. There is no next greater element, so the answer is -1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,4], nums2 = [1,2,3,4]
<strong>Output:</strong> [3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,<u>2</u>,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,<u>4</u>]. There is no next greater element, so the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length <= nums2.length <= 1000</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>4</sup></code></li>
<li>All integers in <code>nums1</code> and <code>nums2</code> are <strong>unique</strong>.</li>
<li>All the integers of <code>nums1</code> also appear in <code>nums2</code>.</li>
</ul>
<p> </p>
<strong>Follow up:</strong> Could you find an <code>O(nums1.length + nums2.length)</code> solution?
|
Stack; Array; Hash Table; Monotonic Stack
|
Python
|
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stk = []
d = {}
for x in nums2[::-1]:
while stk and stk[-1] < x:
stk.pop()
if stk:
d[x] = stk[-1]
stk.append(x)
return [d.get(x, -1) for x in nums1]
|
496
|
Next Greater Element I
|
Easy
|
<p>The <strong>next greater element</strong> of some element <code>x</code> in an array is the <strong>first greater</strong> element that is <strong>to the right</strong> of <code>x</code> in the same array.</p>
<p>You are given two <strong>distinct 0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, where <code>nums1</code> is a subset of <code>nums2</code>.</p>
<p>For each <code>0 <= i < nums1.length</code>, find the index <code>j</code> such that <code>nums1[i] == nums2[j]</code> and determine the <strong>next greater element</strong> of <code>nums2[j]</code> in <code>nums2</code>. If there is no next greater element, then the answer for this query is <code>-1</code>.</p>
<p>Return <em>an array </em><code>ans</code><em> of length </em><code>nums1.length</code><em> such that </em><code>ans[i]</code><em> is the <strong>next greater element</strong> as described above.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]
<strong>Output:</strong> [-1,3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,<u>4</u>,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [<u>1</u>,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,<u>2</u>]. There is no next greater element, so the answer is -1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,4], nums2 = [1,2,3,4]
<strong>Output:</strong> [3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,<u>2</u>,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,<u>4</u>]. There is no next greater element, so the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length <= nums2.length <= 1000</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>4</sup></code></li>
<li>All integers in <code>nums1</code> and <code>nums2</code> are <strong>unique</strong>.</li>
<li>All the integers of <code>nums1</code> also appear in <code>nums2</code>.</li>
</ul>
<p> </p>
<strong>Follow up:</strong> Could you find an <code>O(nums1.length + nums2.length)</code> solution?
|
Stack; Array; Hash Table; Monotonic Stack
|
Rust
|
use std::collections::HashMap;
impl Solution {
pub fn next_greater_element(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
let mut stk = Vec::new();
let mut d = HashMap::new();
for &x in nums2.iter().rev() {
while let Some(&top) = stk.last() {
if top <= x {
stk.pop();
} else {
break;
}
}
if let Some(&top) = stk.last() {
d.insert(x, top);
}
stk.push(x);
}
nums1
.into_iter()
.map(|x| *d.get(&x).unwrap_or(&-1))
.collect()
}
}
|
496
|
Next Greater Element I
|
Easy
|
<p>The <strong>next greater element</strong> of some element <code>x</code> in an array is the <strong>first greater</strong> element that is <strong>to the right</strong> of <code>x</code> in the same array.</p>
<p>You are given two <strong>distinct 0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, where <code>nums1</code> is a subset of <code>nums2</code>.</p>
<p>For each <code>0 <= i < nums1.length</code>, find the index <code>j</code> such that <code>nums1[i] == nums2[j]</code> and determine the <strong>next greater element</strong> of <code>nums2[j]</code> in <code>nums2</code>. If there is no next greater element, then the answer for this query is <code>-1</code>.</p>
<p>Return <em>an array </em><code>ans</code><em> of length </em><code>nums1.length</code><em> such that </em><code>ans[i]</code><em> is the <strong>next greater element</strong> as described above.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]
<strong>Output:</strong> [-1,3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,<u>4</u>,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [<u>1</u>,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,<u>2</u>]. There is no next greater element, so the answer is -1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,4], nums2 = [1,2,3,4]
<strong>Output:</strong> [3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,<u>2</u>,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,<u>4</u>]. There is no next greater element, so the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length <= nums2.length <= 1000</code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>4</sup></code></li>
<li>All integers in <code>nums1</code> and <code>nums2</code> are <strong>unique</strong>.</li>
<li>All the integers of <code>nums1</code> also appear in <code>nums2</code>.</li>
</ul>
<p> </p>
<strong>Follow up:</strong> Could you find an <code>O(nums1.length + nums2.length)</code> solution?
|
Stack; Array; Hash Table; Monotonic Stack
|
TypeScript
|
function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
const stk: number[] = [];
const d: Record<number, number> = {};
for (const x of nums2.reverse()) {
while (stk.length && stk.at(-1)! < x) {
stk.pop();
}
d[x] = stk.length ? stk.at(-1)! : -1;
stk.push(x);
}
return nums1.map(x => d[x]);
}
|
497
|
Random Point in Non-overlapping Rectangles
|
Medium
|
<p>You are given an array of non-overlapping axis-aligned rectangles <code>rects</code> where <code>rects[i] = [a<sub>i</sub>, b<sub>i</sub>, x<sub>i</sub>, y<sub>i</sub>]</code> indicates that <code>(a<sub>i</sub>, b<sub>i</sub>)</code> is the bottom-left corner point of the <code>i<sup>th</sup></code> rectangle and <code>(x<sub>i</sub>, y<sub>i</sub>)</code> is the top-right corner point of the <code>i<sup>th</sup></code> rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.</p>
<p>Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.</p>
<p><strong>Note</strong> that an integer point is a point that has integer coordinates.</p>
<p>Implement the <code>Solution</code> class:</p>
<ul>
<li><code>Solution(int[][] rects)</code> Initializes the object with the given rectangles <code>rects</code>.</li>
<li><code>int[] pick()</code> Returns a random integer point <code>[u, v]</code> inside the space covered by one of the given rectangles.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0497.Random%20Point%20in%20Non-overlapping%20Rectangles/images/lc-pickrandomrec.jpg" style="width: 419px; height: 539px;" />
<pre>
<strong>Input</strong>
["Solution", "pick", "pick", "pick", "pick", "pick"]
[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]
<strong>Output</strong>
[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]
<strong>Explanation</strong>
Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);
solution.pick(); // return [1, -2]
solution.pick(); // return [1, -1]
solution.pick(); // return [-1, -2]
solution.pick(); // return [-2, -2]
solution.pick(); // return [0, 0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= rects.length <= 100</code></li>
<li><code>rects[i].length == 4</code></li>
<li><code>-10<sup>9</sup> <= a<sub>i</sub> < x<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>-10<sup>9</sup> <= b<sub>i</sub> < y<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>x<sub>i</sub> - a<sub>i</sub> <= 2000</code></li>
<li><code>y<sub>i</sub> - b<sub>i</sub> <= 2000</code></li>
<li>All the rectangles do not overlap.</li>
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li>
</ul>
|
Reservoir Sampling; Array; Math; Binary Search; Ordered Set; Prefix Sum; Randomized
|
C++
|
class Solution {
public:
vector<int> s;
vector<vector<int>> rects;
Solution(vector<vector<int>>& rects) {
int n = rects.size();
s.resize(n + 1);
for (int i = 0; i < n; ++i) s[i + 1] = s[i] + (rects[i][2] - rects[i][0] + 1) * (rects[i][3] - rects[i][1] + 1);
this->rects = rects;
srand(time(nullptr));
}
vector<int> pick() {
int n = rects.size();
int v = 1 + rand() % s[n];
int idx = lower_bound(s.begin(), s.end(), v) - s.begin();
auto& rect = rects[idx - 1];
int x = rect[0] + rand() % (rect[2] - rect[0] + 1);
int y = rect[1] + rand() % (rect[3] - rect[1] + 1);
return {x, y};
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(rects);
* vector<int> param_1 = obj->pick();
*/
|
497
|
Random Point in Non-overlapping Rectangles
|
Medium
|
<p>You are given an array of non-overlapping axis-aligned rectangles <code>rects</code> where <code>rects[i] = [a<sub>i</sub>, b<sub>i</sub>, x<sub>i</sub>, y<sub>i</sub>]</code> indicates that <code>(a<sub>i</sub>, b<sub>i</sub>)</code> is the bottom-left corner point of the <code>i<sup>th</sup></code> rectangle and <code>(x<sub>i</sub>, y<sub>i</sub>)</code> is the top-right corner point of the <code>i<sup>th</sup></code> rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.</p>
<p>Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.</p>
<p><strong>Note</strong> that an integer point is a point that has integer coordinates.</p>
<p>Implement the <code>Solution</code> class:</p>
<ul>
<li><code>Solution(int[][] rects)</code> Initializes the object with the given rectangles <code>rects</code>.</li>
<li><code>int[] pick()</code> Returns a random integer point <code>[u, v]</code> inside the space covered by one of the given rectangles.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0497.Random%20Point%20in%20Non-overlapping%20Rectangles/images/lc-pickrandomrec.jpg" style="width: 419px; height: 539px;" />
<pre>
<strong>Input</strong>
["Solution", "pick", "pick", "pick", "pick", "pick"]
[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]
<strong>Output</strong>
[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]
<strong>Explanation</strong>
Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);
solution.pick(); // return [1, -2]
solution.pick(); // return [1, -1]
solution.pick(); // return [-1, -2]
solution.pick(); // return [-2, -2]
solution.pick(); // return [0, 0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= rects.length <= 100</code></li>
<li><code>rects[i].length == 4</code></li>
<li><code>-10<sup>9</sup> <= a<sub>i</sub> < x<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>-10<sup>9</sup> <= b<sub>i</sub> < y<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>x<sub>i</sub> - a<sub>i</sub> <= 2000</code></li>
<li><code>y<sub>i</sub> - b<sub>i</sub> <= 2000</code></li>
<li>All the rectangles do not overlap.</li>
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li>
</ul>
|
Reservoir Sampling; Array; Math; Binary Search; Ordered Set; Prefix Sum; Randomized
|
Go
|
type Solution struct {
s []int
rects [][]int
}
func Constructor(rects [][]int) Solution {
n := len(rects)
s := make([]int, n+1)
for i, v := range rects {
s[i+1] = s[i] + (v[2]-v[0]+1)*(v[3]-v[1]+1)
}
return Solution{s, rects}
}
func (this *Solution) Pick() []int {
n := len(this.rects)
v := 1 + rand.Intn(this.s[len(this.s)-1])
left, right := 0, n
for left < right {
mid := (left + right) >> 1
if this.s[mid] >= v {
right = mid
} else {
left = mid + 1
}
}
rect := this.rects[left-1]
x, y := rect[0]+rand.Intn(rect[2]-rect[0]+1), rect[1]+rand.Intn(rect[3]-rect[1]+1)
return []int{x, y}
}
|
497
|
Random Point in Non-overlapping Rectangles
|
Medium
|
<p>You are given an array of non-overlapping axis-aligned rectangles <code>rects</code> where <code>rects[i] = [a<sub>i</sub>, b<sub>i</sub>, x<sub>i</sub>, y<sub>i</sub>]</code> indicates that <code>(a<sub>i</sub>, b<sub>i</sub>)</code> is the bottom-left corner point of the <code>i<sup>th</sup></code> rectangle and <code>(x<sub>i</sub>, y<sub>i</sub>)</code> is the top-right corner point of the <code>i<sup>th</sup></code> rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.</p>
<p>Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.</p>
<p><strong>Note</strong> that an integer point is a point that has integer coordinates.</p>
<p>Implement the <code>Solution</code> class:</p>
<ul>
<li><code>Solution(int[][] rects)</code> Initializes the object with the given rectangles <code>rects</code>.</li>
<li><code>int[] pick()</code> Returns a random integer point <code>[u, v]</code> inside the space covered by one of the given rectangles.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0497.Random%20Point%20in%20Non-overlapping%20Rectangles/images/lc-pickrandomrec.jpg" style="width: 419px; height: 539px;" />
<pre>
<strong>Input</strong>
["Solution", "pick", "pick", "pick", "pick", "pick"]
[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]
<strong>Output</strong>
[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]
<strong>Explanation</strong>
Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);
solution.pick(); // return [1, -2]
solution.pick(); // return [1, -1]
solution.pick(); // return [-1, -2]
solution.pick(); // return [-2, -2]
solution.pick(); // return [0, 0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= rects.length <= 100</code></li>
<li><code>rects[i].length == 4</code></li>
<li><code>-10<sup>9</sup> <= a<sub>i</sub> < x<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>-10<sup>9</sup> <= b<sub>i</sub> < y<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>x<sub>i</sub> - a<sub>i</sub> <= 2000</code></li>
<li><code>y<sub>i</sub> - b<sub>i</sub> <= 2000</code></li>
<li>All the rectangles do not overlap.</li>
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li>
</ul>
|
Reservoir Sampling; Array; Math; Binary Search; Ordered Set; Prefix Sum; Randomized
|
Java
|
class Solution {
private int[] s;
private int[][] rects;
private Random random = new Random();
public Solution(int[][] rects) {
int n = rects.length;
s = new int[n + 1];
for (int i = 0; i < n; ++i) {
s[i + 1] = s[i] + (rects[i][2] - rects[i][0] + 1) * (rects[i][3] - rects[i][1] + 1);
}
this.rects = rects;
}
public int[] pick() {
int n = rects.length;
int v = 1 + random.nextInt(s[n]);
int left = 0, right = n;
while (left < right) {
int mid = (left + right) >> 1;
if (s[mid] >= v) {
right = mid;
} else {
left = mid + 1;
}
}
int[] rect = rects[left - 1];
return new int[] {rect[0] + random.nextInt(rect[2] - rect[0] + 1),
rect[1] + random.nextInt(rect[3] - rect[1] + 1)};
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(rects);
* int[] param_1 = obj.pick();
*/
|
497
|
Random Point in Non-overlapping Rectangles
|
Medium
|
<p>You are given an array of non-overlapping axis-aligned rectangles <code>rects</code> where <code>rects[i] = [a<sub>i</sub>, b<sub>i</sub>, x<sub>i</sub>, y<sub>i</sub>]</code> indicates that <code>(a<sub>i</sub>, b<sub>i</sub>)</code> is the bottom-left corner point of the <code>i<sup>th</sup></code> rectangle and <code>(x<sub>i</sub>, y<sub>i</sub>)</code> is the top-right corner point of the <code>i<sup>th</sup></code> rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.</p>
<p>Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.</p>
<p><strong>Note</strong> that an integer point is a point that has integer coordinates.</p>
<p>Implement the <code>Solution</code> class:</p>
<ul>
<li><code>Solution(int[][] rects)</code> Initializes the object with the given rectangles <code>rects</code>.</li>
<li><code>int[] pick()</code> Returns a random integer point <code>[u, v]</code> inside the space covered by one of the given rectangles.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0497.Random%20Point%20in%20Non-overlapping%20Rectangles/images/lc-pickrandomrec.jpg" style="width: 419px; height: 539px;" />
<pre>
<strong>Input</strong>
["Solution", "pick", "pick", "pick", "pick", "pick"]
[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]
<strong>Output</strong>
[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]
<strong>Explanation</strong>
Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);
solution.pick(); // return [1, -2]
solution.pick(); // return [1, -1]
solution.pick(); // return [-1, -2]
solution.pick(); // return [-2, -2]
solution.pick(); // return [0, 0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= rects.length <= 100</code></li>
<li><code>rects[i].length == 4</code></li>
<li><code>-10<sup>9</sup> <= a<sub>i</sub> < x<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>-10<sup>9</sup> <= b<sub>i</sub> < y<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>x<sub>i</sub> - a<sub>i</sub> <= 2000</code></li>
<li><code>y<sub>i</sub> - b<sub>i</sub> <= 2000</code></li>
<li>All the rectangles do not overlap.</li>
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li>
</ul>
|
Reservoir Sampling; Array; Math; Binary Search; Ordered Set; Prefix Sum; Randomized
|
Python
|
class Solution:
def __init__(self, rects: List[List[int]]):
self.rects = rects
self.s = [0] * len(rects)
for i, (x1, y1, x2, y2) in enumerate(rects):
self.s[i] = self.s[i - 1] + (x2 - x1 + 1) * (y2 - y1 + 1)
def pick(self) -> List[int]:
v = random.randint(1, self.s[-1])
idx = bisect_left(self.s, v)
x1, y1, x2, y2 = self.rects[idx]
return [random.randint(x1, x2), random.randint(y1, y2)]
# Your Solution object will be instantiated and called as such:
# obj = Solution(rects)
# param_1 = obj.pick()
|
498
|
Diagonal Traverse
|
Medium
|
<p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0498.Diagonal%20Traverse/images/diag1-grid.jpg" style="width: 334px; height: 334px;" />
<pre>
<strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]]
<strong>Output:</strong> [1,2,4,7,5,3,6,8,9]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]]
<strong>Output:</strong> [1,2,3,4]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= mat[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Matrix; Simulation
|
C++
|
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
vector<int> ans;
vector<int> t;
for (int k = 0; k < m + n - 1; ++k) {
int i = (k < n) ? 0 : k - n + 1;
int j = (k < n) ? k : n - 1;
while (i < m && j >= 0) {
t.push_back(mat[i][j]);
++i;
--j;
}
if (k % 2 == 0) {
ranges::reverse(t);
}
ans.insert(ans.end(), t.begin(), t.end());
t.clear();
}
return ans;
}
};
|
498
|
Diagonal Traverse
|
Medium
|
<p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0498.Diagonal%20Traverse/images/diag1-grid.jpg" style="width: 334px; height: 334px;" />
<pre>
<strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]]
<strong>Output:</strong> [1,2,4,7,5,3,6,8,9]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]]
<strong>Output:</strong> [1,2,3,4]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= mat[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Matrix; Simulation
|
C#
|
public class Solution {
public int[] FindDiagonalOrder(int[][] mat) {
int m = mat.Length;
int n = mat[0].Length;
List<int> ans = new List<int>();
for (int k = 0; k < m + n - 1; k++) {
List<int> t = new List<int>();
int i = k < n ? 0 : k - n + 1;
int j = k < n ? k : n - 1;
while (i < m && j >= 0) {
t.Add(mat[i][j]);
i++;
j--;
}
if (k % 2 == 0) {
t.Reverse();
}
ans.AddRange(t);
}
return ans.ToArray();
}
}
|
498
|
Diagonal Traverse
|
Medium
|
<p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0498.Diagonal%20Traverse/images/diag1-grid.jpg" style="width: 334px; height: 334px;" />
<pre>
<strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]]
<strong>Output:</strong> [1,2,4,7,5,3,6,8,9]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]]
<strong>Output:</strong> [1,2,3,4]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= mat[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Matrix; Simulation
|
Go
|
func findDiagonalOrder(mat [][]int) []int {
m := len(mat)
n := len(mat[0])
ans := make([]int, 0, m*n)
for k := 0; k < m+n-1; k++ {
t := make([]int, 0)
var i, j int
if k < n {
i = 0
j = k
} else {
i = k - n + 1
j = n - 1
}
for i < m && j >= 0 {
t = append(t, mat[i][j])
i++
j--
}
if k%2 == 0 {
slices.Reverse(t)
}
ans = append(ans, t...)
}
return ans
}
|
498
|
Diagonal Traverse
|
Medium
|
<p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0498.Diagonal%20Traverse/images/diag1-grid.jpg" style="width: 334px; height: 334px;" />
<pre>
<strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]]
<strong>Output:</strong> [1,2,4,7,5,3,6,8,9]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]]
<strong>Output:</strong> [1,2,3,4]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 10<sup>4</sup></code></li>
<li><code>1 <= m * n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= mat[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Matrix; Simulation
|
Java
|
class Solution {
public int[] findDiagonalOrder(int[][] mat) {
int m = mat.length, n = mat[0].length;
int[] ans = new int[m * n];
int idx = 0;
List<Integer> t = new ArrayList<>();
for (int k = 0; k < m + n - 1; ++k) {
int i = k < n ? 0 : k - n + 1;
int j = k < n ? k : n - 1;
while (i < m && j >= 0) {
t.add(mat[i][j]);
++i;
--j;
}
if (k % 2 == 0) {
Collections.reverse(t);
}
for (int v : t) {
ans[idx++] = v;
}
t.clear();
}
return ans;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.