PracticeStrings

Level Code Swap

EasyStringstraversalcountingcomparison Time not estimated Not started

Context

In a puzzle game, a level displays a binary code and has a target code. A move exchanges the symbols at any two positions in the displayed code. Help the game determine the fewest moves needed to reach the target code, or recognize that it cannot be reached.

Problem

Given the current binary code and the target binary code, determine the minimum number of moves required to transform the current code into the target. In one move, you may exchange the symbols at any two positions of the current code. Positions may be chosen in any order, and each position can contain only 0 or 1. Return -1 if no sequence of exchanges can produce the target code.

Examples

Example 1
Input: current = "1010"target = "1010"
Output: 0
Explanation: The two codes are identical, so both mismatch counters remain 0 and the executed output is 0.
Example 2
Input: current = "1100"target = "0011"
Output: 2
Explanation: The codes produce two mismatches in each orientation, and the executed output is 2.
Example 3
Input: current = "100"target = "010"
Output: 1
Explanation: The codes produce one mismatch in each orientation, and the executed output is 1.

Constraints

  • 1 <= len(current) <= 100
  • current: alphabet binary
  • len(current) <= len(target) <= len(current)
  • target: alphabet binary
  • current and target contain binary characters only.
  • Types: current is str, target is str; result is int

Function signature

def minimum_code_swaps(current: str, target: str) -> int
current str
The binary code currently displayed by the level.
target str
The binary code the level requires.
returns int
The minimum number of arbitrary-position exchanges needed to make current equal target, or -1 when the transformation is impossible.

Adapted from MBPP problem task_838 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Approved · c020r1-abs_238_v214 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1