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
What type of content would you like to see more on this channel?
Anonymous Poll
29%
A) 📚 Coding resources (books, articles, and tips)
45%
B) 💻 Daily LeetCode-style questions with solutions
3%
C) 🗳 Polls Q-A on coding-related topics
13%
D) 🏆 Coding challenges with leaderboards
10%
E) 🎥 Video explanation
👍2
Leetcode with dani
What type of content would you like to see more on this channel?
I’d be happy if you suggest any specific topic you want to be covered
🌟 Day 6 Challenge: Integer to Roman 🌟
🔗 Problem Link: Integer to Roman
📝 Problem Statement:
Roman numerals are fascinating representations of numbers, constructed using the following symbols:
• I (1), V (5), X (10), L (50), C (100), D (500), M (1000).
To form Roman numerals, we combine these symbols from largest to smallest, using subtraction for specific cases like 4 (IV) and 9 (IX). Your task is to convert any integer between 1 and 3999 into its Roman numeral equivalent!
✨ Examples:
• Input:
• Input:
• Input:
🔍 Approach: Greedy Algorithm with Predefined Values
1. Create a list of pairs (value, symbol) sorted in descending order, including subtractive combinations (e.g., 4, 9, 40).
2. Iterate through this list, subtracting the largest possible value from
💻 Solution Code:
📖 Explanation with Example (1994):
1. Subtract 1000 → 'M', remaining
2. Subtract 900 → 'CM', remaining
3. Subtract 90 → 'XC', remaining
4. Subtract 4 → 'IV'. Result:
⏳ Complexity Analysis:
• Time Complexity: O(1) (fixed number of iterations over 13 symbols).
• Space Complexity: O(1) (output string has a maximum fixed length).
💡 Test Yourself!
Can you solve this problem efficiently?
🔗 Problem Link: Integer to Roman
📝 Problem Statement:
Roman numerals are fascinating representations of numbers, constructed using the following symbols:
• I (1), V (5), X (10), L (50), C (100), D (500), M (1000).
To form Roman numerals, we combine these symbols from largest to smallest, using subtraction for specific cases like 4 (IV) and 9 (IX). Your task is to convert any integer between 1 and 3999 into its Roman numeral equivalent!
✨ Examples:
• Input:
num = 3 → Output: "III"• Input:
num = 58 → Output: "LVIII" (L = 50, V = 5, III = 3)• Input:
num = 1994 → Output: "MCMXCIV" (M = 1000, CM = 900, XC = 90, IV = 4)🔍 Approach: Greedy Algorithm with Predefined Values
1. Create a list of pairs (value, symbol) sorted in descending order, including subtractive combinations (e.g., 4, 9, 40).
2. Iterate through this list, subtracting the largest possible value from
num, and appending the corresponding symbol to your result.💻 Solution Code:
def intToRoman(num: int) -> str:
val_sym = [
(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
]
res = []
for value, symbol in val_sym:
while num >= value:
res.append(symbol)
num -= value
if num == 0:
break
return ''.join(res)
📖 Explanation with Example (1994):
1. Subtract 1000 → 'M', remaining
num = 994.2. Subtract 900 → 'CM', remaining
num = 94.3. Subtract 90 → 'XC', remaining
num = 4.4. Subtract 4 → 'IV'. Result:
"MCMXCIV".⏳ Complexity Analysis:
• Time Complexity: O(1) (fixed number of iterations over 13 symbols).
• Space Complexity: O(1) (output string has a maximum fixed length).
💡 Test Yourself!
Can you solve this problem efficiently?
👍2
Day 6 question 2
Difficulty : Hard
▎LeetCode Question: Minimum Window Substring
▎Problem Statement:
Given two strings
▎Example:
• Input:
• Output:
▎Constraints:
•
•
▎Solution Explanation:
1. Initialization: Create dictionaries to store the frequency of characters in string
2. Sliding Window: Expand the window by moving the right pointer. Update the
3. Contraction: When the window contains all required characters, contract the window by moving the left pointer. Update the
4. Result: Return the minimum window substring. If no valid window is found, return an empty string.
▎Python Code:
Here’s the solution using the sliding window technique:
▎Complexity Analysis:
• Time Complexity: O(N + M), where N is the length of string
• Space Complexity: O(M), for storing the frequency of characters in
Difficulty : Hard
▎LeetCode Question: Minimum Window Substring
▎Problem Statement:
Given two strings
s and t, find the minimum window in s which will contain all the characters in t. If there is no such window in s that covers all characters in t, return the empty string "".▎Example:
• Input:
s = "ADOBECODEBANC", t = "ABC"• Output:
"BANC"▎Constraints:
•
1 <= s.length, t.length <= 10^5•
s and t consist of uppercase and lowercase English letters.▎Solution Explanation:
1. Initialization: Create dictionaries to store the frequency of characters in string
t and the current window. Use variables to track the number of unique characters required and formed in the window.2. Sliding Window: Expand the window by moving the right pointer. Update the
window_counts and formed variables.3. Contraction: When the window contains all required characters, contract the window by moving the left pointer. Update the
window_counts and formed variables. While contracting, check if the current window is smaller than the minimum window found so far.4. Result: Return the minimum window substring. If no valid window is found, return an empty string.
▎Python Code:
Here’s the solution using the sliding window technique:
def minWindow(s: str, t: str) -> str:
if not t or not s:
return ""
dict_t = {}
for char in t:
dict_t[char] = dict_t.get(char, 0) + 1
required = len(dict_t)
formed = 0
window_counts = {}
left, right = 0, 0
ans = float('inf'), None, None
while right < len(s):
character = s[right]
window_counts[character] = window_counts.get(character, 0) + 1
if character in dict_t and window_counts[character] == dict_t[character]:
formed += 1
while left <= right and formed == required:
character = s[left]
if right - left + 1 < ans[0]:
ans = (right - left + 1, left, right)
window_counts[character] -= 1
if character in dict_t and window_counts[character] < dict_t[character]:
formed -= 1
left += 1
right += 1
return "" if ans[0] == float('inf') else s[ans[1]: ans[2] + 1]
▎Complexity Analysis:
• Time Complexity: O(N + M), where N is the length of string
s and M is the length of string t.• Space Complexity: O(M), for storing the frequency of characters in
t.👍2
Leetcode with dani
Day 6 question 2 Difficulty : Hard ▎LeetCode Question: Minimum Window Substring ▎Problem Statement: Given two strings s and t, find the minimum window in s which will contain all the characters in t. If there is no such window in s that covers all characters…
I post questions for all of you, so please choose a question based on your experience. Make sure to understand the sliding window technique before attempting to solve this question, as it is a difficult one. This question is intended for those who understand the sliding window concept and have practiced previously
Sure! Here’s the formatted response for the Minimum Average Difference problem, similar to your example:
---
🌟 Day 6 Challenge: Q 3 Minimum Average Difference 🌟 Medium
🔗 Problem Link: Minimum Average Difference
📝 Problem Statement:
You are given a non-negative integer array
✨ Examples:
• Input:
• Input:
• Input:
🔍 Approach: Prefix Sum Calculation
1. Calculate the total sum of the array to help compute right averages.
2. Iterate through each index, maintaining a running sum (left sum) of elements from the start.
3. For each index, compute the left average and right average based on the sums.
4. Calculate the absolute difference between these two averages and track the minimum difference and corresponding index.
💻 Solution Code:
📖 Explanation with Example (1994):
1. For each index, keep track of the left sum and calculate the left average.
2. Compute the right average using the total sum minus the left sum.
3. Calculate the absolute difference between left and right averages.
4. Track the smallest difference and its corresponding index.
⏳ Complexity Analysis:
• Time Complexity: O(n) (single pass through the array).
• Space Complexity: O(1) (only a few variables used for calculation).
💡 Test Yourself!
Can you solve this problem efficiently? Dive in and share your solution with us! Let's see your coding skills shine! 🌟
---
🌟 Day 6 Challenge: Q 3 Minimum Average Difference 🌟 Medium
🔗 Problem Link: Minimum Average Difference
📝 Problem Statement:
You are given a non-negative integer array
nums. Your task is to find the index i such that the absolute difference between the average of the first i + 1 elements and the average of the last n - i - 1 elements is minimized. If there are multiple indices with the same minimum difference, return the smallest index.✨ Examples:
• Input:
nums = [2, 5, 3, 9, 5, 3] → Output: 3• Input:
nums = [0] → Output: 0• Input:
nums = [1, 2, 3, 4, 5, 6] → Output: 2🔍 Approach: Prefix Sum Calculation
1. Calculate the total sum of the array to help compute right averages.
2. Iterate through each index, maintaining a running sum (left sum) of elements from the start.
3. For each index, compute the left average and right average based on the sums.
4. Calculate the absolute difference between these two averages and track the minimum difference and corresponding index.
💻 Solution Code:
def minimumAverageDifference(nums):
n = len(nums)
total_sum = sum(nums) # Calculate the total sum of the array
left_sum = 0 # Initialize left sum
min_diff = float('inf') # Initialize minimum difference to infinity
min_index = -1 # Initialize minimum index
for i in range(n):
left_sum += nums[i] # Update left sum with the current element
# Calculate left average
left_avg = left_sum // (i + 1)
# Calculate right average
if i < n - 1:
right_avg = (total_sum - left_sum) // (n - i - 1)
else:
right_avg = 0 # If it's the last element, right average is 0
# Calculate absolute difference
diff = abs(left_avg - right_avg)
# Update minimum difference and index if a new minimum is found
if diff < min_diff:
min_diff = diff
min_index = i
return min_index
# Example usage:
print(minimumAverageDifference([2, 5, 3, 9, 5, 3])) # Output: 3
print(minimumAverageDifference([0])) # Output: 0
📖 Explanation with Example (1994):
1. For each index, keep track of the left sum and calculate the left average.
2. Compute the right average using the total sum minus the left sum.
3. Calculate the absolute difference between left and right averages.
4. Track the smallest difference and its corresponding index.
⏳ Complexity Analysis:
• Time Complexity: O(n) (single pass through the array).
• Space Complexity: O(1) (only a few variables used for calculation).
💡 Test Yourself!
Can you solve this problem efficiently? Dive in and share your solution with us! Let's see your coding skills shine! 🌟