Least Operators to Express Number — LeetCode 964 Python Solution

HardMemoizationMathDynamic Programming
Problem
#964
Reading time
3 min

The 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.

Example

Input
x = 3, target = 19
Output
5
Explanation
3 * 3 + 3 * 3 + 3 / 3.

Python solution

Python
class Solution:
    def leastOpsExpressTarget(self, x: int, target: int) -> int:
        @cache
        def dfs(v: int) -> int:
            if x >= v:
                return min(v * 2 - 1, 2 * (x - v))
            k = 2
            while x**k < v:
                k += 1
            if x**k - v < v:
                return min(k + dfs(x**k - v), k - 1 + dfs(v - x ** (k - 1)))
            return k - 1 + dfs(v - x ** (k - 1))

        return dfs(target)

Complexity

MeasureComplexity
TimeO(\log_{x}{target})
SpaceO(\log_{x}{target}) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 964. Least Operators to Express Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming and Memoization.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 964. Least Operators to Express Number?
LeetCode 964. Least Operators to Express Number is rated Hard on LeetCode.
What is the time complexity of LeetCode 964. Least Operators to Express Number?
The Python solution on this page runs in O(\log_{x}{target}).
What is the space complexity of LeetCode 964. Least Operators to Express Number?
The Python solution on this page uses O(\log_{x}{target}) auxiliary space.
What topics does LeetCode 964. Least Operators to Express Number cover?
LeetCode 964. Least Operators to Express Number is tagged Memoization, Math and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview