#964

Least Operators to Express Number

Hard
MathDynamic ProgrammingMemoizationDynamic ProgrammingBreadth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to build up the minimum number of operations needed to reach each possible value up to the target. By storing previously computed results, we avoid redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a dictionary to store the minimum operations needed to reach each value.
  2. 2Step 2: Initialize the dictionary with the starting value x requiring 0 operations.
  3. 3Step 3: For each value in the dictionary, apply each operator, updating the dictionary with the minimum operations needed to reach new values.
solution.py13 lines
1def leastOperators(x, target):
2    dp = {x: 0}
3    for value in range(1, target + 1):
4        if value in dp:
5            ops = dp[value]
6            for op in ['+', '-', '*', '/']:
7                if op == '+': new_value = value + x
8                elif op == '-': new_value = value - x
9                elif op == '*': new_value = value * x
10                elif op == '/': new_value = value / x
11                if new_value <= target and (new_value not in dp or dp[new_value] > ops + 1):
12                    dp[new_value] = ops + 1
13    return dp.get(target, -1)

Complexity note: The complexity is linear because we only iterate through values up to the target once, storing results in a dictionary to avoid redundant calculations.

  • 1Understanding operator precedence is crucial for forming valid expressions.
  • 2Dynamic programming can significantly reduce the number of operations by reusing previously computed results.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.