Skip to content

Instantly share code, notes, and snippets.

@psy901
Last active June 11, 2025 02:25
Show Gist options
  • Save psy901/327fb3fe7e8673759787013bf2ceac66 to your computer and use it in GitHub Desktop.
Save psy901/327fb3fe7e8673759787013bf2ceac66 to your computer and use it in GitHub Desktop.
gcdOfStrings
fun gcdOfStrings(str1: String, str2: String): String {
// find the shorter string
var short: String
val long: String
if (str1.length > str2.length) {
short = str2
long = str1
} else {
short = str1
long = str2
}
// find all prefixes from the shorter string
// TODO: we can improve this to find "tryable" prefixes (e.g. divide the short str by 2 ?)
val mutableList = mutableListOf<String>()
for (i in short.length downTo 0) {
mutableList.add(short.substring(0, i))
}
// iterating from the largest prefix
var result: String = ""
for (prefix in mutableList) {
if (prefix.isEmpty())
break
if (isDivisible(short, prefix) && isDivisible(long, prefix)) {
result = prefix
break
}
}
// return the string if found
return result
}
// recursion function to determine if str is divisible by the prefix
fun isDivisible(str: String, prefix: String): Boolean {
if (str.isEmpty()) // reached an end
return true
if (!str.startsWith(prefix)) // not divisible
return false
else
return isDivisible(str.substringAfter(prefix), prefix) // keep recursion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment