HardNo. 1896

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

Pattern
Stack
Topics
Stack, Math, String, Dynamic Programming
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

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

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.

Free to download. Check it runs on your machine, then pick a plan.