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

ยท

1 min read

Leetcode #16 3 Sum Closest

๐Ÿ“Œ Problem Statement

Given an array of integers nums and a target integer target, find three integers in nums such that the sum is closest to target.

Constraints:

  • Each number in nums can be used only once in a triplet.

  • The solution must return the sum of the closest triplet, not the triplet itself.

  • There is exactly one solution that is closest to target.

๐Ÿš€ Code Implementation

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        ans=nums[0]+nums[1]+nums[2]
        nums.sort()
        diff=abs(ans-target)
        for i in range(len(nums)):
            first=nums[i]
            start=i+1
            end=len(nums)-1
            while(start<end):
                if(first+nums[start]+nums[end]==target):
                    return target
                elif(abs(first+nums[start]+nums[end]-target))<diff:
                    diff=abs(first+nums[start]+nums[end]-target)
                    ans=first+nums[start]+nums[end]
                if(first+nums[start]+nums[end]>target):
                    end=end-1
                else:
                    start=start+1
        return ans

Leetcode #46 Permutations

๐Ÿ“Œ Problem Statement

Given a set of distinct integers nums, return all possible permutations of the elements in nums.

Constraints

  • Each number in nums must be used exactly once in each permutation.

  • The order of numbers matters in the permutations.

  • The solution must return all unique permutations of nums.

๐Ÿš€ Code Implementation

class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = []
        def backtrack(path,available):
            if not available:
                result.append(path)
                return 
            for i in range(len(available)):
                backtrack(path+[available[i]],available[:i] +available[i+1:])    
        backtrack([],nums)
        return result
ย