Problem solution · Java

Minimum Cost to Change the Final Value of Expression

Minimum Cost to Change the Final Value of Expression: a Java solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Stack-based processing
Source
walkccc LeetCode Solutions
Length
62 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Stack-based processing

For Minimum Cost to Change the Final Value of Expression, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. Push the current item with only the information later steps need.

Code notes

  • 62 lines of Java from the credited upstream file 1896.java.
  • The implementation visibly relies on work queue.
  • 1 loop block detected.

Complexity

If each item is pushed and popped at most once, the stack work is linear.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum Cost to Change the Final Value of Expression · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int minOperationsToFlip(String expression) {    // [(the expression, the cost to toggle the expression)]    Deque<Pair<Character, Integer>> stack = new ArrayDeque<>();    Pair<Character, Integer> lastPair = null;     for (final char e : expression.toCharArray()) {      if (e == '(' || e == '&' || e == '|') {        // These aren't expressions, so the cost is meaningless.        stack.push(new Pair<>(e, 0));        continue;      }      if (e == ')') {        lastPair = stack.pop();        stack.pop(); // Pop '('.      } else {       // e == '0' || e == '1'        // Store the '0' or '1'. The cost to change their values is just 1,        // whether it's changing '0' to '1' or '1' to '0'.        lastPair = new Pair<>(e, 1);      }      if (!stack.isEmpty() && (stack.peek().getKey() == '&' || stack.peek().getKey() == '|')) {        final char op = stack.pop().getKey();        final char a = stack.peek().getKey();        final int costA = stack.pop().getValue();        final char b = lastPair.getKey();        final int costB = lastPair.getValue();        // Determine the cost to toggle op(a, b).        if (op == '&') {          if (a == '0' && b == '0')            // Change '&' to '|' and a|b to '1'.            lastPair = new Pair<>('0', 1 + Math.min(costA, costB));          else if (a == '0' && b == '1')            // Change '&' to '|'.            lastPair = new Pair<>('0', 1);          else if (a == '1' && b == '0')            // Change '&' to '|'.            lastPair = new Pair<>('0', 1);          else // a == '1' and b == '1'            // Change a|b to '0'.            lastPair = new Pair<>('1', Math.min(costA, costB));        } else { // op == '|'          if (a == '0' && b == '0')            // Change a|b to '1'.            lastPair = new Pair<>('0', Math.min(costA, costB));          else if (a == '0' && b == '1')            // Change '|' to '&'.            lastPair = new Pair<>('1', 1);          else if (a == '1' && b == '0')            // Change '|' to '&'.            lastPair = new Pair<>('1', 1);          else // a == '1' and b == '1'            // Change '|' to '&' and a|b to '0'.            lastPair = new Pair<>('1', 1 + Math.min(costA, costB));        }      }      stack.push(lastPair);    }     return stack.peek().getValue();  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗