Isomorphic Strings - Leetcode 205 - Python

Sdílet
Vložit
  • čas přidán 5. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🐦 Twitter: / neetcode1
    🥷 Discord: / discord
    🐮 Support the channel: / neetcode
    ⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
    💡 CODING SOLUTIONS: • Coding Interview Solut...
    💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
    🌲 TREE PLAYLIST: • Invert Binary Tree - D...
    💡 GRAPH PLAYLIST: • Course Schedule - Grap...
    💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
    💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
    💡 BINARY SEARCH PLAYLIST: • Binary Search
    📚 STACK PLAYLIST: • Stack Problems
    Problem Link: leetcode.com/problems/isomorp...
    0:00 - Read the problem
    0:45 - Drawing Explanation
    6:32 - Coding Explanation
    leetcode 205
    This question was identified as a facebook coding interview question from here: github.com/xizhengszhang/Leet...
    #coding #interview #python
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
  • Věda a technologie

Komentáře • 67

  • @NeetCode
    @NeetCode  Před 2 lety +5

    ⭐ BLIND-75 PLAYLIST: czcams.com/video/KLlXCFG5TnA/video.html

  • @raghavdewangan6585
    @raghavdewangan6585 Před 9 měsíci +9

    such an easy solution, i was reading this problem and just had no idea what isomorhpic was or how to even remotely solve it. thanks bro

  • @gerryramosftw
    @gerryramosftw Před rokem +6

    Your videos are seriously top notch, there are so many other tutorials out there that essentially read the code line by line. But you provide an intuitive approach to how to solve the problem, in a way that similar approach can also be applied to similar problems.
    I'm going to keep watching most likely all of your videos and most likely subscribe on your website as well just to be able to go through the material. The quality really speaks for itself
    Thank you

  • @leetcoderlandon8353
    @leetcoderlandon8353 Před 2 lety +13

    Great Work! I love your videos. I often watch them to practice my English Speaking by repeating your explanations. It really helps. For this question, you can use ONE DICTIONARY and check duplicates in its values.
    class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
    match = dict()
    for index in range(len(s)):
    if s[index] not in match:
    match[s[index]] = t[index] # new map
    else:
    if t[index] != match[s[index]]: # check existing map
    return False

    values = match.values()
    return len(set(values)) == len(values) # check if any duplicates

    • @bg-sj9tx
      @bg-sj9tx Před 2 lety +1

      O(n) space and O(1) in time complexity ?

  • @user-vj4lx6bc3i
    @user-vj4lx6bc3i Před rokem +7

    In my opinion, your explanation is brilliant, Thank you a lot!

  • @YasirYSR
    @YasirYSR Před 2 lety +4

    I am addicted to your channel. great work

  • @surajnair2617
    @surajnair2617 Před 2 lety +1

    Amazing question..this is why Facebook is my favorite tool to generate isomorphic strings.

  • @bg-sj9tx
    @bg-sj9tx Před 2 lety +2

    Om pretty sure you can use one map and store em in key val pair and check if the current char in on of string != to the prev value in the other str

  • @LunaFlahy
    @LunaFlahy Před rokem +1

    Thanks for your intuition, which inspired me to come out with an approach to this problem. I tried Try and Except and it works too.

    • @LunaFlahy
      @LunaFlahy Před rokem

      class Solution:
      def isIsomorphic(self, s: str, t: str) -> bool:
      dic = {}
      for i in range(len(s)):
      if s[i] not in dic and t[i] not in dic.values():
      dic[s[i]] = t[i] #create hashtable
      else:
      try:
      if t[i] != dic[s[i]]:
      return False
      except:
      return False
      return True

  • @triplestrikee875
    @triplestrikee875 Před 2 lety

    Great solution! I love your videos.

  • @codearabawy
    @codearabawy Před rokem

    Great explanation, thanks bro!

  • @tawkeer4
    @tawkeer4 Před 6 měsíci

    i couldn't understand the question from leetcode so i had to come here.
    Thank you for making me understand

  • @0yustas0
    @0yustas0 Před 2 lety +6

    You need only one dict for this task.
    just check, that account of unique characters is the smame
    class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
    d = {}
    for i, n in enumerate(s):
    if n not in d: d[n]=t[i]
    else:
    if d[n] != t[i]:
    return False
    return len(d.keys()) == len(set(d.values()))

    • @jaad9848
      @jaad9848 Před 2 lety +1

      yeah you can use Counter and make it less lines

    • @rohithkumarnainar228
      @rohithkumarnainar228 Před rokem

      I thought the same and checking anyone mentioned the same in the comment section :)

  • @barsayten7222
    @barsayten7222 Před rokem

    you are a life saver!

  • @user-hg9qy6ny2p
    @user-hg9qy6ny2p Před 6 měsíci

    Thanks for the sol 🙏

  • @dwarfling
    @dwarfling Před rokem

    you can do it without reverse map. if you do check both strings: isIsomorphic(s,t) && isIsomorphic(t,s) - makes impl simpler!

  • @weepingwillow2056
    @weepingwillow2056 Před 2 lety +1

    جميل جدا. مشكور
    Great 👍 Thanks

  • @jared6976
    @jared6976 Před 2 lety +1

    Suggestion: Reconstruct Itinerary (Graph)

  • @kushagrabhadauria8322
    @kushagrabhadauria8322 Před rokem +2

    Not Working Your code ....giving error in 3rd example of paper to title
    what to do ?

  • @shaniceshipp8677
    @shaniceshipp8677 Před rokem

    You saved my life!

  • @pacomarmolejo3492
    @pacomarmolejo3492 Před rokem

    is it O(1) space as worst case the dictionary will always be of size 128 (ascii)?

  • @mehmanmanafov1441
    @mehmanmanafov1441 Před rokem

    Thanks!

  • @bandhammanikanta6302
    @bandhammanikanta6302 Před 2 lety

    Great Explanation. I'm wonder if there is any other Optimal solution.

    • @codearabawy
      @codearabawy Před rokem

      You can solve it with one hashmap only: look at my solution here:
      leetcode.com/problems/isomorphic-strings/discuss/2298081/C-one-Map-solution

  • @LamNguyen-nm1id
    @LamNguyen-nm1id Před rokem

    if i'm not mistaken, is time complexity O(n) and space complexity O(n) as well?

  • @abhisheksunkale6672
    @abhisheksunkale6672 Před 2 lety +2

    is it less efficient to do it in just one mapping and check while mapping if key already exits or value already exists then return false ? or big(O)will be bad in my case

  • @AndresMForero
    @AndresMForero Před rokem

    Thank you. I finally understand what is isomorphic haha. pretty good job man. thank you so much.

  • @sanooosai
    @sanooosai Před 4 měsíci

    great thank you

  • @ajaygaurav4748
    @ajaygaurav4748 Před 3 měsíci

    thanks

  • @tanmaydash803
    @tanmaydash803 Před rokem +1

    here is my solution
    def isomerphic(a,b):
    map1=[]
    map2=[]
    for idx in a:
    map1.append(a.index(idx))
    for idx in b:
    map2.append(b.index(idx))
    print(map1)
    print(map2)
    if map1==map2:
    return True
    return False
    a=("bar")
    b=("foo")
    print(isomerphic(a,b))

  • @CloudPrince1234
    @CloudPrince1234 Před rokem +2

    Using this code it seems to return true for "babc"/"baba". If I'm reading this right, it doesn't seem to do a check on the last character.

    • @visase2036
      @visase2036 Před rokem

      It does ,
      As we maintain 2 diff map one for babc and one for baba
      You will have b-->b, a-->a and c--->a in the first Map and in the secondMap you have b-->b,a-->a,(a--->c) this check will fail and returns false.

  • @PrateekDas-yn8ce
    @PrateekDas-yn8ce Před 9 měsíci

    in 3:29 you could just use this example :
    s =
    "badc"
    t =
    "baba"

  • @renuvelhal5154
    @renuvelhal5154 Před 2 lety

    can anybody help me by explaining whd did we only tranverse string s and not string t

  • @Codenames560
    @Codenames560 Před 2 lety +2

    hmm to me, this questions is tricky and harder than other easy questions

  • @athirahasri9703
    @athirahasri9703 Před 3 měsíci

    Hi. I am new to Python. Can anyone explain me this line?
    if ((c1 in mapST and mapST[c1] != c2) or
    (c2 in mapTS and mapTS[c2] != c1)):

  • @helinity1743
    @helinity1743 Před rokem +1

    This is the most efficent solution i guess:
    class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
    return len(set(zip(s,t))) == len(set(s)) == len(set(t))
    NOTE: THIS SOLUTION IS NOT CODED BY ME.

  • @sergeyeremenko
    @sergeyeremenko Před 2 lety

    one map and one set is enough

  • @mykagg
    @mykagg Před 10 měsíci

    Hey, you missed one Condition i.e. "No two characters may map to the same character" for BAR you mapped (a-> o and r->o).

  • @emanuelvidalrm
    @emanuelvidalrm Před 2 lety +11

    Will I ever be as clever as you? :(

    • @HikmalPramudya
      @HikmalPramudya Před rokem +2

      how bout now bro?

    • @emanuelvidalrm
      @emanuelvidalrm Před rokem +4

      @@HikmalPramudya Haha, since then I've manage to get my first internship as a full stack developer! I guess hardwork pays in the end. Still, not as smart as you tho, but maybe one day :D

    • @HikmalPramudya
      @HikmalPramudya Před rokem +2

      @@emanuelvidalrm thank for your answer.. thats build my confidence to be like you. as now i still lack of confidence cuz this leetcode complication hahaha. hopefully i can be like you one year later

  • @sajramkisho9991
    @sajramkisho9991 Před 2 lety +2

    class Solution {
    public boolean isIsomorphic(String s, String t) {
    if(s.length()!=t.length()) return false;

    HashMap map=new HashMap();


    for(int i=0;i

  • @trungthanhbp
    @trungthanhbp Před 2 lety +1

    can we just use 1 map :-?

    • @amyotun
      @amyotun Před 2 lety

      @Land Keeper - you can do that. In foo and bar example, try to insert f : o#, o# : f, etc. in hashmap.Then, you will see why they are not isomorphic. However, I prefer to solve with 2 hashmap approach which is more cleaner.

  • @niranjanbhondave88
    @niranjanbhondave88 Před 6 měsíci

    A rather sly solution from my side😂. I have managed to use a single map, but I use two traversals. (C++ solution)
    class Solution {
    public:
    bool check(string s, string t)
    {
    mapmp;
    for(int i=0;i

  • @notcountdankula
    @notcountdankula Před 11 měsíci

    More optimized solution:
    class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:

    map = {}
    for i in range(len(s)):
    if s[i] not in map:
    if t[i] not in map.values():
    map[s[i]] = t[i]

    else:
    return False
    else:
    if t[i] != map[s[i]]:
    return False
    return True

    • @semro
      @semro Před 9 měsíci

      `if t[i] not in map.values()`
      isn't this operation O(n) time complexity?

  • @Desh_Bhakt_
    @Desh_Bhakt_ Před 14 dny

    DOUBTTTT !!!!!!
    bruh how can you check the mapping condition ,(i.e. if loop ) because the mapping is not even there, meaning the hashmaps mapST, mapTS were empty right ?? so how can you check the if condition without adding elements in the map itself.

  • @indranilchatterjee6164
    @indranilchatterjee6164 Před 2 lety +1

    A solution using one HashMap:
    class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
    charMap = {}

    if len(s) != len(t):
    return False

    for i, ch in enumerate(s):
    if ch in charMap:
    if charMap[ch] != t[i]:
    return False
    else:
    if t[i] in charMap.values():
    return False
    charMap[ch] = t[i]

    return True

    • @bogdanyarotsky2233
      @bogdanyarotsky2233 Před rokem +2

      This solution has O(n^2) complexity because iterating over values of map is O(n) in the worst case. But the direction is right. I was able to pull this off in O(n) by using a map + hashset to store values mapped in t string

  • @TheElementFive
    @TheElementFive Před 2 lety

    My solution with more explicit tests for possible cases:
    def isIsomorphic(self, s: str, t: str) -> bool:
    s_instances = {letter: None for letter in set(s)}

    for idx, val in enumerate(t):
    if not s_instances[s[idx]] and val in s_instances.values():
    return False
    elif s_instances[s[idx]] and s_instances[s[idx]] != val:
    return False
    elif not s_instances[s[idx]] and val not in s_instances.values():
    s_instances[s[idx]] = val
    return True

  • @craftsworld3237
    @craftsworld3237 Před 3 měsíci +1

    whot an accent!!!!!!

  • @a_jaycee8643
    @a_jaycee8643 Před 2 měsíci

    you live and you learn ... fk me

  • @karthikreddygaddam3104
    @karthikreddygaddam3104 Před 2 lety +1

    if Len(set(str1))==Len(set(str2)):
    TRUE
    else:
    FALSE

  • @sabu4539
    @sabu4539 Před 7 měsíci +1

    easy solution
    const hash = new Map();
    if(new Set(s).size != new Set(t).size) return false;
    for(let i = 0; i < s.length; i++){
    if(!hash.has(s[i])) {
    hash.set(s[i], t[i]);
    } else if(hash.get(s[i]) != t[i]) {
    return false;
    }
    }
    return true;

  • @6a.s.harishkumar62
    @6a.s.harishkumar62 Před 3 měsíci +2

    // Java Code :
    class Solution {
    public boolean isIsomorphic(String s, String t) {
    // HashMap NC
    HashMap mapST = new HashMap();
    HashMap mapTS = new HashMap();
    int n = s.length(); // t.length() == s.length() !
    for(int idx = 0; idx < n; idx++){
    char st = s.charAt(idx);
    char ts = t.charAt(idx);
    if((mapST.containsKey(st) && mapST.get(st) != ts) ||
    (mapTS.containsKey(ts) && mapTS.get(ts) != st)){
    return false;
    }
    mapST.put(st, ts);
    mapTS.put(ts, st);
    }
    return true; // TC = SC = O(n) !
    }
    }