LeetCode Entry
154. Find Minimum in Rotated Sorted Array II
Binary search in shifted array with duplicates
154. Find Minimum in Rotated Sorted Array II hard substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1361
Problem TLDR
Binary search in shifted array with duplicates
Intuition
// 3 4 5 6 7 1 2 3
// 3 1
// false false
// 3 1 3
// false true false
- compare all elements with last
- slice duplicates out in O(N)
Approach
- use built-in functions, Rust: partition_point, position, slices [..], Kotlin: binarySearch {..}, indexOfFirst
- x.inv() is -1-x
Complexity
-
Time complexity: \(O(n|logn)\)
-
Space complexity: \(O(1)\)
Code
fun findMin(n: IntArray) = n[n.asList().binarySearch(
max(0, n.indexOfFirst { it != n.last()})) {
if (it <= n.last()) 1 else -1 }.inv()]
pub fn find_min(n: Vec<i32>) -> i32 {
let n = &n[n.iter().position(|&x| x != n[n.len()-1]).unwrap_or(0)..];
n[n.partition_point(|&x|x > n[n.len()-1])]
}