Day 1 of LeetCode

Day 1 of LeetCode

ยท

2 min read

Going to start this series to document what I did, learned when doing LeetCode, specifically NeetCode 150.

Q1

217. Contains Duplicate

Easy. Array

My initial thought was to use Hashset.

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(nums) != len(set(nums))

Q2

242. Valid Anagram

Easy. Array

I can count the frequency of each letter in the two strings, if the frequencies are the same, which means t is an anagram of s .

countS.get(s[i], 0) gets the current count of s[i] in the dictionary countS. If s[i] is not yet a key in countS, it returns 0.

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False

        countS = self.countFrequency(s)
        countT = self.countFrequency(t)

        return countS == countT

    def countFrequency(self, s: str) -> dict:
        count = {}
        for i in range(len(s)):
            count[s[i]] = 1 + count.get(s[i], 0)

        return count

Q3

49. Group Anagrams

Medium. Array

Use a code to represent each string, if two strings have the same code they are anagrams. Then use a dictionary to group the strings with same code together.

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        group = {}
        for s in strs:
            code = self.encode(s)
            if code not in group:
                group[code] = []
            group[code].append(s)

        res = []
        for g in group.values():
            res.append(g)

        return res

    # To encode a string, if two strings have the same code they are anagrams.
    def encode(self, s: str) -> str:
        count = [0] * 26
        for c in s:
            count[ord(c) - ord('a')] += 1
        return str(count)

Did you find this article valuable?

Support ๐Ÿฐ Evelyn's Learning Journey by becoming a sponsor. Any amount is appreciated!

ย