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.
Return the minimum cost to change the final value of the expression.
For example, if expression = "1|1|(0&0)&1", its value is 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new expression evaluates to 0.
The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows:
Turn a '1' into a '0'.
Turn a '0' into a '1'.
Turn a '&' into a '|'.
Turn a '|' into a '&'.
Note:'&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.
Input & Output
Example 1 — Basic Expression
$Input:expression = "1|1|(0&0)&1"
›Output:1
💡 Note:Original evaluates to 1 (since 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1). We can change the first '1' to '0' to get 0|1|(0&0)&1 = 0, with cost 1.
Example 2 — Simple AND
$Input:expression = "(1)&(0)"
›Output:1
💡 Note:Original evaluates to 0 (since 1&0 = 0). We can change '0' to '1' to get 1&1 = 1, with cost 1.
Example 3 — Single Operand
$Input:expression = "0"
›Output:1
💡 Note:Original evaluates to 0. We need to change it to 1, so we flip the '0' to '1' with cost 1.
Constraints
1 ≤ expression.length ≤ 105
expression consists of '1', '0', '&', '|', '(', and ')'
Minimum Cost to Change the Final Value of Expression — Solution
The key insight is to use dynamic programming on the expression tree, tracking the minimum cost to make each subexpression evaluate to both 0 and 1. The optimal approach uses memoization with recursive parsing to achieve O(n²) time complexity and O(n) space complexity.
Common Approaches
✓
Brute Force - Try All Combinations
⏱️ Time: O(2^n)
Space: O(n)
Try changing every possible combination of operands and operators in the expression, evaluate each combination to see if it flips the result, and return the minimum cost among valid combinations.
Memoization - Parse Tree with DP
⏱️ Time: O(n²)
Space: O(n)
Parse the expression into a binary tree structure, then use recursive dynamic programming with memoization to calculate minimum cost to make each subtree evaluate to 0 or 1.
Stack-Based Expression Parsing
⏱️ Time: O(n)
Space: O(n)
Parse the expression using a stack-based approach, similar to expression evaluation. For each operator encountered, calculate the minimum cost to achieve both possible outputs (0 and 1) by considering operand modifications and operator changes.
Brute Force - Try All Combinations — Algorithm Steps
Parse the expression to identify all operands and operators
Generate all possible combinations of changes
For each combination, evaluate the modified expression
Keep track of minimum cost that flips the result
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Original
Evaluate original expression
2
Generate
Try all combinations of changes
3
Find Min
Return minimum cost that flips result
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
struct ParseResult {
int value;
int cost_to_0;
int cost_to_1;
int pos;
};
struct ParseResult parse_expression(const char* s, int pos);
struct ParseResult parse_term(const char* s, int pos);
int min_int(int a, int b) {
return a < b ? a : b;
}
int min_4(int a, int b, int c, int d) {
return min_int(min_int(a, b), min_int(c, d));
}
struct ParseResult parse_expression(const char* s, int pos) {
struct ParseResult result1 = parse_term(s, pos);
int val1 = result1.value;
int cost1_0 = result1.cost_to_0;
int cost1_1 = result1.cost_to_1;
pos = result1.pos;
while (pos < strlen(s) && (s[pos] == '&' || s[pos] == '|')) {
char op = s[pos];
pos += 1;
struct ParseResult result2 = parse_term(s, pos);
int val2 = result2.value;
int cost2_0 = result2.cost_to_0;
int cost2_1 = result2.cost_to_1;
pos = result2.pos;
int new_val, new_cost_0, new_cost_1;
if (op == '&') {
new_val = val1 & val2;
if (new_val == 0) {
new_cost_0 = min_4(0, 1, cost1_0, cost2_0);
new_cost_1 = min_int(cost1_1 + cost2_1, 1 + min_int(cost1_1, cost2_1));
} else {
new_cost_1 = 0;
new_cost_0 = min_int(cost1_0, cost2_0);
}
} else {
new_val = val1 | val2;
if (new_val == 1) {
new_cost_1 = min_4(0, 1, cost1_1, cost2_1);
new_cost_0 = min_int(cost1_0 + cost2_0, 1 + min_int(cost1_0, cost2_0));
} else {
new_cost_0 = 0;
new_cost_1 = min_int(cost1_1, cost2_1);
}
}
val1 = new_val;
cost1_0 = new_cost_0;
cost1_1 = new_cost_1;
}
struct ParseResult result = {val1, cost1_0, cost1_1, pos};
return result;
}
struct ParseResult parse_term(const char* s, int pos) {
if (s[pos] == '(') {
pos += 1;
struct ParseResult result = parse_expression(s, pos);
pos = result.pos + 1;
struct ParseResult final_result = {result.value, result.cost_to_0, result.cost_to_1, pos};
return final_result;
} else {
int digit = s[pos] - '0';
struct ParseResult result;
if (digit == 0) {
result.value = 0;
result.cost_to_0 = 0;
result.cost_to_1 = 1;
result.pos = pos + 1;
} else {
result.value = 1;
result.cost_to_0 = 1;
result.cost_to_1 = 0;
result.pos = pos + 1;
}
return result;
}
}
int solution(char* expression) {
struct ParseResult result = parse_expression(expression, 0);
int original_val = result.value;
int cost_to_0 = result.cost_to_0;
int cost_to_1 = result.cost_to_1;
if (original_val == 0) {
return cost_to_1;
} else {
return cost_to_0;
}
}
int main() {
char expression[1000];
fgets(expression, sizeof(expression), stdin);
expression[strcspn(expression, "\n")] = 0;
// Remove quotes if present
int len = strlen(expression);
if (len > 1 && expression[0] == '"' && expression[len-1] == '"') {
memmove(expression, expression + 1, len - 2);
expression[len - 2] = '\0';
}
int result = solution(expression);
printf("%d\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(2^n)
For n operands and operators, we try all 2^n possible combinations
n
2n
✓ Linear Growth
Space Complexity
O(n)
Stack space for expression evaluation and recursion
n
2n
⚡ Linearithmic Space
28.5K Views
MediumFrequency
~35 minAvg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.