PracticeStrings

Level Code Swap Count

EasyStringstraversalcomparisoncounting Time not estimated Not started

Context

In a puzzle game, a player has a current level code and a required level code. One move may exchange the symbols at any two positions in the current code. Determine the fewest moves needed to reach the required code, or report that it cannot be reached.

Problem

Write a function that compares the current level code with the required level code. A move swaps the symbols at any two positions, with no restriction on their distance. Return the minimum number of moves needed to transform the current code into the required code. If transformation is impossible, return -1. The codes may be empty, and both inputs always have the same length. The result must depend only on the number of positions whose symbols differ, not on a particular sequence of swaps.

Examples

Example 1
Input: current_code = "10101"required_code = "10101"
Output: 0
Explanation: The identical codes produce mismatch_count 0 and the executed result 0.
Example 2
Input: current_code = "1100"required_code = "0011"
Output: 2
Explanation: The codes produce mismatch_count 4, so the executed result is 2.
Example 3
Input: current_code = "000"required_code = "001"
Output: -1
Explanation: The codes produce mismatch_count 1, so the executed result is -1.

Constraints

  • 0 <= len(current_code) <= 100000
  • current_code: alphabet binary
  • len(current_code) <= len(required_code) <= len(current_code)
  • required_code: alphabet binary
  • current_code and required_code contain binary characters only.
  • Types: current_code is str, required_code is str; result is int

Function signature

def minimum_code_swaps(current_code: str, required_code: str) -> int
current_code str
The player's current binary level code.
required_code str
The binary level code needed to unlock the next level.
returns int
The minimum number of arbitrary swaps, or -1 when no sequence of swaps can produce the required code.

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

Notes

  • Swaps may use any two positions, including positions far apart.
  • The infeasible result is -1.
Approved · c017-abs_459_v111 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1