All problems
0400EasyMathStringEuclidean AlgorithmGreatest Common Divisor

Longest Shared Ribbon Tile

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1071Greatest Common Divisor of Strings

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A weaving shop records a ribbon as a string of uppercase letters, one letter per stitched panel.

A pattern x tiles a pattern y when laying out some whole number of copies of x back to back reproduces y letter for letter. So RG tiles RGRG and RGRGRG, and every pattern tiles itself.

You are given ribbons ribbonA and ribbonB. Return the longest pattern that tiles both of them. If no pattern tiles both, return the empty string. Whenever such a pattern exists there is exactly one longest one, so the answer is never ambiguous.

Examples

Example 1

Input
ribbonA = "RGBRGB", ribbonB = "RGBRGBRGB"
Output
"RGB"

Two copies of `RGB` give `ribbonA` and three copies give `ribbonB`. Laying `RGBRGB` or `RGBRGBRGB` end to end does not reproduce both ribbons.

Example 2

Input
ribbonA = "PQPQPQPQ", ribbonB = "PQPQ"
Output
"PQPQ"

Two copies of `PQPQ` give `ribbonA`, and one copy is `ribbonB` itself.

Example 3

Input
ribbonA = "MNM", ribbonB = "MN"
Output
""

Laying `M`, `N`, `MN` or `MNM` end to end never reproduces both ribbons, so there is no shared tile and the answer is the empty string.

Example 4

Input
ribbonA = "TTTT", ribbonB = "TT"
Output
"TT"

Two copies of `TT` give `ribbonA` and one copy is `ribbonB`.

Example 5

Input
ribbonA = "XYXY", ribbonB = "XYX"
Output
""

Laying `X`, `Y`, `XY`, `XYX` or `XYXY` end to end never reproduces both ribbons, so the answer is the empty string.

Constraints

  • 1 <= ribbonA.length, ribbonB.length <= 1000
  • ribbonA and ribbonB consist of uppercase English letters only.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def gcd_of_strings(ribbonA: str, ribbonB: str) -> str:
Java
public String gcdOfStrings(String ribbonA, String ribbonB)
September 7
Apply