Ctrl K

Paying to Match Bits

Medium
You are given two binary strings current and wanted of the same length n, plus an integer far_cost. Turn current into wanted by applying these operations to current as many times as you like: - pick any two distinct indices i and j and flip both current[i] and current[j], at a cost of far_cost; - pick an index i < n - 1 and flip the neighbouring characters current[i] and current[i + 1], at a cost of 1. Flipping a character means changing 0 to 1 or 1 to 0. Return the minimum total cost that makes current equal to wanted, or -1 if that cannot be done.
Example 1
current='0110', wanted='1001', far_cost=3 → 2

All four positions differ. Two neighbour flips, on positions 0 and 1 and then 2 and 3, cost 1 + 1 = 2.

Example 2
current='100001', wanted='000000', far_cost=2 → 2

Positions 0 and 5 differ. A chain of neighbour flips from 0 to 5 would cost 5, while a single far flip costs only 2.

Example 3
current='111', wanted='110', far_cost=1 → -1

Only one position differs, and every operation flips exactly two bits, so an odd number of mismatches can never be fixed.

Constraints
  • 1 ≤ n ≤ 500, len(current) == len(wanted) == n
  • 1 ≤ far_cost ≤ 500
  • Both strings contain only the characters 0 and 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Mirror Fragment MediumAll Balanced Bracket Strings MediumFewest Letter Edits MediumWays to Read a Digit Code MediumWeaving Two Strings Medium
loading Python…
Input
current='0110', wanted='1001', far_cost=3
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 116 tests on the server, hidden ones included.