#1538
Medium Algorithms Guess the majority in a hidden array
Array Math Interactive
68.8% acceptance
Mar 31, 2026
147
122
// This is the ArrayReader's API interface.
// You should not implement it, or speculate about its implementation
struct ArrayReader;
impl ArrayReader {
// Compares 4 different elements in the array
// return 4 if the values of the 4 elements are the same (0 or 1).
// return 2 if three elements have a value equal to 0 and one element has value equal to 1 or vice versa.
// return 0 : if two element have a value equal to 0 and two elements have a value equal to 1.
pub fn query(a: i32, b: i32, c: i32, d: i32) -> i32 {}
// Returns the length of the array
pub fn length() -> i32 {}
};
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn get_majority(reader: &ArrayReader) -> i32 {
let n = reader.length();
let base = reader.query(0, 1, 2, 3);
let mut same_count = 1;
let mut diff_count = 0;
let mut diff_index = -1;
let same_as_zero_for_four = reader.query(1, 2, 3, 4) == base;
if same_as_zero_for_four {
same_count += 1;
} else {
diff_count += 1;
diff_index = 4;
}
for i in 5..n {
if reader.query(1, 2, 3, i) == base {
same_count += 1;
} else {
diff_count += 1;
diff_index = i;
}
}
let same_as_four_for_one = reader.query(0, 2, 3, 4) == base;
if same_as_four_for_one == same_as_zero_for_four {
same_count += 1;
} else {
diff_count += 1;
diff_index = 1;
}
let same_as_four_for_two = reader.query(0, 1, 3, 4) == base;
if same_as_four_for_two == same_as_zero_for_four {
same_count += 1;
} else {
diff_count += 1;
diff_index = 2;
}
let same_as_four_for_three = reader.query(0, 1, 2, 4) == base;
if same_as_four_for_three == same_as_zero_for_four {
same_count += 1;
} else {
diff_count += 1;
diff_index = 3;
}
if same_count == diff_count {
-1
} else if same_count > diff_count {
0
} else {
diff_index
}
}
}