fa
Feedback
Leetcode with dani

Leetcode with dani

رفتن به کانال در Telegram

Join us and let's tackle leet code questions together: improve your problem-solving skills Preparing for coding interviews learning new algorithms and data structures connect with other coding enthusiasts

نمایش بیشتر
1 258
مشترکین
اطلاعاتی وجود ندارد24 ساعت
+17 روز
-730 روز
آرشیو پست ها
Day 5 🗓 Daily Challenge #1 🧩 Build Array from Permutation Given an array nums, build a new array ans where ans[i] = nums[nums[i]] for every index i. Can you solve it without extra space? (Hint: Think modulo!) 🔗 Problem Link: 📌 Difficulty: Easy 🏷 Tags: #Array #InPlace 💡 Let’s see your optimized solutions! 👉 Drop your approach in the comments! 📊 Problem Breakdown #2 🔄 Matrix Rotation Check Given two n x n matrices, determine if one can be obtained by rotating the other 90°, 180°, or 270°. How would you efficiently check all possible rotations? 🔗 Problem Link: 📌 Difficulty: Medium 🏷 Tags: #Matrix #Transpose 🤔 Think about transpose + reverse vs. brute force. Which is better? 👉 Share your code snippets! 🚀 Advanced Problem Alert! 🔢 Tuple with Same Product Find the number of tuples (a, b, c, d) such that a*b = c*d where all elements are distinct. Can you avoid an O(n⁴) solution? (Hint: Hash maps are your friend!) 🔗 Problem Link: 📌 Difficulty: Medium 🏷 Tags: #HashTable #Combinatorics 💥 Challenge: Optimize for large arrays! 👉 Post your best time complexity in the comments!

https://t.me/+axQMvWILZ505Yjlk Check this channel; it's better to share good resources I find in a separate channel rather than posting them here. I post new resources that teach you full stack development, including HTML, CSS, JavaScript, Bootstrap, Node.js, React, Git, MongoDB, APIs, and more

Day 4 Q1 Insert Delete GetRandom O(1) Link: Difficulty: Medium Problem Description: Design a data structure that supports the following operations in average O(1) time—insert, remove, and getRandom. insert(val): Inserts an item val into the set if not already present. Returns true if the item was successfully inserted. remove(val): Removes an item val from the set if present. Returns true if the item existed and was removed. getRandom(): Returns a random element from the current set of elements. Each element must have an equal probability of being returned. Example: Input: ["RandomizedSet", "insert", "remove", "insert", "getRandom"] [[], [1], [2], [2], []] Output: [null, true, false, true, 1] Day 4 Q2 Find Players With Zero or One Losses Link: Difficulty: Medium Problem Description: Given an array of match results where each match is represented as [winner, loser], identify two sorted lists: The first list contains players who have not lost any matches. The second list contains players who have lost exactly one match. If a player lost more than once, they should not appear in either list. Example: Input: matches = [[2,3], [1,3], [5,4], [6,4]] Output: [[1,2,6], [3,4]] Day 4 Q3 Shuffle String Link: Difficulty: Easy Problem Description: You are given a string s and an integer array indices of the same length. The task is to build a new string by shuffling s such that the character at the i-th position moves to indices[i] in the resulting string. Example: Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] Output: "leetcode"

Problem: Find Words That Can Be Formed by Characters Problem Link: You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words. Example 1: Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6 Explanation: The strings "cat" and "hat" can be formed using the characters of chars, so the total length is 3 + 3 = 6. Example 2: Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" Output: 10 Explanation: The strings "hello" and "world" can be formed using the characters of chars, so the total length is 5 + 5 = 10. Constraints: 1 <= words.length <= 1000 1 <= words[i].length, chars.length <= 100 words[i] and chars consist of lowercase English letters. Challenge: Can you solve this problem efficiently? Try it out and share your approach!

Easy Problem: Two Sum (LeetCode #1) Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. Example:
Input: nums = [2, 7, 11, 15], target = 9  
Output: [0, 1]  
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].  
Constraints: - 2 <= nums.length <= 10^4 - -10^9 <= nums[i] <= 10^9 - Only one valid answer exists. Practice here: LeetCode --- Medium Problem: Maximum Subarray (LeetCode #53) Given an integer array nums, find the subarray with the largest sum, and return its sum. Example:
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]  
Output: 6  
Explanation: The subarray [4, -1, 2, 1] has the largest sum = 6.  
Constraints: - 1 <= nums.length <= 10^5 - -10^4 <= nums[i] <= 10^4 Hint: Use Kadane's Algorithm (Greedy/Sliding Window approach) to solve this efficiently! Practice here: LeetCode --- Medium Problem: Valid Parentheses (LeetCode #20) Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Example:
Input: s = "()[]{}"  
Output: true  

Input: s = "(]"  
Output: false  
Constraints: - 1 <= s.length <= 10^4 - s consists of parentheses only '()[]{}'. Hint: Use a stack to ensure proper matching of parentheses! Practice here: LeetCode

To solve this problem, we need to find all unique triplets in an array that sum to zero. The solution must avoid duplicate triplets and efficiently handle the input constraints. Approach Sort the Array: Sorting helps in efficiently finding triplets and avoiding duplicates by allowing us to skip over identical elements. Iterate with a Fixed Element: For each element in the array (up to the third last element), treat it as the first element of the triplet. Two-Pointer Technique: Use two pointers (left and right) to find the remaining two elements such that their sum with the fixed element equals zero. Adjust the pointers based on whether the current sum is less than or greater than zero. Skip Duplicates: After finding a valid triplet, skip over any subsequent duplicate elements to avoid adding the same triplet multiple times.
def threeSum(nums):
    res = []
    nums.sort()
    n = len(nums)
    for i in range(n - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue  # Skip duplicate elements for the first element of the triplet
        left, right = i + 1, n - 1
        while left < right:
            current_sum = nums[i] + nums[left] + nums[right]
            if current_sum == 0:
                res.append([nums[i], nums[left], nums[right]])
                # Skip duplicates for the second element
                while left < right and nums[left] == nums[left + 1]:
                    left += 1
                # Skip duplicates for the third element
                while left < right and nums[right] == nums[right - 1]:
                    right -= 1
                left += 1
                right -= 1
            elif current_sum < 0:
                left += 1
            else:
                right -= 1
    return res 
Explanation Sorting the Array: This step ensures that any duplicates are adjacent, making it easier to skip them. Fixed Element Iteration: For each element in the array (excluding the last two to ensure there are elements left for the other two pointers), we check if it's a duplicate of the previous element. If it is, we skip it to avoid duplicate triplets. Two-Pointer Technique: The left pointer starts right after the fixed element, and the right pointer starts at the end of the array. Depending on the sum of the three elements, we adjust the pointers inward: If the sum is zero, we add the triplet to the result and move both pointers inward, skipping any duplicates. If the sum is less than zero, we move the left pointer to the right to increase the sum. If the sum is greater than zero, we move the right pointer to the left to decrease the sum. Skipping Duplicates: After finding a valid triplet, we move the left pointer past all duplicates of the current left element and the right pointer past all duplicates of the current right element to avoid adding the same triplet again. This approach efficiently finds all unique triplets with a time complexity of O(n^2), which is optimal for the given problem constraints.

Day2 Q3 167. Two Sum II - Input Array Is Sorted Medium Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space. Example 1: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. Example 2: Input: numbers = [2,3,4], target = 6 Output: [1,3] Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. Example 3: Input: numbers = [-1,0], target = -1 Output: [1,2] Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. Constraints: 2 <= numbers.length <= 3 * 104 -1000 <= numbers[i] <= 1000 numbers is sorted in non-decreasing order. -1000 <= target <= 1000 The tests are generated such that there is exactly one solution. Try

Day2 Q2 15. 3Sum Medium Hint Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0. try

class Solution: def nextPermutation(self, nums: List[int]) -&gt; None: """ Do not return anything, modify nums in-place inste
class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        r = len(nums)-1
        while r>=1:
            if nums[r] >nums[r-1]:
                if r+1<len(nums) and nums[r+1] >nums[r-1]:
                    k = 2
                    while (r+k<len(nums) and  nums[r+k] >nums[r-1]):
                        k+=1
                    k-=1
                    nums[r+k],nums[r-1]=nums[r-1],nums[r+k]
                else:
                    nums[r],nums[r-1]=nums[r-1],nums[r]
                break
            else:
                r -= 1
        l = len(nums)-1
        while l>r:
            if nums[l] <nums[r]:
                nums[l],nums[r] = nums[r],nums[l]
            l-=1
            r+=1

Day 2 Q1 31. Next Permutation Medium A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). For example, the next permutation of arr = [1,2,3] is [1,3,2]. Similarly, the next permutation of arr = [2,3,1] is [3,1,2]. While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement. Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory. Example 1: Input: nums = [1,2,3] Output: [1,3,2] Example 2: Input: nums = [3,2,1] Output: [1,2,3] Example 3: Input: nums = [1,1,5] Output: [1,5,1] Topics : Two pointer and Array Submit

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height:
            return 0
        left = 0
        right = len(height) - 1
        left_max = right_max = 0
        total = 0
        while left < right:
            if height[left] < height[right]:
                if height[left] >= left_max:
                    left_max = height[left]
                else:
                    total += left_max - height[left]
                left += 1
            else:
                if height[right] >= right_max:
                    right_max = height[right]
                else:
                    total += right_max - height[right]
                right -= 1
        return total

u can invite ur friends to do questions together
u can invite ur friends to do questions together

image_2025-02-03_21-00-16.png0.80 KB

photo content

42. Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute
42. Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Example 1: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Example 2: Input: height = [4,2,0,3,2,5] Output: 9 Constraints: n == height.length 1 <= n <= 2 * 104 0 <= height[i] <= 105 who wants to try answering this question? Don’t worry, it’s not too scary! 😄 Try

Check this Website it has good road map to practice leetcode questions https://neetcode.io/roadmap

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
       
        num_indices = {}
        for i, num in enumerate(nums):
            if num in num_indices and i - num_indices[num] <= k:
                return True
            num_indices[num] = i

        return False

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
       
        num_indices = {}
        for i, num in enumerate(nums):
            if num in num_indices and i - num_indices[num] <= k:
                return True
            num_indices[num] = i

        return False