Minimum Cost to Change the Final Value of Expression — LeetCode 1896 Python Solution

HardStackMathStringDynamic Programming
Problem
#1896
Pattern
Stack
Reading time
2 min

The problem

You are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'. For example, "()1|1" and "(1)&()" are not valid while "1", "(((1))|(0))", and "1|(0&(1))" are valid expressions.

Example

Input
expression = "1&(0|1)"
Output
1
Explanation
We can turn "1&(0|1)" into "1&(0&1)" by changing the '|' to a '&' using 1 operation.

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1896. Minimum Cost to Change the Final Value of Expression is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1896. Minimum Cost to Change the Final Value of Expression?
LeetCode 1896. Minimum Cost to Change the Final Value of Expression is rated Hard on LeetCode.
What topics does LeetCode 1896. Minimum Cost to Change the Final Value of Expression cover?
LeetCode 1896. Minimum Cost to Change the Final Value of Expression is tagged Stack, Math, String 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