পাঠসূচি
  1. 11. Two Sum - বাংলায় LeetCode - পাইথন
  2. 2118. Pascal's Triangle - বাংলায় LeetCode - Python
  3. 3217. Contains Duplicate - বাংলায় LeetCode - পাইথন
  4. 4242. Valid Anagram - বাংলায় LeetCode - পাইথন

242. Valid Anagram - বাংলায় LeetCode - পাইথন

LeetCode · পাঠ 4 · English · ভিডিও বাংলায়

242. Valid Anagram - বাংলায় LeetCode - পাইথনWatch on YouTube

ভিডিওটির ভাষা বাংলা।

Contents

[A1] - Sorting

Time: O(nlog(n))

Space: O(1)

class Solution(object):
    def isAnagram(self, s, t):
        s_sorted = sorted(s)
        t_sorted = sorted(t)

        if s_sorted == t_sorted:
            return True
        else:
            return False
class Solution(object):
    def isAnagram(self, s, t):
        return sorted(s)==sorted(t) # comparing two lists

Comment: In python, string is immutable. That is why here I am using sorted() function instead of sort() as sorted() returns a completely new string and don’t modify the original string.

[A2] - Hash Table

Time: O(n)

Space: O(n)

class Solution(object):
    def isAnagram(self, s, t):
        if len(s)!=len(t):
            return False
        ds, dt= {}, {}
        for i in range(len(s)):
            ds[s[i]] = 1 + ds.get(s[i],0)
            dt[t[i]] = 1 + dt.get(t[i],0)
        for c in ds:
            if ds[c] != dt.get(c,0):
                return False
        return True

Comment: Here we are building our own hash table and checking if the count of all the elements is same.

[A3] - Counter Function

Time: O(n)

Space: O(n)

class Solution(object):
    def isAnagram(self, s, t):
        return Counter(s)==Counter(t)

Comment: This approach works exactly same as A2. We are just using the Counter() function which is handling everything by itself. This approach is probably not suitable for interview.

কোনো ভুল পেয়েছেন? LinkedIn-এ জানান।