FastPrepMinimum Rotations for the Longest Common Prefix

Minimum Rotations for the Longest Common Prefix

Wells Fargo logoWells Fargo● MediumFULLTIMEOA
Learn

Problem statement

You are given two nonempty strings fixed and rotating. The first string never changes.

In one rotation of rotating, move its first character to the end or move its last character to the front. You may perform either operation any number of times.

First maximize the length of the common prefix between fixed and the rotated string. Among all rotations that achieve this maximum length, return the minimum number of rotations. If the maximum common-prefix length is 0, return -1.

Function

minimumRotationsForLongestPrefix(fixed: String, rotating: String) → int

Examples

Example 1

fixed = "fm47abcde"rotating = "47ghijfm"return = 2

Move m and then f from the end to the front. The rotated string starts with fm47, the longest possible common prefix.

Example 2

fixed = "abcde"rotating = "cabfg"return = 1

Move c from the front to the end. The strings then share prefix ab.

Example 3

fixed = "abc"rotating = "xyz"return = -1

No rotation starts with a, so no nonempty common prefix exists.

Example 4

fixed = "hello"rotating = "hello"return = 0

The unrotated strings already have the longest possible prefix.

Constraints

  • 1 <= fixed.length, rotating.length <= 2 * 10^5.
  • Both strings contain visible ASCII characters.

More Wells Fargo problems

See Wells Fargo hiring insights
public int minimumRotationsForLongestPrefix(String fixed, String rotating) {
  // write your code here
}
fixed"fm47abcde"
rotating"47ghijfm"
expected2
Checking account…