LeetCode Entry
1979. Find Greatest Common Divisor of Array
GCD of min & max
1979. Find Greatest Common Divisor of Array easy substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1424
Problem TLDR
GCD of min & max
Intuition
Iterate and find the min, max, then the gcd.
Approach
- remember gcd: ab bab means a/b b should not be 0, then the recursive call of b,a%b
- Rust: sort gives the shortest code; also there is a minmax from itertools
- Kotlin: make the entire solution recursive
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
fun findGCD(n: IntArray, a:Int=n.max(), b:Int=n.min()):Int=
if(b==0)a else findGCD(n, b,a%b)
pub fn find_gcd(n: Vec<i32>) -> i32 {
let (mut b, mut a) = n.into_iter().minmax().into_option().unwrap();
while b > 0 { (a, b) = (b, a % b) } a
}
Comments