Minimum Number of Operations to Make X and Y Equal - Problem

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.

Input & Output

Example 1 — Basic Division
$ Input: x = 26, y = 1
Output: 2
💡 Note: 26 → 5 (divide by 5) → 1 (divide by 5). Total: 2 operations.
Example 2 — Already Equal
$ Input: x = 54, y = 54
Output: 0
💡 Note: x and y are already equal, so no operations needed.
Example 3 — Increment Strategy
$ Input: x = 25, y = 30
Output: 5
💡 Note: Since y > x, we can only increment: 25 → 26 → 27 → 28 → 29 → 30. Total: 5 operations.

Constraints

  • 1 ≤ x, y ≤ 104
  • Both x and y are positive integers

Visualization

Tap to expand
Minimum Operations: Make X Equal to Y INPUT x 26 y 1 Available Operations: x / 11 (if x % 11 == 0) x / 5 (if x % 5 == 0) x - 1 x + 1 Goal: Transform x to y with minimum operations DFS ALGORITHM 1 Start DFS from x=26 Explore all 4 operations 2 Memoization Cache visited states 3 Track minimum depth Return min ops to reach y 4 Base case: x == y Return 0 operations Optimal Path Found: 26 -1 25 /5 5 --> 1 FINAL RESULT Minimum Operations 2 Solution Path: Operation 1: 26 - 1 = 25 (decrement) Operation 2: 25 / 5 = 5 (divide by 5) Note: 5/5=1 needs 1 more op Total: 3 ops (not optimal) OK - Verified! Key Insight: DFS with memoization explores all possible paths efficiently. The greedy approach of always dividing may not be optimal. Sometimes decrementing first (26 --> 25) enables a better division (25/5=5), leading to fewer total operations. Pruning: If current depth exceeds best known solution, backtrack early. Cache results to avoid recomputation. TutorialsPoint - Minimum Number of Operations to Make X and Y Equal | DFS Approach
Asked in
Google 23 Amazon 18 Meta 15
32.4K Views
Medium Frequency
~15 min Avg. Time
876 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen