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
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
🤔2
Leetcode with dani
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…
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
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
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 :
Submit
LeetCode
Next Permutation - LeetCode
Can you solve this real interview question? Next Permutation - 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…
* For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2…
👍1
Leetcode with dani
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…
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
Leetcode with dani
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…
YouTube
Next Permutation | Leetcode #31
This video explains the next permutation problem which uses a very unique concept of creating the next greater sequence from an array. I have shown the entire intuition step by step using simple examples with reasons for each step.Please watch the entire…
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
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
LeetCode
3Sum - LeetCode
Can you solve this real interview question? 3Sum - 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…
Notice that the solution set must not contain…
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
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
LeetCode
Two Sum II - Input Array Is Sorted - LeetCode
Can you solve this real interview question? Two Sum II - Input Array Is Sorted - 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…
Leetcode with dani
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. …
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.
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.
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.
Easy Problem: Two Sum (LeetCode #1)
Given an array of integers
Example:
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
Example:
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
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:
Constraints:
- 1 <= s.length <= 10^4
-
Hint: Use a stack to ensure proper matching of parentheses!
Practice here: LeetCode
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
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!
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!
LeetCode
Find Words That Can Be Formed by Characters - LeetCode
Can you solve this real interview question? Find Words That Can Be Formed by Characters - 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 for…
A string is good if it can be formed by characters from chars (each character can only be used once for…
Day 4 Q 1
1. Insert Delete GetRandom O(1)
Link
Problem: Design a data structure that supports insert, remove, and getRandom operations in average O(1) time.
Key Points:
Use a dynamic array to store elements for O(1) random access.
Pair it with a hash map to track element indices for O(1) insertion/deletion.
For removal, swap the target element with the last element in the array to avoid shifting.
Example:
Insert 1 → [1]. Insert 2 → [1,2]. Remove 1 → [2]. getRandom() returns 2.
Day 4 Q 2
2. Find Players With Zero or One Losses
Link
Problem: Given match outcomes as [winner, loser], return two lists: players with 0 losses and those with 1 loss, sorted in ascending order.
Key Approach:
Use a hash map to count losses for each player.
Track all players (including winners with 0 losses).
Filter and sort results based on loss counts (0 or 1).
Example:
Input: [[1,3],[2,1],[4,2],[5,2]]
Output: [[4,5], [1,3]]
(Players 4,5 never lost; 1,3 lost once)
Day 4 Q 3
3. Shuffle String
Link
Problem: Reconstruct a string using an index array. For s = "abc" and indices = [0,2,1], return "acb".
Approach:
Create a result array of the same length as s.
Place each character s[i] at result[indices[i]].
Convert the array to a string.
Example:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
1. Insert Delete GetRandom O(1)
Link
Problem: Design a data structure that supports insert, remove, and getRandom operations in average O(1) time.
Key Points:
Use a dynamic array to store elements for O(1) random access.
Pair it with a hash map to track element indices for O(1) insertion/deletion.
For removal, swap the target element with the last element in the array to avoid shifting.
Example:
Insert 1 → [1]. Insert 2 → [1,2]. Remove 1 → [2]. getRandom() returns 2.
Day 4 Q 2
2. Find Players With Zero or One Losses
Link
Problem: Given match outcomes as [winner, loser], return two lists: players with 0 losses and those with 1 loss, sorted in ascending order.
Key Approach:
Use a hash map to count losses for each player.
Track all players (including winners with 0 losses).
Filter and sort results based on loss counts (0 or 1).
Example:
Input: [[1,3],[2,1],[4,2],[5,2]]
Output: [[4,5], [1,3]]
(Players 4,5 never lost; 1,3 lost once)
Day 4 Q 3
3. Shuffle String
Link
Problem: Reconstruct a string using an index array. For s = "abc" and indices = [0,2,1], return "acb".
Approach:
Create a result array of the same length as s.
Place each character s[i] at result[indices[i]].
Convert the array to a string.
Example:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
LeetCode
Insert Delete GetRandom O(1) - LeetCode
Can you solve this real interview question? Insert Delete GetRandom O(1) - Implement the RandomizedSet class:
* RandomizedSet() Initializes the RandomizedSet object.
* bool insert(int val) Inserts an item val into the set if not present. Returns true if…
* RandomizedSet() Initializes the RandomizedSet object.
* bool insert(int val) Inserts an item val into the set if not present. Returns true if…
👍1
https://news.1rj.ru/str/+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
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
❤3👍1
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!
🗓 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!
LeetCode
Build Array from Permutation - LeetCode
Can you solve this real interview question? Build Array from Permutation - Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.
A zero-based permutation…
A zero-based permutation…
👍3
Leetcode with dani
Day 4 Q 1 1. Insert Delete GetRandom O(1) Link Problem: Design a data structure that supports insert, remove, and getRandom operations in average O(1) time. Key Points: Use a dynamic array to store elements for O(1) random access. Pair it with a hash map…
▎🌟 Day 4 Coding Challenges: Solutions Explanations 🌟
Welcome to Day 4 of our coding journey! Today, we tackle some exciting problems that challenge our data structure skills. Let’s dive in!
---
▎🏗 Q1: Insert Delete GetRandom O(1)
▎Problem Statement:
Design a data structure that supports insert, remove, and getRandom operations in average O(1) time.
▎💡 Solution:
To achieve O(1) time complexity for all operations, we can employ a clever combination of a dynamic array and a hash map:
1. Dynamic Array: Stores elements, allowing for O(1) random access.
2. Hash Map: Tracks the indices of elements for O(1) insertion and deletion.
3. Removal Strategy: Swap the target element with the last element to avoid shifting.
▎🔍 Python Implementation:
▎🚀 Example Usage:
---
▎🏆 Q2: Find Players With Zero or One Losses
▎Problem Statement:
Given match outcomes as
1. Players with 0 losses.
2. Players with exactly 1 loss.
▎💡 Solution:
We can efficiently solve this using:
• A hash map to count losses.
• A set to track all players.
▎🔍 Python Implementation:
▎🚀 Example Usage:
---
▎🔄 Q3: Shuffle String
▎Problem Statement:
Reconstruct a string using an index array. For
▎💡 Solution:
We create a result array of the same length as
▎🔍 Python Implementation:
▎🚀 Example Usage:
Welcome to Day 4 of our coding journey! Today, we tackle some exciting problems that challenge our data structure skills. Let’s dive in!
---
▎🏗 Q1: Insert Delete GetRandom O(1)
▎Problem Statement:
Design a data structure that supports insert, remove, and getRandom operations in average O(1) time.
▎💡 Solution:
To achieve O(1) time complexity for all operations, we can employ a clever combination of a dynamic array and a hash map:
1. Dynamic Array: Stores elements, allowing for O(1) random access.
2. Hash Map: Tracks the indices of elements for O(1) insertion and deletion.
3. Removal Strategy: Swap the target element with the last element to avoid shifting.
▎🔍 Python Implementation:
import random
class RandomizedSet:
def __init__(self):
self.array = [] # For O(1) random access
self.indices = {} # Maps elements to their indices
def insert(self, val: int) -> bool:
if val in self.indices:
return False # Element already exists
self.indices[val] = len(self.array)
self.array.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.indices:
return False # Element does not exist
index = self.indices[val]
last_element = self.array[-1]
# Swap and remove
self.array[index] = last_element
self.indices[last_element] = index
self.array.pop()
del self.indices[val]
return True
def getRandom(self) -> int:
return random.choice(self.array)
▎🚀 Example Usage:
randomizedSet = RandomizedSet()
print(randomizedSet.insert(1)) # True
print(randomizedSet.remove(2)) # False
print(randomizedSet.insert(2)) # True
print(randomizedSet.getRandom()) # Either 1 or 2
print(randomizedSet.remove(1)) # True
print(randomizedSet.insert(2)) # False
print(randomizedSet.getRandom()) # 2
---
▎🏆 Q2: Find Players With Zero or One Losses
▎Problem Statement:
Given match outcomes as
[[winner, loser]], return two sorted lists:1. Players with 0 losses.
2. Players with exactly 1 loss.
▎💡 Solution:
We can efficiently solve this using:
• A hash map to count losses.
• A set to track all players.
▎🔍 Python Implementation:
def findWinners(matches):
loss_counts = {}
players = set()
for winner, loser in matches:
players.add(winner)
players.add(loser)
loss_counts[loser] = loss_counts.get(loser, 0) + 1
zero_losses = sorted([player for player in players if loss_counts.get(player, 0) == 0])
one_loss = sorted([player for player in players if loss_counts.get(player, 0) == 1])
return [zero_losses, one_loss]
▎🚀 Example Usage:
matches = [[1, 3], [2, 1], [4, 2], [5, 2]]
result = findWinners(matches)
print(result) # Output: [[4, 5], [1, 3]]
---
▎🔄 Q3: Shuffle String
▎Problem Statement:
Reconstruct a string using an index array. For
s = "abc" and indices = [0, 2, 1], return "acb".▎💡 Solution:
We create a result array of the same length as
s and place each character at its corresponding index from the indices array.▎🔍 Python Implementation:
def restoreString(s, indices):
result = [''] * len(s)
for i, idx in enumerate(indices):
result[idx] = s[i]
return ''.join(result)
▎🚀 Example Usage:
s = "codeleet"
indices = [4, 5, 6, 7, 0, 2, 1, 3]
result = restoreString(s, indices)
print(result) # Output: "leetcode"
👍5
Hey Coders! 👋
Today, let's dive into a classic challenge: 3Sum! 🎯
▎Problem Statement:
Given an integer array
• i ≠ j ≠ k
• nums[i] + nums[j] + nums[k] = 0
▎Example:
Input:
Output:
Explanation:
• The triplet
• The triplet
▎Constraints:
• 3 ≤ nums.length ≤ 3000
• -10⁵ ≤ nums[i] ≤ 10⁵
▎Approach:
1. Sorting: The array is sorted to make it easier to find the triplets.
2. Fixed Pointer: The outer loop fixes the first element of the triplet.
3. Two-pointer Technique: The inner loop uses two pointers to find the other two elements that sum up to zero with the fixed element.
4. Avoiding Duplicates: The code skips over duplicate elements to ensure that only unique triplets are added to the result.
▎Complexity Analysis:
• Time Complexity: O(n²)
• Space Complexity: O(1) (excluding the space required for the output)
▎Challenge:
Can you solve it with a time complexity of O(n²) ? 🤔
▎Hint:
Think about how you can reduce the problem to a two-sum problem after fixing one element.
▎Solution Code (Python):
Today, let's dive into a classic challenge: 3Sum! 🎯
▎Problem Statement:
Given an integer array
nums, your task is to return all the unique triplets [nums[i], nums[j], nums[k]] such that:• i ≠ j ≠ k
• nums[i] + nums[j] + nums[k] = 0
▎Example:
Input:
nums = [-1, 0, 1, 2, -1, -4] Output:
[[-1, -1, 2], [-1, 0, 1]] Explanation:
• The triplet
[-1, 0, 1] sums to zero.• The triplet
[-1, -1, 2] also sums to zero.▎Constraints:
• 3 ≤ nums.length ≤ 3000
• -10⁵ ≤ nums[i] ≤ 10⁵
▎Approach:
1. Sorting: The array is sorted to make it easier to find the triplets.
2. Fixed Pointer: The outer loop fixes the first element of the triplet.
3. Two-pointer Technique: The inner loop uses two pointers to find the other two elements that sum up to zero with the fixed element.
4. Avoiding Duplicates: The code skips over duplicate elements to ensure that only unique triplets are added to the result.
▎Complexity Analysis:
• Time Complexity: O(n²)
• Space Complexity: O(1) (excluding the space required for the output)
▎Challenge:
Can you solve it with a time complexity of O(n²) ? 🤔
▎Hint:
Think about how you can reduce the problem to a two-sum problem after fixing one element.
▎Solution Code (Python):
def threeSum(nums):
nums.sort()
result = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
result.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
return result
👍3
people = {
'Alice': 30,
'Bob': 25,
'Charlie': 35,
'David': 20,
'Eve': 28
}Sorting by Age:
You can sort the dictionary using the sorted() function combined with a lambda function. Here’s the code:
# Sort the dictionary by age
sorted_by_age = dict(sorted(people.items(), key=lambda item: item[1]))
# Display the sorted dictionary