1-liner in Python


  • 9

    Edit: For an even shorter solution, check out mathsam's answer below and my comment on it.

    class Solution:
        def isIsomorphic(self, s, t):
            return all(map({}.setdefault, a, b) == list(b) for a, b in ((s, t), (t, s)))

  • 1
    T

    6666666666666666666


  • 12
    M

    A similar one

    def isIsomorphic(self, s, t):
        return [s.find(i) for i in s] == [t.find(j) for j in t]

  • 2

    Oh wow, that's neat. And can be improved further:

    def isIsomorphic(self, s, t):
        return map(s.find, s) == map(t.find, t)
    

    There's a catch, though. It's quadratic in time. For example, consider 'a' * n + 'b' * n, where find needs to go through the n 'a' characters for every one of the n 'b' characters. But apparently the online judge doesn't have such a case, as I got this accepted in 64 ms.

    A good mix of the two approaches is this:

    def isIsomorphic(self, s, t):
        f = lambda s: map({}.setdefault, s, range(len(s)))
        return f(s) == f(t)
    

    Could be turned into a one-liner, but I wasn't able to do so in a nice way.


  • 0
    J

    map({}.setdefault, a, b)
    doesn't setdefault need 2 arguments


  • 0

    @jain98 No, it needs one or two. But it always does get two here, so I don't know what you mean.


  • 0
    A
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.