Skip to content

Commit 2934733

Browse files
committed
LC 3011. Find if Array Can Be Sorted (Rust)
1 parent 30f476e commit 2934733

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,7 @@ to the solution in this repository.
777777
| [2966. Divide Array Into Arrays With Max Difference][lc2966] | 🟠 Medium | [![rust](res/rs.png)][lc2966rs] |
778778
| [2971. Find Polygon With the Largest Perimeter][lc2971] | 🟠 Medium | [![rust](res/rs.png)][lc2971rs] |
779779
| [3005. Count Elements With Maximum Frequency][lc3005] | 🟢 Easy | [![rust](res/rs.png)][lc3005rs] |
780+
| [3011. Find if Array Can Be Sorted][lc3011] | 🟠 Medium | [![rust](res/rs.png)][lc3011rs] |
780781
| [3043. Find the Length of the Longest Common Prefix][lc3043] | 🟠 Medium | [![rust](res/rs.png)][lc3043rs] |
781782
| [3068. Find the Maximum Sum of Node Values][lc3068] | 🔴 Hard | [![rust](res/rs.png)][lc3068rs] |
782783
| [3075. Maximize Happiness of Selected Children][lc3075] | 🟠 Medium | [![rust](res/rs.png)][lc3075rs] |
@@ -2489,6 +2490,8 @@ to the solution in this repository.
24892490
[lc2971rs]: leetcode/find-polygon-with-the-largest-perimeter.rs
24902491
[lc3005]: https://leetcode.com/problems/count-elements-with-maximum-frequency/
24912492
[lc3005rs]: leetcode/count-elements-with-maximum-frequency.rs
2493+
[lc3011]: https://leetcode.com/problems/find-if-array-can-be-sorted/
2494+
[lc3011rs]: leetcode/find-if-array-can-be-sorted.rs
24922495
[lc3043]: https://leetcode.com/problems/find-the-length-of-the-longest-common-prefix/
24932496
[lc3043rs]: leetcode/find-the-length-of-the-longest-common-prefix.rs
24942497
[lc3068]: https://leetcode.com/problems/find-the-maximum-sum-of-node-values/
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// 3011. Find if Array Can Be Sorted
2+
// 🟠 Medium
3+
//
4+
// https://leetcode.com/problems/find-if-array-can-be-sorted/
5+
//
6+
// Tags: Array - Bit Manipulation - Sorting
7+
8+
struct Solution;
9+
impl Solution {
10+
/// Group the values by the number of set bits using `count_ones()` then check that each
11+
/// group's max is less than the next group's min.
12+
///
13+
/// Time complexity: O(n) - We iterate over the values three times, once to group them, once to
14+
/// get the min and one to get the max.
15+
/// Space complexity: O(n) - The max memory used will be a chunk size, which could be n if all
16+
/// the values in the input had the same number of set bits, since n <= 100, we could call it
17+
/// constant space.
18+
///
19+
/// Runtime 2 ms Beats 100%
20+
/// Memory 2.16 MB Beats 100%
21+
#[allow(dead_code)]
22+
pub fn can_sort_array_loop(nums: Vec<i32>) -> bool {
23+
let mut last_max = i32::MIN;
24+
for chunk in nums.chunk_by(|a, b| a.count_ones() == b.count_ones()) {
25+
if let Some(&cur_min) = chunk.iter().min() {
26+
if cur_min < last_max {
27+
return false;
28+
}
29+
last_max = *chunk.iter().max().unwrap();
30+
}
31+
}
32+
true
33+
}
34+
35+
/// Same solution but compress everything into one iterator chain, use `try_fold()` to break
36+
/// early when we find a pair of chunks that cannot be sorted.
37+
///
38+
/// Runtime 0 ms Beats 100%
39+
/// Memory 2.17 MB Beats 100%
40+
#[allow(dead_code)]
41+
pub fn can_sort_array(nums: Vec<i32>) -> bool {
42+
nums.chunk_by(|a, b| a.count_ones() == b.count_ones())
43+
.try_fold(i32::MIN, |last_max, chunk| {
44+
if *chunk.iter().min()? < last_max {
45+
None
46+
} else {
47+
Some(*chunk.iter().max()?)
48+
}
49+
})
50+
.is_some()
51+
}
52+
}
53+
54+
// Tests.
55+
fn main() {
56+
let tests = [
57+
(vec![8, 4, 2, 30, 15], true),
58+
(vec![1, 2, 3, 4, 5], true),
59+
(vec![3, 16, 8, 4, 2], false),
60+
];
61+
println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len());
62+
let mut success = 0;
63+
for (i, t) in tests.iter().enumerate() {
64+
let res = Solution::can_sort_array(t.0.clone());
65+
if res == t.1 {
66+
success += 1;
67+
println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i);
68+
} else {
69+
println!(
70+
"\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m",
71+
i, t.1, res
72+
);
73+
}
74+
}
75+
println!();
76+
if success == tests.len() {
77+
println!("\x1b[30;42m✔ All tests passed!\x1b[0m")
78+
} else if success == 0 {
79+
println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m")
80+
} else {
81+
println!(
82+
"\x1b[31mx\x1b[95m {} tests failed!\x1b[0m",
83+
tests.len() - success
84+
)
85+
}
86+
}

0 commit comments

Comments
 (0)