LeetCode #3800 — MEDIUM

Minimum Cost to Make Two Binary Strings Equal

Move from brute-force thinking to an efficient approach using greedy strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given two binary strings s and t, both of length n, and three positive integers flipCost, swapCost, and crossCost.

You are allowed to apply the following operations any number of times (in any order) to the strings s and t:

  • Choose any index i and flip s[i] or t[i] (change '0' to '1' or '1' to '0'). The cost of this operation is flipCost.
  • Choose two distinct indices i and j, and swap either s[i] and s[j] or t[i] and t[j]. The cost of this operation is swapCost.
  • Choose an index i and swap s[i] with t[i]. The cost of this operation is crossCost.

Return an integer denoting the minimum total cost needed to make the strings s and t equal.

Example 1:

Input: s = "01000", t = "10111", flipCost = 10, swapCost = 2, crossCost = 2

Output: 16

Explanation:

We can perform the following operations:

  • Swap s[0] and s[1] (swapCost = 2). After this operation, s = "10000" and t = "10111".
  • Cross swap s[2] and t[2] (crossCost = 2). After this operation, s = "10100" and t = "10011".
  • Swap s[2] and s[3] (swapCost = 2). After this operation, s = "10010" and t = "10011".
  • Flip s[4] (flipCost = 10). After this operation, s = t = "10011".

The total cost is 2 + 2 + 2 + 10 = 16.

Example 2:

Input: s = "001", t = "110", flipCost = 2, swapCost = 100, crossCost = 100

Output: 6

Explanation:

Flipping all the bits of s makes the strings equal, and the total cost is 3 * flipCost = 3 * 2 = 6.

Example 3:

Input: s = "1010", t = "1010", flipCost = 5, swapCost = 5, crossCost = 5

Output: 0

Explanation:

The strings are already equal, so no operations are required.

Constraints:

  • n == s.length == t.length
  • 1 <= n <= 105​​​​​​​
  • 1 <= flipCost, swapCost, crossCost <= 109
  • s and t consist only of the characters '0' and '1'.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given two binary strings s and t, both of length n, and three positive integers flipCost, swapCost, and crossCost. You are allowed to apply the following operations any number of times (in any order) to the strings s and t: Choose any index i and flip s[i] or t[i] (change '0' to '1' or '1' to '0'). The cost of this operation is flipCost. Choose two distinct indices i and j, and swap either s[i] and s[j] or t[i] and t[j]. The cost of this operation is swapCost. Choose an index i and swap s[i] with t[i]. The cost of this operation is crossCost. Return an integer denoting the minimum total cost needed to make the strings s and t equal.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Greedy

Example 1

"01000"
"10111"
10
2
2

Example 2

"001"
"110"
2
100
100

Example 3

"1010"
"1010"
5
5
5
Step 02

Core Insight

What unlocks the optimal approach

  • Count mismatches: <code>a</code> = #(s = '0' , t = '1' ) <code>, b</code> = #(s = '1' , t = '0').
  • Pair opposite mismatches: <code>p = min( a , b)</code>. Fix each pair with cost <code>min(swapCost , 2 * flipCost)</code>.
  • Update counts: <code>a = a - p</code>, <code>b = b - p</code>. Let <code>r = abs( a - b)</code>.
  • Fix remaining mismatches in pairs: each pair costs <code>min(crossCost + swapCost , 2 * flipCost)</code>.
  • If one mismatch remains (<code>r % 2 == 1</code>), pay <code>flipCost</code>.
  • Sum all costs for the answer.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3800: Minimum Cost to Make Two Binary Strings Equal
class Solution {
    public long minimumCost(String s, String t, int flipCost, int swapCost, int crossCost) {
        long[] diff = new long[2];
        int n = s.length();
        for (int i = 0; i < n; i++) {
            char c1 = s.charAt(i), c2 = t.charAt(i);
            if (c1 != c2) {
                diff[c1 - '0']++;
            }
        }

        long ans = (diff[0] + diff[1]) * flipCost;

        long mx = Math.max(diff[0], diff[1]);
        long mn = Math.min(diff[0], diff[1]);
        ans = Math.min(ans, mn * swapCost + (mx - mn) * flipCost);

        long avg = (mx + mn) / 2;
        ans = Math.min(
            ans, (avg - mn) * crossCost + avg * swapCost + (mx + mn - avg * 2) * flipCost);
        return ans;
    }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n log n)
Space
O(1)

Approach Breakdown

EXHAUSTIVE
O(2ⁿ) time
O(n) space

Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.

GREEDY
O(n log n) time
O(1) space

Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.

Shortcut: Sort + single pass → O(n log n). If no sort needed → O(n). The hard part is proving it works.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.