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

You are given two positive integers x and y. Your goal is to transform x into y using the minimum number of operations.

In each operation, you can perform exactly one of the following actions on x:

  • Divide by 11: If x is divisible by 11, you can set x = x / 11
  • Divide by 5: If x is divisible by 5, you can set x = x / 5
  • Decrement: Set x = x - 1
  • Increment: Set x = x + 1

Return the minimum number of operations required to make x equal to y.

Example: If x = 26 and y = 1, you could: increment to 27, divide by 3 (not allowed), or decrement to 25, divide by 5 to get 5, decrement to 4, 3, 2, 1. But there might be a shorter path!

Input & Output

example_1.py โ€” Basic Case
$ Input: [26, 1]
โ€บ Output: 5
๐Ÿ’ก Note: 26 โ†’ 25 (decrement) โ†’ 5 (divide by 5) โ†’ 4 (decrement) โ†’ 3 (decrement) โ†’ 2 (decrement) โ†’ 1 (decrement). Total: 5 operations. Alternative paths exist but this is optimal.
example_2.py โ€” Division by 11
$ Input: [54, 2]
โ€บ Output: 4
๐Ÿ’ก Note: 54 โ†’ 55 (increment) โ†’ 5 (divide by 11) โ†’ 4 (decrement) โ†’ 3 (decrement) โ†’ 2 (decrement). Total: 4 operations using the divide by 11 operation.
example_3.py โ€” Simple Case
$ Input: [25, 30]
โ€บ Output: 5
๐Ÿ’ก Note: Since x < y, we can only increment. 25 โ†’ 26 โ†’ 27 โ†’ 28 โ†’ 29 โ†’ 30. Total: 5 operations (simple increments).

Constraints

  • 1 โ‰ค x, y โ‰ค 104
  • x and y are positive integers
  • At most one operation per step

Visualization

Tap to expand
๐ŸŽฎ Number Transformation GameSTARTX=26TARGETY=1252751-1+1รท5 (FAST!)-1,-1,-1,-1๐Ÿ” BFS Strategyโœ“ Explore level by levelโœ“ Mark visited roomsโœ“ Use fast teleporters when possibleโœ“ First path found = shortest path
Understanding the Visualization
1
Start at room X
Begin your journey at the starting number
2
Explore neighbors
Use all available moves: divide (if possible) or increment/decrement
3
Mark visited rooms
Avoid revisiting the same number to prevent infinite loops
4
Find target Y
Return the number of moves when you first reach the target
Key Takeaway
๐ŸŽฏ Key Insight: BFS guarantees the shortest path because it explores all possibilities at distance k before exploring distance k+1. The division operations act as 'express routes' that can dramatically reduce the number of steps needed.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
43.4K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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