Longest Repeated Block Shared by Two Strings

Quick Overview

Longest Repeated Block Shared by Two Strings. A nonempty string x divides a string when repeating x one or more times produces that entire string.

Longest Repeated Block Shared by Two Strings

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem A nonempty string x divides a string when repeating x one or more times produces that entire string. Return the longest x dividing both str1 and str2, or the empty string if no such block exists. ```cpp class Solution { public: string gcdOfStrings(string str1, string str2); }; ``` ### Examples **Example 1:** ```text Input: str1 = "XYXYXYXY", str2 = "XYXYXY" Output: "XY" Explanation: Repeating XY four and three times yields the two strings; their lengths have greatest common divisor2. ``` **Example 2:** ```text Input: str1 = "ABAB", str2 = "ABAC" Output: "" Explanation: The final C prevents a common repeated block. ``` ### Constraints - Each input length lies between 1 and 1000, inclusive. - All letters are uppercase English letters. ### Contract considerations The result is a prefix block, and the full strings must consist entirely of its repetitions. ```hint Read the boundary condition What should be returned when a proposed common block fails to reproduce a character of either whole input? ``` ### Boundary reminders The result is a prefix block, and the full strings must consist entirely of its repetitions.

Overview: Longest Repeated Block Shared by Two Strings. A nonempty string x divides a string when repeating x one or more times produces that entire string.

Google logo
Google
Source window: 0–3 months · as of Oct 21, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

A nonempty string x divides a string when repeating x one or more times produces that entire string. Return the longest x dividing both str1 and str2, or the empty string if no such block exists.

class Solution {
public:
    string gcdOfStrings(string str1, string str2);
};

Examples

Example 1:

Input: str1 = "XYXYXYXY", str2 = "XYXYXY"
Output: "XY"
Explanation: Repeating XY four and three times yields the two strings; their lengths have greatest common divisor2.

Example 2:

Input: str1 = "ABAB", str2 = "ABAC"
Output: ""
Explanation: The final C prevents a common repeated block.

Constraints

  • Each input length lies between 1 and 1000, inclusive.
  • All letters are uppercase English letters.

Contract considerations

The result is a prefix block, and the full strings must consist entirely of its repetitions.

Boundary reminders

The result is a prefix block, and the full strings must consist entirely of its repetitions.