Least Operators to Express Number - Problem

Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).

For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.

When writing such an expression, we adhere to the following conventions:

  • The division operator (/) returns rational numbers.
  • There are no parentheses placed anywhere.
  • We use the usual order of operations: multiplication and division happen before addition and subtraction.
  • It is not allowed to use the unary negation operator (-). For example, x - x is a valid expression as it only uses subtraction, but -x + x is not because it uses negation.

We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.

Input & Output

Example 1 — Small Target
$ Input: x = 3, target = 19
Output: 5
💡 Note: We can write 19 as 3*3*3 - 3 - 3 - 3 + 3/3, which uses 5 operators: 3 multiplications + 2 subtractions = 5 total operators
Example 2 — Simple Case
$ Input: x = 5, target = 501
Output: 8
💡 Note: 501 can be expressed as 5*5*5*4 + 1, where 4 = 5-1 and 1 = 5/5, requiring 8 operators total
Example 3 — Edge Case
$ Input: x = 100, target = 100
Output: 1
💡 Note: Target equals x, so we just need 1 occurrence of x with 0 operators between

Constraints

  • 2 ≤ x ≤ 100
  • 1 ≤ target ≤ 2 × 108

Visualization

Tap to expand
Least Operators to Express Number INPUT x = 3 target=19 Goal: Build 19 using 3s Available operations: + - * / Standard order of operations Powers of 3: 3^0 = 1 3^1 = 3 3^2 = 9 3^3 = 27 Cost to make 3^k: k ops (k-1 multiplies) ALGORITHM STEPS 1 Express as powers 19 = 27 - 9 + 1 2 Count operators 27: 3*3*3 (2 ops) 3 DP/BFS approach Min ops to reach target 4 Optimize path Choose add or subtract Calculation: 3*3*3 - 3*3 + 3/3 = 19 27 - 9 + 1 = 19 Operators used: * * - * + / Total: 5 operators FINAL RESULT Optimal Expression: 3*3*3 - 3*3 + 3/3 = 27 - 9 + 1 = 19 Output: 5 Operator Breakdown: 3 * 3 = 9 (1 op) 9 * 3 = 27 (1 op) 3 * 3 = 9 (1 op) 3 / 3 = 1 (1 op) + 1 combine op = 5 total OK Key Insight: Express target as sum/difference of powers of x. Each power x^k requires (k-1) multiply operators. Special case: x^0 = 1 = x/x requires 1 division. Use BFS or DP to find minimum operators by exploring whether to overshoot or undershoot at each power level, choosing the cheaper path. TutorialsPoint - Least Operators to Express Number | Optimized Mathematical Approach
Asked in
Google 15 Facebook 12 Microsoft 8
28.0K Views
Medium Frequency
~35 min Avg. Time
845 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