|
| 1 | +// 1574. Shortest Subarray to be Removed to Make Array Sorted |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/ |
| 5 | +// |
| 6 | +// Tags: Array - Two Pointers - Binary Search - Stack - Monotonic Stack |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Find the longest increasing subarrays from left and right and use a two pointer |
| 11 | + /// approach to grow the subarray on the left and shrink the one on the left to make sure |
| 12 | + /// we can concatenate them. |
| 13 | + /// |
| 14 | + /// Time complexity: O(n) - Two pointer approach. |
| 15 | + /// Space complexity: O(1) - Constant extra memory used. |
| 16 | + /// |
| 17 | + /// Runtime 0 ms Beats 100% |
| 18 | + /// Memory 3.79 MB Beats 100% |
| 19 | + pub fn find_length_of_shortest_subarray(arr: Vec<i32>) -> i32 { |
| 20 | + let mut right = arr.len() - 1; |
| 21 | + while right > 0 && arr[right] >= arr[right - 1] { |
| 22 | + right -= 1; |
| 23 | + } |
| 24 | + let mut res = right; |
| 25 | + let mut left = 0; |
| 26 | + while left < right && (left == 0 || arr[left - 1] <= arr[left]) { |
| 27 | + while right < arr.len() && arr[left] > arr[right] { |
| 28 | + right += 1; |
| 29 | + } |
| 30 | + left += 1; |
| 31 | + res = res.min(right - left); |
| 32 | + } |
| 33 | + res as i32 |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// Tests. |
| 38 | +fn main() { |
| 39 | + let tests = [ |
| 40 | + (vec![1, 2, 3, 10, 4, 2, 3, 5], 3), |
| 41 | + (vec![5, 4, 3, 2, 1], 4), |
| 42 | + (vec![1, 2, 3], 0), |
| 43 | + ]; |
| 44 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 45 | + let mut success = 0; |
| 46 | + for (i, t) in tests.iter().enumerate() { |
| 47 | + let res = Solution::find_length_of_shortest_subarray(t.0.clone()); |
| 48 | + if res == t.1 { |
| 49 | + success += 1; |
| 50 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 51 | + } else { |
| 52 | + println!( |
| 53 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 54 | + i, t.1, res |
| 55 | + ); |
| 56 | + } |
| 57 | + } |
| 58 | + println!(); |
| 59 | + if success == tests.len() { |
| 60 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 61 | + } else if success == 0 { |
| 62 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 63 | + } else { |
| 64 | + println!( |
| 65 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 66 | + tests.len() - success |
| 67 | + ) |
| 68 | + } |
| 69 | +} |
0 commit comments