Day-4 Leetcode Coding Journey: Mastering Problem-Solving Techniques

ยท

1 min read

Leetcode #47 Permutations II

๐Ÿ“Œ Problem Statement

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

Constraints:

  • Each number in nums can be used only once per permutation.

  • The output should contain only unique permutations (no duplicates).

  • The solution should return all possible unique permutations.

๐Ÿš€ Code Implementation

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res=[]
        nums.sort()  
        used=[False]*len(nums) 

        def backtrack(path):
            if len(path)==len(nums):
                res.append(path[:])  
                return

            for i in range(len(nums)):
                if used[i]:  
                    continue
                if i>0 and nums[i]==nums[i-1] and not used[i-1]:
                    continue
                used[i]=True
                path.append(nums[i])
                backtrack(path)
                path.pop()
                used[i]=False

        backtrack([])
        return res

Leetcode #49 Group Anagrams

๐Ÿ“Œ Problem Statement

Given an array of strings strs, group the anagrams together. You may return the answer in any order.

Constraints:

  • An anagram is a word or phrase formed by rearranging the letters of another.

  • All inputs will be lowercase English letters.

  • The solution must return groups of anagrams.

๐Ÿš€ Code Implementation

from collections import defaultdict
class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        anagrams=defaultdict(list) 

        for word in strs:
            sorted_word=tuple(sorted(word)) 
            anagrams[sorted_word].append(word)
        return list(anagrams.values())
ย