Isomorphic Strings - Leetcode 205 - Python

Поделиться
HTML-код
  • Опубликовано: 29 ноя 2024

Комментарии • 73

  • @NeetCode
    @NeetCode  3 года назад +8

    ⭐ BLIND-75 PLAYLIST: ruclips.net/video/KLlXCFG5TnA/видео.html

  • @raghavdewangan6585
    @raghavdewangan6585 Год назад +15

    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 Год назад +10

    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

  • @hudsonriverrunner
    @hudsonriverrunner 3 года назад +14

    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 3 года назад +1

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

  • @ОленаЄфименко-б6ю
    @ОленаЄфименко-б6ю 2 года назад +8

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

  • @bg-sj9tx
    @bg-sj9tx 3 года назад +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

  • @YasirYSR
    @YasirYSR 3 года назад +5

    I am addicted to your channel. great work

  • @surajnair2617
    @surajnair2617 2 года назад +1

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

  • @LunaFlahy
    @LunaFlahy Год назад +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 Год назад

      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

  • @tawkeer4
    @tawkeer4 11 месяцев назад

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

  • @dwarfling
    @dwarfling Год назад

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

  • @tanmaydash803
    @tanmaydash803 Год назад +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 Год назад +3

    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 Год назад

      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.

  • @jared6976
    @jared6976 3 года назад +1

    Suggestion: Reconstruct Itinerary (Graph)

  • @thepriestofvaranasi
    @thepriestofvaranasi Месяц назад

    Isn't the space complexity O(1) since we can have atmost 26 mappings in both the dictionaries right?

  • @bandhammanikanta
    @bandhammanikanta 2 года назад

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

    • @codearabawy
      @codearabawy 2 года назад

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

  • @helinity1743
    @helinity1743 2 года назад +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.

  • @6a.s.harishkumar62
    @6a.s.harishkumar62 8 месяцев назад +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) !
    }
    }

  • @notcountdankula
    @notcountdankula Год назад

    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 Год назад +1

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

  • @barsayten7222
    @barsayten7222 Год назад

    you are a life saver!

  • @triplestrikee875
    @triplestrikee875 3 года назад

    Great solution! I love your videos.

  • @codearabawy
    @codearabawy 2 года назад

    Great explanation, thanks bro!

  • @HarshitPrasad-n8e
    @HarshitPrasad-n8e 11 месяцев назад

    Thanks for the sol 🙏

  • @Codenames560
    @Codenames560 2 года назад +2

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

  • @LamNguyen-nm1id
    @LamNguyen-nm1id 2 года назад +1

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

    • @carpediemcotidiem
      @carpediemcotidiem Месяц назад

      Yes, I suspect space complexity is O(s+t) as it uses 2 Hash Maps which will each be a maximum length equal to the length of each string

  • @shaniceshipp8677
    @shaniceshipp8677 2 года назад

    You saved my life!

  • @weepingwillow2056
    @weepingwillow2056 3 года назад +1

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

  • @sajramkisho9991
    @sajramkisho9991 3 года назад +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

  • @kushagrabhadauria8322
    @kushagrabhadauria8322 2 года назад +2

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

    • @mahdiranjbar3569
      @mahdiranjbar3569 2 месяца назад

      try this:
      class Solution(object):
      def isIsomorphic(self, s, t):
      """
      :type s: str
      :type t: str
      :rtype: bool
      """
      d = {}
      for i in range(len(s)):
      if s[i] not in d:
      if t[i] in d.values():
      return False
      d[s[i]] = t[i]
      else:
      if d[s[i]] != t[i]:
      return False
      return True

  • @abhisheksunkale6672
    @abhisheksunkale6672 3 года назад +3

    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

  • @pacomarmolejo3492
    @pacomarmolejo3492 2 года назад

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

  • @niranjanbhondave88
    @niranjanbhondave88 11 месяцев назад

    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

  • @sergeyeremenko
    @sergeyeremenko 3 года назад

    one map and one set is enough

  • @emanuelvidalrm
    @emanuelvidalrm 3 года назад +14

    Will I ever be as clever as you? :(

    • @HikmalPramudya
      @HikmalPramudya Год назад +3

      how bout now bro?

    • @emanuelvidalrm
      @emanuelvidalrm Год назад +5

      @@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 Год назад +3

      @@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

    • @vineetkukreti2280
      @vineetkukreti2280 3 месяца назад

      ​@@HikmalPramudya bro what about now ??

    • @vineetkukreti2280
      @vineetkukreti2280 3 месяца назад

      ​@@emanuelvidalrm bro did you become clever??

  • @ajaygaurav4748
    @ajaygaurav4748 8 месяцев назад

    thanks

  • @sanooosai
    @sanooosai 9 месяцев назад

    great thank you

  • @athirahasri9703
    @athirahasri9703 8 месяцев назад

    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)):

  • @Yoo_broo_Jr
    @Yoo_broo_Jr 5 месяцев назад

    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.

  • @trungthanhbp
    @trungthanhbp 3 года назад +1

    can we just use 1 map :-?

    • @amyotun
      @amyotun 3 года назад

      @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.

  • @indranilchatterjee6164
    @indranilchatterjee6164 2 года назад +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 2 года назад +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 3 года назад

    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

  • @PrateekDas-yn8ce
    @PrateekDas-yn8ce Год назад

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

  • @renuvelhal5154
    @renuvelhal5154 2 года назад

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

    • @JohnJones-it5dn
      @JohnJones-it5dn 2 года назад

      u use both at same time as they are the same size

  • @AndresMForero
    @AndresMForero 2 года назад

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

  • @craftsworld3237
    @craftsworld3237 8 месяцев назад +1

    whot an accent!!!!!!

  • @mykagg
    @mykagg Год назад

    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).

  • @karthikreddygaddam3104
    @karthikreddygaddam3104 3 года назад +1

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

  • @a_jaycee8643
    @a_jaycee8643 7 месяцев назад

    you live and you learn ... fk me

  • @sabu4539
    @sabu4539 Год назад +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;