PracticeStrings
Level Code Swap
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:
0Explanation: 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:
2Explanation: The codes produce two mismatches in each orientation, and the executed output is 2.
Example 3
Input:
current = "100"target = "010"Output:
1Explanation: The codes produce one mismatch in each orientation, and the executed output is 1.
Constraints
1 <= len(current) <= 100current: alphabet binarylen(current) <= len(target) <= len(current)target: alphabet binarycurrent and target contain binary characters only.- Types:
currentis str,targetis str; result is int
Function signature
def minimum_code_swaps(current: str, target: str) -> int
currentstr- The binary code currently displayed by the level.
targetstr- 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.
Code
Saved