Fewest highlighted stretches in an inline line diff
Your task
A code review page shows a changed line twice, the old version above the new one, and highlights the characters that changed. It leaves as many characters unhighlighted as it can. Among the ways to do that, it picks one with the fewest highlighted stretches, because scattered one-letter highlights are hard to read.
Write fewest_highlights(before, after) that returns the number of highlighted stretches in that best choice.
Input and output:
beforeandafter: the old and the new version of the line, each 0 to 300 printable ASCII characters (codes 32 to 126). Characters are compared exactly, soaandAdiffer.- Returns an integer.
Rules:
- A choice pairs some characters of
beforewith equal characters ofafter. Pairs keep their order. If position i ofbeforeis paired with position j ofafter, any later paired position ofbeforeis paired with a position later than j. No character is in 2 pairs. - Every character that is not in a pair is highlighted.
- A stretch is a run of highlighted characters that sit next to each other in the same line, made as long as it can be.
- The page only considers choices with the most pairs. Among those, return the smallest total number of stretches in
beforeandaftertogether.
Examples
fewest_highlights(before: str, after: str) -> intExample 1
Input
fewest_highlights("const color = 'red';", "const colour = 'red';")Output
1Example 2
Input
fewest_highlights("total = price * qty", "total = price * qty + tax")Output
1Example 3
Input
fewest_highlights("getUser(id)", "fetchUserById(id)")Output
4