From 2086d5edcde18dcc14f2546eb9ccabe1424c1b16 Mon Sep 17 00:00:00 2001 From: Harshil Date: Mon, 14 Oct 2024 21:10:53 +0530 Subject: [PATCH 01/19] Create 2530. Maximal Score After Applying K Operations Added daily problem of 14-10-2024. --- ... Maximal Score After Applying K Operations | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 2530. Maximal Score After Applying K Operations diff --git a/2530. Maximal Score After Applying K Operations b/2530. Maximal Score After Applying K Operations new file mode 100644 index 0000000..9faf043 --- /dev/null +++ b/2530. Maximal Score After Applying K Operations @@ -0,0 +1,48 @@ +You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0. + +In one operation: + +choose an index i such that 0 <= i < nums.length, +increase your score by nums[i], and +replace nums[i] with ceil(nums[i] / 3). +Return the maximum possible score you can attain after applying exactly k operations. + +The ceiling function ceil(val) is the least integer greater than or equal to val. + + + +Example 1: + +Input: nums = [10,10,10,10,10], k = 5 +Output: 50 +Explanation: Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50. +Example 2: + +Input: nums = [1,10,3,3,3], k = 3 +Output: 17 +Explanation: You can do the following operations: +Operation 1: Select i = 1, so nums becomes [1,4,3,3,3]. Your score increases by 10. +Operation 2: Select i = 1, so nums becomes [1,2,3,3,3]. Your score increases by 4. +Operation 3: Select i = 2, so nums becomes [1,1,1,3,3]. Your score increases by 3. +The final score is 10 + 4 + 3 = 17. + + +Constraints: + +1 <= nums.length, k <= 105 +1 <= nums[i] <= 109 + + +Solution: +class Solution: + def maxKelements(self, nums: List[int], k: int) -> int: + nums = [-i for i in nums] + heapify(nums) + + res = 0 + for i in range(k): + t = -heappop(nums) + res += t + heappush(nums, -ceil(t / 3)) + + return res From 336349c8fab417b36f8805e192eb33e3ff0ef5c2 Mon Sep 17 00:00:00 2001 From: Harshil Date: Mon, 14 Oct 2024 21:34:14 +0530 Subject: [PATCH 02/19] Create 632. Smallest Range Covering Elements from K Lists Smallest Range Covering Elements from K Lists #hacktoberfest #hacktoberfest-accepted #hacktoberfest2024 --- ...llest Range Covering Elements from K Lists | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 632. Smallest Range Covering Elements from K Lists diff --git a/632. Smallest Range Covering Elements from K Lists b/632. Smallest Range Covering Elements from K Lists new file mode 100644 index 0000000..1ea0954 --- /dev/null +++ b/632. Smallest Range Covering Elements from K Lists @@ -0,0 +1,63 @@ +Problem Statement: + +You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. + +We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c. + + + +Example 1: + +Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] +Output: [20,24] +Explanation: +List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. +List 2: [0, 9, 12, 20], 20 is in range [20,24]. +List 3: [5, 18, 22, 30], 22 is in range [20,24]. +Example 2: + +Input: nums = [[1,2,3],[1,2,3],[1,2,3]] +Output: [1,1] + + +Constraints: + +nums.length == k +1 <= k <= 3500 +1 <= nums[i].length <= 50 +-105 <= nums[i][j] <= 105 +nums[i] is sorted in non-decreasing order. + + +Solution: +from typing import List +import heapq + + +class Solution: + def smallestRange(self, nums: List[List[int]]) -> List[int]: + heap = [(row[0], i, 0) for i, row in enumerate(nums)] + heapq.heapify(heap) + ans = [-10**9, 10**9] + right = max(row[0] for row in nums) + while heap: + left, row, col = heapq.heappop(heap) + if right - left < ans[1] - ans[0]: + ans = [left, right] + if col + 1 == len(nums[row]): + return ans + right = max(right, nums[row][col + 1]) + heapq.heappush(heap, (nums[row][col + 1], row, col + 1)) + +# Tests: +if __name__ == '__main__': + s = Solution() + # test case 1 + output1 = s.smallestRange([[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]) + expected_output1 = [20,24] + assert output1 == expected_output1, f"Expected {expected_output1}, but got {output1}" + # test case 2 + output2 = s.smallestRange([[1,2,3],[1,2,3],[1,2,3]]) + expected_output2 = [1,1] + assert output2 == expected_output2, f"Expected {expected_output2}, but got {output2}" + print("All tests passed!") From 223b07bd7617cb2cfc935e4ec061daa7c86fdcbd Mon Sep 17 00:00:00 2001 From: Ankit Kumar Date: Wed, 23 Oct 2024 11:27:34 +0530 Subject: [PATCH 03/19] Create substringWithConcatenationOfAllWorldsLeetcode30.java Create substringWithConcatenationOfAllWorldsLeetcode30.java --- ...ithConcatenationOfAllWorldsLeetcode30.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 substringWithConcatenationOfAllWorldsLeetcode30.java diff --git a/substringWithConcatenationOfAllWorldsLeetcode30.java b/substringWithConcatenationOfAllWorldsLeetcode30.java new file mode 100644 index 0000000..51aea84 --- /dev/null +++ b/substringWithConcatenationOfAllWorldsLeetcode30.java @@ -0,0 +1,33 @@ +class Solution { + public List findSubstring(String s, String[] words) { + List ans = new ArrayList<>(); + int n = s.length(); + int m = words.length; + int w = words[0].length(); + + HashMap map = new HashMap<>(); + for(String x : words) + map.put(x, map.getOrDefault(x,0)+1); + + for(int i=0; i temp = new HashMap<>(); + int count = 0; + for(int j=i,k=i; j+w <= n; j=j+w){ + String word = s.substring(j,j+w); + temp.put(word,temp.getOrDefault(word,0)+1); + count++; + + if(count==m){ + if(map.equals(temp)){ + ans.add(k); + } + String remove = s.substring(k,k+w); + temp.computeIfPresent(remove, (a, b) -> (b > 1) ? b - 1 : null); + count--; + k=k+w; + } + } + } + return ans; + } +} From ccd0510072ce611464ace8b2611bb82fe5c1d6b4 Mon Sep 17 00:00:00 2001 From: Ankit Kumar Date: Wed, 23 Oct 2024 11:31:53 +0530 Subject: [PATCH 04/19] Create splitAStringIntoNumberOfUniqueSubstrings.java Create splitAStringIntoNumberOfUniqueSubstrings.java --- splitAStringIntoNumberOfUniqueSubstrings.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 splitAStringIntoNumberOfUniqueSubstrings.java diff --git a/splitAStringIntoNumberOfUniqueSubstrings.java b/splitAStringIntoNumberOfUniqueSubstrings.java new file mode 100644 index 0000000..33bb0a6 --- /dev/null +++ b/splitAStringIntoNumberOfUniqueSubstrings.java @@ -0,0 +1,20 @@ +class Solution { + public int maxUniqueSplit(String s) { + return backtrack(0, s, new HashSet<>()); + } + private int backtrack(int start, String s, HashSet seen) { + if (start == s.length()) { + return 0; + } + int maxSplits = 0; + for (int end = start + 1; end <= s.length(); end++) { + String substring = s.substring(start, end); + if (!seen.contains(substring)) { + seen.add(substring); + maxSplits = Math.max(maxSplits, 1 + backtrack(end, s, seen)); + seen.remove(substring); + } + } + return maxSplits; + } +} From bf7948cea52943818d52d36938c3ada79fad0a0a Mon Sep 17 00:00:00 2001 From: Nilakshi13 Date: Mon, 28 Oct 2024 12:57:46 +0530 Subject: [PATCH 05/19] Added GreddyAlgoProblems --- .../BuyTwoChocolates.py | 6 +-- GreedyAlgoProblems/Jump_Game_45.java | 43 +++++++++++++++++++ GreedyAlgoProblems/Jump_Game_55.java | 35 +++++++++++++++ 3 files changed, 81 insertions(+), 3 deletions(-) rename BuyTwoChocolates(20thDec23) => GreedyAlgoProblems/BuyTwoChocolates.py (96%) create mode 100644 GreedyAlgoProblems/Jump_Game_45.java create mode 100644 GreedyAlgoProblems/Jump_Game_55.java diff --git a/BuyTwoChocolates(20thDec23) b/GreedyAlgoProblems/BuyTwoChocolates.py similarity index 96% rename from BuyTwoChocolates(20thDec23) rename to GreedyAlgoProblems/BuyTwoChocolates.py index 1a5b4c8..57133cb 100644 --- a/BuyTwoChocolates(20thDec23) +++ b/GreedyAlgoProblems/BuyTwoChocolates.py @@ -1,4 +1,5 @@ -# Here is the solution in Python. +""" +Difficulty Level - Easy You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money. You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative. @@ -17,8 +18,7 @@ 2 <= prices.length <= 50 1 <= prices[i] <= 100 1 <= money <= 100 - -SOLUTION: +""" class Solution: def buyChoco(self, prices: List[int], money: int) -> int: ans=money-sum(sorted(prices)[:2]) diff --git a/GreedyAlgoProblems/Jump_Game_45.java b/GreedyAlgoProblems/Jump_Game_45.java new file mode 100644 index 0000000..cf04777 --- /dev/null +++ b/GreedyAlgoProblems/Jump_Game_45.java @@ -0,0 +1,43 @@ +/* +Difficulty - Medium +Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where: + +0 <= j <= nums[i] and +i + j < n +Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1]. + +Example 1: + +Input: nums = [2,3,1,1,4] +Output: 2 +Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. + +Example 2: + +Input: nums = [2,3,0,1,4] +Output: 2 + +Constraints: + +1 <= nums.length <= 104 +0 <= nums[i] <= 1000 +It's guaranteed that you can reach nums[n - 1]. +*/ + +class Solution { + public int jump(int[] nums) { + int left=0; + int right=0; + int jumps=0; + while(right maxIndex) + return false; + maxIndex = Math.max(maxIndex, i + nums[i]); + } + return true; + } +} \ No newline at end of file From d17a63ca388a6b6ea48fcc8ffe542f60c0ab5e21 Mon Sep 17 00:00:00 2001 From: AyushKumar55 Date: Mon, 28 Oct 2024 13:07:14 +0530 Subject: [PATCH 06/19] Revert "Added GreddyAlgoProblems" This reverts commit bf7948cea52943818d52d36938c3ada79fad0a0a. --- ...ocolates.py => BuyTwoChocolates(20thDec23) | 6 +-- GreedyAlgoProblems/Jump_Game_45.java | 43 ------------------- GreedyAlgoProblems/Jump_Game_55.java | 35 --------------- 3 files changed, 3 insertions(+), 81 deletions(-) rename GreedyAlgoProblems/BuyTwoChocolates.py => BuyTwoChocolates(20thDec23) (96%) delete mode 100644 GreedyAlgoProblems/Jump_Game_45.java delete mode 100644 GreedyAlgoProblems/Jump_Game_55.java diff --git a/GreedyAlgoProblems/BuyTwoChocolates.py b/BuyTwoChocolates(20thDec23) similarity index 96% rename from GreedyAlgoProblems/BuyTwoChocolates.py rename to BuyTwoChocolates(20thDec23) index 57133cb..1a5b4c8 100644 --- a/GreedyAlgoProblems/BuyTwoChocolates.py +++ b/BuyTwoChocolates(20thDec23) @@ -1,5 +1,4 @@ -""" -Difficulty Level - Easy +# Here is the solution in Python. You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money. You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative. @@ -18,7 +17,8 @@ 2 <= prices.length <= 50 1 <= prices[i] <= 100 1 <= money <= 100 -""" + +SOLUTION: class Solution: def buyChoco(self, prices: List[int], money: int) -> int: ans=money-sum(sorted(prices)[:2]) diff --git a/GreedyAlgoProblems/Jump_Game_45.java b/GreedyAlgoProblems/Jump_Game_45.java deleted file mode 100644 index cf04777..0000000 --- a/GreedyAlgoProblems/Jump_Game_45.java +++ /dev/null @@ -1,43 +0,0 @@ -/* -Difficulty - Medium -Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where: - -0 <= j <= nums[i] and -i + j < n -Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1]. - -Example 1: - -Input: nums = [2,3,1,1,4] -Output: 2 -Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. - -Example 2: - -Input: nums = [2,3,0,1,4] -Output: 2 - -Constraints: - -1 <= nums.length <= 104 -0 <= nums[i] <= 1000 -It's guaranteed that you can reach nums[n - 1]. -*/ - -class Solution { - public int jump(int[] nums) { - int left=0; - int right=0; - int jumps=0; - while(right maxIndex) - return false; - maxIndex = Math.max(maxIndex, i + nums[i]); - } - return true; - } -} \ No newline at end of file From 4ccea4b3429caefb81088a929ffbde0ec375876d Mon Sep 17 00:00:00 2001 From: AyushKumar55 Date: Mon, 28 Oct 2024 13:22:02 +0530 Subject: [PATCH 07/19] Added Greddy Algo. Problems --- GreedyAlgoProblems/BuyTwoChocolates_2706.java | 35 ++++++++++++++ GreedyAlgoProblems/JumpGame2_45.java | 46 +++++++++++++++++++ GreedyAlgoProblems/JumpGame_55.java | 35 ++++++++++++++ 3 files changed, 116 insertions(+) create mode 100644 GreedyAlgoProblems/BuyTwoChocolates_2706.java create mode 100644 GreedyAlgoProblems/JumpGame2_45.java create mode 100644 GreedyAlgoProblems/JumpGame_55.java diff --git a/GreedyAlgoProblems/BuyTwoChocolates_2706.java b/GreedyAlgoProblems/BuyTwoChocolates_2706.java new file mode 100644 index 0000000..838ebef --- /dev/null +++ b/GreedyAlgoProblems/BuyTwoChocolates_2706.java @@ -0,0 +1,35 @@ +/* +Difficulty - EASY +You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money. + +You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. + +Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative. + +Example 1: + +Input: prices = [1,2,2], money = 3 +Output: 0 +Explanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. + +Example 2: + +Input: prices = [3,2,3], money = 3 +Output: 3 +Explanation: You cannot buy 2 chocolates without going in debt, so we return 3. + +Constraints: + +2 <= prices.length <= 50 +1 <= prices[i] <= 100 +1 <= money <= 100 +*/ + +class Solution { + public int buyChoco(int[] prices, int money) { + Arrays.sort(prices); + if(prices[0] + prices[1] <= money) + return money - (prices[0] + prices[1]); + return money; + } +} \ No newline at end of file diff --git a/GreedyAlgoProblems/JumpGame2_45.java b/GreedyAlgoProblems/JumpGame2_45.java new file mode 100644 index 0000000..b9c51e2 --- /dev/null +++ b/GreedyAlgoProblems/JumpGame2_45.java @@ -0,0 +1,46 @@ +/* +You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. + +Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where: + +0 <= j <= nums[i] and +i + j < n +Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1]. + +Example 1: + +Input: nums = [2,3,1,1,4] +Output: 2 +Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. + +Example 2: + +Input: nums = [2,3,0,1,4] +Output: 2 + +Constraints: + +1 <= nums.length <= 104 +0 <= nums[i] <= 1000 +It's guaranteed that you can reach nums[n - 1]. +*/ + +class Solution { + public int jump(int[] nums) { + int left=0; + int right=0; + int jumps=0; + while(right maxIndex) + return false; + maxIndex = Math.max(maxIndex, i + nums[i]); + } + return true; + } +} \ No newline at end of file From ef65f7162aac4a89cff92a337f533404e99f0845 Mon Sep 17 00:00:00 2001 From: ayush-singh-225 Date: Mon, 28 Oct 2024 23:57:40 +0530 Subject: [PATCH 08/19] leetcode 2501 solution uploaded --- 2501. Longest Square Streak in an Array | 60 +++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 2501. Longest Square Streak in an Array diff --git a/2501. Longest Square Streak in an Array b/2501. Longest Square Streak in an Array new file mode 100644 index 0000000..725f5a3 --- /dev/null +++ b/2501. Longest Square Streak in an Array @@ -0,0 +1,60 @@ +Problem Statement: + +You are given an integer array nums. A subsequence of nums is called a square streak if: + +The length of the subsequence is at least 2, and +after sorting the subsequence, each element (except the first element) is the square of the previous number. +Return the length of the longest square streak in nums, or return -1 if there is no square streak. + +A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. + + +Example 1: + +Input: nums = [4,3,6,16,8,2] +Output: 3 +Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16]. +- 4 = 2 * 2. +- 16 = 4 * 4. +Therefore, [4,16,2] is a square streak. +It can be shown that every subsequence of length 4 is not a square streak. +Example 2: + +Input: nums = [2,3,5,6,7] +Output: -1 +Explanation: There is no square streak in nums so return -1. + + +Constraints: + +2 <= nums.length <= 105 +2 <= nums[i] <= 105 + + +Solution: + +class Solution { +public: + int longestSquareStreak(vector& nums) { + int max = -1; + unordered_set numSet(nums.begin(), nums.end()); + vector sortedNums(numSet.begin(), numSet.end()); + + sort(sortedNums.begin(), sortedNums.end()); + + for (int num : sortedNums) { + long long curr = num; + int count = 0; + + while (numSet.count(curr)) { + numSet.erase(curr); + curr *= curr; + count++; + } + + max = max(max, count); + } + + return max > 1 ? max : -1; + } +}; \ No newline at end of file From 4037fb6b57d11ede93092810ad2530bf76b94fa9 Mon Sep 17 00:00:00 2001 From: Megha Date: Tue, 29 Oct 2024 21:13:12 +0530 Subject: [PATCH 09/19] initial status --- 2501. Longest Square Streak in an Array | 60 ++++++++++++++++++ ... Maximal Score After Applying K Operations | 48 ++++++++++++++ ...llest Range Covering Elements from K Lists | 63 +++++++++++++++++++ BuyTwoChocolates(20thDec23) | 27 ++++++++ GreedyAlgoProblems/BuyTwoChocolates_2706.java | 35 +++++++++++ GreedyAlgoProblems/JumpGame2_45.java | 46 ++++++++++++++ GreedyAlgoProblems/JumpGame_55.java | 35 +++++++++++ ImageSmoother (19thDec23) | 43 +++++++++++++ ... Difficulty of a Job Schedule(29thDec2023) | 46 ++++++++++++++ ...um Time to Make Rope Colorful(27thDec2023) | 39 ++++++++++++ README.md | 2 + Search Insert Position.java | 24 +++++++ splitAStringIntoNumberOfUniqueSubstrings.java | 20 ++++++ ...ithConcatenationOfAllWorldsLeetcode30.java | 33 ++++++++++ 14 files changed, 521 insertions(+) create mode 100644 2501. Longest Square Streak in an Array create mode 100644 2530. Maximal Score After Applying K Operations create mode 100644 632. Smallest Range Covering Elements from K Lists create mode 100644 BuyTwoChocolates(20thDec23) create mode 100644 GreedyAlgoProblems/BuyTwoChocolates_2706.java create mode 100644 GreedyAlgoProblems/JumpGame2_45.java create mode 100644 GreedyAlgoProblems/JumpGame_55.java create mode 100644 ImageSmoother (19thDec23) create mode 100644 Minimum Difficulty of a Job Schedule(29thDec2023) create mode 100644 Minimum Time to Make Rope Colorful(27thDec2023) create mode 100644 README.md create mode 100644 Search Insert Position.java create mode 100644 splitAStringIntoNumberOfUniqueSubstrings.java create mode 100644 substringWithConcatenationOfAllWorldsLeetcode30.java diff --git a/2501. Longest Square Streak in an Array b/2501. Longest Square Streak in an Array new file mode 100644 index 0000000..725f5a3 --- /dev/null +++ b/2501. Longest Square Streak in an Array @@ -0,0 +1,60 @@ +Problem Statement: + +You are given an integer array nums. A subsequence of nums is called a square streak if: + +The length of the subsequence is at least 2, and +after sorting the subsequence, each element (except the first element) is the square of the previous number. +Return the length of the longest square streak in nums, or return -1 if there is no square streak. + +A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. + + +Example 1: + +Input: nums = [4,3,6,16,8,2] +Output: 3 +Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16]. +- 4 = 2 * 2. +- 16 = 4 * 4. +Therefore, [4,16,2] is a square streak. +It can be shown that every subsequence of length 4 is not a square streak. +Example 2: + +Input: nums = [2,3,5,6,7] +Output: -1 +Explanation: There is no square streak in nums so return -1. + + +Constraints: + +2 <= nums.length <= 105 +2 <= nums[i] <= 105 + + +Solution: + +class Solution { +public: + int longestSquareStreak(vector& nums) { + int max = -1; + unordered_set numSet(nums.begin(), nums.end()); + vector sortedNums(numSet.begin(), numSet.end()); + + sort(sortedNums.begin(), sortedNums.end()); + + for (int num : sortedNums) { + long long curr = num; + int count = 0; + + while (numSet.count(curr)) { + numSet.erase(curr); + curr *= curr; + count++; + } + + max = max(max, count); + } + + return max > 1 ? max : -1; + } +}; \ No newline at end of file diff --git a/2530. Maximal Score After Applying K Operations b/2530. Maximal Score After Applying K Operations new file mode 100644 index 0000000..9faf043 --- /dev/null +++ b/2530. Maximal Score After Applying K Operations @@ -0,0 +1,48 @@ +You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0. + +In one operation: + +choose an index i such that 0 <= i < nums.length, +increase your score by nums[i], and +replace nums[i] with ceil(nums[i] / 3). +Return the maximum possible score you can attain after applying exactly k operations. + +The ceiling function ceil(val) is the least integer greater than or equal to val. + + + +Example 1: + +Input: nums = [10,10,10,10,10], k = 5 +Output: 50 +Explanation: Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50. +Example 2: + +Input: nums = [1,10,3,3,3], k = 3 +Output: 17 +Explanation: You can do the following operations: +Operation 1: Select i = 1, so nums becomes [1,4,3,3,3]. Your score increases by 10. +Operation 2: Select i = 1, so nums becomes [1,2,3,3,3]. Your score increases by 4. +Operation 3: Select i = 2, so nums becomes [1,1,1,3,3]. Your score increases by 3. +The final score is 10 + 4 + 3 = 17. + + +Constraints: + +1 <= nums.length, k <= 105 +1 <= nums[i] <= 109 + + +Solution: +class Solution: + def maxKelements(self, nums: List[int], k: int) -> int: + nums = [-i for i in nums] + heapify(nums) + + res = 0 + for i in range(k): + t = -heappop(nums) + res += t + heappush(nums, -ceil(t / 3)) + + return res diff --git a/632. Smallest Range Covering Elements from K Lists b/632. Smallest Range Covering Elements from K Lists new file mode 100644 index 0000000..1ea0954 --- /dev/null +++ b/632. Smallest Range Covering Elements from K Lists @@ -0,0 +1,63 @@ +Problem Statement: + +You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. + +We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c. + + + +Example 1: + +Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] +Output: [20,24] +Explanation: +List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. +List 2: [0, 9, 12, 20], 20 is in range [20,24]. +List 3: [5, 18, 22, 30], 22 is in range [20,24]. +Example 2: + +Input: nums = [[1,2,3],[1,2,3],[1,2,3]] +Output: [1,1] + + +Constraints: + +nums.length == k +1 <= k <= 3500 +1 <= nums[i].length <= 50 +-105 <= nums[i][j] <= 105 +nums[i] is sorted in non-decreasing order. + + +Solution: +from typing import List +import heapq + + +class Solution: + def smallestRange(self, nums: List[List[int]]) -> List[int]: + heap = [(row[0], i, 0) for i, row in enumerate(nums)] + heapq.heapify(heap) + ans = [-10**9, 10**9] + right = max(row[0] for row in nums) + while heap: + left, row, col = heapq.heappop(heap) + if right - left < ans[1] - ans[0]: + ans = [left, right] + if col + 1 == len(nums[row]): + return ans + right = max(right, nums[row][col + 1]) + heapq.heappush(heap, (nums[row][col + 1], row, col + 1)) + +# Tests: +if __name__ == '__main__': + s = Solution() + # test case 1 + output1 = s.smallestRange([[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]) + expected_output1 = [20,24] + assert output1 == expected_output1, f"Expected {expected_output1}, but got {output1}" + # test case 2 + output2 = s.smallestRange([[1,2,3],[1,2,3],[1,2,3]]) + expected_output2 = [1,1] + assert output2 == expected_output2, f"Expected {expected_output2}, but got {output2}" + print("All tests passed!") diff --git a/BuyTwoChocolates(20thDec23) b/BuyTwoChocolates(20thDec23) new file mode 100644 index 0000000..1a5b4c8 --- /dev/null +++ b/BuyTwoChocolates(20thDec23) @@ -0,0 +1,27 @@ +# Here is the solution in Python. +You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money. +You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. +Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative. + +Example 1: +Input: prices = [1,2,2], money = 3 +Output: 0 +Explanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. + +Example 2: +Input: prices = [3,2,3], money = 3 +Output: 3 +Explanation: You cannot buy 2 chocolates without going in debt, so we return 3. + +Constraints: +2 <= prices.length <= 50 +1 <= prices[i] <= 100 +1 <= money <= 100 + +SOLUTION: +class Solution: + def buyChoco(self, prices: List[int], money: int) -> int: + ans=money-sum(sorted(prices)[:2]) + if ans>=0: + return ans + return money diff --git a/GreedyAlgoProblems/BuyTwoChocolates_2706.java b/GreedyAlgoProblems/BuyTwoChocolates_2706.java new file mode 100644 index 0000000..838ebef --- /dev/null +++ b/GreedyAlgoProblems/BuyTwoChocolates_2706.java @@ -0,0 +1,35 @@ +/* +Difficulty - EASY +You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money. + +You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. + +Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative. + +Example 1: + +Input: prices = [1,2,2], money = 3 +Output: 0 +Explanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. + +Example 2: + +Input: prices = [3,2,3], money = 3 +Output: 3 +Explanation: You cannot buy 2 chocolates without going in debt, so we return 3. + +Constraints: + +2 <= prices.length <= 50 +1 <= prices[i] <= 100 +1 <= money <= 100 +*/ + +class Solution { + public int buyChoco(int[] prices, int money) { + Arrays.sort(prices); + if(prices[0] + prices[1] <= money) + return money - (prices[0] + prices[1]); + return money; + } +} \ No newline at end of file diff --git a/GreedyAlgoProblems/JumpGame2_45.java b/GreedyAlgoProblems/JumpGame2_45.java new file mode 100644 index 0000000..b9c51e2 --- /dev/null +++ b/GreedyAlgoProblems/JumpGame2_45.java @@ -0,0 +1,46 @@ +/* +You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. + +Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where: + +0 <= j <= nums[i] and +i + j < n +Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1]. + +Example 1: + +Input: nums = [2,3,1,1,4] +Output: 2 +Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. + +Example 2: + +Input: nums = [2,3,0,1,4] +Output: 2 + +Constraints: + +1 <= nums.length <= 104 +0 <= nums[i] <= 1000 +It's guaranteed that you can reach nums[n - 1]. +*/ + +class Solution { + public int jump(int[] nums) { + int left=0; + int right=0; + int jumps=0; + while(right maxIndex) + return false; + maxIndex = Math.max(maxIndex, i + nums[i]); + } + return true; + } +} \ No newline at end of file diff --git a/ImageSmoother (19thDec23) b/ImageSmoother (19thDec23) new file mode 100644 index 0000000..ce85078 --- /dev/null +++ b/ImageSmoother (19thDec23) @@ -0,0 +1,43 @@ +# Here is the solution in Python. +An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). +Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it. + +Example 1: +Input: img = [[1,1,1],[1,0,1],[1,1,1]] +Output: [[0,0,0],[0,0,0],[0,0,0]] +Explanation: +For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 +For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 +For the point (1,1): floor(8/9) = floor(0.88888889) = 0 + +Example 2: +Input: img = [[100,200,100],[200,50,200],[100,200,100]] +Output: [[137,141,137],[141,138,141],[137,141,137]] +Explanation: +For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137 +For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141 +For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138 + +Constraints: +m == img.length +n == img[i].length +1 <= m, n <= 200 +0 <= img[i][j] <= 255 + +class Solution: + def imageSmoother(self, img: List[List[int]]) -> List[List[int]]: + ans=[] + n=len(img) + m=len(img[0]) + for r,row in enumerate(img): + ans.append([]) + for c,col in enumerate(row): + s=0 + count=0 + for dx in range(-1,2): + for dy in range(-1,2): + if 0<=r+dx int: + n = len(jobDifficulty) + if d > n: + return -1 + dp = [[inf] * (d + 1) for _ in range(n + 1)] + dp[0][0] = 0 + + for i in range(1, n + 1): + for k in range(1, d + 1): + maxDifficulty = 0 # max(job[j + 1..i]) + for j in range(i - 1, k - 2, -1): # 1-based + maxDifficulty = max(maxDifficulty, jobDifficulty[j]) + dp[i][k] = min(dp[i][k], dp[j][k - 1] + maxDifficulty) + + return dp[n][d] diff --git a/Minimum Time to Make Rope Colorful(27thDec2023) b/Minimum Time to Make Rope Colorful(27thDec2023) new file mode 100644 index 0000000..c3a557c --- /dev/null +++ b/Minimum Time to Make Rope Colorful(27thDec2023) @@ -0,0 +1,39 @@ +1578. Minimum Time to Make Rope Colorful + +Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon. +Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope. +Return the minimum time Bob needs to make the rope colorful. + +Example 1: +Input: colors = "abaac", neededTime = [1,2,3,4,5] +Output: 3 +Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green. +Bob can remove the blue balloon at index 2. This takes 3 seconds. +There are no longer two consecutive balloons of the same color. Total time = 3. + +Example 2: +Input: colors = "abc", neededTime = [1,2,3] +Output: 0 +Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope. + +Example 3: +Input: colors = "aabaa", neededTime = [1,2,3,4,1] +Output: 2 +Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove. +There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2. + +Constraints: +n == colors.length == neededTime.length +1 <= n <= 105 +1 <= neededTime[i] <= 104 + +SOLUTION: +class Solution: + def minCost(self, colors: str, neededTime: List[int]) -> int: + n, i, j, sumPeak = len(colors), 0, 1, 0 + while i < n: + if j < n and colors[j] == colors[i]: j += 1 + else: + sumPeak += max(neededTime[i: j]) + i, j = j, j + 1 + return sum(neededTime) - sumPeak diff --git a/README.md b/README.md new file mode 100644 index 0000000..38427a6 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# Leetcoding +Basically the repository will contain the solutions of the Leetcode's daily problem of the day. diff --git a/Search Insert Position.java b/Search Insert Position.java new file mode 100644 index 0000000..ecca4ae --- /dev/null +++ b/Search Insert Position.java @@ -0,0 +1,24 @@ +class Solution { + public int searchInsert(int[] nums, int target) { + int l=nums.length,s=0,e=l; + while(s()); + } + private int backtrack(int start, String s, HashSet seen) { + if (start == s.length()) { + return 0; + } + int maxSplits = 0; + for (int end = start + 1; end <= s.length(); end++) { + String substring = s.substring(start, end); + if (!seen.contains(substring)) { + seen.add(substring); + maxSplits = Math.max(maxSplits, 1 + backtrack(end, s, seen)); + seen.remove(substring); + } + } + return maxSplits; + } +} diff --git a/substringWithConcatenationOfAllWorldsLeetcode30.java b/substringWithConcatenationOfAllWorldsLeetcode30.java new file mode 100644 index 0000000..51aea84 --- /dev/null +++ b/substringWithConcatenationOfAllWorldsLeetcode30.java @@ -0,0 +1,33 @@ +class Solution { + public List findSubstring(String s, String[] words) { + List ans = new ArrayList<>(); + int n = s.length(); + int m = words.length; + int w = words[0].length(); + + HashMap map = new HashMap<>(); + for(String x : words) + map.put(x, map.getOrDefault(x,0)+1); + + for(int i=0; i temp = new HashMap<>(); + int count = 0; + for(int j=i,k=i; j+w <= n; j=j+w){ + String word = s.substring(j,j+w); + temp.put(word,temp.getOrDefault(word,0)+1); + count++; + + if(count==m){ + if(map.equals(temp)){ + ans.add(k); + } + String remove = s.substring(k,k+w); + temp.computeIfPresent(remove, (a, b) -> (b > 1) ? b - 1 : null); + count--; + k=k+w; + } + } + } + return ans; + } +} From cf36427ec4c56330ecd24bff0026223f7e8e1d86 Mon Sep 17 00:00:00 2001 From: Megha Date: Tue, 29 Oct 2024 21:37:05 +0530 Subject: [PATCH 10/19] Solution to reverse integer in java --- Reverse Integer.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Reverse Integer.java diff --git a/Reverse Integer.java b/Reverse Integer.java new file mode 100644 index 0000000..fe091dc --- /dev/null +++ b/Reverse Integer.java @@ -0,0 +1,19 @@ +class Solution { + public int reverse(int x) { + + int t1=x;long r=0; + do{ + r=(r*10)+(t1%10); + t1/=10; + }while(t1!=0); + + if((r>=(-(Math.pow(2,31)))) && (r<=(Math.pow(2,31)-1))) + return (int)r; + else + return 0; + } + public static void main(String args[]){ + Solution obj = new Solution(); + System.out.println(obj.reverse(1234)); + } + } \ No newline at end of file From 35a5dd9807f8f9ef98404ce659afcb12258fc97b Mon Sep 17 00:00:00 2001 From: Megha Date: Wed, 30 Oct 2024 00:57:36 +0530 Subject: [PATCH 11/19] Adding solution to power of an integer --- 50.Pow(x,n).java | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 50.Pow(x,n).java diff --git a/50.Pow(x,n).java b/50.Pow(x,n).java new file mode 100644 index 0000000..cc59795 --- /dev/null +++ b/50.Pow(x,n).java @@ -0,0 +1,9 @@ +class Solution { + public double myPow(double x, int n) { + return(Math.pow(x,n)); + } + public static void main(String args[]){ + Solution obj = new Solution(); + System.out.println(obj.myPow(2.0,4)); + } + } \ No newline at end of file From c2311e01bfa06f389729615fef514d62b3348a9e Mon Sep 17 00:00:00 2001 From: Ayush Karan Date: Wed, 30 Oct 2024 21:16:20 -0700 Subject: [PATCH 12/19] Add files via upload --- spiralarray.java | 52 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 spiralarray.java diff --git a/spiralarray.java b/spiralarray.java new file mode 100644 index 0000000..dd80a60 --- /dev/null +++ b/spiralarray.java @@ -0,0 +1,52 @@ +//Print the spiral order matrix as output for a given matrix of numbers. + +package array; +import java.util.*; +public class array_2D_hw1 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print(("Number of rows: ")); + int rows=sc.nextInt(); + System.out.println("Number of columns: "); + int cols=sc.nextInt(); + + + int arr [][]= new int[rows][cols]; + + for(int i=0;i=col_start;i--){ + System.out.print(arr[row_end][i]+" "); + } + row_end--; + + for(int i = row_end;i>=row_start;i--){ + System.out.print(arr[i][col_start]+" "); + } + col_start++; + } + sc.close(); + } +} From e6077d8e288562e5cf69a69c19be5460d7123524 Mon Sep 17 00:00:00 2001 From: Ayush Karan Date: Wed, 30 Oct 2024 21:25:37 -0700 Subject: [PATCH 13/19] Add files via upload --- Guess_a_number.java | 66 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Guess_a_number.java diff --git a/Guess_a_number.java b/Guess_a_number.java new file mode 100644 index 0000000..2814481 --- /dev/null +++ b/Guess_a_number.java @@ -0,0 +1,66 @@ +/* WAP to generate a random number between 1 to 100 & ask user toguess that nuumber. + * If user's guess is greater than your number, print "Too large guess...try again" + * If user's guess is smaller than your number, print "Too samll guess...try again" + * Repeat this process till either: + * 1)User guesses the right answer (print: "WOOHOO, You guessed it right!") + * 2)Give the user a option to stop the program by typing any negative number + * MAXIMUM ALOOWED ATTEMPTES FOR USER=7 + * If the user guesses the right answered in the limit then alsotell him about the number of attempts he took + * even if user guesses or not tell him what the number was + */ + + +import java.util.Scanner; +public class PROJECT { + public static void project() { + Scanner sc = new Scanner(System.in); + int num = (int) (Math.random() * 100) + 1; + int guess = 0; + int tries=1; + System.out.println("Maximum attempts to guess the number: 7"); + + do { + System.out.print("Guess a number between 1 to 100 (to exit type any number less than 1): "); + guess = sc.nextInt(); + if (guess == num) { + System.out.println("WOOHOO, You guessed it right!"); + System.out.println("No. of attempts taken: "+(tries)); + break; + } + else if(guess>num && guess<100) { + System.out.println("Too large guess...try again"); + } + else if(guess>0 && guess= 7) { + System.out.println("Maximum attempts limit crossed. Better luck next time!"); + break; + } + tries++; + + } while (guess>0); + System.out.println("My number was: "+ num); + sc.close(); + } + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("DO YOU WANT TO PLAY A GAME? (Y/N) : "); + char ch = sc.next().charAt(0); + if (ch=='Y'||ch=='y') { + System.out.println("Let's play a game of guessing a random number"); + project(); + } + else if(ch=='N'||ch=='n') { + System.out.println("OK...as you wish...GOOD BYE!"); + } + else { + System.out.println("Invalid choice"); + } + sc.close(); + } +} \ No newline at end of file From 627900c3a7cef3bcbceefb6302c9c11379c5166f Mon Sep 17 00:00:00 2001 From: Ayush Karan Date: Thu, 31 Oct 2024 10:01:17 +0530 Subject: [PATCH 14/19] Delete Guess_a_number.java --- Guess_a_number.java | 66 --------------------------------------------- 1 file changed, 66 deletions(-) delete mode 100644 Guess_a_number.java diff --git a/Guess_a_number.java b/Guess_a_number.java deleted file mode 100644 index 2814481..0000000 --- a/Guess_a_number.java +++ /dev/null @@ -1,66 +0,0 @@ -/* WAP to generate a random number between 1 to 100 & ask user toguess that nuumber. - * If user's guess is greater than your number, print "Too large guess...try again" - * If user's guess is smaller than your number, print "Too samll guess...try again" - * Repeat this process till either: - * 1)User guesses the right answer (print: "WOOHOO, You guessed it right!") - * 2)Give the user a option to stop the program by typing any negative number - * MAXIMUM ALOOWED ATTEMPTES FOR USER=7 - * If the user guesses the right answered in the limit then alsotell him about the number of attempts he took - * even if user guesses or not tell him what the number was - */ - - -import java.util.Scanner; -public class PROJECT { - public static void project() { - Scanner sc = new Scanner(System.in); - int num = (int) (Math.random() * 100) + 1; - int guess = 0; - int tries=1; - System.out.println("Maximum attempts to guess the number: 7"); - - do { - System.out.print("Guess a number between 1 to 100 (to exit type any number less than 1): "); - guess = sc.nextInt(); - if (guess == num) { - System.out.println("WOOHOO, You guessed it right!"); - System.out.println("No. of attempts taken: "+(tries)); - break; - } - else if(guess>num && guess<100) { - System.out.println("Too large guess...try again"); - } - else if(guess>0 && guess= 7) { - System.out.println("Maximum attempts limit crossed. Better luck next time!"); - break; - } - tries++; - - } while (guess>0); - System.out.println("My number was: "+ num); - sc.close(); - } - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - System.out.print("DO YOU WANT TO PLAY A GAME? (Y/N) : "); - char ch = sc.next().charAt(0); - if (ch=='Y'||ch=='y') { - System.out.println("Let's play a game of guessing a random number"); - project(); - } - else if(ch=='N'||ch=='n') { - System.out.println("OK...as you wish...GOOD BYE!"); - } - else { - System.out.println("Invalid choice"); - } - sc.close(); - } -} \ No newline at end of file From 998d5a396cfdf7f4cb04d6c2ae8a42288c2f9a25 Mon Sep 17 00:00:00 2001 From: Ayush Karan Date: Wed, 30 Oct 2024 21:37:47 -0700 Subject: [PATCH 15/19] Guess a number file --- Guess_a_number.java | 66 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Guess_a_number.java diff --git a/Guess_a_number.java b/Guess_a_number.java new file mode 100644 index 0000000..2814481 --- /dev/null +++ b/Guess_a_number.java @@ -0,0 +1,66 @@ +/* WAP to generate a random number between 1 to 100 & ask user toguess that nuumber. + * If user's guess is greater than your number, print "Too large guess...try again" + * If user's guess is smaller than your number, print "Too samll guess...try again" + * Repeat this process till either: + * 1)User guesses the right answer (print: "WOOHOO, You guessed it right!") + * 2)Give the user a option to stop the program by typing any negative number + * MAXIMUM ALOOWED ATTEMPTES FOR USER=7 + * If the user guesses the right answered in the limit then alsotell him about the number of attempts he took + * even if user guesses or not tell him what the number was + */ + + +import java.util.Scanner; +public class PROJECT { + public static void project() { + Scanner sc = new Scanner(System.in); + int num = (int) (Math.random() * 100) + 1; + int guess = 0; + int tries=1; + System.out.println("Maximum attempts to guess the number: 7"); + + do { + System.out.print("Guess a number between 1 to 100 (to exit type any number less than 1): "); + guess = sc.nextInt(); + if (guess == num) { + System.out.println("WOOHOO, You guessed it right!"); + System.out.println("No. of attempts taken: "+(tries)); + break; + } + else if(guess>num && guess<100) { + System.out.println("Too large guess...try again"); + } + else if(guess>0 && guess= 7) { + System.out.println("Maximum attempts limit crossed. Better luck next time!"); + break; + } + tries++; + + } while (guess>0); + System.out.println("My number was: "+ num); + sc.close(); + } + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("DO YOU WANT TO PLAY A GAME? (Y/N) : "); + char ch = sc.next().charAt(0); + if (ch=='Y'||ch=='y') { + System.out.println("Let's play a game of guessing a random number"); + project(); + } + else if(ch=='N'||ch=='n') { + System.out.println("OK...as you wish...GOOD BYE!"); + } + else { + System.out.println("Invalid choice"); + } + sc.close(); + } +} \ No newline at end of file From 3dab3028f96cb4f9cc97fb1b215514b701f889d0 Mon Sep 17 00:00:00 2001 From: ayush-singh-225 Date: Thu, 31 Oct 2024 23:27:37 +0530 Subject: [PATCH 16/19] Leetcode 31oct solution uploaded --- 2463.Minimum-Total-Distance-Traveled | 60 ++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 2463.Minimum-Total-Distance-Traveled diff --git a/2463.Minimum-Total-Distance-Traveled b/2463.Minimum-Total-Distance-Traveled new file mode 100644 index 0000000..b6421bc --- /dev/null +++ b/2463.Minimum-Total-Distance-Traveled @@ -0,0 +1,60 @@ +Problem Statement: + +There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at most limitj robots. + +The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially. + +All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving. + +At any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots. + +Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired. + +Note that + +All robots move at the same speed. +If two robots move in the same direction, they will never collide. +If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other. +If a robot passes by a factory that reached its limits, it crosses it as if it does not exist. +If the robot moved from a position x to a position y, the distance it moved is |y - x|. + + +Solution: + +class Solution { +public: + long long minimumTotalDistance(vector& robot, vector>& factory) { + sort(robot.begin(), robot.end()); + sort(factory.begin(), factory.end()); + + int m = robot.size(), n = factory.size(); + vector> dp(m + 1, vector(n + 1)); + + for (int i = 0; i < m; i++) { + dp[i][n] = LLONG_MAX; + } + + for (int j = n - 1; j >= 0; j--) { + long long prefix = 0; + deque> qq; + qq.push_back({m, 0}); + + for (int i = m - 1; i >= 0; i--) { + prefix += abs(robot[i] - factory[j][0]); + + while (!qq.empty() && qq.front().first > i + factory[j][1]) { + qq.pop_front(); + } + + while (!qq.empty() && qq.back().second >= dp[i][j + 1] - prefix) { + qq.pop_back(); + } + + qq.push_back({i, dp[i][j + 1] - prefix}); + dp[i][j] = qq.front().second + prefix; + } + } + + return dp[0][0]; + } +}; \ No newline at end of file From 8abe370293d8b6c4d5964ff20320269407832e45 Mon Sep 17 00:00:00 2001 From: Harshil Date: Tue, 28 Oct 2025 22:15:13 +0530 Subject: [PATCH 17/19] Create 1. Two Sum --- 1. Two Sum | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 1. Two Sum diff --git a/1. Two Sum b/1. Two Sum new file mode 100644 index 0000000..b940c57 --- /dev/null +++ b/1. Two Sum @@ -0,0 +1,8 @@ +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + pair_idx = {} + + for i, num in enumerate(nums): + if target - num in pair_idx: + return [i, pair_idx[target - num]] + pair_idx[num] = i From acbdc103df695b77a763461312f4445be4ce3073 Mon Sep 17 00:00:00 2001 From: Harshil Date: Tue, 28 Oct 2025 22:51:27 +0530 Subject: [PATCH 18/19] Create 4. Median of Two Sorted Arrays --- 4. Median of Two Sorted Arrays | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 4. Median of Two Sorted Arrays diff --git a/4. Median of Two Sorted Arrays b/4. Median of Two Sorted Arrays new file mode 100644 index 0000000..83eab12 --- /dev/null +++ b/4. Median of Two Sorted Arrays @@ -0,0 +1,13 @@ +class Solution: + def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: + # Merge the two sorted arrays + merged = sorted(nums1 + nums2) + length = len(merged) + + # Check if the total length is even or odd + if length % 2 == 0: + # If even, return the average of the two middle elements + return (merged[length // 2 - 1] + merged[length // 2]) / 2 + else: + # If odd, return the middle element + return merged[length // 2] From b2eb982d6b65e35fe9ea37662df73bfcf10e6c6a Mon Sep 17 00:00:00 2001 From: Shagun Vishnoi Date: Tue, 28 Oct 2025 23:40:01 +0530 Subject: [PATCH 19/19] edited 4 files and added power code in python --- .DS_Store | Bin 0 -> 6148 bytes GreedyAlgoProblems/BuyTwoChocolates_2706.java | 2 ++ Guess_a_number.java | 2 +- spiralarray.java => array/spiralarray.java | 2 +- pow(x,n).py | 4 +++ splitAStringIntoNumberOfUniqueSubstrings.java | 2 ++ ...ithConcatenationOfAllWorldsLeetcode30.java | 29 ++++++++++++------ 7 files changed, 29 insertions(+), 12 deletions(-) create mode 100644 .DS_Store rename spiralarray.java => array/spiralarray.java (94%) create mode 100644 pow(x,n).py diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..fd4f0949ff1f8827ebbd9ee58863552b3e805b26 GIT binary patch literal 6148 zcmeHK%Sr<=6g{aeR8%OsaXC9ziv5FWsR(W?bR)R2wWSIjrubNNH@NU8s(yq&(SLC# z{($Euv7I;-x)PClhvdxMo0B^^8IlPA)4cE3ff|4+i(qM;)e@7ql!BGKXOn28kI}H+ zxlEIBp`|+hssb{1WgK9LYup9%XLdNJi&&DjTD?))qpv!9etmd4n>E6Ce;%(*&B^pz ze0-JrHcD+$Q9&0sytJp!TLk&-_l|8GGy8y79}_e% zq6#V6^rh(WX@CT`;hSv@_+~5d^6yN}sn=sg?qW3WANyZguEY(;dC1gis(>n>3KSHO z^_^DTaHzE^pbDr0a|L95h*$(;kC{Webg;5V0AiVLYrL1Ugm5B{vB%6IBQ)cvL`OCL zh+!O^{>ZnBJ!TFa9mXF%jL&TR3B}m#>_4*2VPc0`s{*P(sKAYB@3L5@jml4^4jr MtPEPI0>7%jCl{M_SpWb4 literal 0 HcmV?d00001 diff --git a/GreedyAlgoProblems/BuyTwoChocolates_2706.java b/GreedyAlgoProblems/BuyTwoChocolates_2706.java index 838ebef..54269fa 100644 --- a/GreedyAlgoProblems/BuyTwoChocolates_2706.java +++ b/GreedyAlgoProblems/BuyTwoChocolates_2706.java @@ -25,6 +25,8 @@ 1 <= money <= 100 */ +import java.util.Arrays; + class Solution { public int buyChoco(int[] prices, int money) { Arrays.sort(prices); diff --git a/Guess_a_number.java b/Guess_a_number.java index 2814481..708b84e 100644 --- a/Guess_a_number.java +++ b/Guess_a_number.java @@ -11,7 +11,7 @@ import java.util.Scanner; -public class PROJECT { +public class Guess_a_number { public static void project() { Scanner sc = new Scanner(System.in); int num = (int) (Math.random() * 100) + 1; diff --git a/spiralarray.java b/array/spiralarray.java similarity index 94% rename from spiralarray.java rename to array/spiralarray.java index dd80a60..c918276 100644 --- a/spiralarray.java +++ b/array/spiralarray.java @@ -2,7 +2,7 @@ package array; import java.util.*; -public class array_2D_hw1 { +public class spiralarray { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(("Number of rows: ")); diff --git a/pow(x,n).py b/pow(x,n).py new file mode 100644 index 0000000..d0de787 --- /dev/null +++ b/pow(x,n).py @@ -0,0 +1,4 @@ +class Solution(object): + def myPow(self, x, n): + a=pow(x,n) + return a \ No newline at end of file diff --git a/splitAStringIntoNumberOfUniqueSubstrings.java b/splitAStringIntoNumberOfUniqueSubstrings.java index 33bb0a6..e373868 100644 --- a/splitAStringIntoNumberOfUniqueSubstrings.java +++ b/splitAStringIntoNumberOfUniqueSubstrings.java @@ -1,3 +1,5 @@ +import java.util.HashSet; + class Solution { public int maxUniqueSplit(String s) { return backtrack(0, s, new HashSet<>()); diff --git a/substringWithConcatenationOfAllWorldsLeetcode30.java b/substringWithConcatenationOfAllWorldsLeetcode30.java index 51aea84..85db42e 100644 --- a/substringWithConcatenationOfAllWorldsLeetcode30.java +++ b/substringWithConcatenationOfAllWorldsLeetcode30.java @@ -1,19 +1,28 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + class Solution { - public List findSubstring(String s, String[] words) { - List ans = new ArrayList<>(); - int n = s.length(); - int m = words.length; - int w = words[0].length(); + /** + * @param s + * @param words + * @return + */ + public List findSubstring(final String s, final String[] words) { + final List ans = new ArrayList<>(); + final int n = s.length(); + final int m = words.length; + final int w = words[0].length(); - HashMap map = new HashMap<>(); - for(String x : words) + final HashMap map = new HashMap<>(); + for(final String x : words) map.put(x, map.getOrDefault(x,0)+1); for(int i=0; i temp = new HashMap<>(); + final HashMap temp = new HashMap<>(); int count = 0; for(int j=i,k=i; j+w <= n; j=j+w){ - String word = s.substring(j,j+w); + final String word = s.substring(j,j+w); temp.put(word,temp.getOrDefault(word,0)+1); count++; @@ -21,7 +30,7 @@ public List findSubstring(String s, String[] words) { if(map.equals(temp)){ ans.add(k); } - String remove = s.substring(k,k+w); + final String remove = s.substring(k,k+w); temp.computeIfPresent(remove, (a, b) -> (b > 1) ? b - 1 : null); count--; k=k+w;