Skip to content

Commit 4b28853

Browse files
committed
LC 2009. Minimum Number of Operations to Make Array Continuous (Rust SW)
1 parent 7b3dc5c commit 4b28853

File tree

3 files changed

+141
-0
lines changed

3 files changed

+141
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@ Solutions to LeetCode problems. The first column links to the problem in LeetCod
254254
| [446. Arithmetic Slices II - Subsequence][lc446] | 🔴 Hard | [![python](res/py.png)][lc446py] |
255255
| [451. Sort Characters By Frequency][lc451] | 🟠 Medium | [![python](res/py.png)][lc451py] |
256256
| [452. Minimum Number of Arrows to Burst Balloons][lc452] | 🟠 Medium | [![python](res/py.png)][lc452py] |
257+
| [456. 132 Pattern][lc456] | 🟠 Medium | [![rust](res/rs.png)][lc456rs] |
257258
| [458. Poor Pigs][lc458] | 🔴 Hard | [![python](res/py.png)][lc458py] |
258259
| [460. LFU Cache][lc460] | 🔴 Hard | [![python](res/py.png)][lc460py] |
259260
| [472. Concatenated Words][lc472] | 🔴 Hard | [![python](res/py.png)][lc472py] [![rust](res/rs.png)][lc472rs] |
@@ -522,6 +523,7 @@ Solutions to LeetCode problems. The first column links to the problem in LeetCod
522523
| [1991. Find the Middle Index in Array][lc1991] | 🟢 Easy | [![python](res/py.png)][lc1991py] |
523524
| [1996. The Number of Weak Characters in the Game][lc1996] | 🟠 Medium | [![python](res/py.png)][lc1996py] |
524525
| [2007. Find Original Array From Doubled Array][lc2007] | 🟠 Medium | [![python](res/py.png)][lc2007py] |
526+
| [2009. Minimum Number of Operations to Make Array Continuous][lc2009] | 🔴 Hard | [![rust](res/rs.png)][lc2009rs] |
525527
| [2013. Detect Squares][lc2013] | 🟠 Medium | [![python](res/py.png)][lc2013py] |
526528
| [2024. Maximize the Confusion of an Exam][lc2024] | 🟠 Medium | [![rust](res/rs.png)][lc2024rs] |
527529
| [2090. K Radius Subarray Averages][lc2090] | 🟠 Medium | [![rust](res/rs.png)][lc2090rs] |
@@ -1132,6 +1134,8 @@ Solutions to LeetCode problems. The first column links to the problem in LeetCod
11321134
[lc451py]: leetcode/sort-characters-by-frequency.py
11331135
[lc452]: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/
11341136
[lc452py]: leetcode/minimum-number-of-arrows-to-burst-balloons.py
1137+
[lc456]: https://leetcode.com/problems/132-pattern/
1138+
[lc456rs]: leetcode/132-pattern.rs
11351139
[lc458]: https://leetcode.com/problems/poor-pigs/
11361140
[lc458py]: leetcode/poor-pigs.py
11371141
[lc460]: https://leetcode.com/problems/lfu-cache/
@@ -1730,6 +1734,8 @@ Solutions to LeetCode problems. The first column links to the problem in LeetCod
17301734
[lc1996py]: leetcode/the-number-of-weak-characters-in-the-game.py
17311735
[lc2007]: https://leetcode.com/problems/find-original-array-from-doubled-array/
17321736
[lc2007py]: leetcode/find-original-array-from-doubled-array.py
1737+
[lc2009]: https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/
1738+
[lc2009rs]: leetcode/minimum-number-of-operations-to-make-array-continuous.rs
17331739
[lc2013]: https://leetcode.com/problems/detect-squares/
17341740
[lc2013py]: leetcode/detect-squares.py
17351741
[lc2024]: https://leetcode.com/problems/maximize-the-confusion-of-an-exam/

leetcode/132-pattern.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// 456. 132 Pattern
2+
// 🟠 Medium
3+
//
4+
// https://leetcode.com/problems/132-pattern/
5+
//
6+
// Tags: Array - Binary Search - Stack - Monotonic Stack - Ordered Set
7+
8+
struct Solution;
9+
impl Solution {
10+
/// Precompute an array of minimum prefix at each position, then iterate
11+
/// from the back of the input storing the biggest values seen to the right.
12+
/// At each position, we pop any values from the stack that are smaller than
13+
/// the minimum at the current point, since we won't be able to use them,
14+
/// then we check if the current value is a peak between the top of the
15+
/// stack and the minimum to the left, if it is, we return true, we found a
16+
/// 132 pattern, otherwise we push the value into the monotonic stack, where
17+
/// it will be the smallest value at the top, and keep searching.
18+
///
19+
/// Time complexity: O(n) - We iterate twice over the input array, once
20+
/// forward and once backwards, we also may push and pop each element into
21+
/// the stack, but once at most.
22+
/// Space complexity: O(n) - The vector of minimums and the stack are O(n)
23+
///
24+
/// Runtime 9 ms Beats 25.40%
25+
/// Memory 5.34 MB Beats 9.89%
26+
pub fn find132pattern(nums: Vec<i32>) -> bool {
27+
let mins = nums
28+
.iter()
29+
.scan(nums[0], |state, &x| {
30+
*state = x.min(*state);
31+
Some(*state)
32+
})
33+
.collect::<Vec<i32>>();
34+
// A monotonic stack with the biggest values seen to the right.
35+
let mut stack = vec![nums[nums.len() - 1]];
36+
for i in (0..nums.len() - 1).rev() {
37+
if nums[i] <= mins[i] {
38+
continue;
39+
}
40+
while !stack.is_empty() && *stack.last().unwrap() <= mins[i] {
41+
stack.pop();
42+
}
43+
if !stack.is_empty() && *stack.last().unwrap() < nums[i] {
44+
return true;
45+
}
46+
stack.push(nums[i]);
47+
}
48+
false
49+
}
50+
}
51+
52+
// Tests.
53+
fn main() {
54+
let tests = [
55+
(vec![3, 1, 4, 2], true),
56+
(vec![-1, 3, 2, 0], true),
57+
(vec![1, 2, 3, 4], false),
58+
(vec![3, 5, 0, 3, 4], true),
59+
(vec![1, 0, 1, -4, -3], false),
60+
];
61+
for t in tests {
62+
assert_eq!(Solution::find132pattern(t.0), t.1);
63+
}
64+
println!("\x1b[92m» All tests passed!\x1b[0m")
65+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// 2009. Minimum Number of Operations to Make Array Continuous
2+
// 🔴 Hard
3+
//
4+
// https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/
5+
//
6+
// Tags: Array - Binary Search
7+
8+
struct Solution;
9+
impl Solution {
10+
/// Sort the input, then use a sliding window technique, the sliding window
11+
/// is computed using the value of the left edge and the value that the
12+
/// right edge should have for the array to be continuous. When we find these
13+
/// two indexes, we know that the elements between these two indexes can be
14+
/// used as part of the continuous array, and we will need to change all
15+
/// the others. We try all left boundaries and keep the one that results in
16+
/// the least amount of substitutions.
17+
///
18+
/// Time complexity: O(n*log(n)) - Sorting the input vector has the highest
19+
/// complexity, the sliding window algorithm runs in O(n) because r never
20+
/// moves backwards.
21+
/// Space complexity: O(n) - We keep a local copy of nums, in languages that
22+
/// let us mutate the input, we could sort the input vector. Besides that,
23+
/// we use, probably, O(log(n)) extra space for the sorting and constant
24+
/// extra space besides that.
25+
///
26+
/// Runtime 21 ms Beats 100%
27+
/// Memory 3.90 MB Beats 100%
28+
pub fn min_operations(nums: Vec<i32>) -> i32 {
29+
// We are looking for a minimum number of substitutions.
30+
let mut res = i32::MAX;
31+
let n = nums.len();
32+
let offset = n as i32 - 1;
33+
// We want a sorted copy of nums with all duplicates removed.
34+
let mut nums = nums;
35+
nums.sort_unstable();
36+
nums.dedup();
37+
// Store the value that should be at the right end of the continuous vector.
38+
let mut x;
39+
let mut r = 0;
40+
for l in 0..nums.len() {
41+
x = nums[l] + offset;
42+
while r < nums.len() && nums[r] <= x {
43+
r += 1;
44+
// if r >= nums.len() || nums[r] > x {
45+
// break;
46+
//}
47+
}
48+
// We can use the elements between l and r-1 to build a continuous
49+
// sequence, how many more do we need? These we need to convert.
50+
res = res.min((n + l - r) as i32);
51+
if r == nums.len() {
52+
break;
53+
}
54+
}
55+
res
56+
}
57+
}
58+
59+
// Tests.
60+
fn main() {
61+
let tests = [
62+
(vec![4, 2, 5, 3], 0),
63+
(vec![1, 2, 3, 5, 6], 1),
64+
(vec![1, 10, 100, 1000], 3),
65+
];
66+
for t in tests {
67+
assert_eq!(Solution::min_operations(t.0), t.1);
68+
}
69+
println!("\x1b[92m» All tests passed!\x1b[0m")
70+
}

0 commit comments

Comments
 (0)