diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..fd4f094 Binary files /dev/null and b/.DS_Store differ 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 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 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/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] 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 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/GreedyAlgoProblems/BuyTwoChocolates_2706.java b/GreedyAlgoProblems/BuyTwoChocolates_2706.java new file mode 100644 index 0000000..54269fa --- /dev/null +++ b/GreedyAlgoProblems/BuyTwoChocolates_2706.java @@ -0,0 +1,37 @@ +/* +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 +*/ + +import java.util.Arrays; + +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/Guess_a_number.java b/Guess_a_number.java new file mode 100644 index 0000000..708b84e --- /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 Guess_a_number { + 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 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 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=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(); + } +} 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 new file mode 100644 index 0000000..e373868 --- /dev/null +++ b/splitAStringIntoNumberOfUniqueSubstrings.java @@ -0,0 +1,22 @@ +import java.util.HashSet; + +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; + } +} diff --git a/substringWithConcatenationOfAllWorldsLeetcode30.java b/substringWithConcatenationOfAllWorldsLeetcode30.java new file mode 100644 index 0000000..85db42e --- /dev/null +++ b/substringWithConcatenationOfAllWorldsLeetcode30.java @@ -0,0 +1,42 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +class Solution { + /** + * @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(); + + 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<>(); + int count = 0; + for(int j=i,k=i; j+w <= n; j=j+w){ + final 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); + } + final String remove = s.substring(k,k+w); + temp.computeIfPresent(remove, (a, b) -> (b > 1) ? b - 1 : null); + count--; + k=k+w; + } + } + } + return ans; + } +}