EasyStringMathRecursion

Greatest Common Divisor of Strings

LeetCode
1 approach, code in all languages

Say a string t divides a string s when s can be built by writing t some whole number of times back to back (for example, "ab" divides "ababab").

Given two strings str1 and str2, return the longest string x that divides both of them. If there is no such non-empty string, return an empty string.

Example 1

Input: str1 = "ABABAB", str2 = "ABAB"

Output: "AB"

"AB" repeated forms both inputs, and no longer common block exists.

Example 2

Input: str1 = "LEET", str2 = "CODE"

Output: ""

The two strings share no repeating block, so the answer is empty.

Constraints

  • 1 ≤ str1.length ≤ 10^3
  • 1 ≤ str2.length ≤ 10^3
  • str1 and str2 consist of uppercase English letters only
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now