#2998
Medium Algorithms Minimum number of operations to make x and y equal
Dynamic Programming Breadth-First Search Memoization
48.4% acceptance
Feb 25, 2026
286
23
You are given two positive integers x and y.
In one operation, you can do one of the four following operations:
Divide x by 11 if x is a multiple of 11.
Divide x by 5 if x is a multiple of 5.
Decrement x by 1.
Increment x by 1.
Return the minimum number of operations required to make x and y equal.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn minimum_operations_to_make_equal(x: i32, y: i32) -> i32 {
use std::collections::VecDeque;
if x == y { return 0; }
let max_val = 10_0010usize;
let mut dist = vec![i32::MAX; max_val + 1];
let mut queue = VecDeque::new();
dist[x as usize] = 0;
queue.push_back(x as usize);
while let Some(v) = queue.pop_front() {
let d = dist[v];
if v == y as usize { return d; }
let mut nbrs = Vec::with_capacity(4);
if v > 0 { nbrs.push(v - 1); }
if v + 1 <= max_val { nbrs.push(v + 1); }
if v % 5 == 0 && v / 5 > 0 { nbrs.push(v / 5); }
if v % 11 == 0 && v / 11 > 0 { nbrs.push(v / 11); }
for nv in nbrs {
if dist[nv] == i32::MAX {
dist[nv] = d + 1;
queue.push_back(nv);
}
}
}
dist[y as usize]
}
}