Leetcode with dani
Maximise the number of toys that can be purchased with amount K Given an array consisting of the cost of toys. Given an integer K depicting the amount of money available to purchase toys. Write a program to find the maximum number of toys one can buy with…
how many of u can solve this problem with in 45min. share ur answer
🤝2👍1
Leetcode with dani
Maximise the number of toys that can be purchased with amount K Given an array consisting of the cost of toys. Given an integer K depicting the amount of money available to purchase toys. Write a program to find the maximum number of toys one can buy with…
answer:
def max_toys(cost, K):
cost.sort()
count = 0
total_cost = 0
for price in cost:
if total_cost + price <= K:
total_cost += price
count += 1
else:
break
return count
N = 10
K = 50
cost = [1, 12, 5, 111, 200, 1000, 10, 9, 12, 15]
print(max_toys(cost, K)) # Output: 6
i could not post in the previous days for some reason, and I apologize for that. I will start posting from now on
👍4☃1
Hey everyone! 🌟 We're on the lookout for a admin to help out with our programming channel! If you know at least one programming language and love sharing knowledge, we’d love to have you on board. We’re looking for someone who can post regularly and connect with our awesome community. If you’re interested, drop us a message! 😊
👍4
Count distinct elements in every window of size k
Given an array of size N and an integer K, return the count of distinct numbers in all windows of size K.
Examples:
Input: arr[] = {1, 2, 1, 3, 4, 2, 3}, K = 4
Output: 3 4 4 3
Explanation:
First window is {1, 2, 1, 3}, count of distinct numbers is 3
Second window is {2, 1, 3, 4} count of distinct numbers is 4
Third window is {1, 3, 4, 2} count of distinct numbers is 4
Fourth window is {3, 4, 2, 3} count of distinct numbers is 3
Input: arr[] = {1, 2, 4, 4}, K = 2
Output: 2 2 1
Explanation:
First window is {1, 2}, count of distinct numbers is 2
First window is {2, 4}, count of distinct numbers is 2
First window is {4, 4}, count of distinct numbers is 1
Given an array of size N and an integer K, return the count of distinct numbers in all windows of size K.
Examples:
Input: arr[] = {1, 2, 1, 3, 4, 2, 3}, K = 4
Output: 3 4 4 3
Explanation:
First window is {1, 2, 1, 3}, count of distinct numbers is 3
Second window is {2, 1, 3, 4} count of distinct numbers is 4
Third window is {1, 3, 4, 2} count of distinct numbers is 4
Fourth window is {3, 4, 2, 3} count of distinct numbers is 3
Input: arr[] = {1, 2, 4, 4}, K = 2
Output: 2 2 1
Explanation:
First window is {1, 2}, count of distinct numbers is 2
First window is {2, 4}, count of distinct numbers is 2
First window is {4, 4}, count of distinct numbers is 1
👍2
Question: Find the majority element in an array, which is defined as the element that appears more than n/2 times. Use an efficient algorithm to solve this in linear time O(n) and constant space O(1).
🌟 Finding the Majority Element in an Array 🌟
Have you ever wondered how to identify the element that appears more than half the time in an array? 🤔 Let’s dive into a clever algorithm that does just that: The Boyer-Moore Voting Algorithm! 🗳
▎🔍 How It Works:
1. Initialization:
- Start with two variables:
-
-
2. Candidate Selection:
- Loop through each element in the array:
- If
- If the current element matches the
- If it doesn’t match, decrease
3. Verification (Optional):
- After the first pass, you can run through the array again to confirm that your
▎📈 Why Use This Algorithm?
- Time Complexity: \\( O(n) \\) – Efficiently processes the array in linear time!
- Space Complexity: \\( O(1) \\) – Uses only a constant amount of extra space!
▎🚀 Example:
Consider the array:
- The algorithm will help you find that 2 is the majority element! 🎉
This method is not only efficient but also elegant.
Have you ever wondered how to identify the element that appears more than half the time in an array? 🤔 Let’s dive into a clever algorithm that does just that: The Boyer-Moore Voting Algorithm! 🗳
▎🔍 How It Works:
1. Initialization:
- Start with two variables:
-
candidate = None-
count = 02. Candidate Selection:
- Loop through each element in the array:
- If
count is 0, set the current element as the new candidate.- If the current element matches the
candidate, increase count.- If it doesn’t match, decrease
count.3. Verification (Optional):
- After the first pass, you can run through the array again to confirm that your
candidate is indeed the majority element!▎📈 Why Use This Algorithm?
- Time Complexity: \\( O(n) \\) – Efficiently processes the array in linear time!
- Space Complexity: \\( O(1) \\) – Uses only a constant amount of extra space!
▎🚀 Example:
Consider the array:
[2, 2, 1, 1, 1, 2, 2]. - The algorithm will help you find that 2 is the majority element! 🎉
This method is not only efficient but also elegant.
👍4
👍2
any one who wants to sell dogs talks to me https://news.1rj.ru/str/askeber i will buy with good price
👍2☃1
Python Tips: Two Confusing methods.
strip() and split() Methods
strip(): This method removes any leading or trailing spaces or specific characters from a string.
split(): This method splits a string into a list of substrings based on a specified separator.
To see
strip() and split() Methods
strip(): This method removes any leading or trailing spaces or specific characters from a string.
text = " Hello, World! "
print(text.strip()) # Output: "Hello, World!"
split(): This method splits a string into a list of substrings based on a specified separator.
data = "apple,banana,cherry"
print(data.split(',')) # Output: ['apple', 'banana', 'cherry']
To see
split() in action, check out the [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) problem on LeetCode, where you'll split version strings using a dot (.) as the separator.LeetCode
Compare Version Numbers - LeetCode
Can you solve this real interview question? Compare Version Numbers - Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring…
⚡3👍1
1. 3Sum (Hard)
Denoscription: Given an integer array
- Example: For input
Denoscription: Given an integer array
nums, return all unique triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. - Example: For input
nums = [-1,0,1,2,-1,-4], the output should be [[-1,-1,2],[-1,0,1]].2. Minimum Window Substring (Hard)
Denoscription: Given two strings
- Example: For
Denoscription: Given two strings
s and t, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return an empty string.- Example: For
s = "ADOBECODEBANC" and t = "ABC", the minimum window is "BANC".3. Fruit Into Baskets (Easy)
Denoscription: You are visiting a farm and have a basket that can hold at most two types of fruits. You want to maximize the number of fruits you collect. Given an array of integers representing the types of fruits in a row, find the maximum number of fruits you can collect in one basket.
- Example: For input
Denoscription: You are visiting a farm and have a basket that can hold at most two types of fruits. You want to maximize the number of fruits you collect. Given an array of integers representing the types of fruits in a row, find the maximum number of fruits you can collect in one basket.
- Example: For input
[1,2,1], the maximum number of fruits collected is 3.
Leetcode with dani
3. Fruit Into Baskets (Easy) Denoscription: You are visiting a farm and have a basket that can hold at most two types of fruits. You want to maximize the number of fruits you collect. Given an array of integers representing the types of fruits in a row, find…
1. 3Sum (Hard)
Answer: The solution involves sorting the array and using a two-pointer technique to find triplets that sum to zero. The time complexity is O(n^2).
2. Minimum Window Substring (Hard)
Answer: Use a sliding window approach to maintain a count of characters and expand/shrink the window until the minimum substring is found. The time complexity is O(n).
3. Fruit Into Baskets (Easy)
Answer: Utilize a sliding window to track the types of fruits and their counts, ensuring you only have two types at any time. The maximum length of the window gives the answer. The time complexity is O(n).
Answer: The solution involves sorting the array and using a two-pointer technique to find triplets that sum to zero. The time complexity is O(n^2).
2. Minimum Window Substring (Hard)
Answer: Use a sliding window approach to maintain a count of characters and expand/shrink the window until the minimum substring is found. The time complexity is O(n).
3. Fruit Into Baskets (Easy)
Answer: Utilize a sliding window to track the types of fruits and their counts, ensuring you only have two types at any time. The maximum length of the window gives the answer. The time complexity is O(n).
Leetcode with dani
1. 3Sum (Hard) Answer: The solution involves sorting the array and using a two-pointer technique to find triplets that sum to zero. The time complexity is O(n^2). 2. Minimum Window Substring (Hard) Answer: Use a sliding window approach to maintain…
▎1. 3Sum
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
▎2. Minimum Window Substring
from collections import Counter
def minWindow(s, t):
if not t or not s:
return ""
dict_t = Counter(t)
required = len(dict_t)
l, r = 0, 0
formed = 0
window_counts = {}
ans = float("inf"), None, None
while r < len(s):
character = s[r]
window_counts[character] = window_counts.get(character, 0) + 1
if character in dict_t and window_counts[character] == dict_t[character]:
formed += 1
while l <= r and formed == required:
character = s[l]
if r - l + 1 < ans[0]:
ans = (r - l + 1, l, r)
window_counts[character] -= 1
if character in dict_t and window_counts[character] < dict_t[character]:
formed -= 1
l += 1
r += 1
return "" if ans[0] == float("inf") else s[ans[1]: ans[2] + 1]
▎3. Fruit Into Baskets
def totalFruits(fruits):
left, right = 0, 0
basket = {}
max_fruits = 0
while right < len(fruits):
basket[fruits[right]] = basket.get(fruits[right], 0) + 1
while len(basket) > 2:
basket[fruits[left]] -= 1
if basket[fruits[left]] == 0:
del basket[fruits[left]]
left += 1
max_fruits = max(max_fruits, right - left + 1)
right += 1
return max_fruits
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
▎2. Minimum Window Substring
from collections import Counter
if not t or not s:
return ""
dict_t = Counter(t)
required = len(dict_t)
l, r = 0, 0
formed = 0
window_counts = {}
ans = float("inf"), None, None
while r < len(s):
character = s[r]
window_counts[character] = window_counts.get(character, 0) + 1
if character in dict_t and window_counts[character] == dict_t[character]:
formed += 1
while l <= r and formed == required:
character = s[l]
if r - l + 1 < ans[0]:
ans = (r - l + 1, l, r)
window_counts[character] -= 1
if character in dict_t and window_counts[character] < dict_t[character]:
formed -= 1
l += 1
r += 1
return "" if ans[0] == float("inf") else s[ans[1]: ans[2] + 1]
▎3. Fruit Into Baskets
left, right = 0, 0
basket = {}
max_fruits = 0
while right < len(fruits):
basket[fruits[right]] = basket.get(fruits[right], 0) + 1
while len(basket) > 2:
basket[fruits[left]] -= 1
if basket[fruits[left]] == 0:
del basket[fruits[left]]
left += 1
max_fruits = max(max_fruits, right - left + 1)
right += 1
return max_fruits
👍8
🚀 Explore Palindrome Challenges with the Two-Pointer Technique!🧑💻
Palindromes are a classic problem type that can be efficiently tackled using the two-pointer technique. Whether you're just starting or looking to refine your skills, these questions will help you master this approach. Check out these palindrome problems:
1.Valid Palindrome
🔗 [Link](https://leetcode.com/problems/valid-palindrome/)
Denoscription: Determine if a string is a palindrome, considering only alphanumeric characters and ignoring cases.
2. Valid Palindrome II
🔗 [Link](https://leetcode.com/problems/valid-palindrome-ii/)
Denoscription: Can the string become a palindrome by deleting just one character?
3. Palindrome Linked List
🔗 [Link](https://leetcode.com/problems/palindrome-linked-list/)
Denoscription: Check if a singly linked list is a palindrome using two pointers and a bit of list manipulation.
4. Longest Palindromic Substring
🔗 [Link](https://leetcode.com/problems/longest-palindromic-substring/)
Denoscription: Find the longest palindromic substring in a given string, with pointers expanding from each character.
5. Palindromic Substrings
🔗 [Link](https://leetcode.com/problems/palindromic-substrings/)
Denoscription: Count how many palindromic substrings are present in the string using two pointers.
6. Shortest Palindrome.
🔗 [Link](https://leetcode.com/problems/shortest-palindrome/)
Denoscription: Find the shortest palindrome by adding characters to the start of the string.
7. Palindrome Partitioning
🔗 [Link](https://leetcode.com/problems/palindrome-partitioning/)
Denoscription: Partition a string into all possible palindromic substrings.
8. Palindrome Pairs
🔗 [Link](https://leetcode.com/problems/palindrome-pairs/)
Denoscription: Given a list of words, find all pairs of distinct indices that form palindromes.
Ready to boost your problem-solving skills? Dive into these problems, practice your two-pointer technique, and ace those palindrome challenges! 💥
Happy Coding! 💻💡
Palindromes are a classic problem type that can be efficiently tackled using the two-pointer technique. Whether you're just starting or looking to refine your skills, these questions will help you master this approach. Check out these palindrome problems:
1.Valid Palindrome
🔗 [Link](https://leetcode.com/problems/valid-palindrome/)
Denoscription: Determine if a string is a palindrome, considering only alphanumeric characters and ignoring cases.
2. Valid Palindrome II
🔗 [Link](https://leetcode.com/problems/valid-palindrome-ii/)
Denoscription: Can the string become a palindrome by deleting just one character?
3. Palindrome Linked List
🔗 [Link](https://leetcode.com/problems/palindrome-linked-list/)
Denoscription: Check if a singly linked list is a palindrome using two pointers and a bit of list manipulation.
4. Longest Palindromic Substring
🔗 [Link](https://leetcode.com/problems/longest-palindromic-substring/)
Denoscription: Find the longest palindromic substring in a given string, with pointers expanding from each character.
5. Palindromic Substrings
🔗 [Link](https://leetcode.com/problems/palindromic-substrings/)
Denoscription: Count how many palindromic substrings are present in the string using two pointers.
6. Shortest Palindrome.
🔗 [Link](https://leetcode.com/problems/shortest-palindrome/)
Denoscription: Find the shortest palindrome by adding characters to the start of the string.
7. Palindrome Partitioning
🔗 [Link](https://leetcode.com/problems/palindrome-partitioning/)
Denoscription: Partition a string into all possible palindromic substrings.
8. Palindrome Pairs
🔗 [Link](https://leetcode.com/problems/palindrome-pairs/)
Denoscription: Given a list of words, find all pairs of distinct indices that form palindromes.
Ready to boost your problem-solving skills? Dive into these problems, practice your two-pointer technique, and ace those palindrome challenges! 💥
Happy Coding! 💻💡
LeetCode
Valid Palindrome - LeetCode
Can you solve this real interview question? Valid Palindrome - A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters…
👍4
#Q20 #leet_codeQ15 Medium noscript. 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 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.
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.
👍4