cswork / libraryOpen practice workspace

Coding questions · Jerry.Ai

Determine a one-step string transformation

This question evaluates proficiency in string manipulation and algorithmic reasoning, focusing on edit operations, positional changes, and edge-case handling.

Given two lowercase strings source and target, determine whether target can be obtained from source using at most one of the following operations, and output one valid operation if possible.

Allowed operations:

  1. add c: Insert one character c at any position in source.
  2. delete c: Delete one occurrence of character c from source.
  3. replace x y: Replace one occurrence of character x in source with character y.
  4. move c: Remove one occurrence of character c from its current position and insert it at another position in the string.

If source is already equal to target, output no_change. If no single operation can transform source into target, output impossible. If multiple valid operations exist, output any one valid operation.

Examples:

source = "baren", target = "bbren"
output: replace a b
source = "banan", target = "banana"
output: add a
source = "abcde", target = "acdeb"
output: move b

Expected follow-up: design an efficient solution that handles long strings, ideally in linear time.

One-Step String Transformation

Return a deterministic operation describing how to transform source into target using at most one add, delete, replace, or move operation, or return impossible.

Constraints

  • source and target are lowercase strings.
  • Return no_change if the strings are already equal.
  • When several operations could work, this grader prefers add/delete, then replace, then the first left-to-right move.

Hints

  1. Length difference determines add and delete cases.
  2. For equal lengths, check replacement before testing moves.