How to check if two strings are isomorphic in Scala

2 Answers

0 votes
def areIsomorphic(s: String, t: String): Boolean = {
  def pattern(str: String) = str.map(ch => str.indexOf(ch))
  
  pattern(s) == pattern(t)
}

println(areIsomorphic("egg", "add"))    
println(areIsomorphic("foo", "bar"))   
println(areIsomorphic("paper", "title"))  



/*
run:

true
false
true

*/

 



answered Dec 19, 2025 by avibootz
0 votes
import scala.collection.mutable
import scala.util.boundary, boundary.break

def isIsomorphic(s: String, t: String): Boolean = boundary:
  // Immediate length check
  if (s.length != t.length) break(false)

  val mapST = mutable.Map[Char, Char]()
  val mapTS = mutable.Map[Char, Char]()

  for (i <- 0 until s.length) {
    val charS = s(i)
    val charT = t(i)

    // Check mapping from S to T
    if (mapST.contains(charS)) {
      if (mapST(charS) != charT) break(false)
    } else {
      mapST(charS) = charT
    }

    // Check mapping from T to S (ensures one-to-one mapping)
    if (mapTS.contains(charT)) {
      if (mapTS(charT) != charS) break(false)
    } else {
      mapTS(charT) = charS
    }
  }
  
  true // Default return value if break is never called

// Test cases
println(isIsomorphic("egg", "add"))     
println(isIsomorphic("foo", "bar"))     
println(isIsomorphic("paper", "title")) 



/*
run:

true
false
true

*/


 



answered Dec 19, 2025 by avibootz
edited Dec 19, 2025 by avibootz
...