Skip to content

Instantly share code, notes, and snippets.

@mfaani
Last active September 28, 2025 20:38
Show Gist options
  • Save mfaani/901d7abd5ab3206c8c0d07f421e11a41 to your computer and use it in GitHub Desktop.
Save mfaani/901d7abd5ab3206c8c0d07f421e11a41 to your computer and use it in GitHub Desktop.
#leetcode #array
class Solution {
func gcdOfStrings(_ str1: String, _ str2: String) -> String {
if str2.count > str1.count {
return findGCDOf(str1: str2, str2: str1)
} else {
return findGCDOf(str1: str2, str2: str1)
}
}
func findGCDOf(str1: String, str2: String) -> String {
// - WHY: Reversing the indexes so we go from big range to small. Otherwise we may find a smaller common devisor and return early.
// - NOTE: `indices` doesn't return the `endIndex`. It only returns _valid_ indexes. So that's awesome.
for i in str2.indices.reversed() {
let subString = String(str2[str1.startIndex...i])
if str1.isDivisible(byRepeating: subString) && str2.isDivisible(byRepeating: subString) {
return subString
}
}
return ""
}
}
extension String {
func isDivisible(byRepeating str: String) -> Bool {
var result = str
while self.count > result.count {
result += str
}
return result == self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment