logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

1071. Greatest Common Divisor of Strings

1 min read
On this pageIntuition
IntuitionApproachComplexityCode

Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

Info

String t divides s if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times)


# Intuition

# Approach

# Complexity

Space ComplexityTime Complexity
O()\text{O}()O()O()\text{O}()O()

# Code

# Alternative

  • Select the smaller string
  • Iterate over all the sub-string possible
    • If the sub-string repeated string.lenght()/subString.length() is equal to the target strings its a divisor
  • If there is a common divisor the strings are formed by repeating some string so we can add them in any order and still get the same result.
public String gcdOfStrings(String str1, String str2) {
	if( !(str1+str2).equals(str2+str1)) return "";
	String smaller = (str1.length() < str2.length()) ? str1 : str2;
	String gcd ="";
	int str1l = str1.length(), str2l = str2.length();
	for (int i = smaller.length(); i > 0; --i) {
		if ( str1l%i == 0 && str2l%i == 0 ) {
			String temp = smaller.substring(0,i);
			int tl = temp.length();
 
			String ts1 = temp.repeat(str1l/tl);
			String ts2 = temp.repeat(str2l/tl);
 
			if(ts1.equals(str1) && ts2.equals(str2)) {
				return temp;
			}
 
		}
	}
 
	return gcd;
}
←Previous796. Rotate StringNext→1299. Replace Elements with Greatest Element on Right Side

On this page

IntuitionApproachComplexityCode