LeetCode Entry
2784. Check if Array is Good
Is combination 1..n,n
2784. Check if Array is Good easy substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1359
Problem TLDR
Is combination 1..n,n
Intuition
- no-brain solution: check every number (1..n) is in array, and count(n)==2
- shortest solution: (1..n)+n==sorted()
- optimal solution: use array indices as visited storage
Approach
- n[0] can be used as extra storage for n[len-1] special case
Complexity
-
Time complexity: \(O(nlogn|n)\)
-
Space complexity: \(O(n|1)\)
Code
fun isGood(n: IntArray) =
(1..<n.size) + (n.size-1) == n.sorted()
pub fn is_good(mut n: Vec<i32>) -> bool {
(0..n.len()).all(|i| { let x = n[i].abs() as usize;
!(x>=n.len()||n[x]<0&&(x<n.len()-1||n[0]<0)) && {
if n[x] < 0 { n[0] *= -1 } else { n[x] *= -1 };1>0}
}) && n[0]<0
}