From 5f3152ede0e97953f7239ae0d0ae7056885e97ae Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 6 Jan 2024 12:06:49 +0530 Subject: [PATCH 001/300] . --- 2024 January/Daily 06-01-24.md | 96 +++++++++++++++++++ README.md | 162 ++++++++++++++------------------- 2 files changed, 165 insertions(+), 93 deletions(-) create mode 100644 2024 January/Daily 06-01-24.md diff --git a/2024 January/Daily 06-01-24.md b/2024 January/Daily 06-01-24.md new file mode 100644 index 0000000..b1bdbef --- /dev/null +++ b/2024 January/Daily 06-01-24.md @@ -0,0 +1,96 @@ +## Today's 06-01-24 [Problem Link](https://leetcode.com/problems/maximum-profit-in-job-scheduling/description/) + +# Intuition + +This question aims to solve the Job Scheduling problem, where a set of jobs with start times, end times, and associated profits needs to be scheduled to maximize the total profit. The intuition involves dynamically determining the optimal schedule to achieve the maximum profit while ensuring that no two jobs overlap in time. + +# Approach + +- Job Class : +- - I created a Job class which is defined to represent each job with its start time (st), end time (et), and profit (p). This encapsulates the information related to each job. +- Sorting : +- - The jobs are sorted based on their start times (st). Sorting is crucial to process jobs sequentially and to facilitate dynamic programming. +- Dynamic Programming Array : +- - I created an array 'gp' of size l+1 to store the maximum profit achievable up to the i-th job. Each element gp[i] represents the maximum profit achievable up to job i. +- Iterative Update : +- - My code iterates through the sorted jobs in reverse order (i from l-1 to 0). For each job, it calculates the profit (lo) by adding the current job's profit to the maximum profit achievable after considering non-overlapping jobs. +- Binary Search Helper Function : +- - I created and used a helper function here. The 'pehlabraYabrabr' function performs a binary search to find the index of the first job whose start time is greater than or equal to the given end time khtm. +- Result : +- - The final result is the maximum profit achievable by scheduling jobs optimally, and it is stored in gp[0], representing the maximum profit achievable starting from the first job. +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $$O(l*logl)=O(sorting)$$ + + +- Space complexity : $$O(l)$$ +. +$$l$$ : length of array ( all 3 array are of same length) + +# Code +``` +// Defining a Job class to represent each job with start time, end time, and profit +class Job { + int st; // start time of this job + int et; // end time of this job + int p; // profit of this job + + Job(int starttime, int endtime, int profit) { + this.st = starttime; + this.et = endtime; + this.p = profit; + } +} + +class Solution { + + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { + int l = profit.length; + Job[] job = new Job[l]; + int[] gp = new int[l + 1]; + + // Creating Job objects and populating the array + for (int i = 0; i < l; i++) { + job[i] = new Job(startTime[i], endTime[i], profit[i]); + } + + // Sorting jobs based on their start times + Arrays.sort(job, (x, y) -> x.st - y.st); + + // Updating startTime array after sorting + for (int i = 0; i < l; i++) { + startTime[i] = job[i].st; + } + + // Dynamic Programming: Iteratively updating the maximum profit + for (int i = l - 1; i >= 0; i--) { + int bb = pehlabraYabrabr(i + 1, startTime, job[i].et); + int lo = job[i].p + gp[bb]; + int mtlo = gp[i + 1]; + gp[i] = Math.max(lo, mtlo); + } + + // Final result is the maximum profit achievable by optimal scheduling + return gp[0]; + } + + // Helper function using binary search to find the index of the first job whose start time is greater than or equal to a given end time + static int pehlabraYabrabr(int suru, int[] startTime, int khtm) { + int l = suru; + int r = startTime.length; + while (l < r) { + int m = (l + r) / 2; + if (khtm <= startTime[m]) { + r = m; + } else { + l = m + 1; + } + } + return l; + } +} + +``` diff --git a/README.md b/README.md index b2cb921..b77b89f 100644 --- a/README.md +++ b/README.md @@ -5,123 +5,99 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 05-01-24 [Problem Link](https://leetcode.com/problems/longest-increasing-subsequence/description/?envType=daily-question&envId=2024-01-05) +## Today's 06-01-24 [Problem Link](https://leetcode.com/problems/maximum-profit-in-job-scheduling/description/) # Intuition -- Dynamic Programming -- - My algorithm must use dynamic programming to efficiently update and maintain the longest increasing subsequence. -- Greedy Choice -- - My algorithm must makes a greedy choice to update the current longest increasing subsequence (a) based on the incoming elements from the input array (nums). - +This question aims to solve the Job Scheduling problem, where a set of jobs with start times, end times, and associated profits needs to be scheduled to maximize the total profit. The intuition involves dynamically determining the optimal schedule to achieve the maximum profit while ensuring that no two jobs overlap in time. # Approach -- ArrayList 'a' -- - I used 'a' to store the current longest increasing subsequence. -- - It starts as an empty ArrayList. -- Iterating through nums -- - My code iterates through each element 's' in the input array nums. -- - For each element : -- - - If a is empty or s is greater than the last element in a, add s to a (greedy choice as it contributes to increasing subsequence). -- - - Otherwise, found the correct position for s in a using the bs function, and update the element at that position with s. -- Binary Search Function 'bs': -- - The 'bs' function performs a binary search on the sorted ArrayList 'a' to find the index of 's' or the index where 's' should be inserted. -- - If 's' is found, it returns the index. If not found, it returns the negation of the insertion point. This insertion point is used to update the current increasing subsequence. -- Return Result : -- - Finally, I returned the length of the longest increasing subsequence is the size of the ArrayList a. ---- -- If you're still having trouble understanding what the binary search functions does here, I would suggest you to please go through this site [search here for binarySearch](https://docs.oracle.com/javase%2F7%2Fdocs%2Fapi%2F%2F/java/util/Collections.html) +- Job Class : +- - I created a Job class which is defined to represent each job with its start time (st), end time (et), and profit (p). This encapsulates the information related to each job. +- Sorting : +- - The jobs are sorted based on their start times (st). Sorting is crucial to process jobs sequentially and to facilitate dynamic programming. +- Dynamic Programming Array : +- - I created an array 'gp' of size l+1 to store the maximum profit achievable up to the i-th job. Each element gp[i] represents the maximum profit achievable up to job i. +- Iterative Update : +- - My code iterates through the sorted jobs in reverse order (i from l-1 to 0). For each job, it calculates the profit (lo) by adding the current job's profit to the maximum profit achievable after considering non-overlapping jobs. +- Binary Search Helper Function : +- - I created and used a helper function here. The 'pehlabraYabrabr' function performs a binary search to find the index of the first job whose start time is greater than or equal to the given end time khtm. +- Result : +- - The final result is the maximum profit achievable by scheduling jobs optimally, and it is stored in gp[0], representing the maximum profit achievable starting from the first job. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + # Complexity -- Time complexity : $$O(l*log(l))$$ +- Time complexity : $$O(l*logl)=O(sorting)$$ - Space complexity : $$O(l)$$ - -$$l$$ : length of array. +. +$$l$$ : length of array ( all 3 array are of same length) + # Code ``` -class Solution { - public int lengthOfLIS(int[] nums) { - - ArrayList a = new ArrayList<>(); - for( int s : nums){ - if( a.isEmpty() || s > a.get( a.size() - 1) ){ - a.add(s); - } - else{ - a.set( bs(a, s) , s); - } - } - return a.size(); - } +// Defining a Job class to represent each job with start time, end time, and profit +class Job { + int st; // start time of this job + int et; // end time of this job + int p; // profit of this job - static int bs( ArrayList a, int s){ - int in = Collections.binarySearch(a, s); - if( in < 0){ - return - in - 1; - } - return in; + Job(int starttime, int endtime, int profit) { + this.st = starttime; + this.et = endtime; + this.p = profit; } } -``` -# Alternate Approach +class Solution { -# Intuition - -- Dynamic Programming Array (gp): + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { + int l = profit.length; + Job[] job = new Job[l]; + int[] gp = new int[l + 1]; -- - My code creates a dynamic programming array (gp) to store the length of the longest increasing subsequence ending at each index i of the array nums. -- Initialization -- - The array gp is initialized with all elements set to 1. This is because each element in nums singularly represents a subsequence of length 1. -- Comparison and Update -- - My code iterates through each element of nums, comparing it with previous elements and updating the gp array based on the increasing subsequence property. -- Final Result -- - The result is the maximum value present in the gp array, which represents the length of the longest increasing subsequence. + // Creating Job objects and populating the array + for (int i = 0; i < l; i++) { + job[i] = new Job(startTime[i], endTime[i], profit[i]); + } + // Sorting jobs based on their start times + Arrays.sort(job, (x, y) -> x.st - y.st); -# Approach - -- Dynamic Programming Array (gp) : -- - gp[i] represents the length of the longest increasing subsequence ending at index i. -- - gp[i] will store the numbers form index '0' to 'i-1' which is smaller than nums[i] = that would be the length of increasing sunsequence with nums[i] as largest of that sequence -- Initialization of gp : -- - Initially, all elements in gp are set to 1 because each element in nums forms a subsequence of length 1. -- - filled with '1' as every element singularly represents a subsequence of length '1' -- Iterative Comparison and Update : -- - My code uses a nested loop to iterate through each pair of indices (i, j) where j is less than i. -- - For each pair, if nums[i] > nums[j], it means that nums[i] can be included in the increasing subsequence ending at index i, and the length is updated accordingly -- Maximum Length in gp : -- - The final result is the maximum value present in the gp array, representing the length of the longest increasing subsequence. ---- -Have a look at the code , still have any confusion then please let me know in the comments -Keep Solving.:) -# Complexity -- Time complexity : $$O(l^2)$$ - + // Updating startTime array after sorting + for (int i = 0; i < l; i++) { + startTime[i] = job[i].st; + } -- Space complexity : $$O(l)$$ - -$$l$$ : length of array. -# Code -``` -class Solution { - public int lengthOfLIS(int[] nums) { - - int[] gp = new int[nums.length]; // gp[i] will store the numbers form index '0' to 'i-1' which is smaller than nums[i] = that would be the length of increasing sunsequence with nums[i] as largest of that sequence - Arrays.fill(gp, 1); // fill with '1' as every element singularly represents a subsequence of length '1' - for( int i = 1; i < nums.length; i++){ - for( int j = 0; j < i; j++){ - if( nums[i] > nums[j]){ - gp[i] = Math.max( gp[i] , gp[j] + 1); - } - } - } - return Arrays.stream(gp).max().getAsInt(); // this will give the maximum value present in array + // Dynamic Programming: Iteratively updating the maximum profit + for (int i = l - 1; i >= 0; i--) { + int bb = pehlabraYabrabr(i + 1, startTime, job[i].et); + int lo = job[i].p + gp[bb]; + int mtlo = gp[i + 1]; + gp[i] = Math.max(lo, mtlo); + } + + // Final result is the maximum profit achievable by optimal scheduling + return gp[0]; + } + + // Helper function using binary search to find the index of the first job whose start time is greater than or equal to a given end time + static int pehlabraYabrabr(int suru, int[] startTime, int khtm) { + int l = suru; + int r = startTime.length; + while (l < r) { + int m = (l + r) / 2; + if (khtm <= startTime[m]) { + r = m; + } else { + l = m + 1; + } + } + return l; } } + ``` From d565043fe42bfbe36e1ece5856f161d84ac013b0 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 6 Jan 2024 12:09:32 +0530 Subject: [PATCH 002/300] . --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b77b89f..7985206 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. ## Today's 06-01-24 [Problem Link](https://leetcode.com/problems/maximum-profit-in-job-scheduling/description/) +## 1235. Maximum Profit in Job Scheduling # Intuition From 30f2a44fd7e10a19897fe8b71c981aa2ad5d6ca1 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 6 Jan 2024 12:13:57 +0530 Subject: [PATCH 003/300] . --- 2024 January/Daily 01-01-24.md | 1 + 2024 January/Daily 02-01-24.md | 1 + 2024 January/Daily 03-01-24.md | 2 +- 2024 January/Daily 04-01-24.md | 1 + 2024 January/Daily 05-01-24 Another Approach.md | 1 + 2024 January/Daily 05-01-24.md | 1 + 2024 January/Daily 06-01-24.md | 1 + 7 files changed, 7 insertions(+), 1 deletion(-) diff --git a/2024 January/Daily 01-01-24.md b/2024 January/Daily 01-01-24.md index 813a4ef..2755972 100644 --- a/2024 January/Daily 01-01-24.md +++ b/2024 January/Daily 01-01-24.md @@ -7,6 +7,7 @@ This is my attemp to make the coding experience easier for you guys so that you ## Always here to assist you guys. ## Todays 01-01-24 [Problem Link](https://leetcode.com/problems/assign-cookies/description/?envType=daily-question&envId=2024-01-01) +## 455. Assign Cookies # Intuition diff --git a/2024 January/Daily 02-01-24.md b/2024 January/Daily 02-01-24.md index afc2aba..7aaacf7 100644 --- a/2024 January/Daily 02-01-24.md +++ b/2024 January/Daily 02-01-24.md @@ -1,4 +1,5 @@ ## Today's 02-01-24 [Problem Link](https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/solutions/4490329/daily-02-01-24/) +## 2610. Convert an Array Into a 2D Array With Conditions # Intuition diff --git a/2024 January/Daily 03-01-24.md b/2024 January/Daily 03-01-24.md index c1b8578..81d5fc0 100644 --- a/2024 January/Daily 03-01-24.md +++ b/2024 January/Daily 03-01-24.md @@ -1,5 +1,5 @@ ## Today's 03-01-24 [Problem Link](https://leetcode.com/problems/number-of-laser-beams-in-a-bank/description/?envType=daily-question&envId=2024-01-03) - +## 2125. Number of Laser Beams in a Bank # Intuition diff --git a/2024 January/Daily 04-01-24.md b/2024 January/Daily 04-01-24.md index 1b4d460..8d5d59a 100644 --- a/2024 January/Daily 04-01-24.md +++ b/2024 January/Daily 04-01-24.md @@ -1,4 +1,5 @@ ## Today's 04-01-24 [Problem Link](https://leetcode.com/problems/minimum-number-of-operations-to-make-array-empty/description/) +## 2870. Minimum Number of Operations to Make Array Empty # Intuition diff --git a/2024 January/Daily 05-01-24 Another Approach.md b/2024 January/Daily 05-01-24 Another Approach.md index 1990b6b..f54f47e 100644 --- a/2024 January/Daily 05-01-24 Another Approach.md +++ b/2024 January/Daily 05-01-24 Another Approach.md @@ -1,4 +1,5 @@ ## Today's 05-01-24 [Problem Link](https://leetcode.com/problems/longest-increasing-subsequence/description/?envType=daily-question&envId=2024-01-05) +## 300. Longest Increasing Subsequence # Intuition diff --git a/2024 January/Daily 05-01-24.md b/2024 January/Daily 05-01-24.md index 28d01f9..22a539e 100644 --- a/2024 January/Daily 05-01-24.md +++ b/2024 January/Daily 05-01-24.md @@ -1,4 +1,5 @@ ## Today's 05-01-24 [Problem Link](https://leetcode.com/problems/longest-increasing-subsequence/description/?envType=daily-question&envId=2024-01-05) +## 300. Longest Increasing Subsequence # Intuition diff --git a/2024 January/Daily 06-01-24.md b/2024 January/Daily 06-01-24.md index b1bdbef..3eb86e7 100644 --- a/2024 January/Daily 06-01-24.md +++ b/2024 January/Daily 06-01-24.md @@ -1,4 +1,5 @@ ## Today's 06-01-24 [Problem Link](https://leetcode.com/problems/maximum-profit-in-job-scheduling/description/) +## 1235. Maximum Profit in Job Scheduling # Intuition From 0fe26a7afed45e150bce13484f98d2bfa958bd3a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 7 Jan 2024 14:57:06 +0530 Subject: [PATCH 004/300] Update README.md --- README.md | 124 ++++++++++++++++++++++-------------------------------- 1 file changed, 51 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index 7985206..9e83685 100644 --- a/README.md +++ b/README.md @@ -5,99 +5,77 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 06-01-24 [Problem Link](https://leetcode.com/problems/maximum-profit-in-job-scheduling/description/) -## 1235. Maximum Profit in Job Scheduling +## Today's 07-01-24 [Problem Link](https://leetcode.com/problems/arithmetic-slices-ii-subsequence/description/?envType=daily-question&envId=2024-01-07) +## 446. Arithmetic Slices II - Subsequence # Intuition -This question aims to solve the Job Scheduling problem, where a set of jobs with start times, end times, and associated profits needs to be scheduled to maximize the total profit. The intuition involves dynamically determining the optimal schedule to achieve the maximum profit while ensuring that no two jobs overlap in time. +An arithmetic slice is a sequence of elements in the array such that the difference between consecutive elements is the same. # Approach -- Job Class : -- - I created a Job class which is defined to represent each job with its start time (st), end time (et), and profit (p). This encapsulates the information related to each job. -- Sorting : -- - The jobs are sorted based on their start times (st). Sorting is crucial to process jobs sequentially and to facilitate dynamic programming. -- Dynamic Programming Array : -- - I created an array 'gp' of size l+1 to store the maximum profit achievable up to the i-th job. Each element gp[i] represents the maximum profit achievable up to job i. -- Iterative Update : -- - My code iterates through the sorted jobs in reverse order (i from l-1 to 0). For each job, it calculates the profit (lo) by adding the current job's profit to the maximum profit achievable after considering non-overlapping jobs. -- Binary Search Helper Function : -- - I created and used a helper function here. The 'pehlabraYabrabr' function performs a binary search to find the index of the first job whose start time is greater than or equal to the given end time khtm. -- Result : -- - The final result is the maximum profit achievable by scheduling jobs optimally, and it is stored in gp[0], representing the maximum profit achievable starting from the first job. +- Initialization : +- - I initialized the variable 'jawab' to keep track of the total number of arithmetic slices. +- Data Structures : +- - I created a 2D array gp to store the number of arithmetic slices. gp[i][j] represents the number of slices ending at index i with the last element at index j. +- - I have used a HashMap called 'map' to store indices of elements with the same value. This is done to efficiently find potential common differences. +- Populate the Map : +- - I iterated through the elements of the array (nums) and populate the map with indices of elements having the same value. The key is the element value, and the value is a list of indices. +- Dynamic Programming : +- - I iterated through each element in the array (nums) using two nested loops. +- - For each pair of indices (i, j) where i is the current index and j is less than i : +- - - Calculate the potential common difference l using the formula 2 * nums[j] - nums[i]. +- - - Check if there are elements with value l in the map. +- - - If yes, iterate through the indices of elements with value l in the map: +- - - - For each index in, if j > in, update gp[i][j] by adding gp[j][in] + 1. This is because a new arithmetic slice is formed by extending the slice ending at index in. +- - - Accumulate the value of gp[i][j] to the overall answer jawab. +- Final Result : +- - The final answer is stored in the variable jawab. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $$O(l*logl)=O(sorting)$$ +- Time complexity : $$O(l^2)$$ -- Space complexity : $$O(l)$$ -. -$$l$$ : length of array ( all 3 array are of same length) - +- Space complexity : $$O(l^2)$$ + + $$l$$ : length of array. # Code ``` -// Defining a Job class to represent each job with start time, end time, and profit -class Job { - int st; // start time of this job - int et; // end time of this job - int p; // profit of this job - - Job(int starttime, int endtime, int profit) { - this.st = starttime; - this.et = endtime; - this.p = profit; - } -} - class Solution { - - public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { - int l = profit.length; - Job[] job = new Job[l]; - int[] gp = new int[l + 1]; - - // Creating Job objects and populating the array - for (int i = 0; i < l; i++) { - job[i] = new Job(startTime[i], endTime[i], profit[i]); + public int numberOfArithmeticSlices(int[] nums) { + int jawab = 0; // Initialize the answer variable to 0 + int[][] gp = new int[nums.length][nums.length]; // 2D array to store the number of arithmetic slices + Map> map = new HashMap<>(); // Map to store indices of elements with the same value + + // Populate the map with indices of elements having the same value + for (int i = 0; i < nums.length; i++) { + map.putIfAbsent(1L * nums[i], new ArrayList<>()); + map.get(1L * nums[i]).add(i); } - // Sorting jobs based on their start times - Arrays.sort(job, (x, y) -> x.st - y.st); - - // Updating startTime array after sorting - for (int i = 0; i < l; i++) { - startTime[i] = job[i].st; - } - - // Dynamic Programming: Iteratively updating the maximum profit - for (int i = l - 1; i >= 0; i--) { - int bb = pehlabraYabrabr(i + 1, startTime, job[i].et); - int lo = job[i].p + gp[bb]; - int mtlo = gp[i + 1]; - gp[i] = Math.max(lo, mtlo); - } - - // Final result is the maximum profit achievable by optimal scheduling - return gp[0]; - } - - // Helper function using binary search to find the index of the first job whose start time is greater than or equal to a given end time - static int pehlabraYabrabr(int suru, int[] startTime, int khtm) { - int l = suru; - int r = startTime.length; - while (l < r) { - int m = (l + r) / 2; - if (khtm <= startTime[m]) { - r = m; - } else { - l = m + 1; + // Iterate through each element in the array + for (int i = 0; i < nums.length; i++) { + for (int j = 0; j < i; j++) { + long l = 2L * nums[j] - nums[i]; // Calculate the potential common difference + + // Check if there are elements in the map with the calculated common difference + if (map.containsKey(l)) { + // Iterate through indices of elements with the calculated common difference + for (int in : map.get(l)) { + if (j > in) { + // Update the count of arithmetic slices in the 2D array + gp[i][j] += gp[j][in] + 1; + } + } + } + jawab += gp[i][j]; // Accumulate the count to the overall answer } } - return l; + + return jawab; // Return the final answer } } From 516beafd66b489b0b5ad18effe2df1af3e0d94f8 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 7 Jan 2024 15:00:54 +0530 Subject: [PATCH 005/300] Create Daily 07-01-24.md --- 2024 January/Daily 07-01-24.md | 75 ++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 2024 January/Daily 07-01-24.md diff --git a/2024 January/Daily 07-01-24.md b/2024 January/Daily 07-01-24.md new file mode 100644 index 0000000..738071c --- /dev/null +++ b/2024 January/Daily 07-01-24.md @@ -0,0 +1,75 @@ +## Today's 07-01-24 [Problem Link](https://leetcode.com/problems/arithmetic-slices-ii-subsequence/description/?envType=daily-question&envId=2024-01-07) +## 446. Arithmetic Slices II - Subsequence + +# Intuition + +An arithmetic slice is a sequence of elements in the array such that the difference between consecutive elements is the same. + +# Approach + +- Initialization : +- - I initialized the variable 'jawab' to keep track of the total number of arithmetic slices. +- Data Structures : +- - I created a 2D array gp to store the number of arithmetic slices. gp[i][j] represents the number of slices ending at index i with the last element at index j. +- - I have used a HashMap called 'map' to store indices of elements with the same value. This is done to efficiently find potential common differences. +- Populate the Map : +- - I iterated through the elements of the array (nums) and populate the map with indices of elements having the same value. The key is the element value, and the value is a list of indices. +- Dynamic Programming : +- - I iterated through each element in the array (nums) using two nested loops. +- - For each pair of indices (i, j) where i is the current index and j is less than i : +- - - Calculate the potential common difference l using the formula 2 * nums[j] - nums[i]. +- - - Check if there are elements with value l in the map. +- - - If yes, iterate through the indices of elements with value l in the map: +- - - - For each index in, if j > in, update gp[i][j] by adding gp[j][in] + 1. This is because a new arithmetic slice is formed by extending the slice ending at index in. +- - - Accumulate the value of gp[i][j] to the overall answer jawab. +- Final Result : +- - The final answer is stored in the variable jawab. +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $$O(l^2)$$ + + +- Space complexity : $$O(l^2)$$ + + $$l$$ : length of array. +# Code +``` +class Solution { + public int numberOfArithmeticSlices(int[] nums) { + int jawab = 0; // Initialize the answer variable to 0 + int[][] gp = new int[nums.length][nums.length]; // 2D array to store the number of arithmetic slices + Map> map = new HashMap<>(); // Map to store indices of elements with the same value + + // Populate the map with indices of elements having the same value + for (int i = 0; i < nums.length; i++) { + map.putIfAbsent(1L * nums[i], new ArrayList<>()); + map.get(1L * nums[i]).add(i); + } + + // Iterate through each element in the array + for (int i = 0; i < nums.length; i++) { + for (int j = 0; j < i; j++) { + long l = 2L * nums[j] - nums[i]; // Calculate the potential common difference + + // Check if there are elements in the map with the calculated common difference + if (map.containsKey(l)) { + // Iterate through indices of elements with the calculated common difference + for (int in : map.get(l)) { + if (j > in) { + // Update the count of arithmetic slices in the 2D array + gp[i][j] += gp[j][in] + 1; + } + } + } + jawab += gp[i][j]; // Accumulate the count to the overall answer + } + } + + return jawab; // Return the final answer + } +} + +``` From 9f452f8709ee5cde25d71ca550416fec83ed2ba0 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 8 Jan 2024 10:32:42 +0530 Subject: [PATCH 006/300] . --- 2024 January/Daily 08-01-24.md | 102 ++++++++++++++++++++++++++ README.md | 129 ++++++++++++++++++++------------- 2 files changed, 180 insertions(+), 51 deletions(-) create mode 100644 2024 January/Daily 08-01-24.md diff --git a/2024 January/Daily 08-01-24.md b/2024 January/Daily 08-01-24.md new file mode 100644 index 0000000..c70fc41 --- /dev/null +++ b/2024 January/Daily 08-01-24.md @@ -0,0 +1,102 @@ +## Today's 08-01-24 [Problem Link](https://leetcode.com/problems/range-sum-of-bst/description/) +## 938. Range Sum of BST + +# Intuition + + +My code will perform an inorder traversal to selectively accumulate values within the specified range. + +--- +# Approach + +- Inorder Traversal : +- - I implemented a recursive inorder traversal function that follows the BST properties : +- - - Recursively traversed the left subtree. +- - - Checked if the current node's value is within the specified range [low, high]. +- - - If true, thrn added the value to the sum. +- - - Recursively traversed the right subtree. +- Main Method (rangeSumBST) : +- - Initialized the static variables (jor, l, h) to store the sum and the low and high values. +- - Initialized 'jor' to zero. +- - Set the low and high values based on the input parameters. +- - Called the inorder method starting from the root of the BST. +- - Returned the final sum. +--- +# Optimizations +- The use of static variables allows for state retention, avoiding the need for passing parameters across recursive calls. +- The 'inorder' traversal efficiently considers only nodes that could contribute to the sum within the specified range, enhancing performance. +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +--- +# Complexity +- Time complexity : $$O(n)$$ + + +- Space complexity : $$O(h)$$ + +--- +$$n$$ : number of nodes +$$h$$ : height of tree + +--- +# Code +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + // Static variables to store the sum, low, and high values + static int jor; + static int l; + static int h; + + // Main method to calculate the range sum in the BST + public int rangeSumBST(TreeNode root, int low, int high) { + // Initialize the sum, low, and high values + jor = 0; + l = low; + h = high; + + // Perform inorder traversal to calculate the sum within the specified range + inorder(root); + + // Return the final sum + return jor; + } + + // Helper method for inorder traversal + static void inorder(TreeNode r) { + // Base case: if the current node is null, return + if (r == null) { + return; + } + + // Recursively traverse the left subtree + inorder(r.left); + + // Check if the value of the current node is within the specified range [low, high] + if (r.val >= l && r.val <= h) { + // If yes, add the value to the sum + jor += r.val; + } + + // Recursively traverse the right subtree + inorder(r.right); + } +} + +``` \ No newline at end of file diff --git a/README.md b/README.md index 9e83685..d9de955 100644 --- a/README.md +++ b/README.md @@ -5,78 +5,105 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 07-01-24 [Problem Link](https://leetcode.com/problems/arithmetic-slices-ii-subsequence/description/?envType=daily-question&envId=2024-01-07) -## 446. Arithmetic Slices II - Subsequence +## Today's 08-01-24 [Problem Link](https://leetcode.com/problems/range-sum-of-bst/description/) +## 938. Range Sum of BST # Intuition -An arithmetic slice is a sequence of elements in the array such that the difference between consecutive elements is the same. +My code will perform an inorder traversal to selectively accumulate values within the specified range. + +--- # Approach -- Initialization : -- - I initialized the variable 'jawab' to keep track of the total number of arithmetic slices. -- Data Structures : -- - I created a 2D array gp to store the number of arithmetic slices. gp[i][j] represents the number of slices ending at index i with the last element at index j. -- - I have used a HashMap called 'map' to store indices of elements with the same value. This is done to efficiently find potential common differences. -- Populate the Map : -- - I iterated through the elements of the array (nums) and populate the map with indices of elements having the same value. The key is the element value, and the value is a list of indices. -- Dynamic Programming : -- - I iterated through each element in the array (nums) using two nested loops. -- - For each pair of indices (i, j) where i is the current index and j is less than i : -- - - Calculate the potential common difference l using the formula 2 * nums[j] - nums[i]. -- - - Check if there are elements with value l in the map. -- - - If yes, iterate through the indices of elements with value l in the map: -- - - - For each index in, if j > in, update gp[i][j] by adding gp[j][in] + 1. This is because a new arithmetic slice is formed by extending the slice ending at index in. -- - - Accumulate the value of gp[i][j] to the overall answer jawab. -- Final Result : -- - The final answer is stored in the variable jawab. +- Inorder Traversal : +- - I implemented a recursive inorder traversal function that follows the BST properties : +- - - Recursively traversed the left subtree. +- - - Checked if the current node's value is within the specified range [low, high]. +- - - If true, thrn added the value to the sum. +- - - Recursively traversed the right subtree. +- Main Method (rangeSumBST) : +- - Initialized the static variables (jor, l, h) to store the sum and the low and high values. +- - Initialized 'jor' to zero. +- - Set the low and high values based on the input parameters. +- - Called the inorder method starting from the root of the BST. +- - Returned the final sum. +--- +# Optimizations +- The use of static variables allows for state retention, avoiding the need for passing parameters across recursive calls. +- The 'inorder' traversal efficiently considers only nodes that could contribute to the sum within the specified range, enhancing performance. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) +--- # Complexity -- Time complexity : $$O(l^2)$$ +- Time complexity : $$O(n)$$ -- Space complexity : $$O(l^2)$$ +- Space complexity : $$O(h)$$ - $$l$$ : length of array. +--- +$$n$$ : number of nodes +$$h$$ : height of tree + +--- # Code ``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ class Solution { - public int numberOfArithmeticSlices(int[] nums) { - int jawab = 0; // Initialize the answer variable to 0 - int[][] gp = new int[nums.length][nums.length]; // 2D array to store the number of arithmetic slices - Map> map = new HashMap<>(); // Map to store indices of elements with the same value - - // Populate the map with indices of elements having the same value - for (int i = 0; i < nums.length; i++) { - map.putIfAbsent(1L * nums[i], new ArrayList<>()); - map.get(1L * nums[i]).add(i); + // Static variables to store the sum, low, and high values + static int jor; + static int l; + static int h; + + // Main method to calculate the range sum in the BST + public int rangeSumBST(TreeNode root, int low, int high) { + // Initialize the sum, low, and high values + jor = 0; + l = low; + h = high; + + // Perform inorder traversal to calculate the sum within the specified range + inorder(root); + + // Return the final sum + return jor; + } + + // Helper method for inorder traversal + static void inorder(TreeNode r) { + // Base case: if the current node is null, return + if (r == null) { + return; } - // Iterate through each element in the array - for (int i = 0; i < nums.length; i++) { - for (int j = 0; j < i; j++) { - long l = 2L * nums[j] - nums[i]; // Calculate the potential common difference - - // Check if there are elements in the map with the calculated common difference - if (map.containsKey(l)) { - // Iterate through indices of elements with the calculated common difference - for (int in : map.get(l)) { - if (j > in) { - // Update the count of arithmetic slices in the 2D array - gp[i][j] += gp[j][in] + 1; - } - } - } - jawab += gp[i][j]; // Accumulate the count to the overall answer - } + // Recursively traverse the left subtree + inorder(r.left); + + // Check if the value of the current node is within the specified range [low, high] + if (r.val >= l && r.val <= h) { + // If yes, add the value to the sum + jor += r.val; } - return jawab; // Return the final answer + // Recursively traverse the right subtree + inorder(r.right); } } -``` +``` \ No newline at end of file From 39d6abdef112c4386a516aac41752867c48c787c Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Mon, 8 Jan 2024 11:33:15 +0530 Subject: [PATCH 007/300] Update README.md --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d9de955..7a97536 100644 --- a/README.md +++ b/README.md @@ -38,14 +38,14 @@ Keep Solving.:) --- # Complexity -- Time complexity : $$O(n)$$ +- Time complexity : $O(n)$ -- Space complexity : $$O(h)$$ +- Space complexity : $O(h)$ --- -$$n$$ : number of nodes -$$h$$ : height of tree +$n$ : number of nodes +$h$ : height of tree --- # Code @@ -106,4 +106,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 2bd573e46239fc01f8807e13aa729c7a8307ea25 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Mon, 8 Jan 2024 11:33:58 +0530 Subject: [PATCH 008/300] Update README.md --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7a97536..5380713 100644 --- a/README.md +++ b/README.md @@ -36,15 +36,14 @@ My code will perform an inorder traversal to selectively accumulate values withi Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) ---- + # Complexity - Time complexity : $O(n)$ + $n$ : number of nodes - Space complexity : $O(h)$ ---- -$n$ : number of nodes $h$ : height of tree --- From a376b7cf3e5d85e78ee3c6be04405a5bb342b724 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Mon, 8 Jan 2024 11:34:43 +0530 Subject: [PATCH 009/300] Update README.md --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5380713..6dea535 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,6 @@ This is my attempt to make the coding experience easier for you guys so that you My code will perform an inorder traversal to selectively accumulate values within the specified range. ---- # Approach - Inorder Traversal : @@ -28,7 +27,7 @@ My code will perform an inorder traversal to selectively accumulate values withi - - Set the low and high values based on the input parameters. - - Called the inorder method starting from the root of the BST. - - Returned the final sum. ---- + # Optimizations - The use of static variables allows for state retention, avoiding the need for passing parameters across recursive calls. - The 'inorder' traversal efficiently considers only nodes that could contribute to the sum within the specified range, enhancing performance. @@ -36,11 +35,11 @@ My code will perform an inorder traversal to selectively accumulate values withi Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - +--- # Complexity - Time complexity : $O(n)$ - $n$ : number of nodes + $n$ : number of nodes - Space complexity : $O(h)$ From bc14f5491aed83d0f34b138167bb83588759dbee Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Mon, 8 Jan 2024 11:35:41 +0530 Subject: [PATCH 010/300] Update Daily 08-01-24.md --- 2024 January/Daily 08-01-24.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/2024 January/Daily 08-01-24.md b/2024 January/Daily 08-01-24.md index c70fc41..ec83e4e 100644 --- a/2024 January/Daily 08-01-24.md +++ b/2024 January/Daily 08-01-24.md @@ -6,7 +6,6 @@ My code will perform an inorder traversal to selectively accumulate values within the specified range. ---- # Approach - Inorder Traversal : @@ -21,7 +20,7 @@ My code will perform an inorder traversal to selectively accumulate values withi - - Set the low and high values based on the input parameters. - - Called the inorder method starting from the root of the BST. - - Returned the final sum. ---- + # Optimizations - The use of static variables allows for state retention, avoiding the need for passing parameters across recursive calls. - The 'inorder' traversal efficiently considers only nodes that could contribute to the sum within the specified range, enhancing performance. @@ -31,14 +30,13 @@ Keep Solving.:) --- # Complexity -- Time complexity : $$O(n)$$ +- Time complexity : $O(n)$ + $n$ : number of nodes -- Space complexity : $$O(h)$$ +- Space complexity : $O(h)$ ---- -$$n$$ : number of nodes -$$h$$ : height of tree +$h$ : height of tree --- # Code @@ -99,4 +97,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 4757219a3a95b826ebc7c944b698573b80fe2986 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 9 Jan 2024 10:31:17 +0530 Subject: [PATCH 011/300] Update README.md --- README.md | 133 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 79 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index 6dea535..b11806f 100644 --- a/README.md +++ b/README.md @@ -5,47 +5,45 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 08-01-24 [Problem Link](https://leetcode.com/problems/range-sum-of-bst/description/) -## 938. Range Sum of BST +## Today's 09-01-24 [Problem Link](https://leetcode.com/problems/leaf-similar-trees/description/?submissionId=1141098031) +## 872. Leaf-Similar Trees + # Intuition - -My code will perform an inorder traversal to selectively accumulate values within the specified range. +The leaf sequence of a tree refers to the sequence of values encountered when performing a depth-first traversal and reaching a leaf node. My intuition is to compare the leaf sequences of both trees to check if they are identical. # Approach -- Inorder Traversal : -- - I implemented a recursive inorder traversal function that follows the BST properties : -- - - Recursively traversed the left subtree. -- - - Checked if the current node's value is within the specified range [low, high]. -- - - If true, thrn added the value to the sum. -- - - Recursively traversed the right subtree. -- Main Method (rangeSumBST) : -- - Initialized the static variables (jor, l, h) to store the sum and the low and high values. -- - Initialized 'jor' to zero. -- - Set the low and high values based on the input parameters. -- - Called the inorder method starting from the root of the BST. -- - Returned the final sum. - -# Optimizations -- The use of static variables allows for state retention, avoiding the need for passing parameters across recursive calls. -- The 'inorder' traversal efficiently considers only nodes that could contribute to the sum within the specified range, enhancing performance. +- Leaf Sequence Extraction : +- - My code defines two static lists (t1 and t2) to store the leaf values of the two trees. +- - Two helper methods (leaf1 and leaf2) are implemented to perform a depth-first traversal of each tree and populate the corresponding leaf lists. +- Leaf Traversal : +- - The 'leaf1' method traverses 'root1', identifies leaf nodes, and adds their values to the list 't1'. +- - Similarly, the 'leaf2' method traverses 'root2', identifies leaf nodes, and adds their values to the list 't2'. +- Comparison : +- - After both leaf lists are populated, the code compares the sizes of 't1' and 't2'. +- - If the sizes are different, the leaf sequences cannot be similar, and the code returns false. +- - If the sizes are the same, the code proceeds to compare each element of t1 with the corresponding element in t2. +- - If any pair of corresponding elements is not equal, the leaf sequences are not similar, and the code returns false. +- Result : +- - If the sizes and elements of t1 and t2 are equal, the leaf sequences are considered similar, and the code returns true. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) ---- + # Complexity -- Time complexity : $O(n)$ +- Time complexity : $$O(n)$$ - $n$ : number of nodes +$$n$$ : number of nodes -- Space complexity : $O(h)$ +- Space complexity : $$O(n + r)$$ +$$r = max(h1, h2) $$ ( since recursion stack is used for DFS trversal ) -$h$ : height of tree +$$h1$$ : height of tree 1 +$$h2$$ : height of tree 2 ---- # Code ``` /** @@ -64,43 +62,70 @@ $h$ : height of tree * } */ class Solution { - // Static variables to store the sum, low, and high values - static int jor; - static int l; - static int h; - - // Main method to calculate the range sum in the BST - public int rangeSumBST(TreeNode root, int low, int high) { - // Initialize the sum, low, and high values - jor = 0; - l = low; - h = high; - - // Perform inorder traversal to calculate the sum within the specified range - inorder(root); - - // Return the final sum - return jor; + // Static lists to store the leaf values of the two trees + static List t1; + static List t2; + + // Main method to check if the leaf sequences of two trees are similar + public boolean leafSimilar(TreeNode root1, TreeNode root2) { + // Initialize the static lists to store leaf values + t1 = new ArrayList<>(); + t2 = new ArrayList<>(); + + // Populate t1 with leaf values of root1 + leaf1(root1); + + // Populate t2 with leaf values of root2 + leaf2(root2); + + // Compare the sizes of the two lists + if (t1.size() != t2.size()) { + return false; + } + + // Compare each element of the two lists + for (int i = 0; i < t1.size(); i++) { + if (t1.get(i) != t2.get(i)) { + return false; + } + } + + // If sizes and elements are equal, the leaf sequences are similar + return true; } - // Helper method for inorder traversal - static void inorder(TreeNode r) { + // Helper method to populate t1 with leaf values of a tree + static void leaf1(TreeNode t) { // Base case: if the current node is null, return - if (r == null) { + if (t == null) { return; } - // Recursively traverse the left subtree - inorder(r.left); + // If the current node is a leaf, add its value to t1 + if (t.left == null && t.right == null) { + t1.add(t.val); + } + + // Recursively call leaf1 on the left and right subtrees + leaf1(t.left); + leaf1(t.right); + } + + // Helper method to populate t2 with leaf values of a tree + static void leaf2(TreeNode t) { + // Base case: if the current node is null, return + if (t == null) { + return; + } - // Check if the value of the current node is within the specified range [low, high] - if (r.val >= l && r.val <= h) { - // If yes, add the value to the sum - jor += r.val; + // If the current node is a leaf, add its value to t2 + if (t.left == null && t.right == null) { + t2.add(t.val); } - // Recursively traverse the right subtree - inorder(r.right); + // Recursively call leaf2 on the left and right subtrees + leaf2(t.left); + leaf2(t.right); } } From c1179e4d40e0fecd71c4dc38b292f73236f09afe Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Tue, 9 Jan 2024 10:32:20 +0530 Subject: [PATCH 012/300] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b11806f..b55c01f 100644 --- a/README.md +++ b/README.md @@ -34,15 +34,15 @@ Keep Solving.:) # Complexity -- Time complexity : $$O(n)$$ +- Time complexity : $O(n)$ -$$n$$ : number of nodes +$n$ : number of nodes -- Space complexity : $$O(n + r)$$ -$$r = max(h1, h2) $$ ( since recursion stack is used for DFS trversal ) +- Space complexity : $O(n + r)$ +$r = max(h1, h2) $ ( since recursion stack is used for DFS trversal ) -$$h1$$ : height of tree 1 -$$h2$$ : height of tree 2 +$h1$ : height of tree 1 +$h2$ : height of tree 2 # Code ``` From cf6bbe6d8340f07d240888daa1d10ac6012ecbc3 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Tue, 9 Jan 2024 10:32:44 +0530 Subject: [PATCH 013/300] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b55c01f..0830e0f 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ Keep Solving.:) $n$ : number of nodes - Space complexity : $O(n + r)$ + $r = max(h1, h2) $ ( since recursion stack is used for DFS trversal ) $h1$ : height of tree 1 From 0bea00592330a25d8db3a2bc58bcc7eb196796cd Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Tue, 9 Jan 2024 10:33:07 +0530 Subject: [PATCH 014/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0830e0f..71f9026 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ $n$ : number of nodes - Space complexity : $O(n + r)$ -$r = max(h1, h2) $ ( since recursion stack is used for DFS trversal ) +$r = max(h1, h2)$ ( since recursion stack is used for DFS trversal ) $h1$ : height of tree 1 $h2$ : height of tree 2 From cfa08dd522c30a28356b53a20f52abbb960d3963 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Tue, 9 Jan 2024 10:33:33 +0530 Subject: [PATCH 015/300] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 71f9026..40a0df4 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ $n$ : number of nodes $r = max(h1, h2)$ ( since recursion stack is used for DFS trversal ) $h1$ : height of tree 1 + $h2$ : height of tree 2 # Code From 20062bd38338b7025ed0be167856dca196d7f348 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Tue, 9 Jan 2024 10:34:08 +0530 Subject: [PATCH 016/300] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 40a0df4..f276158 100644 --- a/README.md +++ b/README.md @@ -36,15 +36,15 @@ Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : number of nodes +- - $n$ : number of nodes - Space complexity : $O(n + r)$ -$r = max(h1, h2)$ ( since recursion stack is used for DFS trversal ) +- - $r = max(h1, h2)$ ( since recursion stack is used for DFS trversal ) -$h1$ : height of tree 1 +- - $h1$ : height of tree 1 -$h2$ : height of tree 2 +- - $h2$ : height of tree 2 # Code ``` From 3f3693d134a5e8c8478974a0294939a9ea00345f Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 9 Jan 2024 10:35:37 +0530 Subject: [PATCH 017/300] Create Daily 09-01-24.md --- 2024 January/Daily 09-01-24.md | 127 +++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 2024 January/Daily 09-01-24.md diff --git a/2024 January/Daily 09-01-24.md b/2024 January/Daily 09-01-24.md new file mode 100644 index 0000000..8034859 --- /dev/null +++ b/2024 January/Daily 09-01-24.md @@ -0,0 +1,127 @@ +## Today's 09-01-24 [Problem Link](https://leetcode.com/problems/leaf-similar-trees/description/?submissionId=1141098031) +## 872. Leaf-Similar Trees + + +# Intuition + +The leaf sequence of a tree refers to the sequence of values encountered when performing a depth-first traversal and reaching a leaf node. My intuition is to compare the leaf sequences of both trees to check if they are identical. + +# Approach + +- Leaf Sequence Extraction : +- - My code defines two static lists (t1 and t2) to store the leaf values of the two trees. +- - Two helper methods (leaf1 and leaf2) are implemented to perform a depth-first traversal of each tree and populate the corresponding leaf lists. +- Leaf Traversal : +- - The 'leaf1' method traverses 'root1', identifies leaf nodes, and adds their values to the list 't1'. +- - Similarly, the 'leaf2' method traverses 'root2', identifies leaf nodes, and adds their values to the list 't2'. +- Comparison : +- - After both leaf lists are populated, the code compares the sizes of 't1' and 't2'. +- - If the sizes are different, the leaf sequences cannot be similar, and the code returns false. +- - If the sizes are the same, the code proceeds to compare each element of t1 with the corresponding element in t2. +- - If any pair of corresponding elements is not equal, the leaf sequences are not similar, and the code returns false. +- Result : +- - If the sizes and elements of t1 and t2 are equal, the leaf sequences are considered similar, and the code returns true. +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + + +# Complexity +- Time complexity : $O(n)$ + +- - $n$ : number of nodes + +- Space complexity : $O(n + r)$ + +- - $r = max(h1, h2)$ ( since recursion stack is used for DFS trversal ) + +- - $h1$ : height of tree 1 + +- - $h2$ : height of tree 2 + +# Code +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + // Static lists to store the leaf values of the two trees + static List t1; + static List t2; + + // Main method to check if the leaf sequences of two trees are similar + public boolean leafSimilar(TreeNode root1, TreeNode root2) { + // Initialize the static lists to store leaf values + t1 = new ArrayList<>(); + t2 = new ArrayList<>(); + + // Populate t1 with leaf values of root1 + leaf1(root1); + + // Populate t2 with leaf values of root2 + leaf2(root2); + + // Compare the sizes of the two lists + if (t1.size() != t2.size()) { + return false; + } + + // Compare each element of the two lists + for (int i = 0; i < t1.size(); i++) { + if (t1.get(i) != t2.get(i)) { + return false; + } + } + + // If sizes and elements are equal, the leaf sequences are similar + return true; + } + + // Helper method to populate t1 with leaf values of a tree + static void leaf1(TreeNode t) { + // Base case: if the current node is null, return + if (t == null) { + return; + } + + // If the current node is a leaf, add its value to t1 + if (t.left == null && t.right == null) { + t1.add(t.val); + } + + // Recursively call leaf1 on the left and right subtrees + leaf1(t.left); + leaf1(t.right); + } + + // Helper method to populate t2 with leaf values of a tree + static void leaf2(TreeNode t) { + // Base case: if the current node is null, return + if (t == null) { + return; + } + + // If the current node is a leaf, add its value to t2 + if (t.left == null && t.right == null) { + t2.add(t.val); + } + + // Recursively call leaf2 on the left and right subtrees + leaf2(t.left); + leaf2(t.right); + } +} + +``` From 4b203c6a4dbbfa0afa36ad27842fd56383eb9696 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 10 Jan 2024 11:24:30 +0530 Subject: [PATCH 018/300] Update README.md --- README.md | 168 ++++++++++++++++++++++++++---------------------------- 1 file changed, 81 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index f276158..3d49110 100644 --- a/README.md +++ b/README.md @@ -5,46 +5,38 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 09-01-24 [Problem Link](https://leetcode.com/problems/leaf-similar-trees/description/?submissionId=1141098031) -## 872. Leaf-Similar Trees +## Today's 10-01-24 [Problem Link](https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/description/) +## 2385. Amount of Time for Binary Tree to Be Infected # Intuition -The leaf sequence of a tree refers to the sequence of values encountered when performing a depth-first traversal and reaching a leaf node. My intuition is to compare the leaf sequences of both trees to check if they are identical. +My code aims to calculate the amount of time it takes to visit all unique nodes in a tree, starting from a specified node. It uses Breadth-First Search (BFS) for traversing the tree and employs a visualization process to represent the tree as an adjacency list. # Approach -- Leaf Sequence Extraction : -- - My code defines two static lists (t1 and t2) to store the leaf values of the two trees. -- - Two helper methods (leaf1 and leaf2) are implemented to perform a depth-first traversal of each tree and populate the corresponding leaf lists. -- Leaf Traversal : -- - The 'leaf1' method traverses 'root1', identifies leaf nodes, and adds their values to the list 't1'. -- - Similarly, the 'leaf2' method traverses 'root2', identifies leaf nodes, and adds their values to the list 't2'. -- Comparison : -- - After both leaf lists are populated, the code compares the sizes of 't1' and 't2'. -- - If the sizes are different, the leaf sequences cannot be similar, and the code returns false. -- - If the sizes are the same, the code proceeds to compare each element of t1 with the corresponding element in t2. -- - If any pair of corresponding elements is not equal, the leaf sequences are not similar, and the code returns false. -- Result : -- - If the sizes and elements of t1 and t2 are equal, the leaf sequences are considered similar, and the code returns true. ---- -Have a look at the code , still have any confusion then please let me know in the comments -Keep Solving.:) +**Visualization:** + - The `visualisation` method performs a BFS traversal of the tree, creating an adjacency list representation of the tree. It uses a `HashMap` named `visual` where each node is mapped to its neighbors. + +**BFS Traversal for Time Calculation:** + - The `amountOfTime` method uses BFS to traverse the tree starting from the specified node (`start`). + - It initializes a queue (`q`) with the starting node and a set (`dekhahua`) to keep track of visited nodes. + - The variable `jawab` is used to store the result, initialized to -1. + - In each iteration, the code explores the neighbors of the current node, marking them as visited and enqueuing them for further exploration. + - The loop continues until all nodes are visited, and `jawab` is incremented at each level of the BFS traversal. + +**Result:** + - The final result is the value of `jawab`, representing the amount of time needed to visit all unique nodes in the tree starting from the specified node. # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(V+E)$ -- - $n$ : number of nodes - -- Space complexity : $O(n + r)$ -- - $r = max(h1, h2)$ ( since recursion stack is used for DFS trversal ) +- Space complexity : $O(V+E)$ -- - $h1$ : height of tree 1 - -- - $h2$ : height of tree 2 +$V$ : number of vertices +$E$ : number of edges # Code ``` @@ -64,71 +56,73 @@ Keep Solving.:) * } */ class Solution { - // Static lists to store the leaf values of the two trees - static List t1; - static List t2; - - // Main method to check if the leaf sequences of two trees are similar - public boolean leafSimilar(TreeNode root1, TreeNode root2) { - // Initialize the static lists to store leaf values - t1 = new ArrayList<>(); - t2 = new ArrayList<>(); - - // Populate t1 with leaf values of root1 - leaf1(root1); - - // Populate t2 with leaf values of root2 - leaf2(root2); - - // Compare the sizes of the two lists - if (t1.size() != t2.size()) { - return false; - } - - // Compare each element of the two lists - for (int i = 0; i < t1.size(); i++) { - if (t1.get(i) != t2.get(i)) { - return false; + // HashMap to store the visualization of the tree + static HashMap> visual; + + public int amountOfTime(TreeNode root, int start) { + // Generated the visualization of the tree + visualisation(root); + + // Queue for BFS traversal starting from the specified node + Queue q = new ArrayDeque<>(Arrays.asList(start)); + + // HashSet to keep track of visited nodes + HashSet dekhahua = new HashSet<>(Arrays.asList(start)); + + // Variable to store the result + int jawab = -1; + + // Performed BFS traversal + while(!q.isEmpty()) { + for (int s = q.size(); s > 0; s--) { + int t = q.poll(); + // Skip if the node is not in the visualization + if (!visual.containsKey(t)) { + continue; + } + // Enqueued neighbors of the current node + for (int n : visual.get(t)) { + if (dekhahua.contains(n)) { + continue; // Skip if the neighbor is already visited + } + dekhahua.add(n); + q.offer(n); + } } + jawab++; } - - // If sizes and elements are equal, the leaf sequences are similar - return true; - } - - // Helper method to populate t1 with leaf values of a tree - static void leaf1(TreeNode t) { - // Base case: if the current node is null, return - if (t == null) { - return; - } - - // If the current node is a leaf, add its value to t1 - if (t.left == null && t.right == null) { - t1.add(t.val); - } - - // Recursively call leaf1 on the left and right subtrees - leaf1(t.left); - leaf1(t.right); + return jawab; } - // Helper method to populate t2 with leaf values of a tree - static void leaf2(TreeNode t) { - // Base case: if the current node is null, return - if (t == null) { - return; - } - - // If the current node is a leaf, add its value to t2 - if (t.left == null && t.right == null) { - t2.add(t.val); + // Method to generate the visualization of the tree + void visualisation(TreeNode root) { + // Queue for BFS traversal + Queue> q = new ArrayDeque<>(Arrays.asList(new Pair<>(root, -1))); + + // Initialized the HashMap + visual = new HashMap<>(); + + // Performed BFS traversal to generate the visualization + while (!q.isEmpty()) { + Pair jora = q.poll(); + TreeNode n = jora.getKey(); + int p = jora.getValue(); + if (p != -1) { + // Add edges to the visualization + visual.putIfAbsent(p, new ArrayList<>()); + visual.putIfAbsent(n.val, new ArrayList<>()); + visual.get(p).add(n.val); + visual.get(n.val).add(p); + } + // Enqueued left and right children for further exploration + if (n.right != null) { + q.add(new Pair<>(n.right, n.val)); + } + if (n.left != null) { + q.add(new Pair<>(n.left, n.val)); + } } - - // Recursively call leaf2 on the left and right subtrees - leaf2(t.left); - leaf2(t.right); } } -``` +``` \ No newline at end of file From 57fdcc9ff22aa966462da92a3813ae04a50be14f Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 10 Jan 2024 11:25:11 +0530 Subject: [PATCH 019/300] Create Daily 10-01-24.md --- 2024 January/Daily 10-01-24.md | 121 +++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 2024 January/Daily 10-01-24.md diff --git a/2024 January/Daily 10-01-24.md b/2024 January/Daily 10-01-24.md new file mode 100644 index 0000000..ee094c7 --- /dev/null +++ b/2024 January/Daily 10-01-24.md @@ -0,0 +1,121 @@ +## Today's 10-01-24 [Problem Link](https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/description/) +## 2385. Amount of Time for Binary Tree to Be Infected + + +# Intuition + +My code aims to calculate the amount of time it takes to visit all unique nodes in a tree, starting from a specified node. It uses Breadth-First Search (BFS) for traversing the tree and employs a visualization process to represent the tree as an adjacency list. + +# Approach + +**Visualization:** + - The `visualisation` method performs a BFS traversal of the tree, creating an adjacency list representation of the tree. It uses a `HashMap` named `visual` where each node is mapped to its neighbors. + +**BFS Traversal for Time Calculation:** + - The `amountOfTime` method uses BFS to traverse the tree starting from the specified node (`start`). + - It initializes a queue (`q`) with the starting node and a set (`dekhahua`) to keep track of visited nodes. + - The variable `jawab` is used to store the result, initialized to -1. + - In each iteration, the code explores the neighbors of the current node, marking them as visited and enqueuing them for further exploration. + - The loop continues until all nodes are visited, and `jawab` is incremented at each level of the BFS traversal. + +**Result:** + - The final result is the value of `jawab`, representing the amount of time needed to visit all unique nodes in the tree starting from the specified node. + + +# Complexity +- Time complexity : $O(V+E)$ + + +- Space complexity : $O(V+E)$ + +$V$ : number of vertices +$E$ : number of edges + +# Code +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + // HashMap to store the visualization of the tree + static HashMap> visual; + + public int amountOfTime(TreeNode root, int start) { + // Generated the visualization of the tree + visualisation(root); + + // Queue for BFS traversal starting from the specified node + Queue q = new ArrayDeque<>(Arrays.asList(start)); + + // HashSet to keep track of visited nodes + HashSet dekhahua = new HashSet<>(Arrays.asList(start)); + + // Variable to store the result + int jawab = -1; + + // Performed BFS traversal + while(!q.isEmpty()) { + for (int s = q.size(); s > 0; s--) { + int t = q.poll(); + // Skip if the node is not in the visualization + if (!visual.containsKey(t)) { + continue; + } + // Enqueued neighbors of the current node + for (int n : visual.get(t)) { + if (dekhahua.contains(n)) { + continue; // Skip if the neighbor is already visited + } + dekhahua.add(n); + q.offer(n); + } + } + jawab++; + } + return jawab; + } + + // Method to generate the visualization of the tree + void visualisation(TreeNode root) { + // Queue for BFS traversal + Queue> q = new ArrayDeque<>(Arrays.asList(new Pair<>(root, -1))); + + // Initialized the HashMap + visual = new HashMap<>(); + + // Performed BFS traversal to generate the visualization + while (!q.isEmpty()) { + Pair jora = q.poll(); + TreeNode n = jora.getKey(); + int p = jora.getValue(); + if (p != -1) { + // Add edges to the visualization + visual.putIfAbsent(p, new ArrayList<>()); + visual.putIfAbsent(n.val, new ArrayList<>()); + visual.get(p).add(n.val); + visual.get(n.val).add(p); + } + // Enqueued left and right children for further exploration + if (n.right != null) { + q.add(new Pair<>(n.right, n.val)); + } + if (n.left != null) { + q.add(new Pair<>(n.left, n.val)); + } + } + } +} + +``` \ No newline at end of file From a05740b63dce8add9cfb90080c7051a57a1d07d6 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 10 Jan 2024 11:26:16 +0530 Subject: [PATCH 020/300] Update Daily 10-01-24.md --- 2024 January/Daily 10-01-24.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/2024 January/Daily 10-01-24.md b/2024 January/Daily 10-01-24.md index ee094c7..9d1ec81 100644 --- a/2024 January/Daily 10-01-24.md +++ b/2024 January/Daily 10-01-24.md @@ -29,6 +29,7 @@ My code aims to calculate the amount of time it takes to visit all unique nodes - Space complexity : $O(V+E)$ $V$ : number of vertices + $E$ : number of edges # Code @@ -118,4 +119,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 5b319733c26e398d7190f811f9899d04dedd6878 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 10 Jan 2024 11:26:34 +0530 Subject: [PATCH 021/300] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3d49110..f6cd9d4 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ My code aims to calculate the amount of time it takes to visit all unique nodes - Space complexity : $O(V+E)$ $V$ : number of vertices + $E$ : number of edges # Code @@ -125,4 +126,4 @@ class Solution { } } -``` \ No newline at end of file +``` From d7d676d7033fa57542bb336b46f20e91594888ec Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 10 Jan 2024 11:38:04 +0530 Subject: [PATCH 022/300] Update Daily 10-01-24.md --- 2024 January/Daily 10-01-24.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/2024 January/Daily 10-01-24.md b/2024 January/Daily 10-01-24.md index 9d1ec81..d50a17d 100644 --- a/2024 January/Daily 10-01-24.md +++ b/2024 January/Daily 10-01-24.md @@ -20,7 +20,8 @@ My code aims to calculate the amount of time it takes to visit all unique nodes **Result:** - The final result is the value of `jawab`, representing the amount of time needed to visit all unique nodes in the tree starting from the specified node. - +--- +Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity - Time complexity : $O(V+E)$ From edca06a9153cccc55d06b59dbc53cdc0cb5dc3fb Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 10 Jan 2024 11:38:30 +0530 Subject: [PATCH 023/300] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f6cd9d4..67e60cf 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,8 @@ My code aims to calculate the amount of time it takes to visit all unique nodes **Result:** - The final result is the value of `jawab`, representing the amount of time needed to visit all unique nodes in the tree starting from the specified node. - +--- +Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity - Time complexity : $O(V+E)$ From 61285e40de7efc877729af42a97e6b7d6b6d363f Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 11 Jan 2024 10:33:04 +0530 Subject: [PATCH 024/300] Update README.md --- README.md | 140 ++++++++++++++++++++++-------------------------------- 1 file changed, 57 insertions(+), 83 deletions(-) diff --git a/README.md b/README.md index 67e60cf..d0b8030 100644 --- a/README.md +++ b/README.md @@ -5,41 +5,43 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 10-01-24 [Problem Link](https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/description/) -## 2385. Amount of Time for Binary Tree to Be Infected +## Today's 11-01-24 [Problem Link](https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/description/) +## 1026. Maximum Difference Between Node and Ancestor # Intuition -My code aims to calculate the amount of time it takes to visit all unique nodes in a tree, starting from a specified node. It uses Breadth-First Search (BFS) for traversing the tree and employs a visualization process to represent the tree as an adjacency list. +My code aims to find the maximum absolute difference between the values of any two nodes in the same path from the root to a leaf in a binary tree. It utilizes a recursive approach to traverse the tree while maintaining the minimum and maximum values encountered along the path. # Approach -**Visualization:** - - The `visualisation` method performs a BFS traversal of the tree, creating an adjacency list representation of the tree. It uses a `HashMap` named `visual` where each node is mapped to its neighbors. +**Base Case:** + - If the root is null, return 0 as there are no nodes to compare. -**BFS Traversal for Time Calculation:** - - The `amountOfTime` method uses BFS to traverse the tree starting from the specified node (`start`). - - It initializes a queue (`q`) with the starting node and a set (`dekhahua`) to keep track of visited nodes. - - The variable `jawab` is used to store the result, initialized to -1. - - In each iteration, the code explores the neighbors of the current node, marking them as visited and enqueuing them for further exploration. - - The loop continues until all nodes are visited, and `jawab` is incremented at each level of the BFS traversal. +**Recursive Calculation:** + - The `maxAncestorDiff` method takes three parameters: the current node `r`, the minimum value encountered so far `chota`, and the maximum value encountered so far `bara`. + - Update `chota` and `bara` based on the current node's value. + - Calculate the current absolute difference (`currentDifference`) between `bara` and `chota`. + +**Recursive Calls for Left and Right Subtrees:** + - Recursively call `maxAncestorDiff` on the left subtree if it exists and update `leftChildMax` with the result. + - Recursively call `maxAncestorDiff` on the right subtree if it exists and update `rightChildMax` with the result. + +**Calculate Maximum Difference:** + - Calculate the maximum difference from the left and right subtrees (`maxFromChild`). + - Return the maximum value among the current path and the subtrees. **Result:** - - The final result is the value of `jawab`, representing the amount of time needed to visit all unique nodes in the tree starting from the specified node. + - The result is the maximum absolute difference among the values of any two nodes in the same path from the root to a leaf. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity -- Time complexity : $O(V+E)$ +- Time complexity : $O(n)$ - -- Space complexity : $O(V+E)$ +$n$ : number of nodes +- Space complexity : $O(h)$ -$V$ : number of vertices - -$E$ : number of edges - +$h$ : height of tree # Code ``` /** @@ -58,73 +60,45 @@ $E$ : number of edges * } */ class Solution { - // HashMap to store the visualization of the tree - static HashMap> visual; - - public int amountOfTime(TreeNode root, int start) { - // Generated the visualization of the tree - visualisation(root); - - // Queue for BFS traversal starting from the specified node - Queue q = new ArrayDeque<>(Arrays.asList(start)); - - // HashSet to keep track of visited nodes - HashSet dekhahua = new HashSet<>(Arrays.asList(start)); - - // Variable to store the result - int jawab = -1; - - // Performed BFS traversal - while(!q.isEmpty()) { - for (int s = q.size(); s > 0; s--) { - int t = q.poll(); - // Skip if the node is not in the visualization - if (!visual.containsKey(t)) { - continue; - } - // Enqueued neighbors of the current node - for (int n : visual.get(t)) { - if (dekhahua.contains(n)) { - continue; // Skip if the neighbor is already visited - } - dekhahua.add(n); - q.offer(n); - } - } - jawab++; + + public int maxAncestorDiff(TreeNode root) { + // Checked if the tree is empty + if (root == null) { + return 0; } - return jawab; + // Called the helper method with the root and initial min/max values + return maxAncestorDiff(root, root.val, root.val); } - // Method to generate the visualization of the tree - void visualisation(TreeNode root) { - // Queue for BFS traversal - Queue> q = new ArrayDeque<>(Arrays.asList(new Pair<>(root, -1))); - - // Initialized the HashMap - visual = new HashMap<>(); - - // Performed BFS traversal to generate the visualization - while (!q.isEmpty()) { - Pair jora = q.poll(); - TreeNode n = jora.getKey(); - int p = jora.getValue(); - if (p != -1) { - // Add edges to the visualization - visual.putIfAbsent(p, new ArrayList<>()); - visual.putIfAbsent(n.val, new ArrayList<>()); - visual.get(p).add(n.val); - visual.get(n.val).add(p); - } - // Enqueued left and right children for further exploration - if (n.right != null) { - q.add(new Pair<>(n.right, n.val)); - } - if (n.left != null) { - q.add(new Pair<>(n.left, n.val)); - } + // Helper method to calculate the maximum ancestor difference recursively + static int maxAncestorDiff(TreeNode r, int chota, int bara) { + // Update the min and max values for the current path + chota = Math.min(chota, r.val); + bara = Math.max(bara, r.val); + + // Calculated the current difference between min and max values in the path + int currentDifference = bara - chota; + + // Initialized variables for maximum differences from left and right subtrees + int leftChildMax = 0; + int rightChildMax = 0; + + // Recursively calculated the maximum difference from the left subtree + if (r.left != null) { + leftChildMax = maxAncestorDiff(r.left, chota, bara); + } + + // Recursively calculated the maximum difference from the right subtree + if (r.right != null) { + rightChildMax = maxAncestorDiff(r.right, chota, bara); } + + // Calculated the maximum difference among the current path and subtrees + int maxFromChild = Math.max(leftChildMax, rightChildMax); + + // Returned the maximum difference among the current path and subtrees + return Math.max(maxFromChild, currentDifference); } } -``` +``` \ No newline at end of file From aa2dec221cde5fc2ef60a56f97b692a771cb9e43 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Thu, 11 Jan 2024 10:34:28 +0530 Subject: [PATCH 025/300] Update README.md --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index d0b8030..e668eb5 100644 --- a/README.md +++ b/README.md @@ -16,20 +16,20 @@ My code aims to find the maximum absolute difference between the values of any t # Approach **Base Case:** - - If the root is null, return 0 as there are no nodes to compare. + - If the root is null, returned 0 as there are no nodes to compare. **Recursive Calculation:** - - The `maxAncestorDiff` method takes three parameters: the current node `r`, the minimum value encountered so far `chota`, and the maximum value encountered so far `bara`. - - Update `chota` and `bara` based on the current node's value. - - Calculate the current absolute difference (`currentDifference`) between `bara` and `chota`. + - My `maxAncestorDiff` method takes three parameters: the current node `r`, the minimum value encountered so far `chota`, and the maximum value encountered so far `bara`. + - Updated `chota` and `bara` based on the current node's value. + - Calculated the current absolute difference (`currentDifference`) between `bara` and `chota`. **Recursive Calls for Left and Right Subtrees:** - - Recursively call `maxAncestorDiff` on the left subtree if it exists and update `leftChildMax` with the result. - - Recursively call `maxAncestorDiff` on the right subtree if it exists and update `rightChildMax` with the result. + - Recursively called `maxAncestorDiff` on the left subtree if it exists and updated `leftChildMax` with the result. + - Recursively called `maxAncestorDiff` on the right subtree if it exists and updated `rightChildMax` with the result. **Calculate Maximum Difference:** - - Calculate the maximum difference from the left and right subtrees (`maxFromChild`). - - Return the maximum value among the current path and the subtrees. + - Calculated the maximum difference from the left and right subtrees (`maxFromChild`). + - Returned the maximum value among the current path and the subtrees. **Result:** - The result is the maximum absolute difference among the values of any two nodes in the same path from the root to a leaf. @@ -101,4 +101,4 @@ class Solution { } } -``` \ No newline at end of file +``` From b831de00055e3ed350a728a8549d1f1827327170 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 11 Jan 2024 10:36:03 +0530 Subject: [PATCH 026/300] Create Daily 11-01-24.md --- 2024 January/Daily 11-01-24.md | 97 ++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 2024 January/Daily 11-01-24.md diff --git a/2024 January/Daily 11-01-24.md b/2024 January/Daily 11-01-24.md new file mode 100644 index 0000000..6b3a441 --- /dev/null +++ b/2024 January/Daily 11-01-24.md @@ -0,0 +1,97 @@ +## Today's 11-01-24 [Problem Link](https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/description/) +## 1026. Maximum Difference Between Node and Ancestor + + +# Intuition + +My code aims to find the maximum absolute difference between the values of any two nodes in the same path from the root to a leaf in a binary tree. It utilizes a recursive approach to traverse the tree while maintaining the minimum and maximum values encountered along the path. + +# Approach + +**Base Case:** + - If the root is null, returned 0 as there are no nodes to compare. + +**Recursive Calculation:** + - My `maxAncestorDiff` method takes three parameters: the current node `r`, the minimum value encountered so far `chota`, and the maximum value encountered so far `bara`. + - Updated `chota` and `bara` based on the current node's value. + - Calculated the current absolute difference (`currentDifference`) between `bara` and `chota`. + +**Recursive Calls for Left and Right Subtrees:** + - Recursively called `maxAncestorDiff` on the left subtree if it exists and updated `leftChildMax` with the result. + - Recursively called `maxAncestorDiff` on the right subtree if it exists and updated `rightChildMax` with the result. + +**Calculate Maximum Difference:** + - Calculated the maximum difference from the left and right subtrees (`maxFromChild`). + - Returned the maximum value among the current path and the subtrees. + +**Result:** + - The result is the maximum absolute difference among the values of any two nodes in the same path from the root to a leaf. +--- +Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : number of nodes +- Space complexity : $O(h)$ + +$h$ : height of tree +# Code +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + public int maxAncestorDiff(TreeNode root) { + // Checked if the tree is empty + if (root == null) { + return 0; + } + // Called the helper method with the root and initial min/max values + return maxAncestorDiff(root, root.val, root.val); + } + + // Helper method to calculate the maximum ancestor difference recursively + static int maxAncestorDiff(TreeNode r, int chota, int bara) { + // Update the min and max values for the current path + chota = Math.min(chota, r.val); + bara = Math.max(bara, r.val); + + // Calculated the current difference between min and max values in the path + int currentDifference = bara - chota; + + // Initialized variables for maximum differences from left and right subtrees + int leftChildMax = 0; + int rightChildMax = 0; + + // Recursively calculated the maximum difference from the left subtree + if (r.left != null) { + leftChildMax = maxAncestorDiff(r.left, chota, bara); + } + + // Recursively calculated the maximum difference from the right subtree + if (r.right != null) { + rightChildMax = maxAncestorDiff(r.right, chota, bara); + } + + // Calculated the maximum difference among the current path and subtrees + int maxFromChild = Math.max(leftChildMax, rightChildMax); + + // Returned the maximum difference among the current path and subtrees + return Math.max(maxFromChild, currentDifference); + } +} + +``` From 751b46102b1951654d45e697b9ec550c1288ee3b Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 12 Jan 2024 10:23:00 +0530 Subject: [PATCH 027/300] Update README.md --- README.md | 116 +++++++++++++++++++++--------------------------------- 1 file changed, 44 insertions(+), 72 deletions(-) diff --git a/README.md b/README.md index e668eb5..00beaa8 100644 --- a/README.md +++ b/README.md @@ -5,100 +5,72 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 11-01-24 [Problem Link](https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/description/) -## 1026. Maximum Difference Between Node and Ancestor - +## Today's 12-01-24 [Problem Link](https://leetcode.com/problems/determine-if-string-halves-are-alike/description/) +## 1704. Determine if String Halves Are Alike # Intuition -My code aims to find the maximum absolute difference between the values of any two nodes in the same path from the root to a leaf in a binary tree. It utilizes a recursive approach to traverse the tree while maintaining the minimum and maximum values encountered along the path. +My code checks whether the two halves of a given string have an equal number of vowels. The comparison is case-insensitive, and the goal is to determine if the two halves are alike in terms of the number of vowels. + # Approach -**Base Case:** - - If the root is null, returned 0 as there are no nodes to compare. -**Recursive Calculation:** - - My `maxAncestorDiff` method takes three parameters: the current node `r`, the minimum value encountered so far `chota`, and the maximum value encountered so far `bara`. - - Updated `chota` and `bara` based on the current node's value. - - Calculated the current absolute difference (`currentDifference`) between `bara` and `chota`. +**Converted to Lowercase:** + - I Convert the input string `s` to lowercase for case-insensitive comparison. -**Recursive Calls for Left and Right Subtrees:** - - Recursively called `maxAncestorDiff` on the left subtree if it exists and updated `leftChildMax` with the result. - - Recursively called `maxAncestorDiff` on the right subtree if it exists and updated `rightChildMax` with the result. +**Initialize Vowel Counter:** + - I initialized a counter variable `vowel` to keep track of the number of vowels. -**Calculate Maximum Difference:** - - Calculated the maximum difference from the left and right subtrees (`maxFromChild`). - - Returned the maximum value among the current path and the subtrees. +**Check First Half:** + - Iterated through the first half of the string (`s.length() / 2`). + - If the current character is a vowel ('a', 'e', 'i', 'o', 'u'), incremented the `vowel` counter. -**Result:** - - The result is the maximum absolute difference among the values of any two nodes in the same path from the root to a leaf. +**Check Second Half:** + - Iterated through the second half of the string (`s.length() / 2` to `s.length()`). + - If the current character is a vowel, decremented the `vowel` counter. + +**Check if Halves Are Alike:** + - If the `vowel` counter is zero after both iterations, return `true`, indicating that the two halves have an equal number of vowels. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(c)$ -$n$ : number of nodes -- Space complexity : $O(h)$ + $c$ : number of characters in array +- Space complexity : $O(1)$ -$h$ : height of tree + # Code ``` -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ class Solution { - - public int maxAncestorDiff(TreeNode root) { - // Checked if the tree is empty - if (root == null) { - return 0; + public boolean halvesAreAlike(String s) { + // Converted the string to lowercase (Note: Strings in Java are immutable) + s = s.toLowerCase(); + + // Initialized a counter for vowels + int vowel = 0; + + // Checked the first half of the string + for (int i = 0; i < s.length() / 2; i++) { + // If the current character is a vowel, incremented the vowel counter + if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u') { + vowel++; + } } - // Called the helper method with the root and initial min/max values - return maxAncestorDiff(root, root.val, root.val); - } - - // Helper method to calculate the maximum ancestor difference recursively - static int maxAncestorDiff(TreeNode r, int chota, int bara) { - // Update the min and max values for the current path - chota = Math.min(chota, r.val); - bara = Math.max(bara, r.val); - // Calculated the current difference between min and max values in the path - int currentDifference = bara - chota; - - // Initialized variables for maximum differences from left and right subtrees - int leftChildMax = 0; - int rightChildMax = 0; - - // Recursively calculated the maximum difference from the left subtree - if (r.left != null) { - leftChildMax = maxAncestorDiff(r.left, chota, bara); - } - - // Recursively calculated the maximum difference from the right subtree - if (r.right != null) { - rightChildMax = maxAncestorDiff(r.right, chota, bara); + // Checked the second half of the string + for (int i = s.length() / 2; i < s.length(); i++) { + // If the current character is a vowel, decremented the vowel counter + if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u') { + vowel--; + } } - // Calculated the maximum difference among the current path and subtrees - int maxFromChild = Math.max(leftChildMax, rightChildMax); - - // Returned the maximum difference among the current path and subtrees - return Math.max(maxFromChild, currentDifference); + // If the vowel counter is 0, the two halves are alike; otherwise, they are not alike + return vowel == 0; } } -``` +``` \ No newline at end of file From 624432cf004eada964d9805b135fbc5566735b3e Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 12 Jan 2024 10:24:17 +0530 Subject: [PATCH 028/300] Create Daily 12-01-24.md --- 2024 January/Daily 12-01-24.md | 69 ++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 2024 January/Daily 12-01-24.md diff --git a/2024 January/Daily 12-01-24.md b/2024 January/Daily 12-01-24.md new file mode 100644 index 0000000..d86363b --- /dev/null +++ b/2024 January/Daily 12-01-24.md @@ -0,0 +1,69 @@ +## Today's 12-01-24 [Problem Link](https://leetcode.com/problems/determine-if-string-halves-are-alike/description/) +## 1704. Determine if String Halves Are Alike + +# Intuition + +My code checks whether the two halves of a given string have an equal number of vowels. The comparison is case-insensitive, and the goal is to determine if the two halves are alike in terms of the number of vowels. + + +# Approach + + +**Converted to Lowercase:** + - I Convert the input string `s` to lowercase for case-insensitive comparison. + +**Initialize Vowel Counter:** + - I initialized a counter variable `vowel` to keep track of the number of vowels. + +**Check First Half:** + - Iterated through the first half of the string (`s.length() / 2`). + - If the current character is a vowel ('a', 'e', 'i', 'o', 'u'), incremented the `vowel` counter. + +**Check Second Half:** + - Iterated through the second half of the string (`s.length() / 2` to `s.length()`). + - If the current character is a vowel, decremented the `vowel` counter. + +**Check if Halves Are Alike:** + - If the `vowel` counter is zero after both iterations, return `true`, indicating that the two halves have an equal number of vowels. +--- +Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + +# Complexity +- Time complexity : $O(c)$ + + $c$ : number of characters in array +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + public boolean halvesAreAlike(String s) { + // Converted the string to lowercase (Note: Strings in Java are immutable) + s = s.toLowerCase(); + + // Initialized a counter for vowels + int vowel = 0; + + // Checked the first half of the string + for (int i = 0; i < s.length() / 2; i++) { + // If the current character is a vowel, incremented the vowel counter + if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u') { + vowel++; + } + } + + // Checked the second half of the string + for (int i = s.length() / 2; i < s.length(); i++) { + // If the current character is a vowel, decremented the vowel counter + if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u') { + vowel--; + } + } + + // If the vowel counter is 0, the two halves are alike; otherwise, they are not alike + return vowel == 0; + } +} + +``` \ No newline at end of file From 988f4a47c103f04a75d43ec8eff5ad3ae2c2dfac Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 13 Jan 2024 10:57:31 +0530 Subject: [PATCH 029/300] Update README.md --- README.md | 74 +++++++++++++++++++------------------------------------ 1 file changed, 26 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 00beaa8..881b4ad 100644 --- a/README.md +++ b/README.md @@ -5,72 +5,50 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 12-01-24 [Problem Link](https://leetcode.com/problems/determine-if-string-halves-are-alike/description/) -## 1704. Determine if String Halves Are Alike +## Today's 12-01-24 [Problem Link](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/description/?envType=daily-question&envId=2024-01-13) +## 1347. Minimum Number of Steps to Make Two Strings Anagram # Intuition -My code checks whether the two halves of a given string have an equal number of vowels. The comparison is case-insensitive, and the goal is to determine if the two halves are alike in terms of the number of vowels. - +As the goal is to find the minimum number of steps required to make two strings, s and t, anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of another. In this context, it means transforming one string into another by changing the order of its characters. # Approach +1. Created a HashMap (`m`) to store the frequency of characters in string `s`. +2. Iterated through each character in string `s` and update its frequency in the HashMap. +3. Initialized a variable `extra` to track the number of extra characters needed in string `t` to make it an anagram of `s`. +4. Iterated through each character in string `t`: + - If the character exists in the HashMap and has a positive frequency, decrement its frequency in the HashMap. + - If the character is not found or has no remaining occurrences in the HashMap, increment the `extra` count. +5. The final value of `extra` represents the minimum number of steps needed to make strings `s` and `t` anagrams. -**Converted to Lowercase:** - - I Convert the input string `s` to lowercase for case-insensitive comparison. - -**Initialize Vowel Counter:** - - I initialized a counter variable `vowel` to keep track of the number of vowels. - -**Check First Half:** - - Iterated through the first half of the string (`s.length() / 2`). - - If the current character is a vowel ('a', 'e', 'i', 'o', 'u'), incremented the `vowel` counter. - -**Check Second Half:** - - Iterated through the second half of the string (`s.length() / 2` to `s.length()`). - - If the current character is a vowel, decremented the `vowel` counter. - -**Check if Halves Are Alike:** - - If the `vowel` counter is zero after both iterations, return `true`, indicating that the two halves have an equal number of vowels. ---- -Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(c)$ +- Time complexity : $O(l)$ - $c$ : number of characters in array -- Space complexity : $O(1)$ +$l$ : length of string +- Space complexity : $O(l)$ # Code ``` class Solution { - public boolean halvesAreAlike(String s) { - // Converted the string to lowercase (Note: Strings in Java are immutable) - s = s.toLowerCase(); - - // Initialized a counter for vowels - int vowel = 0; - - // Checked the first half of the string - for (int i = 0; i < s.length() / 2; i++) { - // If the current character is a vowel, incremented the vowel counter - if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u') { - vowel++; - } + public int minSteps(String s, String t) { + HashMap m = new HashMap<>(); + for( char c : s.toCharArray()){ + m.putIfAbsent(c, 0); + m.put( c, m.getOrDefault(c, 0) + 1); } - - // Checked the second half of the string - for (int i = s.length() / 2; i < s.length(); i++) { - // If the current character is a vowel, decremented the vowel counter - if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u') { - vowel--; + int extra = 0; + for( char c : t.toCharArray()){ + if( m.getOrDefault(c,0) > 0){ + m.put( c, m.get(c) - 1); + } + else{ + extra++; } } - - // If the vowel counter is 0, the two halves are alike; otherwise, they are not alike - return vowel == 0; + return extra; } } - ``` \ No newline at end of file From af80956661f67722b0b228e60dc9124104363772 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 13 Jan 2024 11:01:58 +0530 Subject: [PATCH 030/300] Update README.md --- README.md | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 881b4ad..1347c1f 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,9 @@ As the goal is to find the minimum number of steps required to make two strings, - If the character exists in the HashMap and has a positive frequency, decrement its frequency in the HashMap. - If the character is not found or has no remaining occurrences in the HashMap, increment the `extra` count. 5. The final value of `extra` represents the minimum number of steps needed to make strings `s` and `t` anagrams. - +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) # Complexity - Time complexity : $O(l)$ @@ -33,22 +35,35 @@ $l$ : length of string # Code ``` class Solution { + public int minSteps(String s, String t) { + // Created a HashMap to store the frequency of characters in string s HashMap m = new HashMap<>(); - for( char c : s.toCharArray()){ + + // Counted the frequency of each character in string s + for (char c : s.toCharArray()) { m.putIfAbsent(c, 0); - m.put( c, m.getOrDefault(c, 0) + 1); + m.put(c, m.getOrDefault(c, 0) + 1); } + + // Variable to track the extra characters in string t int extra = 0; - for( char c : t.toCharArray()){ - if( m.getOrDefault(c,0) > 0){ - m.put( c, m.get(c) - 1); - } - else{ + + // Checked characters in string t against the frequency in the HashMap + for (char c : t.toCharArray()) { + // If the character exists in the HashMap and has a positive frequency + if (m.getOrDefault(c, 0) > 0) { + // Decrease the frequency in the HashMap + m.put(c, m.get(c) - 1); + } else { + // If the character is not found or has no remaining occurrences in the HashMap, increment extra extra++; } } + + // Returned the total count of extra characters in string t return extra; } } + ``` \ No newline at end of file From ea7179b976eee59cce597edecde5a82111538fde Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 13 Jan 2024 11:02:33 +0530 Subject: [PATCH 031/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1347c1f..215dea7 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 12-01-24 [Problem Link](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/description/?envType=daily-question&envId=2024-01-13) +## Today's 13-01-24 [Problem Link](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/description/?envType=daily-question&envId=2024-01-13) ## 1347. Minimum Number of Steps to Make Two Strings Anagram # Intuition From d7e38233364196c85169f5ca2b9ac5e3445b6197 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 13 Jan 2024 11:03:52 +0530 Subject: [PATCH 032/300] Create Daily 13-01-24.md --- 2024 January/Daily 13-01-24.md | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 2024 January/Daily 13-01-24.md diff --git a/2024 January/Daily 13-01-24.md b/2024 January/Daily 13-01-24.md new file mode 100644 index 0000000..36793f1 --- /dev/null +++ b/2024 January/Daily 13-01-24.md @@ -0,0 +1,62 @@ +## Today's 13-01-24 [Problem Link](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/description/?envType=daily-question&envId=2024-01-13) +## 1347. Minimum Number of Steps to Make Two Strings Anagram + +# Intuition + +As the goal is to find the minimum number of steps required to make two strings, s and t, anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of another. In this context, it means transforming one string into another by changing the order of its characters. + +# Approach + +1. Created a HashMap (`m`) to store the frequency of characters in string `s`. +2. Iterated through each character in string `s` and update its frequency in the HashMap. +3. Initialized a variable `extra` to track the number of extra characters needed in string `t` to make it an anagram of `s`. +4. Iterated through each character in string `t`: + - If the character exists in the HashMap and has a positive frequency, decrement its frequency in the HashMap. + - If the character is not found or has no remaining occurrences in the HashMap, increment the `extra` count. +5. The final value of `extra` represents the minimum number of steps needed to make strings `s` and `t` anagrams. +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(l)$ + +$l$ : length of string +- Space complexity : $O(l)$ + + +# Code +``` +class Solution { + + public int minSteps(String s, String t) { + // Created a HashMap to store the frequency of characters in string s + HashMap m = new HashMap<>(); + + // Counted the frequency of each character in string s + for (char c : s.toCharArray()) { + m.putIfAbsent(c, 0); + m.put(c, m.getOrDefault(c, 0) + 1); + } + + // Variable to track the extra characters in string t + int extra = 0; + + // Checked characters in string t against the frequency in the HashMap + for (char c : t.toCharArray()) { + // If the character exists in the HashMap and has a positive frequency + if (m.getOrDefault(c, 0) > 0) { + // Decrease the frequency in the HashMap + m.put(c, m.get(c) - 1); + } else { + // If the character is not found or has no remaining occurrences in the HashMap, increment extra + extra++; + } + } + + // Returned the total count of extra characters in string t + return extra; + } +} + +``` \ No newline at end of file From d2c2213ebb652afece43ffbbeef28483c9963439 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 14 Jan 2024 11:13:22 +0530 Subject: [PATCH 033/300] Update README.md --- README.md | 93 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 53 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 215dea7..f39bbb0 100644 --- a/README.md +++ b/README.md @@ -5,65 +5,78 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 13-01-24 [Problem Link](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/description/?envType=daily-question&envId=2024-01-13) -## 1347. Minimum Number of Steps to Make Two Strings Anagram +## Today's 14-01-24 [Problem Link](https://leetcode.com/problems/determine-if-two-strings-are-close/description/?envType=daily-question&envId=2024-01-14) +## 1657. Determine if Two Strings Are Close + # Intuition -As the goal is to find the minimum number of steps required to make two strings, s and t, anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of another. In this context, it means transforming one string into another by changing the order of its characters. +As the goal of this code is to determine if two strings are "close." Two strings are considered "close" if they have the same set of characters and the frequency of each character is the same in both strings. # Approach -1. Created a HashMap (`m`) to store the frequency of characters in string `s`. -2. Iterated through each character in string `s` and update its frequency in the HashMap. -3. Initialized a variable `extra` to track the number of extra characters needed in string `t` to make it an anagram of `s`. -4. Iterated through each character in string `t`: - - If the character exists in the HashMap and has a positive frequency, decrement its frequency in the HashMap. - - If the character is not found or has no remaining occurrences in the HashMap, increment the `extra` count. -5. The final value of `extra` represents the minimum number of steps needed to make strings `s` and `t` anagrams. +- Checked if the lengths of both input strings (`word1` and `word2`) are equal. If not, return `false` since strings of different lengths cannot be "close." + +- Created two HashMaps (`m1` and `m2`) to store the frequency of each character in `word1` and `word2` respectively. + +- Iterated through each character in `word1` and update the frequency in `m1`. + +- Iterated through each character in `word2` and update the frequency in `m2`. + +- Checked if the sets of characters in both HashMaps are equal. If not, return `false` since the characters must be the same for the strings to be "close." + +- Extracted the frequency lists from both HashMaps and sort them. + +- Checked if the sorted frequency lists are equal. If they are, return `true`; otherwise, return `false`. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(l)$ +- Time complexity : $O(nlogn)$ -$l$ : length of string -- Space complexity : $O(l)$ +$n$ : size of array +- Space complexity : $O(n)$ # Code ``` class Solution { - - public int minSteps(String s, String t) { - // Created a HashMap to store the frequency of characters in string s - HashMap m = new HashMap<>(); - - // Counted the frequency of each character in string s - for (char c : s.toCharArray()) { - m.putIfAbsent(c, 0); - m.put(c, m.getOrDefault(c, 0) + 1); + public boolean closeStrings(String word1, String word2) { + // Checked if the lengths of the two words are different, they cannot be "close." + if (word1.length() != word2.length()) { + return false; } - - // Variable to track the extra characters in string t - int extra = 0; - - // Checked characters in string t against the frequency in the HashMap - for (char c : t.toCharArray()) { - // If the character exists in the HashMap and has a positive frequency - if (m.getOrDefault(c, 0) > 0) { - // Decrease the frequency in the HashMap - m.put(c, m.get(c) - 1); - } else { - // If the character is not found or has no remaining occurrences in the HashMap, increment extra - extra++; - } + + // HashMaps to store character frequencies for each word. + HashMap m1 = new HashMap<>(); + HashMap m2 = new HashMap<>(); + + // Counted character frequencies in word1. + for (char ch : word1.toCharArray()) { + m1.merge(ch, 1, Integer::sum); } - - // Returned the total count of extra characters in string t - return extra; + + // Counted character frequencies in word2. + for (char ch : word2.toCharArray()) { + m2.merge(ch, 1, Integer::sum); + } + + // Checked if the sets of characters are the same in both words. + if (!m1.keySet().equals(m2.keySet())) { + return false; + } + + // Extracted frequency lists for each word. + ArrayList f1 = new ArrayList<>(m1.values()); + ArrayList f2 = new ArrayList<>(m2.values()); + + // Sorted frequency lists. + Collections.sort(f1); + Collections.sort(f2); + + // Checked if the sorted frequency lists are equal. + return f1.equals(f2); } } - ``` \ No newline at end of file From 8b611c3b08ac3daf3464c011cbaba1856e1a8fb4 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 14 Jan 2024 11:14:36 +0530 Subject: [PATCH 034/300] Create Daily 14-01-24.md --- 2024 January/Daily 14-01-24.md | 75 ++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 2024 January/Daily 14-01-24.md diff --git a/2024 January/Daily 14-01-24.md b/2024 January/Daily 14-01-24.md new file mode 100644 index 0000000..c8fa2ee --- /dev/null +++ b/2024 January/Daily 14-01-24.md @@ -0,0 +1,75 @@ +## Today's 14-01-24 [Problem Link](https://leetcode.com/problems/determine-if-two-strings-are-close/description/?envType=daily-question&envId=2024-01-14) +## 1657. Determine if Two Strings Are Close + + +# Intuition + +As the goal of this code is to determine if two strings are "close." Two strings are considered "close" if they have the same set of characters and the frequency of each character is the same in both strings. + +# Approach + +- Checked if the lengths of both input strings (`word1` and `word2`) are equal. If not, return `false` since strings of different lengths cannot be "close." + +- Created two HashMaps (`m1` and `m2`) to store the frequency of each character in `word1` and `word2` respectively. + +- Iterated through each character in `word1` and update the frequency in `m1`. + +- Iterated through each character in `word2` and update the frequency in `m2`. + +- Checked if the sets of characters in both HashMaps are equal. If not, return `false` since the characters must be the same for the strings to be "close." + +- Extracted the frequency lists from both HashMaps and sort them. + +- Checked if the sorted frequency lists are equal. If they are, return `true`; otherwise, return `false`. +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(nlogn)$ + +$n$ : size of array +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + public boolean closeStrings(String word1, String word2) { + // Checked if the lengths of the two words are different, they cannot be "close." + if (word1.length() != word2.length()) { + return false; + } + + // HashMaps to store character frequencies for each word. + HashMap m1 = new HashMap<>(); + HashMap m2 = new HashMap<>(); + + // Counted character frequencies in word1. + for (char ch : word1.toCharArray()) { + m1.merge(ch, 1, Integer::sum); + } + + // Counted character frequencies in word2. + for (char ch : word2.toCharArray()) { + m2.merge(ch, 1, Integer::sum); + } + + // Checked if the sets of characters are the same in both words. + if (!m1.keySet().equals(m2.keySet())) { + return false; + } + + // Extracted frequency lists for each word. + ArrayList f1 = new ArrayList<>(m1.values()); + ArrayList f2 = new ArrayList<>(m2.values()); + + // Sorted frequency lists. + Collections.sort(f1); + Collections.sort(f2); + + // Checked if the sorted frequency lists are equal. + return f1.equals(f2); + } +} +``` \ No newline at end of file From 9299d2e5fd04de47b9b827637486289b69e2a9bb Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 15 Jan 2024 11:11:33 +0530 Subject: [PATCH 035/300] Update README.md --- README.md | 119 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 80 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index f39bbb0..813cbe9 100644 --- a/README.md +++ b/README.md @@ -5,78 +5,119 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 14-01-24 [Problem Link](https://leetcode.com/problems/determine-if-two-strings-are-close/description/?envType=daily-question&envId=2024-01-14) -## 1657. Determine if Two Strings Are Close +## Today's 15-01-24 [Problem Link](https://leetcode.com/problems/find-players-with-zero-or-one-losses/description/?envType=daily-question&envId=2024-01-15) +## 2225. Find Players With Zero or One Losses # Intuition -As the goal of this code is to determine if two strings are "close." Two strings are considered "close" if they have the same set of characters and the frequency of each character is the same in both strings. +My Java code aims to find the winners and players who have lost only once in a series of matches. It uses a HashMap to store the count of losses for each player and a HashSet to store the winners. # Approach -- Checked if the lengths of both input strings (`word1` and `word2`) are equal. If not, return `false` since strings of different lengths cannot be "close." +###### HashMap and HashSet Initialization -- Created two HashMaps (`m1` and `m2`) to store the frequency of each character in `word1` and `word2` respectively. +- Initialized `loser` as a HashMap to store the count of losses for each player. +- Initialized `winner` as a HashSet to store the winners. -- Iterated through each character in `word1` and update the frequency in `m1`. +###### Iterated through Matches -- Iterated through each character in `word2` and update the frequency in `m2`. +- For each match in the `matches` array: + - Add the first player of the match to the `winner` set. + - If the second player is not in the `loser` map, add it with a count of 1. + - If the second player is already in the `loser` map, increment its count by 1. -- Checked if the sets of characters in both HashMaps are equal. If not, return `false` since the characters must be the same for the strings to be "close." +###### Identified `Not Lost` Players -- Extracted the frequency lists from both HashMaps and sort them. +- Created a list `notlost` to store players who haven't lost. +- Iterated through the `winner` set: + - If a player is not in the `loser` map, added them to the `notlost` list. -- Checked if the sorted frequency lists are equal. If they are, return `true`; otherwise, return `false`. +###### Identified Players `Lost Only` Once + +- Created a list `lostone` to store players who have lost only once. +- Iterate through the `loser` map: + - If a player has lost only once (count = 1), added them to the `lostone` list. + +###### Sort Lists + +- Sorted both `notlost` and `lostone` lists. + +###### Created a Result List + +- Created a list of lists `jawab` to store the final result. +- Added `notlost` and `lostone` lists to `jawab`. + +###### Return Result + +- Returned the `jawab` list containing the players who haven't lost and those who have lost only once. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + # Complexity -- Time complexity : $O(nlogn)$ +- Time complexity : $O(N + M + K*log(K))$ -$n$ : size of array -- Space complexity : $O(n)$ +$N$ : number of matches +$M$ : number of players +$K$ : number of players who have lost only once +$K*log(K)$ : sorting of lists + +- Space complexity : $O(M+K)$ # Code ``` class Solution { - public boolean closeStrings(String word1, String word2) { - // Checked if the lengths of the two words are different, they cannot be "close." - if (word1.length() != word2.length()) { - return false; + public List> findWinners(int[][] matches) { + // HashMap to store the count of losses for each player + HashMap loser = new HashMap<>(); + // HashSet to store the winners + HashSet winner = new HashSet<>(); + + // Iterated through each match + for (int[] r : matches) { + // Added the first player of the match to the winner set + winner.add(r[0]); + // If the second player is not in the loser map, added it with a count of 1 + // If the second player is already in the loser map, incremented its count by 1 + loser.putIfAbsent(r[1], 0); + loser.put(r[1], loser.get(r[1]) + 1); } - // HashMaps to store character frequencies for each word. - HashMap m1 = new HashMap<>(); - HashMap m2 = new HashMap<>(); + // Lists to store players who haven't lost and those who have lost only once + List notlost = new ArrayList<>(); + List lostone = new ArrayList<>(); - // Counted character frequencies in word1. - for (char ch : word1.toCharArray()) { - m1.merge(ch, 1, Integer::sum); + // Iterated through the winner set + for (int w : winner) { + // If a player is not in the loser map, added them to the notlost list + if (!loser.containsKey(w)) { + notlost.add(w); + } } - // Counted character frequencies in word2. - for (char ch : word2.toCharArray()) { - m2.merge(ch, 1, Integer::sum); + // Iterated through the loser map + for (int lo : loser.keySet()) { + // If a player has lost only once (count = 1), added them to the lostone list + if (loser.get(lo) == 1) { + lostone.add(lo); + } } - // Checked if the sets of characters are the same in both words. - if (!m1.keySet().equals(m2.keySet())) { - return false; - } - - // Extracted frequency lists for each word. - ArrayList f1 = new ArrayList<>(m1.values()); - ArrayList f2 = new ArrayList<>(m2.values()); + // Sorted both notlost and lostone lists + Collections.sort(notlost); + Collections.sort(lostone); - // Sorted frequency lists. - Collections.sort(f1); - Collections.sort(f2); + // List of lists to store the final result + List> jawab = new ArrayList<>(); + jawab.add(notlost); + jawab.add(lostone); - // Checked if the sorted frequency lists are equal. - return f1.equals(f2); + // Returned the result + return jawab; } } + ``` \ No newline at end of file From 0aacd8162485ee6ae5f27e92d79c73c18805eb81 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Mon, 15 Jan 2024 11:12:21 +0530 Subject: [PATCH 036/300] Update README.md --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 813cbe9..cb278a6 100644 --- a/README.md +++ b/README.md @@ -60,8 +60,11 @@ Keep Solving.:) - Time complexity : $O(N + M + K*log(K))$ $N$ : number of matches + $M$ : number of players + $K$ : number of players who have lost only once + $K*log(K)$ : sorting of lists - Space complexity : $O(M+K)$ @@ -120,4 +123,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 7a980fbbf3df64133fdd3b25be293063b6881024 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 15 Jan 2024 11:13:42 +0530 Subject: [PATCH 037/300] Create Daily 15-01-24.md --- 2024 January/Daily 15-01-24.md | 119 +++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 2024 January/Daily 15-01-24.md diff --git a/2024 January/Daily 15-01-24.md b/2024 January/Daily 15-01-24.md new file mode 100644 index 0000000..efd0c7a --- /dev/null +++ b/2024 January/Daily 15-01-24.md @@ -0,0 +1,119 @@ +## Today's 15-01-24 [Problem Link](https://leetcode.com/problems/find-players-with-zero-or-one-losses/description/?envType=daily-question&envId=2024-01-15) +## 2225. Find Players With Zero or One Losses + + +# Intuition + +My Java code aims to find the winners and players who have lost only once in a series of matches. It uses a HashMap to store the count of losses for each player and a HashSet to store the winners. + +# Approach + +###### HashMap and HashSet Initialization + +- Initialized `loser` as a HashMap to store the count of losses for each player. +- Initialized `winner` as a HashSet to store the winners. + +###### Iterated through Matches + +- For each match in the `matches` array: + - Add the first player of the match to the `winner` set. + - If the second player is not in the `loser` map, add it with a count of 1. + - If the second player is already in the `loser` map, increment its count by 1. + +###### Identified `Not Lost` Players + +- Created a list `notlost` to store players who haven't lost. +- Iterated through the `winner` set: + - If a player is not in the `loser` map, added them to the `notlost` list. + +###### Identified Players `Lost Only` Once + +- Created a list `lostone` to store players who have lost only once. +- Iterate through the `loser` map: + - If a player has lost only once (count = 1), added them to the `lostone` list. + +###### Sort Lists + +- Sorted both `notlost` and `lostone` lists. + +###### Created a Result List + +- Created a list of lists `jawab` to store the final result. +- Added `notlost` and `lostone` lists to `jawab`. + +###### Return Result + +- Returned the `jawab` list containing the players who haven't lost and those who have lost only once. +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + + +# Complexity +- Time complexity : $O(N + M + K*log(K))$ + +$N$ : number of matches + +$M$ : number of players + +$K$ : number of players who have lost only once + +$K*log(K)$ : sorting of lists + +- Space complexity : $O(M+K)$ + + +# Code +``` +class Solution { + public List> findWinners(int[][] matches) { + // HashMap to store the count of losses for each player + HashMap loser = new HashMap<>(); + // HashSet to store the winners + HashSet winner = new HashSet<>(); + + // Iterated through each match + for (int[] r : matches) { + // Added the first player of the match to the winner set + winner.add(r[0]); + // If the second player is not in the loser map, added it with a count of 1 + // If the second player is already in the loser map, incremented its count by 1 + loser.putIfAbsent(r[1], 0); + loser.put(r[1], loser.get(r[1]) + 1); + } + + // Lists to store players who haven't lost and those who have lost only once + List notlost = new ArrayList<>(); + List lostone = new ArrayList<>(); + + // Iterated through the winner set + for (int w : winner) { + // If a player is not in the loser map, added them to the notlost list + if (!loser.containsKey(w)) { + notlost.add(w); + } + } + + // Iterated through the loser map + for (int lo : loser.keySet()) { + // If a player has lost only once (count = 1), added them to the lostone list + if (loser.get(lo) == 1) { + lostone.add(lo); + } + } + + // Sorted both notlost and lostone lists + Collections.sort(notlost); + Collections.sort(lostone); + + // List of lists to store the final result + List> jawab = new ArrayList<>(); + jawab.add(notlost); + jawab.add(lostone); + + // Returned the result + return jawab; + } +} + +``` From 973a7774d114d3a51bcc371a1f4043c54e1655a7 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 16 Jan 2024 10:22:38 +0530 Subject: [PATCH 038/300] Update README.md --- README.md | 172 ++++++++++++++++++++++++++---------------------------- 1 file changed, 82 insertions(+), 90 deletions(-) diff --git a/README.md b/README.md index cb278a6..fe4e5db 100644 --- a/README.md +++ b/README.md @@ -5,122 +5,114 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 15-01-24 [Problem Link](https://leetcode.com/problems/find-players-with-zero-or-one-losses/description/?envType=daily-question&envId=2024-01-15) -## 2225. Find Players With Zero or One Losses +## Today's 15-01-24 [Problem Link](https://leetcode.com/problems/insert-delete-getrandom-o1/description/?envType=daily-question&envId=2024-01-16) +## 380. Insert Delete GetRandom O(1) # Intuition -My Java code aims to find the winners and players who have lost only once in a series of matches. It uses a HashMap to store the count of losses for each player and a HashSet to store the winners. +This `RandomizedSet` class aims to efficiently manage a set of unique integers while supporting insert, remove, and getRandom operations. The underlying data structure used by me is a HashSet, ensuring constant-time complexity for basic set operations. # Approach -###### HashMap and HashSet Initialization - -- Initialized `loser` as a HashMap to store the count of losses for each player. -- Initialized `winner` as a HashSet to store the winners. - -###### Iterated through Matches - -- For each match in the `matches` array: - - Add the first player of the match to the `winner` set. - - If the second player is not in the `loser` map, add it with a count of 1. - - If the second player is already in the `loser` map, increment its count by 1. - -###### Identified `Not Lost` Players - -- Created a list `notlost` to store players who haven't lost. -- Iterated through the `winner` set: - - If a player is not in the `loser` map, added them to the `notlost` list. - -###### Identified Players `Lost Only` Once - -- Created a list `lostone` to store players who have lost only once. -- Iterate through the `loser` map: - - If a player has lost only once (count = 1), added them to the `lostone` list. - -###### Sort Lists - -- Sorted both `notlost` and `lostone` lists. - -###### Created a Result List - -- Created a list of lists `jawab` to store the final result. -- Added `notlost` and `lostone` lists to `jawab`. - -###### Return Result - -- Returned the `jawab` list containing the players who haven't lost and those who have lost only once. +#### `insert` Operation: + - **Objective:** Added a new element to the set if it doesn't already exist. + - **Implementation:** + - Checked if the element is already present in the HashSet (`h`). + - If not present, added the element to the HashSet. + +#### `remove` Operation: + - **Objective:** Removed a specified element from the set if it exists. + - **Implementation:** + - Checked if the element is present in the HashSet. + - If present, removed the element. + +#### `getRandom` Operation: + - **Objective:** Returned a random element from the set. + - **Implementation:** + - Generated a random index (`ri`) within the size of the HashSet. + - Iterated through the HashSet using an iterator. + - When the iterator reaches the element at index `ri`, returned that element. + +#### Key Points: + - The use of a HashSet ensures uniqueness and constant-time complexity for insert and remove operations. + - The getRandom operation leverages the fact that HashSet doesn't guarantee any specific order, allowing random access with constant time. + - The random index is generated using `Random().nextInt(h.size())`. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(N + M + K*log(K))$ +- Time complexity : $O(1)$ -$N$ : number of matches -$M$ : number of players - -$K$ : number of players who have lost only once - -$K*log(K)$ : sorting of lists - -- Space complexity : $O(M+K)$ +- Space complexity : $O(n)$ +$n$ : number of unique elements stored in the HashSet # Code ``` -class Solution { - public List> findWinners(int[][] matches) { - // HashMap to store the count of losses for each player - HashMap loser = new HashMap<>(); - // HashSet to store the winners - HashSet winner = new HashSet<>(); - - // Iterated through each match - for (int[] r : matches) { - // Added the first player of the match to the winner set - winner.add(r[0]); - // If the second player is not in the loser map, added it with a count of 1 - // If the second player is already in the loser map, incremented its count by 1 - loser.putIfAbsent(r[1], 0); - loser.put(r[1], loser.get(r[1]) + 1); - } +class RandomizedSet { - // Lists to store players who haven't lost and those who have lost only once - List notlost = new ArrayList<>(); - List lostone = new ArrayList<>(); + // HashSet to store unique integers + static HashSet h; - // Iterated through the winner set - for (int w : winner) { - // If a player is not in the loser map, added them to the notlost list - if (!loser.containsKey(w)) { - notlost.add(w); - } + // Constructor initializes the HashSet + public RandomizedSet() { + h = new HashSet<>(); + } + + // Method to insert a value into the set + public boolean insert(int val) { + // If the set already contains the value, returned false (no insertion) + if (h.contains(val)) { + return false; + } else { + // Otherwise, added the value to the set and returned true (insertion successful) + h.add(val); + return true; } - - // Iterated through the loser map - for (int lo : loser.keySet()) { - // If a player has lost only once (count = 1), added them to the lostone list - if (loser.get(lo) == 1) { - lostone.add(lo); + } + + // Method to remove a value from the set + public boolean remove(int val) { + // If the set contains the value, removed it and return true (removal successful) + if (h.contains(val)) { + h.remove(val); + return true; + } else { + // Otherwise, returned false (value not present, no removal) + return false; + } + } + + // Method to get a random element from the set + public int getRandom() { + // Generated a random index within the size of the set + int randomIndex = new Random().nextInt(h.size()); + int currentIndex = 0; + + // Iterated over the set to find the element at the random index + for (int element : h) { + // If the current index matches the random index, returned the element + if (currentIndex == randomIndex) { + return element; } + currentIndex++; } - // Sorted both notlost and lostone lists - Collections.sort(notlost); - Collections.sort(lostone); - - // List of lists to store the final result - List> jawab = new ArrayList<>(); - jawab.add(notlost); - jawab.add(lostone); - - // Returned the result - return jawab; + // Returned -1 if the set is empty or for any other unexpected condition + return -1; } } +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet obj = new RandomizedSet(); + * boolean param_1 = obj.insert(val); + * boolean param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); + */ + ``` From 4548226d76b3488867bd410598371563d14c0f63 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 16 Jan 2024 10:23:06 +0530 Subject: [PATCH 039/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fe4e5db..e6a7913 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 15-01-24 [Problem Link](https://leetcode.com/problems/insert-delete-getrandom-o1/description/?envType=daily-question&envId=2024-01-16) +## Today's 16-01-24 [Problem Link](https://leetcode.com/problems/insert-delete-getrandom-o1/description/?envType=daily-question&envId=2024-01-16) ## 380. Insert Delete GetRandom O(1) From 505ba1d41b2edb212073c2dfb66697a8c0f1cad7 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 16 Jan 2024 10:24:19 +0530 Subject: [PATCH 040/300] Create Daily 16-01-24.md --- 2024 January/Daily 16-01-24.md | 111 +++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 2024 January/Daily 16-01-24.md diff --git a/2024 January/Daily 16-01-24.md b/2024 January/Daily 16-01-24.md new file mode 100644 index 0000000..884bcc9 --- /dev/null +++ b/2024 January/Daily 16-01-24.md @@ -0,0 +1,111 @@ +## Today's 16-01-24 [Problem Link](https://leetcode.com/problems/insert-delete-getrandom-o1/description/?envType=daily-question&envId=2024-01-16) +## 380. Insert Delete GetRandom O(1) + + +# Intuition + +This `RandomizedSet` class aims to efficiently manage a set of unique integers while supporting insert, remove, and getRandom operations. The underlying data structure used by me is a HashSet, ensuring constant-time complexity for basic set operations. + +# Approach + +#### `insert` Operation: + - **Objective:** Added a new element to the set if it doesn't already exist. + - **Implementation:** + - Checked if the element is already present in the HashSet (`h`). + - If not present, added the element to the HashSet. + +#### `remove` Operation: + - **Objective:** Removed a specified element from the set if it exists. + - **Implementation:** + - Checked if the element is present in the HashSet. + - If present, removed the element. + +#### `getRandom` Operation: + - **Objective:** Returned a random element from the set. + - **Implementation:** + - Generated a random index (`ri`) within the size of the HashSet. + - Iterated through the HashSet using an iterator. + - When the iterator reaches the element at index `ri`, returned that element. + +#### Key Points: + - The use of a HashSet ensures uniqueness and constant-time complexity for insert and remove operations. + - The getRandom operation leverages the fact that HashSet doesn't guarantee any specific order, allowing random access with constant time. + - The random index is generated using `Random().nextInt(h.size())`. +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + + +# Complexity +- Time complexity : $O(1)$ + + +- Space complexity : $O(n)$ + +$n$ : number of unique elements stored in the HashSet + +# Code +``` +class RandomizedSet { + + // HashSet to store unique integers + static HashSet h; + + // Constructor initializes the HashSet + public RandomizedSet() { + h = new HashSet<>(); + } + + // Method to insert a value into the set + public boolean insert(int val) { + // If the set already contains the value, returned false (no insertion) + if (h.contains(val)) { + return false; + } else { + // Otherwise, added the value to the set and returned true (insertion successful) + h.add(val); + return true; + } + } + + // Method to remove a value from the set + public boolean remove(int val) { + // If the set contains the value, removed it and return true (removal successful) + if (h.contains(val)) { + h.remove(val); + return true; + } else { + // Otherwise, returned false (value not present, no removal) + return false; + } + } + + // Method to get a random element from the set + public int getRandom() { + // Generated a random index within the size of the set + int randomIndex = new Random().nextInt(h.size()); + int currentIndex = 0; + + // Iterated over the set to find the element at the random index + for (int element : h) { + // If the current index matches the random index, returned the element + if (currentIndex == randomIndex) { + return element; + } + currentIndex++; + } + + // Returned -1 if the set is empty or for any other unexpected condition + return -1; + } +} + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet obj = new RandomizedSet(); + * boolean param_1 = obj.insert(val); + * boolean param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); + */ + +``` From 021cef5ddc4d4a166b9c7f48f94de1c74ea285a8 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 17 Jan 2024 12:30:12 +0530 Subject: [PATCH 041/300] Update README.md --- README.md | 118 +++++++++++++++--------------------------------------- 1 file changed, 33 insertions(+), 85 deletions(-) diff --git a/README.md b/README.md index e6a7913..901a8d2 100644 --- a/README.md +++ b/README.md @@ -5,114 +5,62 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 16-01-24 [Problem Link](https://leetcode.com/problems/insert-delete-getrandom-o1/description/?envType=daily-question&envId=2024-01-16) -## 380. Insert Delete GetRandom O(1) +## Today's 17-01-24 [Problem Link](https://leetcode.com/problems/unique-number-of-occurrences/description/?envType=daily-question&envId=2024-01-17) +## 1207. Unique Number of Occurrences # Intuition -This `RandomizedSet` class aims to efficiently manage a set of unique integers while supporting insert, remove, and getRandom operations. The underlying data structure used by me is a HashSet, ensuring constant-time complexity for basic set operations. +The goal of this problem is to determine whether the counts of occurrences of distinct elements in the array are unique. To achieve this, I'm using a HashMap to store the count of occurrences for each unique element and then use a HashSet to keep track of the unique counts. If, at any point, I encounter a count that already exists in the HashSet, I can conclude that the counts are not unique. # Approach -#### `insert` Operation: - - **Objective:** Added a new element to the set if it doesn't already exist. - - **Implementation:** - - Checked if the element is already present in the HashSet (`h`). - - If not present, added the element to the HashSet. - -#### `remove` Operation: - - **Objective:** Removed a specified element from the set if it exists. - - **Implementation:** - - Checked if the element is present in the HashSet. - - If present, removed the element. - -#### `getRandom` Operation: - - **Objective:** Returned a random element from the set. - - **Implementation:** - - Generated a random index (`ri`) within the size of the HashSet. - - Iterated through the HashSet using an iterator. - - When the iterator reaches the element at index `ri`, returned that element. - -#### Key Points: - - The use of a HashSet ensures uniqueness and constant-time complexity for insert and remove operations. - - The getRandom operation leverages the fact that HashSet doesn't guarantee any specific order, allowing random access with constant time. - - The random index is generated using `Random().nextInt(h.size())`. +- Created a `HashMap` named `occurrenceCountMap` to store the count of occurrences for each unique element. +- Iterated through the input array (`arr`) and update the counts in the `occurrenceCountMap`. +Created a `HashSet` named `uniqueCounts` to store the counts of occurrences. +- Iterated through the values in the `occurrenceCountMap` and check for uniqueness. +- - If the count is already present in the `uniqueCounts`, returned `false` (counts are not unique). +- - Otherwise, added the count to the `uniqueCounts`. +- If the loop completes without returning `false`, return `true` (counts are unique). --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity -- Time complexity : $O(1)$ +- Time complexity : $O(u)$ - -- Space complexity : $O(n)$ +$u$ : number of unique elements +- Space complexity : $O(u)$ -$n$ : number of unique elements stored in the HashSet # Code ``` -class RandomizedSet { - - // HashSet to store unique integers - static HashSet h; - - // Constructor initializes the HashSet - public RandomizedSet() { - h = new HashSet<>(); - } - - // Method to insert a value into the set - public boolean insert(int val) { - // If the set already contains the value, returned false (no insertion) - if (h.contains(val)) { - return false; - } else { - // Otherwise, added the value to the set and returned true (insertion successful) - h.add(val); - return true; - } - } - - // Method to remove a value from the set - public boolean remove(int val) { - // If the set contains the value, removed it and return true (removal successful) - if (h.contains(val)) { - h.remove(val); - return true; - } else { - // Otherwise, returned false (value not present, no removal) - return false; +class Solution { + public boolean uniqueOccurrences(int[] arr) { + // Creating a HashMap to store the count of occurrences of each unique element. + HashMap m = new HashMap<>(); + + // Iterating through the array and update the counts in the HashMap. + for (int i : arr) { + m.put(i, m.getOrDefault(i, 0) + 1); } - } - - // Method to get a random element from the set - public int getRandom() { - // Generated a random index within the size of the set - int randomIndex = new Random().nextInt(h.size()); - int currentIndex = 0; - // Iterated over the set to find the element at the random index - for (int element : h) { - // If the current index matches the random index, returned the element - if (currentIndex == randomIndex) { - return element; + // Creating a HashSet to store the counts of occurrences. + HashSet h = new HashSet<>(); + + // Iterating through the values in the HashMap and check for uniqueness. + for (int count : m.values()) { + // If the count is already present in the HashSet, returning false. + if (h.contains(count)) { + return false; } - currentIndex++; + // Otherwise, adding the count to the HashSet. + h.add(count); } - // Returned -1 if the set is empty or for any other unexpected condition - return -1; + // If the loop completes without returning false, returning true. + return true; } } -/** - * Your RandomizedSet object will be instantiated and called as such: - * RandomizedSet obj = new RandomizedSet(); - * boolean param_1 = obj.insert(val); - * boolean param_2 = obj.remove(val); - * int param_3 = obj.getRandom(); - */ - ``` From 21ed45f36833ec5014da2a00422761e58b07a757 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 17 Jan 2024 12:31:21 +0530 Subject: [PATCH 042/300] Create Daily 17-01-24.md --- 2024 January/Daily 17-01-24.md | 59 ++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 2024 January/Daily 17-01-24.md diff --git a/2024 January/Daily 17-01-24.md b/2024 January/Daily 17-01-24.md new file mode 100644 index 0000000..13700fd --- /dev/null +++ b/2024 January/Daily 17-01-24.md @@ -0,0 +1,59 @@ +## Today's 17-01-24 [Problem Link](https://leetcode.com/problems/unique-number-of-occurrences/description/?envType=daily-question&envId=2024-01-17) +## 1207. Unique Number of Occurrences + + +# Intuition + +The goal of this problem is to determine whether the counts of occurrences of distinct elements in the array are unique. To achieve this, I'm using a HashMap to store the count of occurrences for each unique element and then use a HashSet to keep track of the unique counts. If, at any point, I encounter a count that already exists in the HashSet, I can conclude that the counts are not unique. + +# Approach + +- Created a `HashMap` named `occurrenceCountMap` to store the count of occurrences for each unique element. +- Iterated through the input array (`arr`) and update the counts in the `occurrenceCountMap`. +Created a `HashSet` named `uniqueCounts` to store the counts of occurrences. +- Iterated through the values in the `occurrenceCountMap` and check for uniqueness. +- - If the count is already present in the `uniqueCounts`, returned `false` (counts are not unique). +- - Otherwise, added the count to the `uniqueCounts`. +- If the loop completes without returning `false`, return `true` (counts are unique). +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(u)$ + +$u$ : number of unique elements +- Space complexity : $O(u)$ + + +# Code +``` +class Solution { + public boolean uniqueOccurrences(int[] arr) { + // Creating a HashMap to store the count of occurrences of each unique element. + HashMap m = new HashMap<>(); + + // Iterating through the array and update the counts in the HashMap. + for (int i : arr) { + m.put(i, m.getOrDefault(i, 0) + 1); + } + + // Creating a HashSet to store the counts of occurrences. + HashSet h = new HashSet<>(); + + // Iterating through the values in the HashMap and check for uniqueness. + for (int count : m.values()) { + // If the count is already present in the HashSet, returning false. + if (h.contains(count)) { + return false; + } + // Otherwise, adding the count to the HashSet. + h.add(count); + } + + // If the loop completes without returning false, returning true. + return true; + } +} + +``` From 58d00144d298bd91194096239b5300432220c0f5 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 18 Jan 2024 10:58:31 +0530 Subject: [PATCH 043/300] Update README.md --- README.md | 75 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 41 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 901a8d2..8fc9c90 100644 --- a/README.md +++ b/README.md @@ -5,61 +5,68 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 17-01-24 [Problem Link](https://leetcode.com/problems/unique-number-of-occurrences/description/?envType=daily-question&envId=2024-01-17) -## 1207. Unique Number of Occurrences +## Today's 17-01-24 [Problem Link](https://leetcode.com/problems/climbing-stairs/description/?envType=daily-question&envId=2024-01-18) +## 70. Climbing Stairs # Intuition -The goal of this problem is to determine whether the counts of occurrences of distinct elements in the array are unique. To achieve this, I'm using a HashMap to store the count of occurrences for each unique element and then use a HashSet to keep track of the unique counts. If, at any point, I encounter a count that already exists in the HashSet, I can conclude that the counts are not unique. +This problem is a classic dynamic programming problem, often referred to as the "Climbing Stairs" problem. The goal is to find the number of distinct ways to climb a staircase with n steps. At each step, one can either climb 1 or 2 steps. The task is to determine the total number of unique combinations to reach the top. # Approach -- Created a `HashMap` named `occurrenceCountMap` to store the count of occurrences for each unique element. -- Iterated through the input array (`arr`) and update the counts in the `occurrenceCountMap`. -Created a `HashSet` named `uniqueCounts` to store the counts of occurrences. -- Iterated through the values in the `occurrenceCountMap` and check for uniqueness. -- - If the count is already present in the `uniqueCounts`, returned `false` (counts are not unique). -- - Otherwise, added the count to the `uniqueCounts`. -- If the loop completes without returning `false`, return `true` (counts are unique). +**Base Cases :** +- If there are 0 steps, there is only one way to climb (doing nothing). +- If there is 1 step, there is only one way to climb (taking one step). + +**Dynamic Programming Array :** +- Created an array step of size `n + 1` to store the number of ways to climb stairs at each step. +- Initialized the base cases (`step[0] = 1` and `step[1] = 1`). + +**Dynamic Programming Loop :** +- Used a loop to iterate from the 2nd step to the nth step. +- For each step `i`, the number of ways to reach that step is the sum of the ways to reach the previous two steps (`step[i - 1] + step[i - 2]`). + +**Result :** + +The final result is stored in `step[n]`, which represents the total number of unique ways to climb n stairs. + --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity -- Time complexity : $O(u)$ +- Time complexity : $O(s)$ -$u$ : number of unique elements -- Space complexity : $O(u)$ +$O(s)$ : steps to reach the top +- Space complexity : $O(s)$ # Code ``` class Solution { - public boolean uniqueOccurrences(int[] arr) { - // Creating a HashMap to store the count of occurrences of each unique element. - HashMap m = new HashMap<>(); - - // Iterating through the array and update the counts in the HashMap. - for (int i : arr) { - m.put(i, m.getOrDefault(i, 0) + 1); + public int climbStairs(int n) { + // Base cases + if (n == 0) { + return 1; } + if (n < 0) { + return 0; + } + + // Array to store the number of ways to climb stairs at each step + int[] step = new int[n + 1]; + + // Base cases for 0 and 1 steps + step[0] = 1; + step[1] = 1; - // Creating a HashSet to store the counts of occurrences. - HashSet h = new HashSet<>(); - - // Iterating through the values in the HashMap and check for uniqueness. - for (int count : m.values()) { - // If the count is already present in the HashSet, returning false. - if (h.contains(count)) { - return false; - } - // Otherwise, adding the count to the HashSet. - h.add(count); + // Dynamic programming loop to calculate the number of ways + for (int i = 2; i <= n; i++) { + step[i] = step[i - 1] + step[i - 2]; } - // If the loop completes without returning false, returning true. - return true; + // Returning the result for climbing n stairs + return step[n]; } } From 9395427aebc48d50cefdbc07c3ddb528aacbc7cb Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 18 Jan 2024 11:00:09 +0530 Subject: [PATCH 044/300] Create Daily 18-01-24.md --- 2024 January/Daily 18-01-24.md | 66 ++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 2024 January/Daily 18-01-24.md diff --git a/2024 January/Daily 18-01-24.md b/2024 January/Daily 18-01-24.md new file mode 100644 index 0000000..6681aae --- /dev/null +++ b/2024 January/Daily 18-01-24.md @@ -0,0 +1,66 @@ +## Today's 17-01-24 [Problem Link](https://leetcode.com/problems/climbing-stairs/description/?envType=daily-question&envId=2024-01-18) +## 70. Climbing Stairs + + +# Intuition + +This problem is a classic dynamic programming problem, often referred to as the "Climbing Stairs" problem. The goal is to find the number of distinct ways to climb a staircase with n steps. At each step, one can either climb 1 or 2 steps. The task is to determine the total number of unique combinations to reach the top. + +# Approach + +**Base Cases :** +- If there are 0 steps, there is only one way to climb (doing nothing). +- If there is 1 step, there is only one way to climb (taking one step). + +**Dynamic Programming Array :** +- Created an array step of size `n + 1` to store the number of ways to climb stairs at each step. +- Initialized the base cases (`step[0] = 1` and `step[1] = 1`). + +**Dynamic Programming Loop :** +- Used a loop to iterate from the 2nd step to the nth step. +- For each step `i`, the number of ways to reach that step is the sum of the ways to reach the previous two steps (`step[i - 1] + step[i - 2]`). + +**Result :** + +The final result is stored in `step[n]`, which represents the total number of unique ways to climb n stairs. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(s)$ + +$O(s)$ : steps to reach the top +- Space complexity : $O(s)$ + + +# Code +``` +class Solution { + public int climbStairs(int n) { + // Base cases + if (n == 0) { + return 1; + } + if (n < 0) { + return 0; + } + + // Array to store the number of ways to climb stairs at each step + int[] step = new int[n + 1]; + + // Base cases for 0 and 1 steps + step[0] = 1; + step[1] = 1; + + // Dynamic programming loop to calculate the number of ways + for (int i = 2; i <= n; i++) { + step[i] = step[i - 1] + step[i - 2]; + } + + // Returning the result for climbing n stairs + return step[n]; + } +} + +``` From 52e72acfa029d638e58c5292e7a6560580813143 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Thu, 18 Jan 2024 16:16:56 +0530 Subject: [PATCH 045/300] Update Daily 18-01-24.md --- 2024 January/Daily 18-01-24.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/2024 January/Daily 18-01-24.md b/2024 January/Daily 18-01-24.md index 6681aae..1d19c5d 100644 --- a/2024 January/Daily 18-01-24.md +++ b/2024 January/Daily 18-01-24.md @@ -1,4 +1,4 @@ -## Today's 17-01-24 [Problem Link](https://leetcode.com/problems/climbing-stairs/description/?envType=daily-question&envId=2024-01-18) +## Today's 18-01-24 [Problem Link](https://leetcode.com/problems/climbing-stairs/description/?envType=daily-question&envId=2024-01-18) ## 70. Climbing Stairs From eaa24bc5f83e4729a25e255902cf20752dff0917 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Thu, 18 Jan 2024 16:17:12 +0530 Subject: [PATCH 046/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8fc9c90..fec7b36 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 17-01-24 [Problem Link](https://leetcode.com/problems/climbing-stairs/description/?envType=daily-question&envId=2024-01-18) +## Today's 18-01-24 [Problem Link](https://leetcode.com/problems/climbing-stairs/description/?envType=daily-question&envId=2024-01-18) ## 70. Climbing Stairs From 00e7932419b83b830920a5c381875354b484dd6b Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 19 Jan 2024 15:10:09 +0530 Subject: [PATCH 047/300] Update README.md --- README.md | 92 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 51 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index fec7b36..45426ba 100644 --- a/README.md +++ b/README.md @@ -5,69 +5,79 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 18-01-24 [Problem Link](https://leetcode.com/problems/climbing-stairs/description/?envType=daily-question&envId=2024-01-18) -## 70. Climbing Stairs +## Today's 19-01-24 [Problem Link](https://leetcode.com/problems/minimum-falling-path-sum/description/?envType=daily-question&envId=2024-01-19) +## 931. Minimum Falling Path Sum # Intuition -This problem is a classic dynamic programming problem, often referred to as the "Climbing Stairs" problem. The goal is to find the number of distinct ways to climb a staircase with n steps. At each step, one can either climb 1 or 2 steps. The task is to determine the total number of unique combinations to reach the top. +My idea is to start from the second last row of the matrix and iteratively calculate the minimum falling path sum for each element. We update each element by adding the minimum value among its three neighboring elements from the next row (bottom, bottom-left, and bottom-right). + +Finally, I found the minimum value in the first row, which represents the minimum falling path sum for the entire matrix. # Approach -**Base Cases :** -- If there are 0 steps, there is only one way to climb (doing nothing). -- If there is 1 step, there is only one way to climb (taking one step). - -**Dynamic Programming Array :** -- Created an array step of size `n + 1` to store the number of ways to climb stairs at each step. -- Initialized the base cases (`step[0] = 1` and `step[1] = 1`). - -**Dynamic Programming Loop :** -- Used a loop to iterate from the 2nd step to the nth step. -- For each step `i`, the number of ways to reach that step is the sum of the ways to reach the previous two steps (`step[i - 1] + step[i - 2]`). - -**Result :** - -The final result is stored in `step[n]`, which represents the total number of unique ways to climb n stairs. +- Iterated from the second last row (`r = rows - 2`) to the first row (`r >= 0`). +- For each element in the current row (`matrix[r][c]`), calculated the minimum falling path sum by considering the three neighboring elements from the next row (bottom, bottom-left, and bottom-right). +- Updated the current element with the sum of its value and the minimum calculated in the previous step. +- After completing the iteration, found the minimum value in the first row, which represents the minimum falling path sum for the entire matrix. +- Returned the minimum falling path sum found in previous step. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + # Complexity -- Time complexity : $O(s)$ +- Time complexity : $O(r*c)$ -$O(s)$ : steps to reach the top -- Space complexity : $O(s)$ +$r$ : rows + +$c$ : columns + +- Space complexity : $O(1)$ # Code ``` + class Solution { - public int climbStairs(int n) { - // Base cases - if (n == 0) { - return 1; + public int minFallingPathSum(int[][] matrix) { + // Getting the number of rows and columns in the matrix + int rows = matrix.length; + int cols = matrix[0].length; + + // Iterating from the second last row to the first row + for (int r = rows - 2; r >= 0; r--) { + // Iterating through each element in the row + for (int c = 0; c < cols; c++) { + int min = Integer.MAX_VALUE; + + // Checking the bottom-left element (if available) + if (c > 0) { + min = Math.min(min, matrix[r + 1][c - 1]); + } + + // Checking the bottom element + int bottom = matrix[r + 1][c]; + min = Math.min(min, bottom); + + // Checking the bottom-right element (if available) + if (c < cols - 1) { + min = Math.min(min, matrix[r + 1][c + 1]); + } + + // Updating the current element with the sum of its value and the minimum of the three neighbors + matrix[r][c] = matrix[r][c] + min; + } } - if (n < 0) { - return 0; - } - - // Array to store the number of ways to climb stairs at each step - int[] step = new int[n + 1]; - - // Base cases for 0 and 1 steps - step[0] = 1; - step[1] = 1; - // Dynamic programming loop to calculate the number of ways - for (int i = 2; i <= n; i++) { - step[i] = step[i - 1] + step[i - 2]; + // Finding the minimum value in the first row, which represents the minimum falling path sum + int minimum = Integer.MAX_VALUE; + for (int i = 0; i < cols; i++) { + minimum = Math.min(minimum, matrix[0][i]); } - // Returning the result for climbing n stairs - return step[n]; + return minimum; } } - ``` From 951d7c0bf8444d0b6162886cafd5a8e40e63b1ed Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 19 Jan 2024 15:11:26 +0530 Subject: [PATCH 048/300] Create Daily 19-01-24.md --- 2024 January/Daily 19-01-24.md | 76 ++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 2024 January/Daily 19-01-24.md diff --git a/2024 January/Daily 19-01-24.md b/2024 January/Daily 19-01-24.md new file mode 100644 index 0000000..adf88e5 --- /dev/null +++ b/2024 January/Daily 19-01-24.md @@ -0,0 +1,76 @@ +## Today's 19-01-24 [Problem Link](https://leetcode.com/problems/minimum-falling-path-sum/description/?envType=daily-question&envId=2024-01-19) +## 931. Minimum Falling Path Sum + + +# Intuition + +My idea is to start from the second last row of the matrix and iteratively calculate the minimum falling path sum for each element. We update each element by adding the minimum value among its three neighboring elements from the next row (bottom, bottom-left, and bottom-right). + +Finally, I found the minimum value in the first row, which represents the minimum falling path sum for the entire matrix. + +# Approach + +- Iterated from the second last row (`r = rows - 2`) to the first row (`r >= 0`). +- For each element in the current row (`matrix[r][c]`), calculated the minimum falling path sum by considering the three neighboring elements from the next row (bottom, bottom-left, and bottom-right). +- Updated the current element with the sum of its value and the minimum calculated in the previous step. +- After completing the iteration, found the minimum value in the first row, which represents the minimum falling path sum for the entire matrix. +- Returned the minimum falling path sum found in previous step. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(r*c)$ + +$r$ : rows + +$c$ : columns + +- Space complexity : $O(1)$ + + +# Code +``` + +class Solution { + public int minFallingPathSum(int[][] matrix) { + // Getting the number of rows and columns in the matrix + int rows = matrix.length; + int cols = matrix[0].length; + + // Iterating from the second last row to the first row + for (int r = rows - 2; r >= 0; r--) { + // Iterating through each element in the row + for (int c = 0; c < cols; c++) { + int min = Integer.MAX_VALUE; + + // Checking the bottom-left element (if available) + if (c > 0) { + min = Math.min(min, matrix[r + 1][c - 1]); + } + + // Checking the bottom element + int bottom = matrix[r + 1][c]; + min = Math.min(min, bottom); + + // Checking the bottom-right element (if available) + if (c < cols - 1) { + min = Math.min(min, matrix[r + 1][c + 1]); + } + + // Updating the current element with the sum of its value and the minimum of the three neighbors + matrix[r][c] = matrix[r][c] + min; + } + } + + // Finding the minimum value in the first row, which represents the minimum falling path sum + int minimum = Integer.MAX_VALUE; + for (int i = 0; i < cols; i++) { + minimum = Math.min(minimum, matrix[0][i]); + } + + return minimum; + } +} +``` From 13701b675431c22cef887695d7f0433851b41b46 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 20 Jan 2024 11:52:54 +0530 Subject: [PATCH 049/300] Update README.md --- README.md | 122 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 72 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 45426ba..beff900 100644 --- a/README.md +++ b/README.md @@ -5,79 +5,101 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 19-01-24 [Problem Link](https://leetcode.com/problems/minimum-falling-path-sum/description/?envType=daily-question&envId=2024-01-19) -## 931. Minimum Falling Path Sum +## Today's 20-01-24 [Problem Link](https://leetcode.com/problems/sum-of-subarray-minimums/description/?envType=daily-question&envId=2024-01-20) +## 907. Sum of Subarray Minimums # Intuition -My idea is to start from the second last row of the matrix and iteratively calculate the minimum falling path sum for each element. We update each element by adding the minimum value among its three neighboring elements from the next row (bottom, bottom-left, and bottom-right). - -Finally, I found the minimum value in the first row, which represents the minimum falling path sum for the entire matrix. +The goal is to find the sum of minimums for all subarrays of the given array. To achieve this, I used two stacks to keep track of elements to the left (`l`) and right (`r`) of each element, and two arrays (`baya` and `daya`) to store the count of elements to the left and right, respectively. # Approach -- Iterated from the second last row (`r = rows - 2`) to the first row (`r >= 0`). -- For each element in the current row (`matrix[r][c]`), calculated the minimum falling path sum by considering the three neighboring elements from the next row (bottom, bottom-left, and bottom-right). -- Updated the current element with the sum of its value and the minimum calculated in the previous step. -- After completing the iteration, found the minimum value in the first row, which represents the minimum falling path sum for the entire matrix. -- Returned the minimum falling path sum found in previous step. - +**Initialize Stacks and Arrays :** +- Created two stacks (`l` and `r`) to keep track of indices for elements to the left and right. +- Initialized two arrays (`baya` and `daya`) to store the count of elements to the left and right, respectively. +**Process Elements to the Left (`l` Stack) :** +- Iterated through the array from left to right. +- Used the stack `l` to keep track of indices of elements encountered. +- For each element, popped elements from the stack until finding an element greater than the current one. +- Updated the `baya` array with the count of elements to the left. +**Process Elements to the Right (`r` Stack) :** +- Iterated through the array from right to left. +- Used the stack `r` to keep track of indices of elements encountered. +- For each element, popped elements from the stack until finding an element greater than or equal to the current one. +- Updated the `daya` array with the count of elements to the right. +**Calculate Sum of Minimums :** +- Iterated through the array. +- For each element, calculated the product of counts from `baya`, `daya`, and the element itself. +- Accumulated the products to obtain the sum of minimums. +**Applied Modulo Operation :** +- To avoid integer overflow, applied the modulo operation (1,000,000,007) to the sum. +**Returned the Result :** +Returned the final sum of minimums after the modulo operation. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(r*c)$ +- Time complexity : $O(l)$ -$r$ : rows - -$c$ : columns - -- Space complexity : $O(1)$ +$l$ : length of the input array +- Space complexity : $O(l)$ # Code ``` - class Solution { - public int minFallingPathSum(int[][] matrix) { - // Getting the number of rows and columns in the matrix - int rows = matrix.length; - int cols = matrix[0].length; - - // Iterating from the second last row to the first row - for (int r = rows - 2; r >= 0; r--) { - // Iterating through each element in the row - for (int c = 0; c < cols; c++) { - int min = Integer.MAX_VALUE; - - // Checking the bottom-left element (if available) - if (c > 0) { - min = Math.min(min, matrix[r + 1][c - 1]); - } - - // Checking the bottom element - int bottom = matrix[r + 1][c]; - min = Math.min(min, bottom); - - // Checking the bottom-right element (if available) - if (c < cols - 1) { - min = Math.min(min, matrix[r + 1][c + 1]); - } - - // Updating the current element with the sum of its value and the minimum of the three neighbors - matrix[r][c] = matrix[r][c] + min; + public int sumSubarrayMins(int[] arr) { + + // Arrays to store the count of subarrays where the current element is the minimum + long[] baya = new long[arr.length]; // Count of elements to the left + long[] daya = new long[arr.length]; // Count of elements to the right + + // Stacks to keep track of indices for elements to the left and right + Stack l = new Stack<>(); + Stack r = new Stack<>(); + + // Processing elements to the left + for (int i = 0; i < arr.length; i++) { + // Popping elements from the stack until finding a greater element + while (!l.isEmpty() && arr[i] < arr[l.peek()]) { + l.pop(); + } + + baya[i] = i + 1; // Default count is the distance to the leftmost element + + if (!l.isEmpty()) { + baya[i] = i - l.peek(); // Updating count based on the position of the greater element } + + l.push(i); // Pushing the current index to the stack } - // Finding the minimum value in the first row, which represents the minimum falling path sum - int minimum = Integer.MAX_VALUE; - for (int i = 0; i < cols; i++) { - minimum = Math.min(minimum, matrix[0][i]); + // Processing elements to the right + for (int i = arr.length - 1; i >= 0; i--) { + // Popping elements from the stack until finding a greater or equal element + while (!r.isEmpty() && arr[i] <= arr[r.peek()]) { + r.pop(); + } + + daya[i] = arr.length - i; // Default count is the distance to the rightmost element + + if (!r.isEmpty()) { + daya[i] = r.peek() - i; // Updating count based on the position of the greater or equal element + } + + r.push(i); // Pushing the current index to the stack } - return minimum; + // Calculating the sum of subarrays' minimums using the counts and the modulo + long minSum = 0; + for (int i = 0; i < arr.length; i++) { + minSum = ( minSum + (baya[i] * arr[i] * daya[i]) % 1_000_000_007 ) % 1_000_000_007 ; + } + + return (int) minSum ; // Return the result after taking the modulo } } + ``` From f96ae730d963c9c060f258968f738d1a87871819 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 20 Jan 2024 11:54:13 +0530 Subject: [PATCH 050/300] Update README.md --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index beff900..52c8faf 100644 --- a/README.md +++ b/README.md @@ -15,25 +15,31 @@ The goal is to find the sum of minimums for all subarrays of the given array. To # Approach -**Initialize Stacks and Arrays :** +**My initialized Stacks and Arrays :** - Created two stacks (`l` and `r`) to keep track of indices for elements to the left and right. - Initialized two arrays (`baya` and `daya`) to store the count of elements to the left and right, respectively. + + **Process Elements to the Left (`l` Stack) :** - Iterated through the array from left to right. - Used the stack `l` to keep track of indices of elements encountered. - For each element, popped elements from the stack until finding an element greater than the current one. - Updated the `baya` array with the count of elements to the left. + **Process Elements to the Right (`r` Stack) :** - Iterated through the array from right to left. - Used the stack `r` to keep track of indices of elements encountered. - For each element, popped elements from the stack until finding an element greater than or equal to the current one. - Updated the `daya` array with the count of elements to the right. + **Calculate Sum of Minimums :** - Iterated through the array. - For each element, calculated the product of counts from `baya`, `daya`, and the element itself. - Accumulated the products to obtain the sum of minimums. + **Applied Modulo Operation :** - To avoid integer overflow, applied the modulo operation (1,000,000,007) to the sum. + **Returned the Result :** Returned the final sum of minimums after the modulo operation. --- From f7ddc8f050a2dce24177c99b6dc609da5849b339 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 20 Jan 2024 11:56:13 +0530 Subject: [PATCH 051/300] Create Daily 20-01-24.md --- 2024 January/Daily 20-01-24.md | 104 +++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 2024 January/Daily 20-01-24.md diff --git a/2024 January/Daily 20-01-24.md b/2024 January/Daily 20-01-24.md new file mode 100644 index 0000000..125bf53 --- /dev/null +++ b/2024 January/Daily 20-01-24.md @@ -0,0 +1,104 @@ +## Today's 20-01-24 [Problem Link](https://leetcode.com/problems/sum-of-subarray-minimums/description/?envType=daily-question&envId=2024-01-20) +## 907. Sum of Subarray Minimums + + +# Intuition + +The goal is to find the sum of minimums for all subarrays of the given array. To achieve this, I used two stacks to keep track of elements to the left (`l`) and right (`r`) of each element, and two arrays (`baya` and `daya`) to store the count of elements to the left and right, respectively. + +# Approach + +**My initialized Stacks and Arrays :** +- Created two stacks (`l` and `r`) to keep track of indices for elements to the left and right. +- Initialized two arrays (`baya` and `daya`) to store the count of elements to the left and right, respectively. + + +**Process Elements to the Left (`l` Stack) :** +- Iterated through the array from left to right. +- Used the stack `l` to keep track of indices of elements encountered. +- For each element, popped elements from the stack until finding an element greater than the current one. +- Updated the `baya` array with the count of elements to the left. + +**Process Elements to the Right (`r` Stack) :** +- Iterated through the array from right to left. +- Used the stack `r` to keep track of indices of elements encountered. +- For each element, popped elements from the stack until finding an element greater than or equal to the current one. +- Updated the `daya` array with the count of elements to the right. + +**Calculated Sum of Minimums :** +- I iterated through the array. +- For each element, calculated the product of counts from `baya`, `daya`, and the element itself. +- Accumulated the products to obtain the sum of minimums. + +**Applied Modulo Operation :** +- To avoid integer overflow, applied the modulo operation (1,000,000,007) to the sum. + +**Returned the Result :** +Returned the final sum of minimums after the modulo operation. +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(l)$ + +$l$ : length of the input array +- Space complexity : $O(l)$ + + +# Code +``` +class Solution { + public int sumSubarrayMins(int[] arr) { + + // Arrays to store the count of subarrays where the current element is the minimum + long[] baya = new long[arr.length]; // Count of elements to the left + long[] daya = new long[arr.length]; // Count of elements to the right + + // Stacks to keep track of indices for elements to the left and right + Stack l = new Stack<>(); + Stack r = new Stack<>(); + + // Processing elements to the left + for (int i = 0; i < arr.length; i++) { + // Popping elements from the stack until finding a greater element + while (!l.isEmpty() && arr[i] < arr[l.peek()]) { + l.pop(); + } + + baya[i] = i + 1; // Default count is the distance to the leftmost element + + if (!l.isEmpty()) { + baya[i] = i - l.peek(); // Updating count based on the position of the greater element + } + + l.push(i); // Pushing the current index to the stack + } + + // Processing elements to the right + for (int i = arr.length - 1; i >= 0; i--) { + // Popping elements from the stack until finding a greater or equal element + while (!r.isEmpty() && arr[i] <= arr[r.peek()]) { + r.pop(); + } + + daya[i] = arr.length - i; // Default count is the distance to the rightmost element + + if (!r.isEmpty()) { + daya[i] = r.peek() - i; // Updating count based on the position of the greater or equal element + } + + r.push(i); // Pushing the current index to the stack + } + + // Calculating the sum of subarrays' minimums using the counts and the modulo + long minSum = 0; + for (int i = 0; i < arr.length; i++) { + minSum = ( minSum + (baya[i] * arr[i] * daya[i]) % 1_000_000_007 ) % 1_000_000_007 ; + } + + return (int) minSum ; // Return the result after taking the modulo + } +} + +``` From 48f8d0f5bd0ff49b9dbc806f68a2cf34f9365890 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 20 Jan 2024 11:56:17 +0530 Subject: [PATCH 052/300] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 52c8faf..a12148e 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,8 @@ The goal is to find the sum of minimums for all subarrays of the given array. To - For each element, popped elements from the stack until finding an element greater than or equal to the current one. - Updated the `daya` array with the count of elements to the right. -**Calculate Sum of Minimums :** -- Iterated through the array. +**Calculated Sum of Minimums :** +- I iterated through the array. - For each element, calculated the product of counts from `baya`, `daya`, and the element itself. - Accumulated the products to obtain the sum of minimums. From 12d0293c0b362792a6b4f6b156dc584e2ac042df Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Sat, 20 Jan 2024 12:29:11 +0530 Subject: [PATCH 053/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a12148e..e301cd5 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ The goal is to find the sum of minimums for all subarrays of the given array. To - To avoid integer overflow, applied the modulo operation (1,000,000,007) to the sum. **Returned the Result :** -Returned the final sum of minimums after the modulo operation. +- Returned the final sum of minimums after the modulo operation. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) From 97748d839885fa2b4b1eafa3c984557e2db5a806 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Sat, 20 Jan 2024 12:29:45 +0530 Subject: [PATCH 054/300] Update Daily 20-01-24.md --- 2024 January/Daily 20-01-24.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/2024 January/Daily 20-01-24.md b/2024 January/Daily 20-01-24.md index 125bf53..b77c161 100644 --- a/2024 January/Daily 20-01-24.md +++ b/2024 January/Daily 20-01-24.md @@ -34,7 +34,7 @@ The goal is to find the sum of minimums for all subarrays of the given array. To - To avoid integer overflow, applied the modulo operation (1,000,000,007) to the sum. **Returned the Result :** -Returned the final sum of minimums after the modulo operation. +- Returned the final sum of minimums after the modulo operation. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) From 17f2175a7540bd764d1ace79c9ea318e7b871462 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 21 Jan 2024 09:59:05 +0530 Subject: [PATCH 055/300] Create Daily 21-01-24.md --- 2024 January/Daily 21-01-24.md | 71 ++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 2024 January/Daily 21-01-24.md diff --git a/2024 January/Daily 21-01-24.md b/2024 January/Daily 21-01-24.md new file mode 100644 index 0000000..16508be --- /dev/null +++ b/2024 January/Daily 21-01-24.md @@ -0,0 +1,71 @@ +## Today's 21-01-24 [Problem Link](https://leetcode.com/problems/house-robber/description/?envType=daily-question&envId=2024-01-21) +## 198. House Robber + + +# Intuition + +My Java code aims to find the maximum amount that can be robbed from an array of houses, where adjacent houses cannot be robbed simultaneously. + +# Approach + +**Base Cases :** +- Handled base cases for arrays with lengths 0, 1, 2, and 3. + +**Initialization :** +- Initialized a pointer `p` to track the position in the array. +- Updated the value at index 2 by adding the value at index 0. + +**Dynamic Programming :** +- Iterated from index 3 to the end of the array. +- Updated the value at the current index by adding the maximum of the values at indices `i-2` and `i-3`. + +**Result Calculation :** +- Returned the maximum value between the last two elements of the modified array. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(l)$ + +$l$ : length of the input array +- Space complexity : $O(1)$ + + +# Code +``` +public class Solution { + + public int rob(int[] nums) { + + // Base cases for small arrays + if (nums.length == 0) { + return 0; + } + if (nums.length == 1) { + return nums[0]; + } + if (nums.length == 2) { + return Math.max(nums[0], nums[1]); + } + if (nums.length == 3) { + return Math.max(nums[0] + nums[2], nums[1]); + } + + // Initializing a pointer 'p' to track the position + int p = 0; + // Updating the value at index 2 by adding the value at index 0 + nums[2] += nums[0]; + + // Iterating from index 3 to the end of the array + for (int i = 3; i < nums.length; i++) { + // Updating the value at the current index by adding the maximum of the two preceding values + nums[i] += Math.max(nums[i - 2], nums[i - 3]); + } + + // Returning the maximum value between the last two elements of the modified array + return Math.max(nums[nums.length - 1], nums[nums.length - 2]); + } +} + +``` \ No newline at end of file From bcdc20d8a4eed62aaa3bbe4e02e15289deab2576 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 21 Jan 2024 09:59:07 +0530 Subject: [PATCH 056/300] Update README.md --- README.md | 117 ++++++++++++++++++++---------------------------------- 1 file changed, 42 insertions(+), 75 deletions(-) diff --git a/README.md b/README.md index e301cd5..97cffcf 100644 --- a/README.md +++ b/README.md @@ -5,107 +5,74 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 20-01-24 [Problem Link](https://leetcode.com/problems/sum-of-subarray-minimums/description/?envType=daily-question&envId=2024-01-20) -## 907. Sum of Subarray Minimums +## Today's 21-01-24 [Problem Link](https://leetcode.com/problems/house-robber/description/?envType=daily-question&envId=2024-01-21) +## 198. House Robber # Intuition -The goal is to find the sum of minimums for all subarrays of the given array. To achieve this, I used two stacks to keep track of elements to the left (`l`) and right (`r`) of each element, and two arrays (`baya` and `daya`) to store the count of elements to the left and right, respectively. +My Java code aims to find the maximum amount that can be robbed from an array of houses, where adjacent houses cannot be robbed simultaneously. # Approach -**My initialized Stacks and Arrays :** -- Created two stacks (`l` and `r`) to keep track of indices for elements to the left and right. -- Initialized two arrays (`baya` and `daya`) to store the count of elements to the left and right, respectively. +**Base Cases :** +- Handled base cases for arrays with lengths 0, 1, 2, and 3. +**Initialization :** +- Initialized a pointer `p` to track the position in the array. +- Updated the value at index 2 by adding the value at index 0. -**Process Elements to the Left (`l` Stack) :** -- Iterated through the array from left to right. -- Used the stack `l` to keep track of indices of elements encountered. -- For each element, popped elements from the stack until finding an element greater than the current one. -- Updated the `baya` array with the count of elements to the left. +**Dynamic Programming :** +- Iterated from index 3 to the end of the array. +- Updated the value at the current index by adding the maximum of the values at indices `i-2` and `i-3`. -**Process Elements to the Right (`r` Stack) :** -- Iterated through the array from right to left. -- Used the stack `r` to keep track of indices of elements encountered. -- For each element, popped elements from the stack until finding an element greater than or equal to the current one. -- Updated the `daya` array with the count of elements to the right. +**Result Calculation :** +- Returned the maximum value between the last two elements of the modified array. -**Calculated Sum of Minimums :** -- I iterated through the array. -- For each element, calculated the product of counts from `baya`, `daya`, and the element itself. -- Accumulated the products to obtain the sum of minimums. - -**Applied Modulo Operation :** -- To avoid integer overflow, applied the modulo operation (1,000,000,007) to the sum. - -**Returned the Result :** -- Returned the final sum of minimums after the modulo operation. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity - Time complexity : $O(l)$ $l$ : length of the input array -- Space complexity : $O(l)$ +- Space complexity : $O(1)$ # Code ``` -class Solution { - public int sumSubarrayMins(int[] arr) { - - // Arrays to store the count of subarrays where the current element is the minimum - long[] baya = new long[arr.length]; // Count of elements to the left - long[] daya = new long[arr.length]; // Count of elements to the right - - // Stacks to keep track of indices for elements to the left and right - Stack l = new Stack<>(); - Stack r = new Stack<>(); - - // Processing elements to the left - for (int i = 0; i < arr.length; i++) { - // Popping elements from the stack until finding a greater element - while (!l.isEmpty() && arr[i] < arr[l.peek()]) { - l.pop(); - } - - baya[i] = i + 1; // Default count is the distance to the leftmost element - - if (!l.isEmpty()) { - baya[i] = i - l.peek(); // Updating count based on the position of the greater element - } - - l.push(i); // Pushing the current index to the stack - } +public class Solution { + + public int rob(int[] nums) { - // Processing elements to the right - for (int i = arr.length - 1; i >= 0; i--) { - // Popping elements from the stack until finding a greater or equal element - while (!r.isEmpty() && arr[i] <= arr[r.peek()]) { - r.pop(); - } - - daya[i] = arr.length - i; // Default count is the distance to the rightmost element - - if (!r.isEmpty()) { - daya[i] = r.peek() - i; // Updating count based on the position of the greater or equal element - } - - r.push(i); // Pushing the current index to the stack + // Base cases for small arrays + if (nums.length == 0) { + return 0; + } + if (nums.length == 1) { + return nums[0]; } + if (nums.length == 2) { + return Math.max(nums[0], nums[1]); + } + if (nums.length == 3) { + return Math.max(nums[0] + nums[2], nums[1]); + } + + // Initializing a pointer 'p' to track the position + int p = 0; + // Updating the value at index 2 by adding the value at index 0 + nums[2] += nums[0]; - // Calculating the sum of subarrays' minimums using the counts and the modulo - long minSum = 0; - for (int i = 0; i < arr.length; i++) { - minSum = ( minSum + (baya[i] * arr[i] * daya[i]) % 1_000_000_007 ) % 1_000_000_007 ; + // Iterating from index 3 to the end of the array + for (int i = 3; i < nums.length; i++) { + // Updating the value at the current index by adding the maximum of the two preceding values + nums[i] += Math.max(nums[i - 2], nums[i - 3]); } - - return (int) minSum ; // Return the result after taking the modulo + + // Returning the maximum value between the last two elements of the modified array + return Math.max(nums[nums.length - 1], nums[nums.length - 2]); } } -``` +``` \ No newline at end of file From 24773c449a3ea47568e8c29f63ea8472de381a0a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 22 Jan 2024 11:53:12 +0530 Subject: [PATCH 057/300] Update README.md --- README.md | 86 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 44 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 97cffcf..0822a55 100644 --- a/README.md +++ b/README.md @@ -5,29 +5,30 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 21-01-24 [Problem Link](https://leetcode.com/problems/house-robber/description/?envType=daily-question&envId=2024-01-21) +## Today's 22-01-24 [Problem Link](https://leetcode.com/problems/house-robber/description/?envType=daily-question&envId=2024-01-21) ## 198. House Robber # Intuition -My Java code aims to find the maximum amount that can be robbed from an array of houses, where adjacent houses cannot be robbed simultaneously. # Approach -**Base Cases :** -- Handled base cases for arrays with lengths 0, 1, 2, and 3. +**Marked the Elements :** +- Iterated through the array. +- Marked the presence of elements by changing the sign of the element at the index equal to the absolute value of the current element. -**Initialization :** -- Initialized a pointer `p` to track the position in the array. -- Updated the value at index 2 by adding the value at index 0. +**Identified Duplicate :** +- If the element at the calculated index is already negative, it means the absolute value of the current element is a duplicate. -**Dynamic Programming :** -- Iterated from index 3 to the end of the array. -- Updated the value at the current index by adding the maximum of the values at indices `i-2` and `i-3`. +**Identifying Missing :** +- Found the positive element in the array, which corresponds to the missing element. -**Result Calculation :** -- Returned the maximum value between the last two elements of the modified array. +**Result Array :** +- Created an array 'result' to store the identified duplicate and missing elements. + +**Return Result :** + - Returned the 'result' array as the final output. --- Have a look at the code , still have any confusion then please let me know in the comments @@ -35,43 +36,44 @@ Keep Solving.:) # Complexity - Time complexity : $O(l)$ -$l$ : length of the input array +$l$ : length of array - Space complexity : $O(1)$ # Code ``` -public class Solution { - - public int rob(int[] nums) { - - // Base cases for small arrays - if (nums.length == 0) { - return 0; - } - if (nums.length == 1) { - return nums[0]; - } - if (nums.length == 2) { - return Math.max(nums[0], nums[1]); +class Solution { + + // Variables to store the duplicate, missing, and the final result + static int duplicate; + static int missing; + static int[] result = new int[2]; + + public int[] findErrorNums(int[] nums) { + + // Iterating through the array + for (int s : nums) { + // Marking the element at the index equal to the absolute value of 's' as negative + if (nums[Math.abs(s) - 1] > 0) { + nums[Math.abs(s) - 1] *= -1; + } else { + // If the element is already negative, it is the duplicate + duplicate = Math.abs(s); + } } - if (nums.length == 3) { - return Math.max(nums[0] + nums[2], nums[1]); + + // Finding the positive element in the array, which corresponds to the missing element + for (int i = 0; i < nums.length; i++) { + if (nums[i] > 0) { + missing = i + 1; + break; + } } - - // Initializing a pointer 'p' to track the position - int p = 0; - // Updating the value at index 2 by adding the value at index 0 - nums[2] += nums[0]; - - // Iterating from index 3 to the end of the array - for (int i = 3; i < nums.length; i++) { - // Updating the value at the current index by adding the maximum of the two preceding values - nums[i] += Math.max(nums[i - 2], nums[i - 3]); - } - - // Returning the maximum value between the last two elements of the modified array - return Math.max(nums[nums.length - 1], nums[nums.length - 2]); + + // Storing the results in the 'result' array + result[0] = duplicate; + result[1] = missing; + return result; } } From 9c418f3daa4967ea494b08c0736f77b0bf0a5c41 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 22 Jan 2024 11:53:42 +0530 Subject: [PATCH 058/300] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0822a55..7775d7f 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,8 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 22-01-24 [Problem Link](https://leetcode.com/problems/house-robber/description/?envType=daily-question&envId=2024-01-21) -## 198. House Robber +## Today's 22git-01-24 [Problem Link](https://leetcode.com/problems/set-mismatch/description/?envType=daily-question&envId=2024-01-22) +## 645. Set Mismatch # Intuition From 147027f655499c6d7e241b36548117f15131436d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 22 Jan 2024 11:54:33 +0530 Subject: [PATCH 059/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7775d7f..b9e5699 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 22git-01-24 [Problem Link](https://leetcode.com/problems/set-mismatch/description/?envType=daily-question&envId=2024-01-22) +## Today's 22-01-24 [Problem Link](https://leetcode.com/problems/set-mismatch/description/?envType=daily-question&envId=2024-01-22) ## 645. Set Mismatch From 39bfb2c17c6eccb201c01a0506bf57cbcef8f1ca Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 22 Jan 2024 11:55:54 +0530 Subject: [PATCH 060/300] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b9e5699..47c642a 100644 --- a/README.md +++ b/README.md @@ -25,10 +25,10 @@ This is my attempt to make the coding experience easier for you guys so that you - Found the positive element in the array, which corresponds to the missing element. **Result Array :** -- Created an array 'result' to store the identified duplicate and missing elements. +- Created an array `jawab` to store the identified duplicate and missing elements. **Return Result :** - - Returned the 'result' array as the final output. + - Returned the `jawab` array as the final output. --- Have a look at the code , still have any confusion then please let me know in the comments From ea68b57810736c6cf1fa4ab4836a54bb23ce3a55 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 22 Jan 2024 11:56:10 +0530 Subject: [PATCH 061/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 47c642a..8979ef2 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ This is my attempt to make the coding experience easier for you guys so that you - Found the positive element in the array, which corresponds to the missing element. **Result Array :** -- Created an array `jawab` to store the identified duplicate and missing elements. +- Created an array `jawab` in start to store the identified duplicate and missing elements. **Return Result :** - Returned the `jawab` array as the final output. From df605b69b3d71420e4363470925031531ad53026 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 22 Jan 2024 11:57:14 +0530 Subject: [PATCH 062/300] Create Daily 22-01-24.md --- 2024 January/Daily 22-01-24.md | 73 ++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 2024 January/Daily 22-01-24.md diff --git a/2024 January/Daily 22-01-24.md b/2024 January/Daily 22-01-24.md new file mode 100644 index 0000000..9e7af58 --- /dev/null +++ b/2024 January/Daily 22-01-24.md @@ -0,0 +1,73 @@ +## Today's 22-01-24 [Problem Link](https://leetcode.com/problems/set-mismatch/description/?envType=daily-question&envId=2024-01-22) +## 645. Set Mismatch + + +# Intuition + + +# Approach + +**Marked the Elements :** +- Iterated through the array. +- Marked the presence of elements by changing the sign of the element at the index equal to the absolute value of the current element. + +**Identified Duplicate :** +- If the element at the calculated index is already negative, it means the absolute value of the current element is a duplicate. + +**Identifying Missing :** +- Found the positive element in the array, which corresponds to the missing element. + +**Result Array :** +- Created an array `jawab` in start to store the identified duplicate and missing elements. + +**Return Result :** + - Returned the `jawab` array as the final output. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(l)$ + +$l$ : length of array +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + + // Variables to store the duplicate, missing, and the final result + static int duplicate; + static int missing; + static int[] result = new int[2]; + + public int[] findErrorNums(int[] nums) { + + // Iterating through the array + for (int s : nums) { + // Marking the element at the index equal to the absolute value of 's' as negative + if (nums[Math.abs(s) - 1] > 0) { + nums[Math.abs(s) - 1] *= -1; + } else { + // If the element is already negative, it is the duplicate + duplicate = Math.abs(s); + } + } + + // Finding the positive element in the array, which corresponds to the missing element + for (int i = 0; i < nums.length; i++) { + if (nums[i] > 0) { + missing = i + 1; + break; + } + } + + // Storing the results in the 'result' array + result[0] = duplicate; + result[1] = missing; + return result; + } +} + +``` \ No newline at end of file From 50c5259c43274fcd12d2f2149de397bdf90639de Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 23 Jan 2024 17:17:50 +0530 Subject: [PATCH 063/300] Update README.md --- README.md | 113 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 71 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 8979ef2..dd627bd 100644 --- a/README.md +++ b/README.md @@ -5,75 +5,104 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 22-01-24 [Problem Link](https://leetcode.com/problems/set-mismatch/description/?envType=daily-question&envId=2024-01-22) -## 645. Set Mismatch +## Today's 23-01-24 [Problem Link](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/description/?envType=daily-question&envId=2024-01-23) +## 1239. Maximum Length of a Concatenated String with Unique Characters # Intuition +As this problem aims to find the maximum length of a concatenated string with unique characters. To achieve this, I need to explore all possible combinations of strings and select those with unique characters. This involves using a bitmask approach to represent the set of characters present in a string efficiently. # Approach -**Marked the Elements :** -- Iterated through the array. -- Marked the presence of elements by changing the sign of the element at the index equal to the absolute value of the current element. +**Initialized a Data Structures :** +- Created an ArrayList `masks` to store the masks of valid strings (strings with unique characters). + +**Generated Masks :** +- Iterated through the input strings (`arr`) and use the `getMask` function to obtain the mask for each string. +- Added valid masks to the `masks` ArrayList. -**Identified Duplicate :** -- If the element at the calculated index is already negative, it means the absolute value of the current element is a duplicate. +**Depth-First Search (DFS) :** +- Implemented the DFS function (`dfs`) to explore all possible combinations of masks and find the maximum length. +- Started DFS from index 0 with an initially empty set (`used`). -**Identifying Missing :** -- Found the positive element in the array, which corresponds to the missing element. +**DFS Exploration :** +- For each mask, checked if it can be added to the current combination (`used`). +- If yes, updated the result (`res`) with the maximum length obtained by adding the current mask. -**Result Array :** -- Created an array `jawab` in start to store the identified duplicate and missing elements. +**Result :** +- The final result is the count of set bits in the `used` mask, representing the maximum length of a concatenated string with unique characters. -**Return Result :** - - Returned the `jawab` array as the final output. +**Helper Function (`getMask`) :** +- The `getMask` function converts a string into a bitmask, where each bit corresponds to a character's presence. +- Returns -1 if the string has duplicate characters, indicating it is not a valid mask. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(l)$ +- Time complexity : $O(2^n)$ + +$n$ : number of valid masks. -$l$ : length of array -- Space complexity : $O(1)$ + +- Space complexity : $O(2^n)$ # Code ``` +import java.util.ArrayList; +import java.util.List; + class Solution { - // Variables to store the duplicate, missing, and the final result - static int duplicate; - static int missing; - static int[] result = new int[2]; - - public int[] findErrorNums(int[] nums) { - - // Iterating through the array - for (int s : nums) { - // Marking the element at the index equal to the absolute value of 's' as negative - if (nums[Math.abs(s) - 1] > 0) { - nums[Math.abs(s) - 1] *= -1; - } else { - // If the element is already negative, it is the duplicate - duplicate = Math.abs(s); + // ArrayList to store the masks of valid strings + static ArrayList masks; + + public int maxLength(List arr) { + masks = new ArrayList<>(); + + // Iterating through the input strings and get their masks, add valid masks to the ArrayList + for (String s : arr) { + int mask = getMask(s); + if (mask != -1) { + masks.add(mask); + } + } + + // Calling the DFS function starting from index 0 with an initially empty set + return dfs(0, 0); + } + + // DFS function to explore all possible combinations of masks + static int dfs(int s, int used) { + // Initialize the result with the count of set bits in the 'used' mask + int res = Integer.bitCount(used); + + // Iterating through the masks and explore valid combinations + for (int i = s; i < masks.size(); i++) { + // Checking if the current mask can be added to the combination + if ((used & masks.get(i)) == 0) { + // Updating the result with the maximum length obtained by adding the current mask + res = Math.max(res, dfs(i + 1, used | masks.get(i))); } } - - // Finding the positive element in the array, which corresponds to the missing element - for (int i = 0; i < nums.length; i++) { - if (nums[i] > 0) { - missing = i + 1; - break; + return res; + } + + // Helper function to get the mask of a string, returns -1 if the string has duplicate characters + static int getMask(String s) { + int mask = 0; + for (char c : s.toCharArray()) { + int i = c - 'a'; + // Checking for duplicate characters in the string + if ((mask & (1 << i)) != 0) { + return -1; } + // Set the corresponding bit for the character in the mask + mask |= 1 << i; } - - // Storing the results in the 'result' array - result[0] = duplicate; - result[1] = missing; - return result; + return mask; } } From 858aa7be922b4cab8d271b2399d57a3117365d0c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 23 Jan 2024 17:18:48 +0530 Subject: [PATCH 064/300] Create Daily 23-01-24.md --- 2024 January/Daily 23-01-24.md | 102 +++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 2024 January/Daily 23-01-24.md diff --git a/2024 January/Daily 23-01-24.md b/2024 January/Daily 23-01-24.md new file mode 100644 index 0000000..b83feaf --- /dev/null +++ b/2024 January/Daily 23-01-24.md @@ -0,0 +1,102 @@ +## Today's 23-01-24 [Problem Link](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/description/?envType=daily-question&envId=2024-01-23) +## 1239. Maximum Length of a Concatenated String with Unique Characters + + +# Intuition + +As this problem aims to find the maximum length of a concatenated string with unique characters. To achieve this, I need to explore all possible combinations of strings and select those with unique characters. This involves using a bitmask approach to represent the set of characters present in a string efficiently. + +# Approach + +**Initialized a Data Structures :** +- Created an ArrayList `masks` to store the masks of valid strings (strings with unique characters). + +**Generated Masks :** +- Iterated through the input strings (`arr`) and use the `getMask` function to obtain the mask for each string. +- Added valid masks to the `masks` ArrayList. + +**Depth-First Search (DFS) :** +- Implemented the DFS function (`dfs`) to explore all possible combinations of masks and find the maximum length. +- Started DFS from index 0 with an initially empty set (`used`). + +**DFS Exploration :** +- For each mask, checked if it can be added to the current combination (`used`). +- If yes, updated the result (`res`) with the maximum length obtained by adding the current mask. + +**Result :** +- The final result is the count of set bits in the `used` mask, representing the maximum length of a concatenated string with unique characters. + +**Helper Function (`getMask`) :** +- The `getMask` function converts a string into a bitmask, where each bit corresponds to a character's presence. +- Returns -1 if the string has duplicate characters, indicating it is not a valid mask. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(2^n)$ + +$n$ : number of valid masks. + + +- Space complexity : $O(2^n)$ + + +# Code +``` +import java.util.ArrayList; +import java.util.List; + +class Solution { + + // ArrayList to store the masks of valid strings + static ArrayList masks; + + public int maxLength(List arr) { + masks = new ArrayList<>(); + + // Iterating through the input strings and get their masks, add valid masks to the ArrayList + for (String s : arr) { + int mask = getMask(s); + if (mask != -1) { + masks.add(mask); + } + } + + // Calling the DFS function starting from index 0 with an initially empty set + return dfs(0, 0); + } + + // DFS function to explore all possible combinations of masks + static int dfs(int s, int used) { + // Initialize the result with the count of set bits in the 'used' mask + int res = Integer.bitCount(used); + + // Iterating through the masks and explore valid combinations + for (int i = s; i < masks.size(); i++) { + // Checking if the current mask can be added to the combination + if ((used & masks.get(i)) == 0) { + // Updating the result with the maximum length obtained by adding the current mask + res = Math.max(res, dfs(i + 1, used | masks.get(i))); + } + } + return res; + } + + // Helper function to get the mask of a string, returns -1 if the string has duplicate characters + static int getMask(String s) { + int mask = 0; + for (char c : s.toCharArray()) { + int i = c - 'a'; + // Checking for duplicate characters in the string + if ((mask & (1 << i)) != 0) { + return -1; + } + // Set the corresponding bit for the character in the mask + mask |= 1 << i; + } + return mask; + } +} + +``` \ No newline at end of file From 15c1f095383cdebb8b892765e9e1a0b9231453fd Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 24 Jan 2024 12:15:08 +0530 Subject: [PATCH 065/300] Update README.md --- README.md | 142 +++++++++++++++++++++++++++++------------------------- 1 file changed, 76 insertions(+), 66 deletions(-) diff --git a/README.md b/README.md index dd627bd..603aa66 100644 --- a/README.md +++ b/README.md @@ -5,104 +5,114 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 23-01-24 [Problem Link](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/description/?envType=daily-question&envId=2024-01-23) -## 1239. Maximum Length of a Concatenated String with Unique Characters +## Today's 24-01-24 [Problem Link](https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/description/?envType=daily-question&envId=2024-01-24) +## 1457. Pseudo-Palindromic Paths in a Binary Tree # Intuition -As this problem aims to find the maximum length of a concatenated string with unique characters. To achieve this, I need to explore all possible combinations of strings and select those with unique characters. This involves using a bitmask approach to represent the set of characters present in a string efficiently. +The goal is to find the number of pseudo-palindromic paths in a binary tree. A pseudo-palindromic path is a path where the frequency of each digit in the path is such that at most one digit has an odd frequency, making it possible to form a palindrome. # Approach -**Initialized a Data Structures :** -- Created an ArrayList `masks` to store the masks of valid strings (strings with unique characters). - -**Generated Masks :** -- Iterated through the input strings (`arr`) and use the `getMask` function to obtain the mask for each string. -- Added valid masks to the `masks` ArrayList. +##### TreeNode Class : + - My code starts with the definition of a `TreeNode` class representing a node in the binary tree. + +##### Main Solution Class : + - The `Solution` class contains a static variable `jawab` to store the final result. -**Depth-First Search (DFS) :** -- Implemented the DFS function (`dfs`) to explore all possible combinations of masks and find the maximum length. -- Started DFS from index 0 with an initially empty set (`used`). + - The `pseudoPalindromicPaths` method initialized the result variable and calls the helper method to traverse the tree and find paths. -**DFS Exploration :** -- For each mask, checked if it can be added to the current combination (`used`). -- If yes, updated the result (`res`) with the maximum length obtained by adding the current mask. +##### Helper Method : + - The `helper` method is my recursive function that traversed the binary tree. + + - For each node encountered : + - It XORs the current node's value with the bitmask `rasta`. + - If the node is a leaf node : + - It checked if the updated bitmask has at most one set bit, indicating a pseudo-palindromic path. + - If true, incremented the result variable `jawab`. + - Recursively called itself for the left and right children, updating the bitmask accordingly. + +##### Bitmask : + - The bitmask `rasta` is used to keep track of the frequency of digits encountered in the path. + + - XOR operation is used to toggle the bit corresponding to the current node's value. -**Result :** -- The final result is the count of set bits in the `used` mask, representing the maximum length of a concatenated string with unique characters. + - The expression `((rasta - 1) & rasta) == 0` checks if the updated bitmask has at most one set bit, ensuring the pseudo-palindromic property. -**Helper Function (`getMask`) :** -- The `getMask` function converts a string into a bitmask, where each bit corresponds to a character's presence. -- Returns -1 if the string has duplicate characters, indicating it is not a valid mask. +##### Result : + - The final result is the count of pseudo-palindromic paths, stored in the `jawab` variable. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) -# Complexity -- Time complexity : $O(2^n)$ -$n$ : number of valid masks. +# Complexity +- Time complexity : $O(N)$ - -- Space complexity : $O(2^n)$ +$N$ : number of nodes in the binary tree, as each node is visited once. +- Space complexity : $O(H)$ +$H$ : height of the binary tree, due to the recursion stack # Code ``` -import java.util.ArrayList; -import java.util.List; - +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ class Solution { - // ArrayList to store the masks of valid strings - static ArrayList masks; + // Static variable to store the result + static int jawab; - public int maxLength(List arr) { - masks = new ArrayList<>(); + public int pseudoPalindromicPaths (TreeNode root) { + // Initializing the result variable + jawab = 0; - // Iterating through the input strings and get their masks, add valid masks to the ArrayList - for (String s : arr) { - int mask = getMask(s); - if (mask != -1) { - masks.add(mask); - } - } + // Calling the helper function to traverse the tree and find paths + helper(0, root); - // Calling the DFS function starting from index 0 with an initially empty set - return dfs(0, 0); + // Returning the final result + return jawab; } - // DFS function to explore all possible combinations of masks - static int dfs(int s, int used) { - // Initialize the result with the count of set bits in the 'used' mask - int res = Integer.bitCount(used); - - // Iterating through the masks and explore valid combinations - for (int i = s; i < masks.size(); i++) { - // Checking if the current mask can be added to the combination - if ((used & masks.get(i)) == 0) { - // Updating the result with the maximum length obtained by adding the current mask - res = Math.max(res, dfs(i + 1, used | masks.get(i))); - } + // Helper function to recursively traverse the tree and find paths + static void helper(int rasta, TreeNode r) { + // Base case: If the current node is null, return + if (r == null) { + return; } - return res; - } - // Helper function to get the mask of a string, returns -1 if the string has duplicate characters - static int getMask(String s) { - int mask = 0; - for (char c : s.toCharArray()) { - int i = c - 'a'; - // Checking for duplicate characters in the string - if ((mask & (1 << i)) != 0) { - return -1; + // Checking if the current node is a leaf node + if (r.left == null && r.right == null) { + // Update=ing the bitmask by toggling the bit corresponding to the current node's value + rasta ^= 1 << r.val; + + // Checking if the updated bitmask has at most one set bit + if (((rasta - 1) & rasta) == 0) { + // If true, incrementing the result variable + jawab++; } - // Set the corresponding bit for the character in the mask - mask |= 1 << i; + + // Returning after processing the leaf node + return; } - return mask; + + // Recursively calling the helper function for the left and right children + helper(rasta ^ 1 << r.val, r.left); + helper(rasta ^ 1 << r.val, r.right); } } From f164cfadfe7800655cd0c7f96182da7d7868901e Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 24 Jan 2024 12:16:27 +0530 Subject: [PATCH 066/300] Create Daily 24-01-24.md --- 2024 January/Daily 24-01-24.md | 112 +++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 2024 January/Daily 24-01-24.md diff --git a/2024 January/Daily 24-01-24.md b/2024 January/Daily 24-01-24.md new file mode 100644 index 0000000..c1979cc --- /dev/null +++ b/2024 January/Daily 24-01-24.md @@ -0,0 +1,112 @@ +## Today's 24-01-24 [Problem Link](https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/description/?envType=daily-question&envId=2024-01-24) +## 1457. Pseudo-Palindromic Paths in a Binary Tree + + +# Intuition + +The goal is to find the number of pseudo-palindromic paths in a binary tree. A pseudo-palindromic path is a path where the frequency of each digit in the path is such that at most one digit has an odd frequency, making it possible to form a palindrome. + +# Approach + +##### TreeNode Class : + - My code starts with the definition of a `TreeNode` class representing a node in the binary tree. + +##### Main Solution Class : + - The `Solution` class contains a static variable `jawab` to store the final result. + + - The `pseudoPalindromicPaths` method initialized the result variable and calls the helper method to traverse the tree and find paths. + +##### Helper Method : + - The `helper` method is my recursive function that traversed the binary tree. + + - For each node encountered : + - It XORs the current node's value with the bitmask `rasta`. + - If the node is a leaf node : + - It checked if the updated bitmask has at most one set bit, indicating a pseudo-palindromic path. + - If true, incremented the result variable `jawab`. + - Recursively called itself for the left and right children, updating the bitmask accordingly. + +##### Bitmask : + - The bitmask `rasta` is used to keep track of the frequency of digits encountered in the path. + + - XOR operation is used to toggle the bit corresponding to the current node's value. + + - The expression `((rasta - 1) & rasta) == 0` checks if the updated bitmask has at most one set bit, ensuring the pseudo-palindromic property. + +##### Result : + - The final result is the count of pseudo-palindromic paths, stored in the `jawab` variable. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(N)$ + +$N$ : number of nodes in the binary tree, as each node is visited once. +- Space complexity : $O(H)$ + +$H$ : height of the binary tree, due to the recursion stack + +# Code +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + // Static variable to store the result + static int jawab; + + public int pseudoPalindromicPaths (TreeNode root) { + // Initializing the result variable + jawab = 0; + + // Calling the helper function to traverse the tree and find paths + helper(0, root); + + // Returning the final result + return jawab; + } + + // Helper function to recursively traverse the tree and find paths + static void helper(int rasta, TreeNode r) { + // Base case: If the current node is null, return + if (r == null) { + return; + } + + // Checking if the current node is a leaf node + if (r.left == null && r.right == null) { + // Update=ing the bitmask by toggling the bit corresponding to the current node's value + rasta ^= 1 << r.val; + + // Checking if the updated bitmask has at most one set bit + if (((rasta - 1) & rasta) == 0) { + // If true, incrementing the result variable + jawab++; + } + + // Returning after processing the leaf node + return; + } + + // Recursively calling the helper function for the left and right children + helper(rasta ^ 1 << r.val, r.left); + helper(rasta ^ 1 << r.val, r.right); + } +} + +``` \ No newline at end of file From 28fac2878968384005e97b9c2448b104960db9db Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 25 Jan 2024 10:31:31 +0530 Subject: [PATCH 067/300] Update README.md --- README.md | 128 ++++++++++++++++++++---------------------------------- 1 file changed, 46 insertions(+), 82 deletions(-) diff --git a/README.md b/README.md index 603aa66..29886a8 100644 --- a/README.md +++ b/README.md @@ -5,114 +5,78 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 24-01-24 [Problem Link](https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/description/?envType=daily-question&envId=2024-01-24) -## 1457. Pseudo-Palindromic Paths in a Binary Tree +## Today's 25-01-24 [Problem Link](https://leetcode.com/problems/longest-common-subsequence/description/?envType=daily-question&envId=2024-01-25) +## 1143. Longest Common Subsequence # Intuition -The goal is to find the number of pseudo-palindromic paths in a binary tree. A pseudo-palindromic path is a path where the frequency of each digit in the path is such that at most one digit has an odd frequency, making it possible to form a palindrome. +This problem aims to find the length of the longest common subsequence (LCS) between two given strings, `text1` and `text2`. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. The code uses dynamic programming to efficiently find the length of the LCS. # Approach -##### TreeNode Class : - - My code starts with the definition of a `TreeNode` class representing a node in the binary tree. +**Dynamic Programming Array (dp) :** + - Created a 2D array `dp` of dimensions `(1 + text1.length()) x (1 + text2.length())` to store the lengths of common subsequences for different prefixes of the input strings. + - `dp[i][j]` represents the length of the LCS for the prefixes of `text1` up to index `i-1` and `text2` up to index `j-1`. -##### Main Solution Class : - - The `Solution` class contains a static variable `jawab` to store the final result. - - - The `pseudoPalindromicPaths` method initialized the result variable and calls the helper method to traverse the tree and find paths. - -##### Helper Method : - - The `helper` method is my recursive function that traversed the binary tree. +**Nested Loop Iteration :** + - Iterated through each character in `text1` (using index `i`). + - For each character in `text1`, iterated through each character in `text2` (using index `j`). - - For each node encountered : - - It XORs the current node's value with the bitmask `rasta`. - - If the node is a leaf node : - - It checked if the updated bitmask has at most one set bit, indicating a pseudo-palindromic path. - - If true, incremented the result variable `jawab`. - - Recursively called itself for the left and right children, updating the bitmask accordingly. - -##### Bitmask : - - The bitmask `rasta` is used to keep track of the frequency of digits encountered in the path. - - - XOR operation is used to toggle the bit corresponding to the current node's value. +**Character Comparison :** + - If the characters at the current positions (i, j) in both strings are equal: + - Incremented the length of the common subsequence by 1: `dp[i + 1][j + 1] = 1 + dp[i][j]`. + - If the characters are not equal: + - Choosed the maximum length from the previous positions: + `dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1])`. + +**Result :** + - The value at the bottom-right corner of the array (`dp[text1.length()][text2.length()]`) contains the length of the longest common subsequence. - - The expression `((rasta - 1) & rasta) == 0` checks if the updated bitmask has at most one set bit, ensuring the pseudo-palindromic property. +**Return :** + - Returned the length of the LCS as the final result. -##### Result : - - The final result is the count of pseudo-palindromic paths, stored in the `jawab` variable. +My dynamic programming approach efficiently breaks down the problem into subproblems, avoiding redundant computations and providing an optimal solution for finding the length of the longest common subsequence. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(N)$ +- Time complexity : $O(a*b)$ -$N$ : number of nodes in the binary tree, as each node is visited once. -- Space complexity : $O(H)$ +$a$ : length of string 'text1' + +$b$ : length of string 'text2' +- Space complexity : $O(a*b)$ -$H$ : height of the binary tree, due to the recursion stack # Code ``` -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ class Solution { - - // Static variable to store the result - static int jawab; - - public int pseudoPalindromicPaths (TreeNode root) { - // Initializing the result variable - jawab = 0; - - // Calling the helper function to traverse the tree and find paths - helper(0, root); - - // Returning the final result - return jawab; - } - - // Helper function to recursively traverse the tree and find paths - static void helper(int rasta, TreeNode r) { - // Base case: If the current node is null, return - if (r == null) { - return; - } - - // Checking if the current node is a leaf node - if (r.left == null && r.right == null) { - // Update=ing the bitmask by toggling the bit corresponding to the current node's value - rasta ^= 1 << r.val; - - // Checking if the updated bitmask has at most one set bit - if (((rasta - 1) & rasta) == 0) { - // If true, incrementing the result variable - jawab++; + + public int longestCommonSubsequence(String text1, String text2) { + + // Creating a 2D array to store the length of common subsequences + int[][] dp = new int[1 + text1.length()][1 + text2.length()]; + + // Iterating through each character in text1 + for (int i = 0; i < text1.length(); i++) { + // Iterating through each character in text2 + for (int j = 0; j < text2.length(); j++) { + // Checking if the characters at the current positions are equal + if (text1.charAt(i) == text2.charAt(j)) { + // If equal, extending the common subsequence length by 1 + dp[i + 1][j + 1] = 1 + dp[i][j]; + } else { + // If not equal, choosing the maximum length from the previous positions + dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]); + } } - - // Returning after processing the leaf node - return; } - // Recursively calling the helper function for the left and right children - helper(rasta ^ 1 << r.val, r.left); - helper(rasta ^ 1 << r.val, r.right); + // The value at the bottom-right corner of the array contains the length of the longest common subsequence + return dp[text1.length()][text2.length()]; } } From 3f0a7fcd035e7350ad3e3114ae394f74c7a19296 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 25 Jan 2024 10:32:50 +0530 Subject: [PATCH 068/300] Create Daily 25-01-24.md --- 2024 January/Daily 25-01-24.md | 76 ++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 2024 January/Daily 25-01-24.md diff --git a/2024 January/Daily 25-01-24.md b/2024 January/Daily 25-01-24.md new file mode 100644 index 0000000..f301635 --- /dev/null +++ b/2024 January/Daily 25-01-24.md @@ -0,0 +1,76 @@ +## Today's 25-01-24 [Problem Link](https://leetcode.com/problems/longest-common-subsequence/description/?envType=daily-question&envId=2024-01-25) +## 1143. Longest Common Subsequence + + +# Intuition + +This problem aims to find the length of the longest common subsequence (LCS) between two given strings, `text1` and `text2`. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. The code uses dynamic programming to efficiently find the length of the LCS. + +# Approach + +**Dynamic Programming Array (dp) :** + - Created a 2D array `dp` of dimensions `(1 + text1.length()) x (1 + text2.length())` to store the lengths of common subsequences for different prefixes of the input strings. + - `dp[i][j]` represents the length of the LCS for the prefixes of `text1` up to index `i-1` and `text2` up to index `j-1`. + +**Nested Loop Iteration :** + - Iterated through each character in `text1` (using index `i`). + - For each character in `text1`, iterated through each character in `text2` (using index `j`). + +**Character Comparison :** + - If the characters at the current positions (i, j) in both strings are equal: + - Incremented the length of the common subsequence by 1: `dp[i + 1][j + 1] = 1 + dp[i][j]`. + - If the characters are not equal: + - Choosed the maximum length from the previous positions: + `dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1])`. + +**Result :** + - The value at the bottom-right corner of the array (`dp[text1.length()][text2.length()]`) contains the length of the longest common subsequence. + +**Return :** + - Returned the length of the LCS as the final result. + +My dynamic programming approach efficiently breaks down the problem into subproblems, avoiding redundant computations and providing an optimal solution for finding the length of the longest common subsequence. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(a*b)$ + +$a$ : length of string 'text1' + +$b$ : length of string 'text2' +- Space complexity : $O(a*b)$ + + +# Code +``` +class Solution { + + public int longestCommonSubsequence(String text1, String text2) { + + // Creating a 2D array to store the length of common subsequences + int[][] dp = new int[1 + text1.length()][1 + text2.length()]; + + // Iterating through each character in text1 + for (int i = 0; i < text1.length(); i++) { + // Iterating through each character in text2 + for (int j = 0; j < text2.length(); j++) { + // Checking if the characters at the current positions are equal + if (text1.charAt(i) == text2.charAt(j)) { + // If equal, extending the common subsequence length by 1 + dp[i + 1][j + 1] = 1 + dp[i][j]; + } else { + // If not equal, choosing the maximum length from the previous positions + dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]); + } + } + } + + // The value at the bottom-right corner of the array contains the length of the longest common subsequence + return dp[text1.length()][text2.length()]; + } +} + +``` \ No newline at end of file From e564f4fbd66502de9c1a62b5ec1825a337561b7f Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 25 Jan 2024 10:33:55 +0530 Subject: [PATCH 069/300] Delete Daily 25-01-24.md --- 2024 January/Daily 25-01-24.md | 76 ---------------------------------- 1 file changed, 76 deletions(-) delete mode 100644 2024 January/Daily 25-01-24.md diff --git a/2024 January/Daily 25-01-24.md b/2024 January/Daily 25-01-24.md deleted file mode 100644 index f301635..0000000 --- a/2024 January/Daily 25-01-24.md +++ /dev/null @@ -1,76 +0,0 @@ -## Today's 25-01-24 [Problem Link](https://leetcode.com/problems/longest-common-subsequence/description/?envType=daily-question&envId=2024-01-25) -## 1143. Longest Common Subsequence - - -# Intuition - -This problem aims to find the length of the longest common subsequence (LCS) between two given strings, `text1` and `text2`. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. The code uses dynamic programming to efficiently find the length of the LCS. - -# Approach - -**Dynamic Programming Array (dp) :** - - Created a 2D array `dp` of dimensions `(1 + text1.length()) x (1 + text2.length())` to store the lengths of common subsequences for different prefixes of the input strings. - - `dp[i][j]` represents the length of the LCS for the prefixes of `text1` up to index `i-1` and `text2` up to index `j-1`. - -**Nested Loop Iteration :** - - Iterated through each character in `text1` (using index `i`). - - For each character in `text1`, iterated through each character in `text2` (using index `j`). - -**Character Comparison :** - - If the characters at the current positions (i, j) in both strings are equal: - - Incremented the length of the common subsequence by 1: `dp[i + 1][j + 1] = 1 + dp[i][j]`. - - If the characters are not equal: - - Choosed the maximum length from the previous positions: - `dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1])`. - -**Result :** - - The value at the bottom-right corner of the array (`dp[text1.length()][text2.length()]`) contains the length of the longest common subsequence. - -**Return :** - - Returned the length of the LCS as the final result. - -My dynamic programming approach efficiently breaks down the problem into subproblems, avoiding redundant computations and providing an optimal solution for finding the length of the longest common subsequence. - ---- -Have a look at the code , still have any confusion then please let me know in the comments -Keep Solving.:) - -# Complexity -- Time complexity : $O(a*b)$ - -$a$ : length of string 'text1' - -$b$ : length of string 'text2' -- Space complexity : $O(a*b)$ - - -# Code -``` -class Solution { - - public int longestCommonSubsequence(String text1, String text2) { - - // Creating a 2D array to store the length of common subsequences - int[][] dp = new int[1 + text1.length()][1 + text2.length()]; - - // Iterating through each character in text1 - for (int i = 0; i < text1.length(); i++) { - // Iterating through each character in text2 - for (int j = 0; j < text2.length(); j++) { - // Checking if the characters at the current positions are equal - if (text1.charAt(i) == text2.charAt(j)) { - // If equal, extending the common subsequence length by 1 - dp[i + 1][j + 1] = 1 + dp[i][j]; - } else { - // If not equal, choosing the maximum length from the previous positions - dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]); - } - } - } - - // The value at the bottom-right corner of the array contains the length of the longest common subsequence - return dp[text1.length()][text2.length()]; - } -} - -``` \ No newline at end of file From fb0a2276c9d2c62f538ba95e5f932a01064bfd1c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 25 Jan 2024 10:34:00 +0530 Subject: [PATCH 070/300] Create Daily 25-01=24.md --- 2024 January/Daily 25-01=24.md | 76 ++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 2024 January/Daily 25-01=24.md diff --git a/2024 January/Daily 25-01=24.md b/2024 January/Daily 25-01=24.md new file mode 100644 index 0000000..f301635 --- /dev/null +++ b/2024 January/Daily 25-01=24.md @@ -0,0 +1,76 @@ +## Today's 25-01-24 [Problem Link](https://leetcode.com/problems/longest-common-subsequence/description/?envType=daily-question&envId=2024-01-25) +## 1143. Longest Common Subsequence + + +# Intuition + +This problem aims to find the length of the longest common subsequence (LCS) between two given strings, `text1` and `text2`. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. The code uses dynamic programming to efficiently find the length of the LCS. + +# Approach + +**Dynamic Programming Array (dp) :** + - Created a 2D array `dp` of dimensions `(1 + text1.length()) x (1 + text2.length())` to store the lengths of common subsequences for different prefixes of the input strings. + - `dp[i][j]` represents the length of the LCS for the prefixes of `text1` up to index `i-1` and `text2` up to index `j-1`. + +**Nested Loop Iteration :** + - Iterated through each character in `text1` (using index `i`). + - For each character in `text1`, iterated through each character in `text2` (using index `j`). + +**Character Comparison :** + - If the characters at the current positions (i, j) in both strings are equal: + - Incremented the length of the common subsequence by 1: `dp[i + 1][j + 1] = 1 + dp[i][j]`. + - If the characters are not equal: + - Choosed the maximum length from the previous positions: + `dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1])`. + +**Result :** + - The value at the bottom-right corner of the array (`dp[text1.length()][text2.length()]`) contains the length of the longest common subsequence. + +**Return :** + - Returned the length of the LCS as the final result. + +My dynamic programming approach efficiently breaks down the problem into subproblems, avoiding redundant computations and providing an optimal solution for finding the length of the longest common subsequence. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(a*b)$ + +$a$ : length of string 'text1' + +$b$ : length of string 'text2' +- Space complexity : $O(a*b)$ + + +# Code +``` +class Solution { + + public int longestCommonSubsequence(String text1, String text2) { + + // Creating a 2D array to store the length of common subsequences + int[][] dp = new int[1 + text1.length()][1 + text2.length()]; + + // Iterating through each character in text1 + for (int i = 0; i < text1.length(); i++) { + // Iterating through each character in text2 + for (int j = 0; j < text2.length(); j++) { + // Checking if the characters at the current positions are equal + if (text1.charAt(i) == text2.charAt(j)) { + // If equal, extending the common subsequence length by 1 + dp[i + 1][j + 1] = 1 + dp[i][j]; + } else { + // If not equal, choosing the maximum length from the previous positions + dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]); + } + } + } + + // The value at the bottom-right corner of the array contains the length of the longest common subsequence + return dp[text1.length()][text2.length()]; + } +} + +``` \ No newline at end of file From 30ce906fa71d739aa8b67f6082d53cf24d8f83b1 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 25 Jan 2024 10:34:26 +0530 Subject: [PATCH 071/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 29886a8..e12978b 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 25-01-24 [Problem Link](https://leetcode.com/problems/longest-common-subsequence/description/?envType=daily-question&envId=2024-01-25) +## Today's 25-01=24 [Problem Link](https://leetcode.com/problems/longest-common-subsequence/description/?envType=daily-question&envId=2024-01-25) ## 1143. Longest Common Subsequence From 9dab88348242aea7d694bb4ab13f6d07114e0c81 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 26 Jan 2024 10:53:33 +0530 Subject: [PATCH 072/300] Update README.md --- README.md | 102 +++++++++++++++++++++++++++++------------------------- 1 file changed, 55 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index e12978b..07988dd 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ +# Celebrating Unity in Diversity: Happy Republic Day! + + # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. @@ -5,78 +8,83 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 25-01=24 [Problem Link](https://leetcode.com/problems/longest-common-subsequence/description/?envType=daily-question&envId=2024-01-25) -## 1143. Longest Common Subsequence +## Today's 26-01-24 [Problem Link](https://leetcode.com/problems/out-of-boundary-paths/description/?envType=daily-question&envId=2024-01-26) +## 576. Out of Boundary Paths # Intuition -This problem aims to find the length of the longest common subsequence (LCS) between two given strings, `text1` and `text2`. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. The code uses dynamic programming to efficiently find the length of the LCS. +This problem involves finding the number of paths a ball can take to move out of a grid within a given number of moves. My goal is to optimize the solution using dynamic programming to avoid redundant calculations. # Approach -**Dynamic Programming Array (dp) :** - - Created a 2D array `dp` of dimensions `(1 + text1.length()) x (1 + text2.length())` to store the lengths of common subsequences for different prefixes of the input strings. - - `dp[i][j]` represents the length of the LCS for the prefixes of `text1` up to index `i-1` and `text2` up to index `j-1`. +I have utilized dynamic programming approach with memoization to efficiently calculate the number of paths. A recursive helper function is defined to explore all possible moves, and a 3D memoization array is used to store and retrieve previously computed results. -**Nested Loop Iteration :** - - Iterated through each character in `text1` (using index `i`). - - For each character in `text1`, iterated through each character in `text2` (using index `j`). - -**Character Comparison :** - - If the characters at the current positions (i, j) in both strings are equal: - - Incremented the length of the common subsequence by 1: `dp[i + 1][j + 1] = 1 + dp[i][j]`. - - If the characters are not equal: - - Choosed the maximum length from the previous positions: - `dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1])`. +#### Recursive Helper Function -**Result :** - - The value at the bottom-right corner of the array (`dp[text1.length()][text2.length()]`) contains the length of the longest common subsequence. +My recursive function is responsible for calculating the number of paths from a given cell with a specified number of remaining moves. Key points of the recursive function include: +- Base cases : Handled scenarios where the ball moves outside the grid or runs out of moves. +- Memoization : Stored and retrieved results using a 3D array to avoid redundant calculations. +- Recursive step : Explored all possible moves (up, down, left, right) and sum up the results with modulo to prevent integer overflow. -**Return :** - - Returned the length of the LCS as the final result. - -My dynamic programming approach efficiently breaks down the problem into subproblems, avoiding redundant computations and providing an optimal solution for finding the length of the longest common subsequence. +#### Code Explanation +My Java code provided implements the described approach. The `findPaths` function initializes the memoization array and calls the recursive helper function. The `helper` function handles the recursive calculations and memoization. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(a*b)$ +- Time complexity : $O(m * n * maxMove)$ -$a$ : length of string 'text1' - -$b$ : length of string 'text2' -- Space complexity : $O(a*b)$ +$m$ : number of rows in the grid +$n$ : number of columns in the grid +$maxMove$ : maximum number of moves allowed +- Space complexity : $O(m * n * (1+maxMove))$ ~ $O(m * n * maxMove)$ # Code ``` class Solution { - - public int longestCommonSubsequence(String text1, String text2) { + + // Modulo value for the result + static int mod = 1_000_000_007; + + // Main function to find paths + public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { - // Creating a 2D array to store the length of common subsequences - int[][] dp = new int[1 + text1.length()][1 + text2.length()]; - - // Iterating through each character in text1 - for (int i = 0; i < text1.length(); i++) { - // Iterating through each character in text2 - for (int j = 0; j < text2.length(); j++) { - // Checking if the characters at the current positions are equal - if (text1.charAt(i) == text2.charAt(j)) { - // If equal, extending the common subsequence length by 1 - dp[i + 1][j + 1] = 1 + dp[i][j]; - } else { - // If not equal, choosing the maximum length from the previous positions - dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]); - } - } + // Creating 3D array to store previously calculated results + Integer[][][] h = new Integer[1 + maxMove][m][n]; + return helper(startRow, startColumn, maxMove, m, n, h); + } + + // Helper function for recursive calculations + static int helper(int r, int c, int max, int m, int n, Integer[][][] h) { + // Base case: if the cell is outside the grid, count it as a path + if (r < 0 || c < 0 || r == m || c == n) { + return 1; + } + + // Base case: if the maximum moves are exhausted, no more paths + if (max == 0) { + return 0; } - // The value at the bottom-right corner of the array contains the length of the longest common subsequence - return dp[text1.length()][text2.length()]; + // If the result for the current state is already calculated, returning it + if (h[max][r][c] != null) { + return h[max][r][c]; + } + + // Recursively calculating of paths by moving in all possible directions + h[max][r][c] = (int) (( + (helper(r, c + 1, max - 1, m, n, h)) * 1L + + helper(r, c - 1, max - 1, m, n, h) + + helper(r + 1, c, max - 1, m, n, h) + + helper(r - 1, c, max - 1, m, n, h) + ) % mod); + + // Storing the calculated result and return it + return h[max][r][c]; } } From 4cf311f78aa3d04d87c837600bc049bcedc6ab80 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 26 Jan 2024 10:56:59 +0530 Subject: [PATCH 073/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 07988dd..ae3ce3d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Celebrating Unity in Diversity: Happy Republic Day! +# Celebrating Unity in Diversity: Happy Republic Day ! :india: # Leetcode Daily Challenge Solutions From 1b5a9d3f001c8d95e2c3663d5b4158b8e444e16a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 26 Jan 2024 10:58:59 +0530 Subject: [PATCH 074/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ae3ce3d..348ac43 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Celebrating Unity in Diversity: Happy Republic Day ! :india: +# Celebrating Unity in Diversity: Happy Republic Day ! :india: :india: # Leetcode Daily Challenge Solutions From 562b8dfa8400743cffd84f16ddda7e8af889ba9c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 26 Jan 2024 11:01:57 +0530 Subject: [PATCH 075/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 348ac43..c81fdaa 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Celebrating Unity in Diversity: Happy Republic Day ! :india: :india: +# Celebrating Unity in Diversity: Happy Republic Day ! :india: [](http://example.com/) # Leetcode Daily Challenge Solutions From d637c94384db3190a6379e4458ea872b9ede0d50 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 26 Jan 2024 11:05:11 +0530 Subject: [PATCH 076/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c81fdaa..644b7bc 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Celebrating Unity in Diversity: Happy Republic Day ! :india: [](http://example.com/) +# Celebrating Unity in Diversity: Happy Republic Day ! :smile: # Leetcode Daily Challenge Solutions From 238210a902edf2170fe5d7f209ad2114ed736d25 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Fri, 26 Jan 2024 11:06:05 +0530 Subject: [PATCH 077/300] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 644b7bc..335e888 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Celebrating Unity in Diversity: Happy Republic Day ! :smile: +# Celebrating Unity in Diversity: Happy Republic Day ! 🇮🇳: # Leetcode Daily Challenge Solutions @@ -88,4 +88,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 053a3858767fe6298efd9a2d28a72f3dda231b49 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Fri, 26 Jan 2024 11:06:16 +0530 Subject: [PATCH 078/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 335e888..a9e8fb6 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Celebrating Unity in Diversity: Happy Republic Day ! 🇮🇳: +# Celebrating Unity in Diversity: Happy Republic Day ! :🇮🇳: # Leetcode Daily Challenge Solutions From 0477915ff3692187252a1eba9c7164172df5120c Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Fri, 26 Jan 2024 11:07:48 +0530 Subject: [PATCH 079/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a9e8fb6..011bfe9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Celebrating Unity in Diversity: Happy Republic Day ! :🇮🇳: +# Celebrating Unity in Diversity: Happy Republic Day ! :india: # Leetcode Daily Challenge Solutions From 1c00a8eaa504822b9f07b37dee8ac6e9bb8dd8c8 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 26 Jan 2024 11:14:54 +0530 Subject: [PATCH 080/300] Create Daily 26-01-24.md --- 2024 January/Daily 26-01-24.md | 84 ++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 2024 January/Daily 26-01-24.md diff --git a/2024 January/Daily 26-01-24.md b/2024 January/Daily 26-01-24.md new file mode 100644 index 0000000..cf01937 --- /dev/null +++ b/2024 January/Daily 26-01-24.md @@ -0,0 +1,84 @@ +# Celebrating Unity in Diversity: Happy Republic Day ! :india: + + +## Today's 26-01-24 [Problem Link](https://leetcode.com/problems/out-of-boundary-paths/description/?envType=daily-question&envId=2024-01-26) +## 576. Out of Boundary Paths + + +# Intuition + +This problem involves finding the number of paths a ball can take to move out of a grid within a given number of moves. My goal is to optimize the solution using dynamic programming to avoid redundant calculations. + +# Approach + +I have utilized dynamic programming approach with memoization to efficiently calculate the number of paths. A recursive helper function is defined to explore all possible moves, and a 3D memoization array is used to store and retrieve previously computed results. + +#### Recursive Helper Function + +My recursive function is responsible for calculating the number of paths from a given cell with a specified number of remaining moves. Key points of the recursive function include: +- Base cases : Handled scenarios where the ball moves outside the grid or runs out of moves. +- Memoization : Stored and retrieved results using a 3D array to avoid redundant calculations. +- Recursive step : Explored all possible moves (up, down, left, right) and sum up the results with modulo to prevent integer overflow. + +#### Code Explanation +My Java code provided implements the described approach. The `findPaths` function initializes the memoization array and calls the recursive helper function. The `helper` function handles the recursive calculations and memoization. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(m * n * maxMove)$ + +$m$ : number of rows in the grid +$n$ : number of columns in the grid +$maxMove$ : maximum number of moves allowed +- Space complexity : $O(m * n * (1+maxMove))$ ~ $O(m * n * maxMove)$ + + +# Code +``` +class Solution { + + // Modulo value for the result + static int mod = 1_000_000_007; + + // Main function to find paths + public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { + + // Creating 3D array to store previously calculated results + Integer[][][] h = new Integer[1 + maxMove][m][n]; + return helper(startRow, startColumn, maxMove, m, n, h); + } + + // Helper function for recursive calculations + static int helper(int r, int c, int max, int m, int n, Integer[][][] h) { + // Base case: if the cell is outside the grid, count it as a path + if (r < 0 || c < 0 || r == m || c == n) { + return 1; + } + + // Base case: if the maximum moves are exhausted, no more paths + if (max == 0) { + return 0; + } + + // If the result for the current state is already calculated, returning it + if (h[max][r][c] != null) { + return h[max][r][c]; + } + + // Recursively calculating of paths by moving in all possible directions + h[max][r][c] = (int) (( + (helper(r, c + 1, max - 1, m, n, h)) * 1L + + helper(r, c - 1, max - 1, m, n, h) + + helper(r + 1, c, max - 1, m, n, h) + + helper(r - 1, c, max - 1, m, n, h) + ) % mod); + + // Storing the calculated result and return it + return h[max][r][c]; + } +} + +``` From 59f0d8b0acf135fc562e927d4b3eb915b1b9132c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 27 Jan 2024 15:43:44 +0530 Subject: [PATCH 081/300] Update README.md --- README.md | 100 +++++++++++++++++++++++++----------------------------- 1 file changed, 47 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index 011bfe9..b5d73ed 100644 --- a/README.md +++ b/README.md @@ -8,84 +8,78 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 26-01-24 [Problem Link](https://leetcode.com/problems/out-of-boundary-paths/description/?envType=daily-question&envId=2024-01-26) -## 576. Out of Boundary Paths +## Today's 27-01-24 [Problem Link](https://leetcode.com/problems/k-inverse-pairs-array/description/?envType=daily-question&envId=2024-01-27) +## 629. K Inverse Pairs Array # Intuition -This problem involves finding the number of paths a ball can take to move out of a grid within a given number of moves. My goal is to optimize the solution using dynamic programming to avoid redundant calculations. +This problem requires counting the number of permutations of numbers from 1 to n with a given number of inverse pairs. An inverse pair in a permutation (a[i], a[j]) is defined as (i < j and a[i] > a[j]). The goal is to find the count of permutations with a specific number of inverse pairs. + # Approach -I have utilized dynamic programming approach with memoization to efficiently calculate the number of paths. A recursive helper function is defined to explore all possible moves, and a 3D memoization array is used to store and retrieve previously computed results. - -#### Recursive Helper Function - -My recursive function is responsible for calculating the number of paths from a given cell with a specified number of remaining moves. Key points of the recursive function include: -- Base cases : Handled scenarios where the ball moves outside the grid or runs out of moves. -- Memoization : Stored and retrieved results using a 3D array to avoid redundant calculations. -- Recursive step : Explored all possible moves (up, down, left, right) and sum up the results with modulo to prevent integer overflow. - -#### Code Explanation -My Java code provided implements the described approach. The `findPaths` function initializes the memoization array and calls the recursive helper function. The `helper` function handles the recursive calculations and memoization. +**Base Case :** + - When j is 0 (no inverse pairs), there is only one way to arrange the numbers, i.e., the ascending order. So, dp[i][0] is set to 1 for all i. + +**Dynamic Programming Transition :** + - For each i and j, I updated the dp[i][j] using the following recurrence relation: + ``` + dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % MOD; + ``` + This accounted for permutations with the same number of inverse pairs as the previous step. + + - Additionally, if (j - i) is non-negative, I subtracted the count of permutations with (j - i) inverse pairs to avoid double counting: + ``` + dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + MOD) % MOD; + ``` + +**Result :** + - The final result is stored in `dp[n][k]`, representing the count of permutations of numbers 1 to n with k inverse pairs. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + # Complexity -- Time complexity : $O(m * n * maxMove)$ +- Time complexity : $O(n*k)$ -$m$ : number of rows in the grid -$n$ : number of columns in the grid -$maxMove$ : maximum number of moves allowed -- Space complexity : $O(m * n * (1+maxMove))$ ~ $O(m * n * maxMove)$ + +- Space complexity : $O(n*k)$ # Code ``` class Solution { + static int MOD = 1_000_000_007; - // Modulo value for the result - static int mod = 1_000_000_007; + // Function to calculate the number of arrays with k inverse pairs + public int kInversePairs(int n, int k) { + // gp[i][j] representing the number of arrays of length i with j inverse pairs + int[][] gp = new int[n + 1][k + 1]; - // Main function to find paths - public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { - - // Creating 3D array to store previously calculated results - Integer[][][] h = new Integer[1 + maxMove][m][n]; - return helper(startRow, startColumn, maxMove, m, n, h); - } - - // Helper function for recursive calculations - static int helper(int r, int c, int max, int m, int n, Integer[][][] h) { - // Base case: if the cell is outside the grid, count it as a path - if (r < 0 || c < 0 || r == m || c == n) { - return 1; - } - - // Base case: if the maximum moves are exhausted, no more paths - if (max == 0) { - return 0; + // Base case: If there are no inverse pairs (j=0), there is only one array (empty array). + for (int i = 0; i <= n; i++) { + gp[i][0] = 1; } - // If the result for the current state is already calculated, returning it - if (h[max][r][c] != null) { - return h[max][r][c]; + // Dynamic Programming to fill the gp array + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= k; ++j) { + // Calculating the number of arrays with j inverse pairs + gp[i][j] = (gp[i][j - 1] + gp[i - 1][j]) % MOD; + + // If j - i is non-negative, subtracting the count of arrays with (j - i) inverse pairs + if (j - i >= 0) { + gp[i][j] = (gp[i][j] - gp[i - 1][j - i] + MOD) % MOD; + } + } } - // Recursively calculating of paths by moving in all possible directions - h[max][r][c] = (int) (( - (helper(r, c + 1, max - 1, m, n, h)) * 1L + - helper(r, c - 1, max - 1, m, n, h) + - helper(r + 1, c, max - 1, m, n, h) + - helper(r - 1, c, max - 1, m, n, h) - ) % mod); - - // Storing the calculated result and return it - return h[max][r][c]; + // Returning the result, which represents the number of arrays of length n with k inverse pairs + return gp[n][k]; } } -``` +``` \ No newline at end of file From 9a4709a2e9a0383bf62dfa416c333e5a46dad4b1 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 27 Jan 2024 15:44:12 +0530 Subject: [PATCH 082/300] Update README.md --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index b5d73ed..e5e8f69 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,3 @@ -# Celebrating Unity in Diversity: Happy Republic Day ! :india: - - # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. From 2fbb6379fde578a24824bda34f3f0560efdbe40c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 27 Jan 2024 15:46:27 +0530 Subject: [PATCH 083/300] Create Daily 27-01-24.md --- 2024 January/Daily 27-01-24.md | 75 ++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 2024 January/Daily 27-01-24.md diff --git a/2024 January/Daily 27-01-24.md b/2024 January/Daily 27-01-24.md new file mode 100644 index 0000000..854c2c8 --- /dev/null +++ b/2024 January/Daily 27-01-24.md @@ -0,0 +1,75 @@ +## Today's 27-01-24 [Problem Link](https://leetcode.com/problems/k-inverse-pairs-array/description/?envType=daily-question&envId=2024-01-27) +## 629. K Inverse Pairs Array + + +# Intuition + +This problem requires counting the number of permutations of numbers from 1 to n with a given number of inverse pairs. An inverse pair in a permutation (a[i], a[j]) is defined as (i < j and a[i] > a[j]). The goal is to find the count of permutations with a specific number of inverse pairs. + + +# Approach + +**Base Case :** + - When j is 0 (no inverse pairs), there is only one way to arrange the numbers, i.e., the ascending order. So, dp[i][0] is set to 1 for all i. + +**Dynamic Programming Transition :** + - For each i and j, I updated the dp[i][j] using the following recurrence relation: + ``` + dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % MOD; + ``` + This accounted for permutations with the same number of inverse pairs as the previous step. + + - Additionally, if (j - i) is non-negative, I subtracted the count of permutations with (j - i) inverse pairs to avoid double counting: + ``` + dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + MOD) % MOD; + ``` + +**Result :** + - The final result is stored in `dp[n][k]`, representing the count of permutations of numbers 1 to n with k inverse pairs. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + + +# Complexity +- Time complexity : $O(n*k)$ + + +- Space complexity : $O(n*k)$ + + +# Code +``` +class Solution { + static int MOD = 1_000_000_007; + + // Function to calculate the number of arrays with k inverse pairs + public int kInversePairs(int n, int k) { + // gp[i][j] representing the number of arrays of length i with j inverse pairs + int[][] gp = new int[n + 1][k + 1]; + + // Base case: If there are no inverse pairs (j=0), there is only one array (empty array). + for (int i = 0; i <= n; i++) { + gp[i][0] = 1; + } + + // Dynamic Programming to fill the gp array + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= k; ++j) { + // Calculating the number of arrays with j inverse pairs + gp[i][j] = (gp[i][j - 1] + gp[i - 1][j]) % MOD; + + // If j - i is non-negative, subtracting the count of arrays with (j - i) inverse pairs + if (j - i >= 0) { + gp[i][j] = (gp[i][j] - gp[i - 1][j - i] + MOD) % MOD; + } + } + } + + // Returning the result, which represents the number of arrays of length n with k inverse pairs + return gp[n][k]; + } +} + +``` \ No newline at end of file From dd7a96516ae71d6dc62b0e59026030245e9d9cd7 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Sat, 27 Jan 2024 22:58:18 +0530 Subject: [PATCH 084/300] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index e5e8f69..a2f9b67 100644 --- a/README.md +++ b/README.md @@ -17,22 +17,22 @@ This problem requires counting the number of permutations of numbers from 1 to n # Approach **Base Case :** - - When j is 0 (no inverse pairs), there is only one way to arrange the numbers, i.e., the ascending order. So, dp[i][0] is set to 1 for all i. + - When j is 0 (no inverse pairs), there is only one way to arrange the numbers, i.e., the ascending order. So, gp[i][0] is set to 1 for all i. **Dynamic Programming Transition :** - - For each i and j, I updated the dp[i][j] using the following recurrence relation: + - For each i and j, I updated the gp[i][j] using the following recurrence relation: ``` - dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % MOD; + gp[i][j] = (gp[i][j - 1] + gp[i - 1][j]) % MOD; ``` This accounted for permutations with the same number of inverse pairs as the previous step. - Additionally, if (j - i) is non-negative, I subtracted the count of permutations with (j - i) inverse pairs to avoid double counting: ``` - dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + MOD) % MOD; + gp[i][j] = (gp[i][j] - gp[i - 1][j - i] + MOD) % MOD; ``` **Result :** - - The final result is stored in `dp[n][k]`, representing the count of permutations of numbers 1 to n with k inverse pairs. + - The final result is stored in `gp[n][k]`, representing the count of permutations of numbers 1 to n with k inverse pairs. --- Have a look at the code , still have any confusion then please let me know in the comments @@ -79,4 +79,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 4a7b5ddc27dc7ad6c7fcd9c5940043f7509b320a Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Sat, 27 Jan 2024 22:58:46 +0530 Subject: [PATCH 085/300] Update Daily 27-01-24.md --- 2024 January/Daily 27-01-24.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/2024 January/Daily 27-01-24.md b/2024 January/Daily 27-01-24.md index 854c2c8..053dd56 100644 --- a/2024 January/Daily 27-01-24.md +++ b/2024 January/Daily 27-01-24.md @@ -10,28 +10,27 @@ This problem requires counting the number of permutations of numbers from 1 to n # Approach **Base Case :** - - When j is 0 (no inverse pairs), there is only one way to arrange the numbers, i.e., the ascending order. So, dp[i][0] is set to 1 for all i. + - When j is 0 (no inverse pairs), there is only one way to arrange the numbers, i.e., the ascending order. So, gp[i][0] is set to 1 for all i. **Dynamic Programming Transition :** - - For each i and j, I updated the dp[i][j] using the following recurrence relation: + - For each i and j, I updated the gp[i][j] using the following recurrence relation: ``` - dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % MOD; + gp[i][j] = (gp[i][j - 1] + gp[i - 1][j]) % MOD; ``` This accounted for permutations with the same number of inverse pairs as the previous step. - Additionally, if (j - i) is non-negative, I subtracted the count of permutations with (j - i) inverse pairs to avoid double counting: ``` - dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + MOD) % MOD; + gp[i][j] = (gp[i][j] - gp[i - 1][j - i] + MOD) % MOD; ``` **Result :** - - The final result is stored in `dp[n][k]`, representing the count of permutations of numbers 1 to n with k inverse pairs. + - The final result is stored in `gp[n][k]`, representing the count of permutations of numbers 1 to n with k inverse pairs. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity - Time complexity : $O(n*k)$ @@ -72,4 +71,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 6bb664e97ca2c83d684f001d7b600d11ea8c2a36 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 28 Jan 2024 10:26:16 +0530 Subject: [PATCH 086/300] Update README.md --- README.md | 118 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 70 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index a2f9b67..e76912c 100644 --- a/README.md +++ b/README.md @@ -5,78 +5,100 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 27-01-24 [Problem Link](https://leetcode.com/problems/k-inverse-pairs-array/description/?envType=daily-question&envId=2024-01-27) -## 629. K Inverse Pairs Array +## Today's 28-01-24 [Problem Link](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/description/?envType=daily-question&envId=2024-01-28) +## 1074. Number of Submatrices That Sum to Target # Intuition -This problem requires counting the number of permutations of numbers from 1 to n with a given number of inverse pairs. An inverse pair in a permutation (a[i], a[j]) is defined as (i < j and a[i] > a[j]). The goal is to find the count of permutations with a specific number of inverse pairs. - # Approach -**Base Case :** - - When j is 0 (no inverse pairs), there is only one way to arrange the numbers, i.e., the ascending order. So, gp[i][0] is set to 1 for all i. - -**Dynamic Programming Transition :** - - For each i and j, I updated the gp[i][j] using the following recurrence relation: - ``` - gp[i][j] = (gp[i][j - 1] + gp[i - 1][j]) % MOD; - ``` - This accounted for permutations with the same number of inverse pairs as the previous step. - - - Additionally, if (j - i) is non-negative, I subtracted the count of permutations with (j - i) inverse pairs to avoid double counting: - ``` - gp[i][j] = (gp[i][j] - gp[i - 1][j - i] + MOD) % MOD; - ``` - -**Result :** - - The final result is stored in `gp[n][k]`, representing the count of permutations of numbers 1 to n with k inverse pairs. +**Initialized Variables :** + - `jawab`: A static variable to store the final result. + - `r`: Number of rows in the matrix. + - `c`: Number of columns in the matrix. + - `m`: A HashMap to store cumulative sum frequencies. + +**Calculated Cumulative Sums :** + - Iterated over each row in the matrix and calculated cumulative sums for each element in that row. This is done to efficiently compute the sum of submatrices. + +**Iterated Over Column Combinations :** + - Used two nested loops to iterate over all possible combinations of columns (ic and j). + - For each column combination, initialized the HashMap (`m`) to store cumulative sum frequencies. + +**Calculate Cumulative Sums for Submatrices :** + - Iterated over each row to calculate the cumulative sum (`jor`) for submatrices. + - Adjusted the cumulative sum if `ic` is greater than 0 (not the first column). + +**Updated Result and HashMap :** + - Updated the result (`jawab`) by adding the frequency of the target cumulative sum found in the HashMap. + - Updated the HashMap with the current cumulative sum and its frequency. + +**Return Result :** + - Returned the final result, which represents the count of submatrices with the target sum. + +My approach leverages cumulative sums and dynamic programming to efficiently count submatrices with a target sum, making it an optimized solution. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - - # Complexity -- Time complexity : $O(n*k)$ +- Time complexity : $O(r * c^2)$ +$r$ : number of rows in the matrix -- Space complexity : $O(n*k)$ +$c$ : number of columns in the matrix +- Space complexity : $O(c)$ # Code ``` -class Solution { - static int MOD = 1_000_000_007; - // Function to calculate the number of arrays with k inverse pairs - public int kInversePairs(int n, int k) { - // gp[i][j] representing the number of arrays of length i with j inverse pairs - int[][] gp = new int[n + 1][k + 1]; - - // Base case: If there are no inverse pairs (j=0), there is only one array (empty array). - for (int i = 0; i <= n; i++) { - gp[i][0] = 1; +class Solution { + static int jawab; // Static variable to store the final result + static int r; // Number of rows in the matrix + static int c; // Number of columns in the matrix + static HashMap m; // HashMap to store the cumulative sum frequencies + + public int numSubmatrixSumTarget(int[][] matrix, int target) { + jawab = 0; // Initialize the result to 0 + r = matrix.length; // Number of rows in the matrix + c = matrix[0].length; // Number of columns in the matrix + + // Calculating the cumulative sum for each row + for (int[] p : matrix) { + for (int j = 1; j < c; j++) { + p[j] += p[j - 1]; + } } - // Dynamic Programming to fill the gp array - for (int i = 1; i <= n; ++i) { - for (int j = 1; j <= k; ++j) { - // Calculating the number of arrays with j inverse pairs - gp[i][j] = (gp[i][j - 1] + gp[i - 1][j]) % MOD; - - // If j - i is non-negative, subtracting the count of arrays with (j - i) inverse pairs - if (j - i >= 0) { - gp[i][j] = (gp[i][j] - gp[i - 1][j - i] + MOD) % MOD; + // Iterating over all possible column combinations + for (int ic = 0; ic < c; ic++) { + for (int j = ic; j < c; j++) { + m = new HashMap<>(); // Initializing the HashMap for each column combination + m.put(0, 1); // Initializing the HashMap with the base case (cumulative sum = 0, frequency = 1) + int jor = 0; // Initializing the cumulative sum variable + + // Iterating over each row to calculate the cumulative sum + for (int p = 0; p < r; p++) { + jor += matrix[p][j]; + + // Adjusting the cumulative sum if ic > 0 (not the first column) + if (ic > 0) { + jor -= matrix[p][ic - 1]; + } + + // Updating the result with the frequency of the target cumulative sum + jawab += m.getOrDefault(jor - target, 0); + + // Updating the HashMap with the current cumulative sum + m.merge(jor, 1, Integer::sum); } } } - - // Returning the result, which represents the number of arrays of length n with k inverse pairs - return gp[n][k]; + return jawab; // Returning the final result } } -``` +``` \ No newline at end of file From 4128cebaf48cde393957434b4166d3768961a134 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 28 Jan 2024 10:28:21 +0530 Subject: [PATCH 087/300] Create Daily 28-01-24.md --- 2024 January/Daily 28-01-24.md | 97 ++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 2024 January/Daily 28-01-24.md diff --git a/2024 January/Daily 28-01-24.md b/2024 January/Daily 28-01-24.md new file mode 100644 index 0000000..05a65df --- /dev/null +++ b/2024 January/Daily 28-01-24.md @@ -0,0 +1,97 @@ +## Today's 28-01-24 [Problem Link](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/description/?envType=daily-question&envId=2024-01-28) +## 1074. Number of Submatrices That Sum to Target + + +# Intuition + + +# Approach + +**Initialized Variables :** + - `jawab`: A static variable to store the final result. + - `r`: Number of rows in the matrix. + - `c`: Number of columns in the matrix. + - `m`: A HashMap to store cumulative sum frequencies. + +**Calculated Cumulative Sums :** + - Iterated over each row in the matrix and calculated cumulative sums for each element in that row. This is done to efficiently compute the sum of submatrices. + +**Iterated Over Column Combinations :** + - Used two nested loops to iterate over all possible combinations of columns (ic and j). + - For each column combination, initialized the HashMap (`m`) to store cumulative sum frequencies. + +**Calculate Cumulative Sums for Submatrices :** + - Iterated over each row to calculate the cumulative sum (`jor`) for submatrices. + - Adjusted the cumulative sum if `ic` is greater than 0 (not the first column). + +**Updated Result and HashMap :** + - Updated the result (`jawab`) by adding the frequency of the target cumulative sum found in the HashMap. + - Updated the HashMap with the current cumulative sum and its frequency. + +**Return Result :** + - Returned the final result, which represents the count of submatrices with the target sum. + +My approach leverages cumulative sums and dynamic programming to efficiently count submatrices with a target sum, making it an optimized solution. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(r * c^2)$ + +$r$ : number of rows in the matrix + +$c$ : number of columns in the matrix +- Space complexity : $O(c)$ + + +# Code +``` + +class Solution { + static int jawab; // Static variable to store the final result + static int r; // Number of rows in the matrix + static int c; // Number of columns in the matrix + static HashMap m; // HashMap to store the cumulative sum frequencies + + public int numSubmatrixSumTarget(int[][] matrix, int target) { + jawab = 0; // Initialize the result to 0 + r = matrix.length; // Number of rows in the matrix + c = matrix[0].length; // Number of columns in the matrix + + // Calculating the cumulative sum for each row + for (int[] p : matrix) { + for (int j = 1; j < c; j++) { + p[j] += p[j - 1]; + } + } + + // Iterating over all possible column combinations + for (int ic = 0; ic < c; ic++) { + for (int j = ic; j < c; j++) { + m = new HashMap<>(); // Initializing the HashMap for each column combination + m.put(0, 1); // Initializing the HashMap with the base case (cumulative sum = 0, frequency = 1) + int jor = 0; // Initializing the cumulative sum variable + + // Iterating over each row to calculate the cumulative sum + for (int p = 0; p < r; p++) { + jor += matrix[p][j]; + + // Adjusting the cumulative sum if ic > 0 (not the first column) + if (ic > 0) { + jor -= matrix[p][ic - 1]; + } + + // Updating the result with the frequency of the target cumulative sum + jawab += m.getOrDefault(jor - target, 0); + + // Updating the HashMap with the current cumulative sum + m.merge(jor, 1, Integer::sum); + } + } + } + return jawab; // Returning the final result + } +} + +``` \ No newline at end of file From bb6a6a7308728e05703bf525e7b10ad827377d6f Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 28 Jan 2024 13:34:55 +0530 Subject: [PATCH 088/300] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index e76912c..fe29d30 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ This is my attempt to make the coding experience easier for you guys so that you # Intuition +The problem is finding the number of submatrices in a given matrix whose sum is equal to a target value. # Approach From 70498ef2b6ac6fac6fd148b4e7178738186d4d27 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 28 Jan 2024 13:35:19 +0530 Subject: [PATCH 089/300] Update Daily 28-01-24.md --- 2024 January/Daily 28-01-24.md | 1 + 1 file changed, 1 insertion(+) diff --git a/2024 January/Daily 28-01-24.md b/2024 January/Daily 28-01-24.md index 05a65df..94ab0c0 100644 --- a/2024 January/Daily 28-01-24.md +++ b/2024 January/Daily 28-01-24.md @@ -4,6 +4,7 @@ # Intuition +The problem is finding the number of submatrices in a given matrix whose sum is equal to a target value. # Approach From d6a6578ee418fe07f4c3a43cb50113a535265882 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 29 Jan 2024 19:32:02 +0530 Subject: [PATCH 090/300] Update README.md --- README.md | 132 +++++++++++++++++++++++------------------------------- 1 file changed, 56 insertions(+), 76 deletions(-) diff --git a/README.md b/README.md index fe29d30..9be10d5 100644 --- a/README.md +++ b/README.md @@ -5,101 +5,81 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 28-01-24 [Problem Link](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/description/?envType=daily-question&envId=2024-01-28) -## 1074. Number of Submatrices That Sum to Target - +## Today's 29-01-24 [Problem Link](https://leetcode.com/problems/implement-queue-using-stacks/description/?envType=daily-question&envId=2024-01-29) +## 232. Implement Queue using Stacks # Intuition -The problem is finding the number of submatrices in a given matrix whose sum is equal to a target value. +My code implements a queue data structure using two stacks (`andar` and `bahar`). A queue follows the First-In-First-Out (FIFO) principle, and stacks follow the Last-In-First-Out (LIFO) principle. By utilizing two stacks cleverly, I can simulate the behavior of a queue efficiently. # Approach -**Initialized Variables :** - - `jawab`: A static variable to store the final result. - - `r`: Number of rows in the matrix. - - `c`: Number of columns in the matrix. - - `m`: A HashMap to store cumulative sum frequencies. - -**Calculated Cumulative Sums :** - - Iterated over each row in the matrix and calculated cumulative sums for each element in that row. This is done to efficiently compute the sum of submatrices. - -**Iterated Over Column Combinations :** - - Used two nested loops to iterate over all possible combinations of columns (ic and j). - - For each column combination, initialized the HashMap (`m`) to store cumulative sum frequencies. +**Initialization :** + - Two stacks, andar and bahar, represent the input and output of the queue. -**Calculate Cumulative Sums for Submatrices :** - - Iterated over each row to calculate the cumulative sum (`jor`) for submatrices. - - Adjusted the cumulative sum if `ic` is greater than 0 (not the first column). +**Push Operation (push method) :** + - Added elements to the input stack (andar), representing the enqueue operation. -**Updated Result and HashMap :** - - Updated the result (`jawab`) by adding the frequency of the target cumulative sum found in the HashMap. - - Updated the HashMap with the current cumulative sum and its frequency. +**Pop Operation (pop method) :** + - Ensured the output stack (bahar) is populated before popping an element. + - Called the peek method to populate the output stack if needed and then pops the front element. -**Return Result :** - - Returned the final result, which represents the count of submatrices with the target sum. +**Peek Operation (peek method) :** + - Transferred elements from the input stack to the output stack if the output stack is empty. + - Ensured the front element of the queue is always at the top of the output stack. + - Returned the front element without removing it. -My approach leverages cumulative sums and dynamic programming to efficiently count submatrices with a target sum, making it an optimized solution. +**Empty Check (empty method) :** + - Checked if both the input and output stacks are empty, indicating an empty queue. + - +My implementation provides an efficient way to simulate the behavior of a queue using two stacks while maintaining the FIFO order of elements. ---- -Have a look at the code , still have any confusion then please let me know in the comments -Keep Solving.:) # Complexity -- Time complexity : $O(r * c^2)$ +- Time complexity : $O(1)$ -$r$ : number of rows in the matrix -$c$ : number of columns in the matrix -- Space complexity : $O(c)$ +- Space complexity : $O(e)$ +$e$ : number of elements in the queue # Code ``` - -class Solution { - static int jawab; // Static variable to store the final result - static int r; // Number of rows in the matrix - static int c; // Number of columns in the matrix - static HashMap m; // HashMap to store the cumulative sum frequencies - - public int numSubmatrixSumTarget(int[][] matrix, int target) { - jawab = 0; // Initialize the result to 0 - r = matrix.length; // Number of rows in the matrix - c = matrix[0].length; // Number of columns in the matrix - - // Calculating the cumulative sum for each row - for (int[] p : matrix) { - for (int j = 1; j < c; j++) { - p[j] += p[j - 1]; - } - } - - // Iterating over all possible column combinations - for (int ic = 0; ic < c; ic++) { - for (int j = ic; j < c; j++) { - m = new HashMap<>(); // Initializing the HashMap for each column combination - m.put(0, 1); // Initializing the HashMap with the base case (cumulative sum = 0, frequency = 1) - int jor = 0; // Initializing the cumulative sum variable - - // Iterating over each row to calculate the cumulative sum - for (int p = 0; p < r; p++) { - jor += matrix[p][j]; - - // Adjusting the cumulative sum if ic > 0 (not the first column) - if (ic > 0) { - jor -= matrix[p][ic - 1]; - } - - // Updating the result with the frequency of the target cumulative sum - jawab += m.getOrDefault(jor - target, 0); - - // Updating the HashMap with the current cumulative sum - m.merge(jor, 1, Integer::sum); - } - } - } - return jawab; // Returning the final result +import java.util.ArrayDeque; +import java.util.Deque; + +// Implementation of a queue using two stacks +class MyQueue { + // Two stacks to represent the queue + private Deque andar = new ArrayDeque<>(); + private Deque bahar = new ArrayDeque<>(); + + // Method to push an element onto the queue + public void push(int x) { + andar.push(x); + } + + // Method to pop an element from the queue + public int pop() { + // Ensuring the output stack is populated before popping + peek(); + return bahar.pop(); + } + + // Method to peek at the front element of the queue + public int peek() { + // If the output stack is empty, transferring elements from input to output + if (bahar.isEmpty()) { + while (!andar.isEmpty()) { + bahar.push(andar.pop()); + } } + return bahar.peek(); + } + + // Method to check if the queue is empty + public boolean empty() { + return andar.isEmpty() && bahar.isEmpty(); + } } ``` \ No newline at end of file From e80ba487cea8c7dd4558c0c5438407acc1696954 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 29 Jan 2024 19:34:02 +0530 Subject: [PATCH 091/300] Create Daily 29-01-24.md --- 2024 January/Daily 29-01-24.md | 78 ++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 2024 January/Daily 29-01-24.md diff --git a/2024 January/Daily 29-01-24.md b/2024 January/Daily 29-01-24.md new file mode 100644 index 0000000..f7192b6 --- /dev/null +++ b/2024 January/Daily 29-01-24.md @@ -0,0 +1,78 @@ +## Today's 29-01-24 [Problem Link](https://leetcode.com/problems/implement-queue-using-stacks/description/?envType=daily-question&envId=2024-01-29) +## 232. Implement Queue using Stacks + +# Intuition + +My code implements a queue data structure using two stacks (`andar` and `bahar`). A queue follows the First-In-First-Out (FIFO) principle, and stacks follow the Last-In-First-Out (LIFO) principle. By utilizing two stacks cleverly, I can simulate the behavior of a queue efficiently. + +# Approach + +**Initialization :** + - Two stacks, andar and bahar, represent the input and output of the queue. + +**Push Operation (push method) :** + - Added elements to the input stack (andar), representing the enqueue operation. + +**Pop Operation (pop method) :** + - Ensured the output stack (bahar) is populated before popping an element. + - Called the peek method to populate the output stack if needed and then pops the front element. + +**Peek Operation (peek method) :** + - Transferred elements from the input stack to the output stack if the output stack is empty. + - Ensured the front element of the queue is always at the top of the output stack. + - Returned the front element without removing it. + +**Empty Check (empty method) :** + - Checked if both the input and output stacks are empty, indicating an empty queue. + - +My implementation provides an efficient way to simulate the behavior of a queue using two stacks while maintaining the FIFO order of elements. + +# Complexity +- Time complexity : $O(1)$ + + +- Space complexity : $O(e)$ + +$e$ : number of elements in the queue + +# Code +``` +import java.util.ArrayDeque; +import java.util.Deque; + +// Implementation of a queue using two stacks +class MyQueue { + // Two stacks to represent the queue + private Deque andar = new ArrayDeque<>(); + private Deque bahar = new ArrayDeque<>(); + + // Method to push an element onto the queue + public void push(int x) { + andar.push(x); + } + + // Method to pop an element from the queue + public int pop() { + // Ensuring the output stack is populated before popping + peek(); + return bahar.pop(); + } + + // Method to peek at the front element of the queue + public int peek() { + // If the output stack is empty, transferring elements from input to output + if (bahar.isEmpty()) { + while (!andar.isEmpty()) { + bahar.push(andar.pop()); + } + } + return bahar.peek(); + } + + // Method to check if the queue is empty + public boolean empty() { + return andar.isEmpty() && bahar.isEmpty(); + } +} + +``` \ No newline at end of file From 19a8e834ec4e627657393a54d07bb0ba353069b0 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 30 Jan 2024 16:32:13 +0530 Subject: [PATCH 092/300] Update README.md --- README.md | 133 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 78 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 9be10d5..5d42664 100644 --- a/README.md +++ b/README.md @@ -5,81 +5,104 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 29-01-24 [Problem Link](https://leetcode.com/problems/implement-queue-using-stacks/description/?envType=daily-question&envId=2024-01-29) -## 232. Implement Queue using Stacks +## Today's 30-01-24 [Problem Link](https://leetcode.com/problems/evaluate-reverse-polish-notation/description/?envType=daily-question&envId=2024-01-30) +## 150. Evaluate Reverse Polish Notation # Intuition -My code implements a queue data structure using two stacks (`andar` and `bahar`). A queue follows the First-In-First-Out (FIFO) principle, and stacks follow the Last-In-First-Out (LIFO) principle. By utilizing two stacks cleverly, I can simulate the behavior of a queue efficiently. +Given an expression in Reverse Polish Notation (RPN), I evaluated the expression and return the result. + +My solution uses a stack to keep track of the numeric values during the evaluation of the RPN expression. # Approach -**Initialization :** - - Two stacks, andar and bahar, represent the input and output of the queue. +**Initialized the Stack :** Created a stack to store numeric values. + +**Iterated Through Tokens :** Loop through each token in the RPN expression. + - If the token is a numeric value, pushed it onto the stack. + - If the token is an operator (+, -, *, /), poped two values from the stack, performed the operation, and pushed the result back onto the stack. -**Push Operation (push method) :** - - Added elements to the input stack (andar), representing the enqueue operation. +**Final Result :** After processing all tokens, the final result is the only element remaining in the stack. Poped it and returned. -**Pop Operation (pop method) :** - - Ensured the output stack (bahar) is populated before popping an element. - - Called the peek method to populate the output stack if needed and then pops the front element. +##### Helper Method +My solution includes a helper method `isNumeric` to check if a given string represents a numeric value. -**Peek Operation (peek method) :** - - Transferred elements from the input stack to the output stack if the output stack is empty. - - Ensured the front element of the queue is always at the top of the output stack. - - Returned the front element without removing it. +My approach leverages the stack data structure to efficiently process and evaluate the RPN expression, handling both numeric values and operators appropriately. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) -**Empty Check (empty method) :** - - Checked if both the input and output stacks are empty, indicating an empty queue. - - -My implementation provides an efficient way to simulate the behavior of a queue using two stacks while maintaining the FIFO order of elements. # Complexity -- Time complexity : $O(1)$ +- Time complexity : $O(t)$ +$t$ : number of tokens in the input expression -- Space complexity : $O(e)$ +- Space complexity : $O(t)$ -$e$ : number of elements in the queue # Code ``` -import java.util.ArrayDeque; -import java.util.Deque; - -// Implementation of a queue using two stacks -class MyQueue { - // Two stacks to represent the queue - private Deque andar = new ArrayDeque<>(); - private Deque bahar = new ArrayDeque<>(); - - // Method to push an element onto the queue - public void push(int x) { - andar.push(x); - } - - // Method to pop an element from the queue - public int pop() { - // Ensuring the output stack is populated before popping - peek(); - return bahar.pop(); - } - - // Method to peek at the front element of the queue - public int peek() { - // If the output stack is empty, transferring elements from input to output - if (bahar.isEmpty()) { - while (!andar.isEmpty()) { - bahar.push(andar.pop()); - } +class Solution { + + // Static stack to store numeric values during evaluation + static Stack num; + + // Method to evaluate Reverse Polish Notation (RPN) expression + public int evalRPN(String[] tokens) { + + // Initializing the stack + num = new Stack<>(); + + // Looping through each token in the expression + for (int i = 0; i < tokens.length; i++) { + String s = tokens[i]; + + // If the token is a numeric value, pushing it onto the stack + if (isNumeric(s)) { + num.push(Integer.parseInt(s)); + } else { + // If the token is an operator, popping two values from the stack + int p1 = num.pop(); + int p2 = num.pop(); + int jawab = 0; + + // Performing the operation based on the operator + if (s.charAt(0) == '+') { + jawab = p2 + p1; + } else if (s.charAt(0) == '-') { + jawab = p2 - p1; + } else if (s.charAt(0) == '*') { + jawab = p2 * p1; + } else if (s.charAt(0) == '/') { + jawab = p2 / p1; + } + + // Pushing the result back onto the stack + num.push(jawab); + } + } + + // The final result is the only element remaining in the stack + return num.pop(); } - return bahar.peek(); - } - // Method to check if the queue is empty - public boolean empty() { - return andar.isEmpty() && bahar.isEmpty(); - } + // Method to check if a string represents a numeric value + static boolean isNumeric(String strNum) { + if (strNum == null) { + return false; + } + try { + // Attempting to parse the string as a double + double d = Double.parseDouble(strNum); + } catch (NumberFormatException nfe) { + // If an exception is caught, the string is not numeric + return false; + } + // If parsing is successful, the string is numeric + return true; + } } ``` \ No newline at end of file From 8479fa6dc72665acb6ec22e5b9215a921b3d8774 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 30 Jan 2024 16:33:21 +0530 Subject: [PATCH 093/300] Create Daily 30-01-24.md --- 2024 January/Daily 30-01-24.md | 101 +++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 2024 January/Daily 30-01-24.md diff --git a/2024 January/Daily 30-01-24.md b/2024 January/Daily 30-01-24.md new file mode 100644 index 0000000..97554c0 --- /dev/null +++ b/2024 January/Daily 30-01-24.md @@ -0,0 +1,101 @@ +## Today's 30-01-24 [Problem Link](https://leetcode.com/problems/evaluate-reverse-polish-notation/description/?envType=daily-question&envId=2024-01-30) +## 150. Evaluate Reverse Polish Notation + +# Intuition + +Given an expression in Reverse Polish Notation (RPN), I evaluated the expression and return the result. + +My solution uses a stack to keep track of the numeric values during the evaluation of the RPN expression. + +# Approach + +**Initialized the Stack :** Created a stack to store numeric values. + +**Iterated Through Tokens :** Loop through each token in the RPN expression. + - If the token is a numeric value, pushed it onto the stack. + - If the token is an operator (+, -, *, /), poped two values from the stack, performed the operation, and pushed the result back onto the stack. + +**Final Result :** After processing all tokens, the final result is the only element remaining in the stack. Poped it and returned. + +##### Helper Method +My solution includes a helper method `isNumeric` to check if a given string represents a numeric value. + +My approach leverages the stack data structure to efficiently process and evaluate the RPN expression, handling both numeric values and operators appropriately. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + + +# Complexity +- Time complexity : $O(t)$ + +$t$ : number of tokens in the input expression + +- Space complexity : $O(t)$ + + +# Code +``` +class Solution { + + // Static stack to store numeric values during evaluation + static Stack num; + + // Method to evaluate Reverse Polish Notation (RPN) expression + public int evalRPN(String[] tokens) { + + // Initializing the stack + num = new Stack<>(); + + // Looping through each token in the expression + for (int i = 0; i < tokens.length; i++) { + String s = tokens[i]; + + // If the token is a numeric value, pushing it onto the stack + if (isNumeric(s)) { + num.push(Integer.parseInt(s)); + } else { + // If the token is an operator, popping two values from the stack + int p1 = num.pop(); + int p2 = num.pop(); + int jawab = 0; + + // Performing the operation based on the operator + if (s.charAt(0) == '+') { + jawab = p2 + p1; + } else if (s.charAt(0) == '-') { + jawab = p2 - p1; + } else if (s.charAt(0) == '*') { + jawab = p2 * p1; + } else if (s.charAt(0) == '/') { + jawab = p2 / p1; + } + + // Pushing the result back onto the stack + num.push(jawab); + } + } + + // The final result is the only element remaining in the stack + return num.pop(); + } + + // Method to check if a string represents a numeric value + static boolean isNumeric(String strNum) { + if (strNum == null) { + return false; + } + try { + // Attempting to parse the string as a double + double d = Double.parseDouble(strNum); + } catch (NumberFormatException nfe) { + // If an exception is caught, the string is not numeric + return false; + } + // If parsing is successful, the string is numeric + return true; + } +} + +``` \ No newline at end of file From 53dfc78137af27852dc2bdb903737e7482d48cdd Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 31 Jan 2024 10:15:10 +0530 Subject: [PATCH 094/300] Update README.md --- README.md | 109 +++++++++++++++++++++--------------------------------- 1 file changed, 42 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index 5d42664..3d8502f 100644 --- a/README.md +++ b/README.md @@ -5,103 +5,78 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 30-01-24 [Problem Link](https://leetcode.com/problems/evaluate-reverse-polish-notation/description/?envType=daily-question&envId=2024-01-30) -## 150. Evaluate Reverse Polish Notation +## Today's 31-01-24 [Problem Link](https://leetcode.com/problems/daily-temperatures/description/?envType=daily-question&envId=2024-01-31) +## 739. Daily Temperatures # Intuition -Given an expression in Reverse Polish Notation (RPN), I evaluated the expression and return the result. +This problem is to find the next higher temperature for each day in a given array of temperatures. To efficiently solve this problem, I used a stack to keep track of the indices of temperatures that we have encountered so far. My idea is to iterate through the array, and for each day, pop the indices from the stack where the corresponding temperatures are lower than the current day's temperature. For each popped index, I calculated the time difference to the current day and updated the result array with this information. -My solution uses a stack to keep track of the numeric values during the evaluation of the RPN expression. # Approach -**Initialized the Stack :** Created a stack to store numeric values. +- Initialized an array `jawab` to store the result, where `jawab[i]` will represent the number of days until a warmer temperature is encountered for the day at index `i`. -**Iterated Through Tokens :** Loop through each token in the RPN expression. - - If the token is a numeric value, pushed it onto the stack. - - If the token is an operator (+, -, *, /), poped two values from the stack, performed the operation, and pushed the result back onto the stack. +- Initialized an empty stack `s` to keep track of indices. -**Final Result :** After processing all tokens, the final result is the only element remaining in the stack. Poped it and returned. +- Iterated through the given array of temperatures using a loop. -##### Helper Method -My solution includes a helper method `isNumeric` to check if a given string represents a numeric value. +- For each day, checked if the stack is not empty and the current temperature is greater than the temperature at the index at the top of the stack. -My approach leverages the stack data structure to efficiently process and evaluate the RPN expression, handling both numeric values and operators appropriately. + - If true, popped the index from the stack, and calculated the time difference between the current day and the popped index. Updated `jawab` with this information. + + - Continued this process until the stack is empty or the top of the stack has a temperature greater than or equal to the current day's temperature. + +- Pushed the current index onto the stack. + +- After the loop, the `jawab` array contained the desired result, representing the number of days until a warmer temperature is encountered for each day. + +- Returned the `jawab` array as the final result. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity -- Time complexity : $O(t)$ +- Time complexity : $O(e)$ -$t$ : number of tokens in the input expression -- Space complexity : $O(t)$ +$e$ : number of elements in the given array of temperatures +- Space complexity : $O(e)$ # Code ``` class Solution { - // Static stack to store numeric values during evaluation - static Stack num; + // Static array to store the result + static int[] jawab; - // Method to evaluate Reverse Polish Notation (RPN) expression - public int evalRPN(String[] tokens) { + // Method to calculate daily temperatures + public int[] dailyTemperatures(int[] temperatures) { - // Initializing the stack - num = new Stack<>(); - - // Looping through each token in the expression - for (int i = 0; i < tokens.length; i++) { - String s = tokens[i]; - - // If the token is a numeric value, pushing it onto the stack - if (isNumeric(s)) { - num.push(Integer.parseInt(s)); - } else { - // If the token is an operator, popping two values from the stack - int p1 = num.pop(); - int p2 = num.pop(); - int jawab = 0; - - // Performing the operation based on the operator - if (s.charAt(0) == '+') { - jawab = p2 + p1; - } else if (s.charAt(0) == '-') { - jawab = p2 - p1; - } else if (s.charAt(0) == '*') { - jawab = p2 * p1; - } else if (s.charAt(0) == '/') { - jawab = p2 / p1; - } - - // Pushing the result back onto the stack - num.push(jawab); - } - } + // Initializing the result array with the length of temperatures array + jawab = new int[temperatures.length]; + + // Stack to keep track of indices of temperatures + Stack s = new Stack<>(); - // The final result is the only element remaining in the stack - return num.pop(); - } + // Iterating through the temperatures array + for (int i = 0; i < temperatures.length; i++) { - // Method to check if a string represents a numeric value - static boolean isNumeric(String strNum) { - if (strNum == null) { - return false; - } - try { - // Attempting to parse the string as a double - double d = Double.parseDouble(strNum); - } catch (NumberFormatException nfe) { - // If an exception is caught, the string is not numeric - return false; + // Checking if the stack is not empty and the current temperature is greater than the temperature at the index at the top of the stack + while (!s.isEmpty() && temperatures[i] > temperatures[s.peek()]) { + // Popping the index from the stack and calculate the time difference to the current day + int g = s.pop(); + jawab[g] = i - g; + } + + // Pushing the current index onto the stack + s.push(i); } - // If parsing is successful, the string is numeric - return true; + + // Returning the result array + return jawab; } } From 09fb2ce3e0c61c8bbf9ed0d177774e3e84ee0906 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 31 Jan 2024 10:16:12 +0530 Subject: [PATCH 095/300] Create Daily 31-01-24.md --- 2024 January/Daily 31-01-24.md | 76 ++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 2024 January/Daily 31-01-24.md diff --git a/2024 January/Daily 31-01-24.md b/2024 January/Daily 31-01-24.md new file mode 100644 index 0000000..8bd069d --- /dev/null +++ b/2024 January/Daily 31-01-24.md @@ -0,0 +1,76 @@ +## Today's 31-01-24 [Problem Link](https://leetcode.com/problems/daily-temperatures/description/?envType=daily-question&envId=2024-01-31) +## 739. Daily Temperatures + +# Intuition + +This problem is to find the next higher temperature for each day in a given array of temperatures. To efficiently solve this problem, I used a stack to keep track of the indices of temperatures that we have encountered so far. My idea is to iterate through the array, and for each day, pop the indices from the stack where the corresponding temperatures are lower than the current day's temperature. For each popped index, I calculated the time difference to the current day and updated the result array with this information. + + +# Approach + +- Initialized an array `jawab` to store the result, where `jawab[i]` will represent the number of days until a warmer temperature is encountered for the day at index `i`. + +- Initialized an empty stack `s` to keep track of indices. + +- Iterated through the given array of temperatures using a loop. + +- For each day, checked if the stack is not empty and the current temperature is greater than the temperature at the index at the top of the stack. + + - If true, popped the index from the stack, and calculated the time difference between the current day and the popped index. Updated `jawab` with this information. + + - Continued this process until the stack is empty or the top of the stack has a temperature greater than or equal to the current day's temperature. + +- Pushed the current index onto the stack. + +- After the loop, the `jawab` array contained the desired result, representing the number of days until a warmer temperature is encountered for each day. + +- Returned the `jawab` array as the final result. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(e)$ + + +$e$ : number of elements in the given array of temperatures +- Space complexity : $O(e)$ + + +# Code +``` +class Solution { + + // Static array to store the result + static int[] jawab; + + // Method to calculate daily temperatures + public int[] dailyTemperatures(int[] temperatures) { + + // Initializing the result array with the length of temperatures array + jawab = new int[temperatures.length]; + + // Stack to keep track of indices of temperatures + Stack s = new Stack<>(); + + // Iterating through the temperatures array + for (int i = 0; i < temperatures.length; i++) { + + // Checking if the stack is not empty and the current temperature is greater than the temperature at the index at the top of the stack + while (!s.isEmpty() && temperatures[i] > temperatures[s.peek()]) { + // Popping the index from the stack and calculate the time difference to the current day + int g = s.pop(); + jawab[g] = i - g; + } + + // Pushing the current index onto the stack + s.push(i); + } + + // Returning the result array + return jawab; + } +} + +``` \ No newline at end of file From e756947dcf7133c325c1a44edac7b267ba069c32 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 1 Feb 2024 10:17:47 +0530 Subject: [PATCH 096/300] Update README.md --- README.md | 95 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 51 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 3d8502f..f3efe07 100644 --- a/README.md +++ b/README.md @@ -5,78 +5,85 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 31-01-24 [Problem Link](https://leetcode.com/problems/daily-temperatures/description/?envType=daily-question&envId=2024-01-31) -## 739. Daily Temperatures +## Today's 01-02-24 [Problem Link](https://leetcode.com/problems/divide-array-into-arrays-with-max-difference/description/?envType=daily-question&envId=2024-02-01) +## 2966. Divide Array Into Arrays With Max Difference # Intuition -This problem is to find the next higher temperature for each day in a given array of temperatures. To efficiently solve this problem, I used a stack to keep track of the indices of temperatures that we have encountered so far. My idea is to iterate through the array, and for each day, pop the indices from the stack where the corresponding temperatures are lower than the current day's temperature. For each popped index, I calculated the time difference to the current day and updated the result array with this information. - +The goal of my code is to divide an array `nums` into subarrays of size 3, sort each subarray, and check whether the differences between adjacent elements in each subarray are within a given threshold `k`. If the differences exceed the threshold for any subarray, my function returns an empty 2D array. Otherwise, it returns the 2D array containing the sorted subarrays. # Approach -- Initialized an array `jawab` to store the result, where `jawab[i]` will represent the number of days until a warmer temperature is encountered for the day at index `i`. - -- Initialized an empty stack `s` to keep track of indices. - -- Iterated through the given array of temperatures using a loop. - -- For each day, checked if the stack is not empty and the current temperature is greater than the temperature at the index at the top of the stack. +**Sorted the Array :** + - Sorted the input array `nums` using `Arrays.sort(nums)`. - - If true, popped the index from the stack, and calculated the time difference between the current day and the popped index. Updated `jawab` with this information. +**Initialized Result Array :** + - Determined the length of the input array `n`. + - Created a 2D array `a` to store the divided subarrays. The number of rows in `a` is calculated as `n/3` since each subarray has 3 elements. - - Continued this process until the stack is empty or the top of the stack has a temperature greater than or equal to the current day's temperature. +**Iterated through Sorted Array in Chunks of 3 :** + - Used a for loop to iterate through the sorted array in chunks of 3. + - Calculated the row index `r` for the result array based on the current index `i`. -- Pushed the current index onto the stack. +**Check Differences and Store Subarrays :** + - Created a temporary array `t` to store the current chunk of 3 elements. + - Checked if the differences between elements in the chunk (`t[2] - t[1]`, `t[2] - t[0]`, `t[1] - t[0]`) exceed the threshold `k`. + - If the condition is met for any chunk, returned an empty 2D array. + - Otherwise, stored the sorted subarray `t` in the result array `a`. -- After the loop, the `jawab` array contained the desired result, representing the number of days until a warmer temperature is encountered for each day. +**Return the Result Array :** + - After processing all chunks, returned the result array `a`. -- Returned the `jawab` array as the final result. +My code divides the array into sorted subarrays of size 3, checks if the differences between elements in each subarray are within a given threshold, and returns the result accordingly. My approach is focused on breaking down the problem into smaller parts and efficiently handling the sorting and validation for each subarray. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(e)$ +- Time complexity : $O(n*logn)$ - -$e$ : number of elements in the given array of temperatures -- Space complexity : $O(e)$ +$n$ : length of the input array +- Space complexity : $O(n)$ # Code ``` class Solution { - - // Static array to store the result - static int[] jawab; - - // Method to calculate daily temperatures - public int[] dailyTemperatures(int[] temperatures) { + public int[][] divideArray(int[] nums, int k) { + // Sorting the input array + Arrays.sort(nums); - // Initializing the result array with the length of temperatures array - jawab = new int[temperatures.length]; + // Calculating the length of the result array + int n = nums.length; - // Stack to keep track of indices of temperatures - Stack s = new Stack<>(); - - // Iterating through the temperatures array - for (int i = 0; i < temperatures.length; i++) { - - // Checking if the stack is not empty and the current temperature is greater than the temperature at the index at the top of the stack - while (!s.isEmpty() && temperatures[i] > temperatures[s.peek()]) { - // Popping the index from the stack and calculate the time difference to the current day - int g = s.pop(); - jawab[g] = i - g; + // Creating a 2D array to store the divided arrays + // Each subarray will have 3 elements + int[][] a = new int[n/3][3]; + + // Iterating through the sorted array in chunks of 3 + for (int i = 0; i <= n - 3; i += 3) { + // Calculating the row index for the result array + int r = i / 3; + + // Creating a temporary array to store the current chunk of 3 elements + int[] t = new int[3]; + t[0] = nums[i]; + t[1] = nums[i+1]; + t[2] = nums[i+2]; + + // Checking if the difference between any two elements in the chunk is greater than k + if (t[2] - t[1] > k || t[2] - t[0] > k || t[1] - t[0] > k) { + // If the condition is not met, returning an empty 2D array + return new int[0][0]; } - - // Pushing the current index onto the stack - s.push(i); + + // Storing the current chunk in the result array + a[r] = t; } - + // Returning the result array - return jawab; + return a; } } From de06a106f5ff12d8a0af8af3ce7f503c41e0abb7 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 1 Feb 2024 10:19:36 +0530 Subject: [PATCH 097/300] Create Daily 01-02-24.md --- 2024 February/Daily 01-02-24.md | 83 +++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 2024 February/Daily 01-02-24.md diff --git a/2024 February/Daily 01-02-24.md b/2024 February/Daily 01-02-24.md new file mode 100644 index 0000000..6f235aa --- /dev/null +++ b/2024 February/Daily 01-02-24.md @@ -0,0 +1,83 @@ +## Today's 01-02-24 [Problem Link](https://leetcode.com/problems/divide-array-into-arrays-with-max-difference/description/?envType=daily-question&envId=2024-02-01) +## 2966. Divide Array Into Arrays With Max Difference + +# Intuition + +The goal of my code is to divide an array `nums` into subarrays of size 3, sort each subarray, and check whether the differences between adjacent elements in each subarray are within a given threshold `k`. If the differences exceed the threshold for any subarray, my function returns an empty 2D array. Otherwise, it returns the 2D array containing the sorted subarrays. + +# Approach + +**Sorted the Array :** + - Sorted the input array `nums` using `Arrays.sort(nums)`. + +**Initialized Result Array :** + - Determined the length of the input array `n`. + - Created a 2D array `a` to store the divided subarrays. The number of rows in `a` is calculated as `n/3` since each subarray has 3 elements. + +**Iterated through Sorted Array in Chunks of 3 :** + - Used a for loop to iterate through the sorted array in chunks of 3. + - Calculated the row index `r` for the result array based on the current index `i`. + +**Check Differences and Store Subarrays :** + - Created a temporary array `t` to store the current chunk of 3 elements. + - Checked if the differences between elements in the chunk (`t[2] - t[1]`, `t[2] - t[0]`, `t[1] - t[0]`) exceed the threshold `k`. + - If the condition is met for any chunk, returned an empty 2D array. + - Otherwise, stored the sorted subarray `t` in the result array `a`. + +**Return the Result Array :** + - After processing all chunks, returned the result array `a`. + +My code divides the array into sorted subarrays of size 3, checks if the differences between elements in each subarray are within a given threshold, and returns the result accordingly. My approach is focused on breaking down the problem into smaller parts and efficiently handling the sorting and validation for each subarray. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(n*logn)$ + +$n$ : length of the input array +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + public int[][] divideArray(int[] nums, int k) { + // Sorting the input array + Arrays.sort(nums); + + // Calculating the length of the result array + int n = nums.length; + + // Creating a 2D array to store the divided arrays + // Each subarray will have 3 elements + int[][] a = new int[n/3][3]; + + // Iterating through the sorted array in chunks of 3 + for (int i = 0; i <= n - 3; i += 3) { + // Calculating the row index for the result array + int r = i / 3; + + // Creating a temporary array to store the current chunk of 3 elements + int[] t = new int[3]; + t[0] = nums[i]; + t[1] = nums[i+1]; + t[2] = nums[i+2]; + + // Checking if the difference between any two elements in the chunk is greater than k + if (t[2] - t[1] > k || t[2] - t[0] > k || t[1] - t[0] > k) { + // If the condition is not met, returning an empty 2D array + return new int[0][0]; + } + + // Storing the current chunk in the result array + a[r] = t; + } + + // Returning the result array + return a; + } +} + +``` \ No newline at end of file From 9f6b74bc935229a4c069ae0ee31b240e27312813 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Thu, 1 Feb 2024 10:49:32 +0530 Subject: [PATCH 098/300] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f3efe07..87da3c5 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ The goal of my code is to divide an array `nums` into subarrays of size 3, sort - If the condition is met for any chunk, returned an empty 2D array. - Otherwise, stored the sorted subarray `t` in the result array `a`. -**Return the Result Array :** +**Result Array :** - After processing all chunks, returned the result array `a`. My code divides the array into sorted subarrays of size 3, checks if the differences between elements in each subarray are within a given threshold, and returns the result accordingly. My approach is focused on breaking down the problem into smaller parts and efficiently handling the sorting and validation for each subarray. @@ -87,4 +87,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 8108092f22d63999959e6b55e59cf60d7af4c955 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Thu, 1 Feb 2024 10:49:56 +0530 Subject: [PATCH 099/300] Update Daily 01-02-24.md --- 2024 February/Daily 01-02-24.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/2024 February/Daily 01-02-24.md b/2024 February/Daily 01-02-24.md index 6f235aa..44a3020 100644 --- a/2024 February/Daily 01-02-24.md +++ b/2024 February/Daily 01-02-24.md @@ -24,7 +24,7 @@ The goal of my code is to divide an array `nums` into subarrays of size 3, sort - If the condition is met for any chunk, returned an empty 2D array. - Otherwise, stored the sorted subarray `t` in the result array `a`. -**Return the Result Array :** +**Result Array :** - After processing all chunks, returned the result array `a`. My code divides the array into sorted subarrays of size 3, checks if the differences between elements in each subarray are within a given threshold, and returns the result accordingly. My approach is focused on breaking down the problem into smaller parts and efficiently handling the sorting and validation for each subarray. @@ -80,4 +80,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 62ad529a727e42ad24ebf422097af1891506e911 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 2 Feb 2024 10:31:52 +0530 Subject: [PATCH 100/300] Update README.md --- README.md | 106 +++++++++++++++++++++++------------------------------- 1 file changed, 45 insertions(+), 61 deletions(-) diff --git a/README.md b/README.md index 87da3c5..eb303b0 100644 --- a/README.md +++ b/README.md @@ -5,86 +5,70 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 01-02-24 [Problem Link](https://leetcode.com/problems/divide-array-into-arrays-with-max-difference/description/?envType=daily-question&envId=2024-02-01) -## 2966. Divide Array Into Arrays With Max Difference +## Today's 02-02-24 [Problem Link](https://leetcode.com/problems/sequential-digits/description/?envType=daily-question&envId=2024-02-02) +## 1291. Sequential Digits # Intuition -The goal of my code is to divide an array `nums` into subarrays of size 3, sort each subarray, and check whether the differences between adjacent elements in each subarray are within a given threshold `k`. If the differences exceed the threshold for any subarray, my function returns an empty 2D array. Otherwise, it returns the 2D array containing the sorted subarrays. +The goal is to efficiently find all sequential digits within a given range (low to high). +A sequential digit is a number where each digit is one more than the previous digit. + # Approach -**Sorted the Array :** - - Sorted the input array `nums` using `Arrays.sort(nums)`. - -**Initialized Result Array :** - - Determined the length of the input array `n`. - - Created a 2D array `a` to store the divided subarrays. The number of rows in `a` is calculated as `n/3` since each subarray has 3 elements. - -**Iterated through Sorted Array in Chunks of 3 :** - - Used a for loop to iterate through the sorted array in chunks of 3. - - Calculated the row index `r` for the result array based on the current index `i`. - -**Check Differences and Store Subarrays :** - - Created a temporary array `t` to store the current chunk of 3 elements. - - Checked if the differences between elements in the chunk (`t[2] - t[1]`, `t[2] - t[0]`, `t[1] - t[0]`) exceed the threshold `k`. - - If the condition is met for any chunk, returned an empty 2D array. - - Otherwise, stored the sorted subarray `t` in the result array `a`. - -**Result Array :** - - After processing all chunks, returned the result array `a`. - -My code divides the array into sorted subarrays of size 3, checks if the differences between elements in each subarray are within a given threshold, and returns the result accordingly. My approach is focused on breaking down the problem into smaller parts and efficiently handling the sorting and validation for each subarray. +- Created a string 'digits' containing all the digits from 1 to 9 in order. +- Converted 'low' and 'high' to strings to get their lengths. +- Iterated through possible lengths, from 'lowLength' to 'highLength'. + - For each length, iterated through 'digits' to find the starting digit for the current length. + - Extracted a substring of the current length from 'digits'. + - Converted the substring to an integer. + - Checked if the integer is within the given range ('low' to 'high'). + - If yes, added it to the result list. +- Finally, returned the list of sequential numbers as the output. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity -- Time complexity : $O(n*logn)$ +- Time complexity : $O(81)$ $\approx$ $O(1)$ -$n$ : length of the input array -- Space complexity : $O(n)$ + +- Space complexity : $O(9)$ $\approx$ $O(1)$ # Code ``` +import java.util.ArrayList; +import java.util.List; + class Solution { - public int[][] divideArray(int[] nums, int k) { - // Sorting the input array - Arrays.sort(nums); - - // Calculating the length of the result array - int n = nums.length; - - // Creating a 2D array to store the divided arrays - // Each subarray will have 3 elements - int[][] a = new int[n/3][3]; - - // Iterating through the sorted array in chunks of 3 - for (int i = 0; i <= n - 3; i += 3) { - // Calculating the row index for the result array - int r = i / 3; - - // Creating a temporary array to store the current chunk of 3 elements - int[] t = new int[3]; - t[0] = nums[i]; - t[1] = nums[i+1]; - t[2] = nums[i+2]; - - // Checking if the difference between any two elements in the chunk is greater than k - if (t[2] - t[1] > k || t[2] - t[0] > k || t[1] - t[0] > k) { - // If the condition is not met, returning an empty 2D array - return new int[0][0]; + public List sequentialDigits(int low, int high) { + ArrayList jawab = new ArrayList<>(); + String digits = "123456789"; + + // Converting low and high to strings to get their lengths + int lowLength = String.valueOf(low).length(); + int highLength = String.valueOf(high).length(); + + // Iterating through possible lengths + for (int length = lowLength; length <= highLength; length++) { + // Iterating through the digits string + for (int start = 0; start + length <= 9; start++) { + // Extracting the substring of the current length + String substring = digits.substring(start, start + length); + + // Converting the substring to an integer + int num = Integer.parseInt(substring); + + // Checking if the number is within the given range + if (num >= low && num <= high) { + // If yes, then adding it to the result list + jawab.add(num); + } } - - // Storing the current chunk in the result array - a[r] = t; } - - // Returning the result array - return a; + // Returning the final answer list + return jawab; } } - ``` From 4c342885b77de1eb1b60f110cfccd1d0dd77d929 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 2 Feb 2024 10:33:05 +0530 Subject: [PATCH 101/300] Create Daily 02-02-24.md --- 2024 February/Daily 02-02-24.md | 67 +++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 2024 February/Daily 02-02-24.md diff --git a/2024 February/Daily 02-02-24.md b/2024 February/Daily 02-02-24.md new file mode 100644 index 0000000..732ebb4 --- /dev/null +++ b/2024 February/Daily 02-02-24.md @@ -0,0 +1,67 @@ +## Today's 02-02-24 [Problem Link](https://leetcode.com/problems/sequential-digits/description/?envType=daily-question&envId=2024-02-02) +## 1291. Sequential Digits + +# Intuition + +The goal is to efficiently find all sequential digits within a given range (low to high). +A sequential digit is a number where each digit is one more than the previous digit. + + +# Approach + +- Created a string 'digits' containing all the digits from 1 to 9 in order. +- Converted 'low' and 'high' to strings to get their lengths. +- Iterated through possible lengths, from 'lowLength' to 'highLength'. + - For each length, iterated through 'digits' to find the starting digit for the current length. + - Extracted a substring of the current length from 'digits'. + - Converted the substring to an integer. + - Checked if the integer is within the given range ('low' to 'high'). + - If yes, added it to the result list. +- Finally, returned the list of sequential numbers as the output. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(81)$ $\approx$ $O(1)$ + + +- Space complexity : $O(9)$ $\approx$ $O(1)$ + + +# Code +``` +import java.util.ArrayList; +import java.util.List; + +class Solution { + public List sequentialDigits(int low, int high) { + ArrayList jawab = new ArrayList<>(); + String digits = "123456789"; + + // Converting low and high to strings to get their lengths + int lowLength = String.valueOf(low).length(); + int highLength = String.valueOf(high).length(); + + // Iterating through possible lengths + for (int length = lowLength; length <= highLength; length++) { + // Iterating through the digits string + for (int start = 0; start + length <= 9; start++) { + // Extracting the substring of the current length + String substring = digits.substring(start, start + length); + + // Converting the substring to an integer + int num = Integer.parseInt(substring); + + // Checking if the number is within the given range + if (num >= low && num <= high) { + // If yes, then adding it to the result list + jawab.add(num); + } + } + } + // Returning the final answer list + return jawab; + } +} +``` From fc9cc08824bc7eff7c824ebceb423032ed2b58bc Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 3 Feb 2024 10:24:37 +0530 Subject: [PATCH 102/300] Update README.md --- README.md | 87 +++++++++++++++++++++++++++---------------------------- 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index eb303b0..27b3b4c 100644 --- a/README.md +++ b/README.md @@ -5,70 +5,69 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 02-02-24 [Problem Link](https://leetcode.com/problems/sequential-digits/description/?envType=daily-question&envId=2024-02-02) -## 1291. Sequential Digits +## Today's 03-02-24 [Problem Link](https://leetcode.com/problems/partition-array-for-maximum-sum/description/?envType=daily-question&envId=2024-02-03) +## 1043. Partition Array for Maximum Sum # Intuition -The goal is to efficiently find all sequential digits within a given range (low to high). -A sequential digit is a number where each digit is one more than the previous digit. +This problem involves partitioning an array into subarrays and finding the maximum sum of these subarrays. To efficiently solve this problem, I have used dynamic programming to keep track of the maximum sum for each subarray ending at a given index. # Approach -- Created a string 'digits' containing all the digits from 1 to 9 in order. -- Converted 'low' and 'high' to strings to get their lengths. -- Iterated through possible lengths, from 'lowLength' to 'highLength'. - - For each length, iterated through 'digits' to find the starting digit for the current length. - - Extracted a substring of the current length from 'digits'. - - Converted the substring to an integer. - - Checked if the integer is within the given range ('low' to 'high'). - - If yes, added it to the result list. -- Finally, returned the list of sequential numbers as the output. +- Initialized a static array `jawab` to store the maximum sum for each subarray ending at index `i`. +- Iterated through the array from index 1 to the length of the array. + - Initialized a variable `b` to the minimum integer value to store the maximum value in the current subarray. + - Iterated through the subarray lengths up to 'k' or 'i', whichever is smaller. + - Updated `b` to the maximum value in the current subarray. + - Updated the maximum sum for the current subarray ending at index `i` using the formula `jawab[i] = max(jawab[i], b * j + jawab[i - j])`. +- Returned the maximum sum after partitioning the array, which is stored in `jawab[arr.length]`. + +My dynamic programming approach efficiently calculates the maximum sum for each subarray, considering previous results to avoid redundant computations and achieve an optimal solution. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + # Complexity -- Time complexity : $O(81)$ $\approx$ $O(1)$ +- Time complexity : $O(l*k)$ - -- Space complexity : $O(9)$ $\approx$ $O(1)$ +$l$ : length of the input array `arr` +$k$ : given +- Space complexity : $O(l)$ # Code ``` -import java.util.ArrayList; -import java.util.List; - class Solution { - public List sequentialDigits(int low, int high) { - ArrayList jawab = new ArrayList<>(); - String digits = "123456789"; - - // Converting low and high to strings to get their lengths - int lowLength = String.valueOf(low).length(); - int highLength = String.valueOf(high).length(); + // Static array to store the maximum sum for each subarray ending at index i + static int[] jawab; + + // Variable to store the length of the subarray considered for partitioning + static int b; + + // Method to calculate the maximum sum after partitioning the array + public int maxSumAfterPartitioning(int[] arr, int k) { + // Initializing the static array to store results + jawab = new int[1 + arr.length]; - // Iterating through possible lengths - for (int length = lowLength; length <= highLength; length++) { - // Iterating through the digits string - for (int start = 0; start + length <= 9; start++) { - // Extracting the substring of the current length - String substring = digits.substring(start, start + length); - - // Converting the substring to an integer - int num = Integer.parseInt(substring); - - // Checking if the number is within the given range - if (num >= low && num <= high) { - // If yes, then adding it to the result list - jawab.add(num); - } + // Iterating through the array + for (int i = 1; i <= arr.length; i++) { + // Initializing b to the minimum integer value + b = Integer.MIN_VALUE; + + // Iterating through the subarray lengths up to 'k' or 'i', whichever is smaller + for (int j = 1; j <= Math.min(i, k); j++) { + // Updating 'b' to the maximum value in the current subarray + b = Math.max(b, arr[i - j]); + + // Updating the maximum sum for the current subarray ending at index i + jawab[i] = Math.max(jawab[i], b * j + jawab[i - j]); } } - // Returning the final answer list - return jawab; + // Returning the maximum sum after partitioning the array + return jawab[arr.length]; } } -``` + +``` \ No newline at end of file From bf4aefb59ebddcaa6a09d01ee68e2f713b574916 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 3 Feb 2024 10:25:45 +0530 Subject: [PATCH 103/300] Create Daily 03-02-24.md --- 2024 February/Daily 03-02-24.md | 66 +++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 2024 February/Daily 03-02-24.md diff --git a/2024 February/Daily 03-02-24.md b/2024 February/Daily 03-02-24.md new file mode 100644 index 0000000..fadb5b7 --- /dev/null +++ b/2024 February/Daily 03-02-24.md @@ -0,0 +1,66 @@ +## Today's 03-02-24 [Problem Link](https://leetcode.com/problems/partition-array-for-maximum-sum/description/?envType=daily-question&envId=2024-02-03) +## 1043. Partition Array for Maximum Sum + +# Intuition + +This problem involves partitioning an array into subarrays and finding the maximum sum of these subarrays. To efficiently solve this problem, I have used dynamic programming to keep track of the maximum sum for each subarray ending at a given index. + + +# Approach + +- Initialized a static array `jawab` to store the maximum sum for each subarray ending at index `i`. +- Iterated through the array from index 1 to the length of the array. + - Initialized a variable `b` to the minimum integer value to store the maximum value in the current subarray. + - Iterated through the subarray lengths up to 'k' or 'i', whichever is smaller. + - Updated `b` to the maximum value in the current subarray. + - Updated the maximum sum for the current subarray ending at index `i` using the formula `jawab[i] = max(jawab[i], b * j + jawab[i - j])`. +- Returned the maximum sum after partitioning the array, which is stored in `jawab[arr.length]`. + +My dynamic programming approach efficiently calculates the maximum sum for each subarray, considering previous results to avoid redundant computations and achieve an optimal solution. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(l*k)$ + +$l$ : length of the input array `arr` +$k$ : given +- Space complexity : $O(l)$ + + +# Code +``` +class Solution { + // Static array to store the maximum sum for each subarray ending at index i + static int[] jawab; + + // Variable to store the length of the subarray considered for partitioning + static int b; + + // Method to calculate the maximum sum after partitioning the array + public int maxSumAfterPartitioning(int[] arr, int k) { + // Initializing the static array to store results + jawab = new int[1 + arr.length]; + + // Iterating through the array + for (int i = 1; i <= arr.length; i++) { + // Initializing b to the minimum integer value + b = Integer.MIN_VALUE; + + // Iterating through the subarray lengths up to 'k' or 'i', whichever is smaller + for (int j = 1; j <= Math.min(i, k); j++) { + // Updating 'b' to the maximum value in the current subarray + b = Math.max(b, arr[i - j]); + + // Updating the maximum sum for the current subarray ending at index i + jawab[i] = Math.max(jawab[i], b * j + jawab[i - j]); + } + } + // Returning the maximum sum after partitioning the array + return jawab[arr.length]; + } +} + +``` \ No newline at end of file From 2c30e4f543d98a0c7564eb753da448bec7a58b8b Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Sat, 3 Feb 2024 11:12:56 +0530 Subject: [PATCH 104/300] Update Daily 03-02-24.md --- 2024 February/Daily 03-02-24.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/2024 February/Daily 03-02-24.md b/2024 February/Daily 03-02-24.md index fadb5b7..dbe5347 100644 --- a/2024 February/Daily 03-02-24.md +++ b/2024 February/Daily 03-02-24.md @@ -26,6 +26,7 @@ Keep Solving.:) - Time complexity : $O(l*k)$ $l$ : length of the input array `arr` + $k$ : given - Space complexity : $O(l)$ @@ -63,4 +64,4 @@ class Solution { } } -``` \ No newline at end of file +``` From ce29b5b809a83ae688ec64e05ebbeb7889c5be7b Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Sat, 3 Feb 2024 11:13:10 +0530 Subject: [PATCH 105/300] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 27b3b4c..dabfc6b 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Keep Solving.:) - Time complexity : $O(l*k)$ $l$ : length of the input array `arr` + $k$ : given - Space complexity : $O(l)$ @@ -70,4 +71,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 703a4b450f3e64a2c26c6a4178bf06bd9779a759 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 4 Feb 2024 11:32:42 +0530 Subject: [PATCH 106/300] Update README.md --- README.md | 99 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 57 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index dabfc6b..30d4b7d 100644 --- a/README.md +++ b/README.md @@ -5,70 +5,85 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 03-02-24 [Problem Link](https://leetcode.com/problems/partition-array-for-maximum-sum/description/?envType=daily-question&envId=2024-02-03) -## 1043. Partition Array for Maximum Sum +## Today's 04-02-24 [Problem Link](https://leetcode.com/problems/minimum-window-substring/description/?envType=daily-question&envId=2024-02-04) +## 76. Minimum Window Substring # Intuition -This problem involves partitioning an array into subarrays and finding the maximum sum of these subarrays. To efficiently solve this problem, I have used dynamic programming to keep track of the maximum sum for each subarray ending at a given index. - # Approach -- Initialized a static array `jawab` to store the maximum sum for each subarray ending at index `i`. -- Iterated through the array from index 1 to the length of the array. - - Initialized a variable `b` to the minimum integer value to store the maximum value in the current subarray. - - Iterated through the subarray lengths up to 'k' or 'i', whichever is smaller. - - Updated `b` to the maximum value in the current subarray. - - Updated the maximum sum for the current subarray ending at index `i` using the formula `jawab[i] = max(jawab[i], b * j + jawab[i - j])`. -- Returned the maximum sum after partitioning the array, which is stored in `jawab[arr.length]`. +**Initialization:** + - I maintained an array `charCount` to store the count of characters in the ASCII range (128 characters). + - Initialized `requiredChars` to the length of string `t`, representing the number of characters required to form the window. + - Set `bestLeftIndex` to -1, indicating no valid window found yet. + - Initialized `minWindowSize` to a value greater than the length of string `s`. + +**Character Counting :** + - Populated the `charCount` array with counts of characters in string `t`. + +**Sliding Window :** + - Used two pointers, `left` and `right`, to define a window. + - Iterated through the string `s` with the right pointer (`right`). + - Updated `charCount` and `requiredChars` based on the character at the right pointer. + - Checked if the current window contains all required characters. + - If the condition is satisfied, update the `bestLeftIndex` and `minWindowSize`. + - Moved the left pointer (`left`) to shrink the window, updating `charCount` and `requiredChars` accordingly. -My dynamic programming approach efficiently calculates the maximum sum for each subarray, considering previous results to avoid redundant computations and achieve an optimal solution. +**Result :** + - The result is the minimum window substring found based on `bestLeftIndex` and `minWindowSize`. + +My sliding window approach efficiently explores all possible windows, ensuring that the minimum window containing all characters of `t` is identified. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(l*k)$ +- Time complexity : $O(s + t)$ -$l$ : length of the input array `arr` +$s$ : length of string `s` -$k$ : given -- Space complexity : $O(l)$ +$t$ : length of string `t` +- Space complexity : $O(1)$ (as the size of the `charCount` array is constant) # Code ``` class Solution { - // Static array to store the maximum sum for each subarray ending at index i - static int[] jawab; - - // Variable to store the length of the subarray considered for partitioning - static int b; - - // Method to calculate the maximum sum after partitioning the array - public int maxSumAfterPartitioning(int[] arr, int k) { - // Initializing the static array to store results - jawab = new int[1 + arr.length]; - - // Iterating through the array - for (int i = 1; i <= arr.length; i++) { - // Initializing b to the minimum integer value - b = Integer.MIN_VALUE; - - // Iterating through the subarray lengths up to 'k' or 'i', whichever is smaller - for (int j = 1; j <= Math.min(i, k); j++) { - // Updating 'b' to the maximum value in the current subarray - b = Math.max(b, arr[i - j]); - - // Updating the maximum sum for the current subarray ending at index i - jawab[i] = Math.max(jawab[i], b * j + jawab[i - j]); + public String minWindow(String s, String t) { + int[] charCount = new int[128]; // Array to store the count of characters + int requiredChars = t.length(); // Number of characters required to form the window + int bestLeftIndex = -1; // Starting index of the best window + int minWindowSize = s.length() + 1; // Minimum window size + + // Initializing charCount array with counts of characters in string 't' + for (char c : t.toCharArray()) + ++charCount[c]; + + // Sliding window approach + for (int left = 0, right = 0; right < s.length(); ++right) { + // Update charCount and requiredChars based on the character at the right pointer + if (--charCount[s.charAt(right)] >= 0) + --requiredChars; + + // Checking if the window contains all required characters + while (requiredChars == 0) { + // Updating the best window if the current window is smaller + if (right - left + 1 < minWindowSize) { + bestLeftIndex = left; + minWindowSize = right - left + 1; + } + + // Moving the left pointer and update charCount and requiredChars + if (++charCount[s.charAt(left++)] > 0) + ++requiredChars; } } - // Returning the maximum sum after partitioning the array - return jawab[arr.length]; + + // Returning the minimum window substring or an empty string if no such window exists + return bestLeftIndex == -1 ? "" : s.substring(bestLeftIndex, bestLeftIndex + minWindowSize); } } -``` +``` \ No newline at end of file From fd9933190c7fff1035947e45528ae677ac10f6e2 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 4 Feb 2024 11:34:32 +0530 Subject: [PATCH 107/300] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 30d4b7d..3d89691 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ This is my attempt to make the coding experience easier for you guys so that you # Intuition +My code is aimed to find the minimum window substring in string `s` that contains all characters of string `t`. I utilized a sliding window approach to efficiently identify the minimum window. # Approach From 7b4f48fc4c74ee41874d2fb2f790b1cec7900df4 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 4 Feb 2024 11:35:08 +0530 Subject: [PATCH 108/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3d89691..be82f0f 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ My code is aimed to find the minimum window substring in string `s` that contain # Approach -**Initialization:** +**Initialization :** - I maintained an array `charCount` to store the count of characters in the ASCII range (128 characters). - Initialized `requiredChars` to the length of string `t`, representing the number of characters required to form the window. - Set `bestLeftIndex` to -1, indicating no valid window found yet. From 24e623918334285047d8fb52771e57afdc4b69c5 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 4 Feb 2024 11:35:57 +0530 Subject: [PATCH 109/300] Create Daily 04-02-24.md --- 2024 February/Daily 04-02-24.md | 83 +++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 2024 February/Daily 04-02-24.md diff --git a/2024 February/Daily 04-02-24.md b/2024 February/Daily 04-02-24.md new file mode 100644 index 0000000..1dec52c --- /dev/null +++ b/2024 February/Daily 04-02-24.md @@ -0,0 +1,83 @@ +## Today's 04-02-24 [Problem Link](https://leetcode.com/problems/minimum-window-substring/description/?envType=daily-question&envId=2024-02-04) +## 76. Minimum Window Substring + +# Intuition + +My code is aimed to find the minimum window substring in string `s` that contains all characters of string `t`. I utilized a sliding window approach to efficiently identify the minimum window. + +# Approach + +**Initialization :** + - I maintained an array `charCount` to store the count of characters in the ASCII range (128 characters). + - Initialized `requiredChars` to the length of string `t`, representing the number of characters required to form the window. + - Set `bestLeftIndex` to -1, indicating no valid window found yet. + - Initialized `minWindowSize` to a value greater than the length of string `s`. + +**Character Counting :** + - Populated the `charCount` array with counts of characters in string `t`. + +**Sliding Window :** + - Used two pointers, `left` and `right`, to define a window. + - Iterated through the string `s` with the right pointer (`right`). + - Updated `charCount` and `requiredChars` based on the character at the right pointer. + - Checked if the current window contains all required characters. + - If the condition is satisfied, update the `bestLeftIndex` and `minWindowSize`. + - Moved the left pointer (`left`) to shrink the window, updating `charCount` and `requiredChars` accordingly. + +**Result :** + - The result is the minimum window substring found based on `bestLeftIndex` and `minWindowSize`. + +My sliding window approach efficiently explores all possible windows, ensuring that the minimum window containing all characters of `t` is identified. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(s + t)$ + +$s$ : length of string `s` + +$t$ : length of string `t` +- Space complexity : $O(1)$ (as the size of the `charCount` array is constant) + + +# Code +``` +class Solution { + public String minWindow(String s, String t) { + int[] charCount = new int[128]; // Array to store the count of characters + int requiredChars = t.length(); // Number of characters required to form the window + int bestLeftIndex = -1; // Starting index of the best window + int minWindowSize = s.length() + 1; // Minimum window size + + // Initializing charCount array with counts of characters in string 't' + for (char c : t.toCharArray()) + ++charCount[c]; + + // Sliding window approach + for (int left = 0, right = 0; right < s.length(); ++right) { + // Update charCount and requiredChars based on the character at the right pointer + if (--charCount[s.charAt(right)] >= 0) + --requiredChars; + + // Checking if the window contains all required characters + while (requiredChars == 0) { + // Updating the best window if the current window is smaller + if (right - left + 1 < minWindowSize) { + bestLeftIndex = left; + minWindowSize = right - left + 1; + } + + // Moving the left pointer and update charCount and requiredChars + if (++charCount[s.charAt(left++)] > 0) + ++requiredChars; + } + } + + // Returning the minimum window substring or an empty string if no such window exists + return bestLeftIndex == -1 ? "" : s.substring(bestLeftIndex, bestLeftIndex + minWindowSize); + } +} + +``` \ No newline at end of file From e15610b9717ce81ee483c6c5e58b0bb9d0edee7a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 4 Feb 2024 11:43:35 +0530 Subject: [PATCH 110/300] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index be82f0f..46c16b0 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. +## Today is 4, a very auspicious day for me. You know, some dates are such that you're bound to keep them in your grateful diary, for me 4 is that day. No words can ever express how grateful I am to god for that feeling. It's a request to all you guys reading my repository - Life is full of ups and downs, happy in a momment and pain in another, you cann't avoid any of these, so remember who you are and keep faith in yourself as I do. +Enjoy my solution and keep coding :) ## Always here to assist you guys. From 49f592e3c07e22a59bf003a200cb3d83ae426929 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 4 Feb 2024 11:44:17 +0530 Subject: [PATCH 111/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 46c16b0..81516f7 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. -## Today is 4, a very auspicious day for me. You know, some dates are such that you're bound to keep them in your grateful diary, for me 4 is that day. No words can ever express how grateful I am to god for that feeling. It's a request to all you guys reading my repository - Life is full of ups and downs, happy in a momment and pain in another, you cann't avoid any of these, so remember who you are and keep faith in yourself as I do. +##### Today is 4, a very auspicious day for me. You know, some dates are such that you're bound to keep them in your grateful diary, for me 4 is that day. No words can ever express how grateful I am to god for that feeling. It's a request to all you guys reading my repository - Life is full of ups and downs, happy in a momment and pain in another, you cann't avoid any of these, so remember who you are and keep faith in yourself as I do. Enjoy my solution and keep coding :) ## Always here to assist you guys. From c0b10c9468c8781e72a1fde6f7f64328fae79165 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Sun, 4 Feb 2024 11:46:36 +0530 Subject: [PATCH 112/300] Update Daily 04-02-24.md --- 2024 February/Daily 04-02-24.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/2024 February/Daily 04-02-24.md b/2024 February/Daily 04-02-24.md index 1dec52c..e75dc93 100644 --- a/2024 February/Daily 04-02-24.md +++ b/2024 February/Daily 04-02-24.md @@ -1,3 +1,6 @@ +##### Today is 4, a very auspicious day for me. You know, some dates are such that you're bound to keep them in your grateful diary, for me 4 is that day. No words can ever express how grateful I am to god for that feeling. It's a request to all you guys reading my repository - Life is full of ups and downs, happy in a momment and pain in another, you cann't avoid any of these, so remember who you are and keep faith in yourself as I do. +Enjoy my solution and keep coding :) + ## Today's 04-02-24 [Problem Link](https://leetcode.com/problems/minimum-window-substring/description/?envType=daily-question&envId=2024-02-04) ## 76. Minimum Window Substring @@ -80,4 +83,4 @@ class Solution { } } -``` \ No newline at end of file +``` From e9589b85d86728fb7b87ce68ab74f6ddbbdab58e Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 5 Feb 2024 15:56:18 +0530 Subject: [PATCH 113/300] Update README.md --- README.md | 107 ++++++++++++++++++++++++------------------------------ 1 file changed, 47 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 81516f7..cd7d9df 100644 --- a/README.md +++ b/README.md @@ -2,90 +2,77 @@ This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. -##### Today is 4, a very auspicious day for me. You know, some dates are such that you're bound to keep them in your grateful diary, for me 4 is that day. No words can ever express how grateful I am to god for that feeling. It's a request to all you guys reading my repository - Life is full of ups and downs, happy in a momment and pain in another, you cann't avoid any of these, so remember who you are and keep faith in yourself as I do. -Enjoy my solution and keep coding :) - ## Always here to assist you guys. -## Today's 04-02-24 [Problem Link](https://leetcode.com/problems/minimum-window-substring/description/?envType=daily-question&envId=2024-02-04) -## 76. Minimum Window Substring +## Today's 05-02-24 [Problem Link](https://leetcode.com/problems/first-unique-character-in-a-string/description/) +## 387. First Unique Character in a String # Intuition -My code is aimed to find the minimum window substring in string `s` that contains all characters of string `t`. I utilized a sliding window approach to efficiently identify the minimum window. +The goal of my code is to find the index of the first non-repeating character in a given string `s`. # Approach -**Initialization :** - - I maintained an array `charCount` to store the count of characters in the ASCII range (128 characters). - - Initialized `requiredChars` to the length of string `t`, representing the number of characters required to form the window. - - Set `bestLeftIndex` to -1, indicating no valid window found yet. - - Initialized `minWindowSize` to a value greater than the length of string `s`. - -**Character Counting :** - - Populated the `charCount` array with counts of characters in string `t`. +**Counted Frequency :** + - Created a HashMap (`m`) to store the frequency of each character in the string. + - Iterated through the string and count the frequency of each character using the HashMap. -**Sliding Window :** - - Used two pointers, `left` and `right`, to define a window. - - Iterated through the string `s` with the right pointer (`right`). - - Updated `charCount` and `requiredChars` based on the character at the right pointer. - - Checked if the current window contains all required characters. - - If the condition is satisfied, update the `bestLeftIndex` and `minWindowSize`. - - Moved the left pointer (`left`) to shrink the window, updating `charCount` and `requiredChars` accordingly. +**Founded First Non-Repeating Character :** + - Iterated through the string again. + - For each character, checked its frequency in the HashMap. + - If the frequency is 1, returned its index. + +**Helper Function (`index`) :** + - A helper function is used to find the index of a specific character in the string. -**Result :** - - The result is the minimum window substring found based on `bestLeftIndex` and `minWindowSize`. - -My sliding window approach efficiently explores all possible windows, ensuring that the minimum window containing all characters of `t` is identified. +**Returned -1 if No Non-Repeating Character :** + - If no non-repeating character is found, returned -1. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(s + t)$ +- Time complexity : $O(n)$ -$s$ : length of string `s` - -$t$ : length of string `t` -- Space complexity : $O(1)$ (as the size of the `charCount` array is constant) +$n$ : length of the input string `s` +- Space complexity : $O(n)$ # Code ``` class Solution { - public String minWindow(String s, String t) { - int[] charCount = new int[128]; // Array to store the count of characters - int requiredChars = t.length(); // Number of characters required to form the window - int bestLeftIndex = -1; // Starting index of the best window - int minWindowSize = s.length() + 1; // Minimum window size - - // Initializing charCount array with counts of characters in string 't' - for (char c : t.toCharArray()) - ++charCount[c]; - - // Sliding window approach - for (int left = 0, right = 0; right < s.length(); ++right) { - // Update charCount and requiredChars based on the character at the right pointer - if (--charCount[s.charAt(right)] >= 0) - --requiredChars; - - // Checking if the window contains all required characters - while (requiredChars == 0) { - // Updating the best window if the current window is smaller - if (right - left + 1 < minWindowSize) { - bestLeftIndex = left; - minWindowSize = right - left + 1; - } - - // Moving the left pointer and update charCount and requiredChars - if (++charCount[s.charAt(left++)] > 0) - ++requiredChars; + + public int firstUniqChar(String s) { + // HashMap to store the frequency of each character in the string + HashMap m = new HashMap<>(); + + // Counting the frequency of each character and storing in the HashMap + for (int i = 0; i < s.length(); i++) { + m.put(s.charAt(i), m.getOrDefault(s.charAt(i), 0) + 1); + } + + // Iterating through the string to find the first non-repeating character + for (char c : s.toCharArray()) { + if (m.get(c) == 1) { + // If found, returning the index using the helper function + return index(s, c); } } - - // Returning the minimum window substring or an empty string if no such window exists - return bestLeftIndex == -1 ? "" : s.substring(bestLeftIndex, bestLeftIndex + minWindowSize); + + // If no non-repeating character is found, returning -1 + return -1; + } + + // Helper function to find the index of a specific character in a string + static int index(String s, char c) { + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == c) { + return i; + } + } + // If the character is not found, returning -1 ( but this will not happen as character is present for sure ) + return -1; } } From 781e9a90aeddcbeb80c8a7e557f5d1fe81736a4f Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 5 Feb 2024 15:57:40 +0530 Subject: [PATCH 114/300] Create Daily 05-02-24.md --- 2024 February/Daily 05-02-24.md | 72 +++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 2024 February/Daily 05-02-24.md diff --git a/2024 February/Daily 05-02-24.md b/2024 February/Daily 05-02-24.md new file mode 100644 index 0000000..6a851d4 --- /dev/null +++ b/2024 February/Daily 05-02-24.md @@ -0,0 +1,72 @@ +## Today's 05-02-24 [Problem Link](https://leetcode.com/problems/first-unique-character-in-a-string/description/) +## 387. First Unique Character in a String + +# Intuition + +The goal of my code is to find the index of the first non-repeating character in a given string `s`. + +# Approach + +**Counted Frequency :** + - Created a HashMap (`m`) to store the frequency of each character in the string. + - Iterated through the string and count the frequency of each character using the HashMap. + +**Founded First Non-Repeating Character :** + - Iterated through the string again. + - For each character, checked its frequency in the HashMap. + - If the frequency is 1, returned its index. + +**Helper Function (`index`) :** + - A helper function is used to find the index of a specific character in the string. + +**Returned -1 if No Non-Repeating Character :** + - If no non-repeating character is found, returned -1. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the input string `s` +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + + public int firstUniqChar(String s) { + // HashMap to store the frequency of each character in the string + HashMap m = new HashMap<>(); + + // Counting the frequency of each character and storing in the HashMap + for (int i = 0; i < s.length(); i++) { + m.put(s.charAt(i), m.getOrDefault(s.charAt(i), 0) + 1); + } + + // Iterating through the string to find the first non-repeating character + for (char c : s.toCharArray()) { + if (m.get(c) == 1) { + // If found, returning the index using the helper function + return index(s, c); + } + } + + // If no non-repeating character is found, returning -1 + return -1; + } + + // Helper function to find the index of a specific character in a string + static int index(String s, char c) { + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == c) { + return i; + } + } + // If the character is not found, returning -1 ( but this will not happen as character is present for sure ) + return -1; + } +} +``` \ No newline at end of file From 69c18ef1b04fee3282f4f5e3b389c963c6219f10 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 5 Feb 2024 15:57:44 +0530 Subject: [PATCH 115/300] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index cd7d9df..6a07d1d 100644 --- a/README.md +++ b/README.md @@ -75,5 +75,4 @@ class Solution { return -1; } } - ``` \ No newline at end of file From 54d940d26f5a43c5f7ce942c1513b3fdf8282bb9 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 6 Feb 2024 10:37:31 +0530 Subject: [PATCH 116/300] Update README.md --- README.md | 111 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 63 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 6a07d1d..5951658 100644 --- a/README.md +++ b/README.md @@ -4,75 +4,90 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 05-02-24 [Problem Link](https://leetcode.com/problems/first-unique-character-in-a-string/description/) -## 387. First Unique Character in a String +## Today's 06-02-24 [Problem Link](https://leetcode.com/problems/group-anagrams/description/?envType=daily-question&envId=2024-02-06) +## 49. Group Anagrams # Intuition -The goal of my code is to find the index of the first non-repeating character in a given string `s`. +The goal of my algorithm is to group anagrams from a given array of strings. Two strings are considered anagrams if they can be rearranged to form the same string. + # Approach -**Counted Frequency :** - - Created a HashMap (`m`) to store the frequency of each character in the string. - - Iterated through the string and count the frequency of each character using the HashMap. -**Founded First Non-Repeating Character :** - - Iterated through the string again. - - For each character, checked its frequency in the HashMap. - - If the frequency is 1, returned its index. - -**Helper Function (`index`) :** - - A helper function is used to find the index of a specific character in the string. +**Initialized the HashMap** : Created a HashMap (`m`) to store anagrams grouped by their sorted representations. + +**Iterate Through Strings** : Looped through each string (`str`) in the input array. + +**Sorted the Characters** : Converted the string to a character array (`c`) and sorted it. This ensured that anagrams have the same sorted representation. + + ```java + char[] c = str.toCharArray(); + Arrays.sort(c); + String s = new String(c); + ``` + +**Group Anagrams** : Used `computeIfAbsent` to add the sorted representation (`s`) as a key in the HashMap. If the key is absent, created a new `ArrayList` as the value. Added the original string to the corresponding list. + + ```java + m.computeIfAbsent(s, p -> new ArrayList<>()).add(str); + ``` -**Returned -1 if No Non-Repeating Character :** - - If no non-repeating character is found, returned -1. + Alternatively, I could have used `putIfAbsent` and `get`: + + ```java + // m.putIfAbsent(s, new ArrayList<>()); + // m.get(s).add(str); + ``` + +**Return the Result** : After processing all strings, returned the grouped anagrams as a list of lists. + + ```java + return new ArrayList<>(m.values()); + ``` + +My approach ensured that anagrams are grouped together based on their sorted representations, allowing for efficient grouping and retrieval. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(N⋅K⋅log(K))$ -$n$ : length of the input string `s` -- Space complexity : $O(n)$ +$N$ : number of strings in the input array. + +$K$ : maximum length of a string. +- Space complexity : $O(M)$ +$M$ : number of unique sorted representations. # Code ``` class Solution { - - public int firstUniqChar(String s) { - // HashMap to store the frequency of each character in the string - HashMap m = new HashMap<>(); - - // Counting the frequency of each character and storing in the HashMap - for (int i = 0; i < s.length(); i++) { - m.put(s.charAt(i), m.getOrDefault(s.charAt(i), 0) + 1); - } - - // Iterating through the string to find the first non-repeating character - for (char c : s.toCharArray()) { - if (m.get(c) == 1) { - // If found, returning the index using the helper function - return index(s, c); - } - } + public List> groupAnagrams(String[] strs) { - // If no non-repeating character is found, returning -1 - return -1; - } - - // Helper function to find the index of a specific character in a string - static int index(String s, char c) { - for (int i = 0; i < s.length(); i++) { - if (s.charAt(i) == c) { - return i; - } + // Initializing a HashMap to store anagrams grouped by their sorted representations + HashMap> m = new HashMap<>(); + + // Iterating through each string in the input array + for (String str : strs) { + // Converting the string to a char array and sort it + char[] c = str.toCharArray(); + Arrays.sort(c); + String s = new String(c); + + // Using computeIfAbsent to add the sorted representation as a key + // If the key is absent, it will create a new ArrayList as the value and add the original string to the corresponding list + m.computeIfAbsent(s, p -> new ArrayList<>()).add(str); + + // Alternative approach using putIfAbsent and get + //m.putIfAbsent(s, new ArrayList<>()); + //m.get(s).add(str); } - // If the character is not found, returning -1 ( but this will not happen as character is present for sure ) - return -1; + + // Returning the grouped anagrams as a list of lists + return new ArrayList<>(m.values()); } } + ``` \ No newline at end of file From 57d27f6a3f76248e907d998b8b73b2f0131b62ab Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 6 Feb 2024 10:38:51 +0530 Subject: [PATCH 117/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5951658..57b88c2 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ The goal of my algorithm is to group anagrams from a given array of strings. Two // m.get(s).add(str); ``` -**Return the Result** : After processing all strings, returned the grouped anagrams as a list of lists. +**Returned the Result** : After processing all strings, returned the grouped anagrams as a list of lists. ```java return new ArrayList<>(m.values()); From 6902a1ed4a12f1e397ebe13588f14076616a19e6 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 6 Feb 2024 10:39:50 +0530 Subject: [PATCH 118/300] Create Daily 06-02-24.md --- 2024 February/Daily 06-02-24.md | 87 +++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 2024 February/Daily 06-02-24.md diff --git a/2024 February/Daily 06-02-24.md b/2024 February/Daily 06-02-24.md new file mode 100644 index 0000000..8163f32 --- /dev/null +++ b/2024 February/Daily 06-02-24.md @@ -0,0 +1,87 @@ +## Today's 06-02-24 [Problem Link](https://leetcode.com/problems/group-anagrams/description/?envType=daily-question&envId=2024-02-06) +## 49. Group Anagrams + +# Intuition + +The goal of my algorithm is to group anagrams from a given array of strings. Two strings are considered anagrams if they can be rearranged to form the same string. + + +# Approach + + +**Initialized the HashMap** : Created a HashMap (`m`) to store anagrams grouped by their sorted representations. + +**Iterate Through Strings** : Looped through each string (`str`) in the input array. + +**Sorted the Characters** : Converted the string to a character array (`c`) and sorted it. This ensured that anagrams have the same sorted representation. + + ```java + char[] c = str.toCharArray(); + Arrays.sort(c); + String s = new String(c); + ``` + +**Group Anagrams** : Used `computeIfAbsent` to add the sorted representation (`s`) as a key in the HashMap. If the key is absent, created a new `ArrayList` as the value. Added the original string to the corresponding list. + + ```java + m.computeIfAbsent(s, p -> new ArrayList<>()).add(str); + ``` + + Alternatively, I could have used `putIfAbsent` and `get`: + + ```java + // m.putIfAbsent(s, new ArrayList<>()); + // m.get(s).add(str); + ``` + +**Returned the Result** : After processing all strings, returned the grouped anagrams as a list of lists. + + ```java + return new ArrayList<>(m.values()); + ``` + +My approach ensured that anagrams are grouped together based on their sorted representations, allowing for efficient grouping and retrieval. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(N⋅K⋅log(K))$ + +$N$ : number of strings in the input array. + +$K$ : maximum length of a string. +- Space complexity : $O(M)$ + +$M$ : number of unique sorted representations. + +# Code +``` +class Solution { + public List> groupAnagrams(String[] strs) { + + // Initializing a HashMap to store anagrams grouped by their sorted representations + HashMap> m = new HashMap<>(); + + // Iterating through each string in the input array + for (String str : strs) { + // Converting the string to a char array and sort it + char[] c = str.toCharArray(); + Arrays.sort(c); + String s = new String(c); + + // Using computeIfAbsent to add the sorted representation as a key + // If the key is absent, it will create a new ArrayList as the value and add the original string to the corresponding list + m.computeIfAbsent(s, p -> new ArrayList<>()).add(str); + + // Alternative approach using putIfAbsent and get + //m.putIfAbsent(s, new ArrayList<>()); + //m.get(s).add(str); + } + + // Returning the grouped anagrams as a list of lists + return new ArrayList<>(m.values()); + } +} + +``` \ No newline at end of file From 8d2fe24c978e0c51baa72a034596cdcbbf4a13b0 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Tue, 6 Feb 2024 11:41:35 +0530 Subject: [PATCH 119/300] Update Daily 06-02-24.md --- 2024 February/Daily 06-02-24.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/2024 February/Daily 06-02-24.md b/2024 February/Daily 06-02-24.md index 8163f32..081c371 100644 --- a/2024 February/Daily 06-02-24.md +++ b/2024 February/Daily 06-02-24.md @@ -11,7 +11,7 @@ The goal of my algorithm is to group anagrams from a given array of strings. Two **Initialized the HashMap** : Created a HashMap (`m`) to store anagrams grouped by their sorted representations. -**Iterate Through Strings** : Looped through each string (`str`) in the input array. +**Iterated Through Strings** : Looped through each string (`str`) in the input array. **Sorted the Characters** : Converted the string to a character array (`c`) and sorted it. This ensured that anagrams have the same sorted representation. @@ -84,4 +84,4 @@ class Solution { } } -``` \ No newline at end of file +``` From c8a897d858c603c1122bf878e4bbef017f1d9979 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Tue, 6 Feb 2024 11:41:47 +0530 Subject: [PATCH 120/300] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 57b88c2..b0e35af 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ The goal of my algorithm is to group anagrams from a given array of strings. Two **Initialized the HashMap** : Created a HashMap (`m`) to store anagrams grouped by their sorted representations. -**Iterate Through Strings** : Looped through each string (`str`) in the input array. +**Iterated Through Strings** : Looped through each string (`str`) in the input array. **Sorted the Characters** : Converted the string to a character array (`c`) and sorted it. This ensured that anagrams have the same sorted representation. @@ -90,4 +90,4 @@ class Solution { } } -``` \ No newline at end of file +``` From 96a01b88ece7356d7fb4a8b676fe8d500d18b035 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 7 Feb 2024 10:24:48 +0530 Subject: [PATCH 121/300] Update README.md --- README.md | 118 ++++++++++++++++++++++++++---------------------------- 1 file changed, 57 insertions(+), 61 deletions(-) diff --git a/README.md b/README.md index b0e35af..4925f2a 100644 --- a/README.md +++ b/README.md @@ -4,90 +4,86 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 06-02-24 [Problem Link](https://leetcode.com/problems/group-anagrams/description/?envType=daily-question&envId=2024-02-06) -## 49. Group Anagrams +## Today's 07-02-24 [Problem Link](https://leetcode.com/problems/sort-characters-by-frequency/description/?envType=daily-question&envId=2024-02-07) +## 451. Sort Characters By Frequency # Intuition -The goal of my algorithm is to group anagrams from a given array of strings. Two strings are considered anagrams if they can be rearranged to form the same string. - +The intuition behind my code is to sort the characters in a given string based on their frequency. To achieve this, I utilized a HashMap to store the frequency of each character in the input string. The maximum frequency is tracked to later iterate through frequencies and build the final answer string. # Approach +**Constructed Frequency Map :** +- A HashMap (`m`) is initialized to store the frequency of each character. +- The input string is iterated, and for each character, its frequency in the map is updated. +- The maximum frequency (`max`) is maintained to determine the order of frequencies in the final result. -**Initialized the HashMap** : Created a HashMap (`m`) to store anagrams grouped by their sorted representations. - -**Iterated Through Strings** : Looped through each string (`str`) in the input array. - -**Sorted the Characters** : Converted the string to a character array (`c`) and sorted it. This ensured that anagrams have the same sorted representation. - - ```java - char[] c = str.toCharArray(); - Arrays.sort(c); - String s = new String(c); - ``` - -**Group Anagrams** : Used `computeIfAbsent` to add the sorted representation (`s`) as a key in the HashMap. If the key is absent, created a new `ArrayList` as the value. Added the original string to the corresponding list. +**Sorted by Frequency :** +- Initialized an empty string (`jawab`) to store the final result. +- Iterated through frequencies in descending order (from the maximum frequency to 1). +- For each frequency, iterated through characters in the frequency map. +- Appended each character to the answer string the number of times equal to its frequency. - ```java - m.computeIfAbsent(s, p -> new ArrayList<>()).add(str); - ``` +**Returned the Result :** +- The final answer string is returned. - Alternatively, I could have used `putIfAbsent` and `get`: - - ```java - // m.putIfAbsent(s, new ArrayList<>()); - // m.get(s).add(str); - ``` - -**Returned the Result** : After processing all strings, returned the grouped anagrams as a list of lists. - - ```java - return new ArrayList<>(m.values()); - ``` - -My approach ensured that anagrams are grouped together based on their sorted representations, allowing for efficient grouping and retrieval. +My approach ensured that the characters in the result string are sorted based on their frequency, with characters having higher frequencies appearing first. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(N⋅K⋅log(K))$ +- Time complexity : $ O(max * u)$ -$N$ : number of strings in the input array. +$max$ : maximum frequency -$K$ : maximum length of a string. -- Space complexity : $O(M)$ +$u$ : number of unique characters in the input string +- Space complexity : $O(u)$ -$M$ : number of unique sorted representations. # Code ``` class Solution { - public List> groupAnagrams(String[] strs) { - - // Initializing a HashMap to store anagrams grouped by their sorted representations - HashMap> m = new HashMap<>(); - - // Iterating through each string in the input array - for (String str : strs) { - // Converting the string to a char array and sort it - char[] c = str.toCharArray(); - Arrays.sort(c); - String s = new String(c); - - // Using computeIfAbsent to add the sorted representation as a key - // If the key is absent, it will create a new ArrayList as the value and add the original string to the corresponding list - m.computeIfAbsent(s, p -> new ArrayList<>()).add(str); - - // Alternative approach using putIfAbsent and get - //m.putIfAbsent(s, new ArrayList<>()); - //m.get(s).add(str); + + // Static variables to store character frequency map, maximum frequency, and the final answer + static HashMap m; + static int max; + static String jawab; + + // Method to sort characters in a string based on their frequency + public String frequencySort(String s) { + + // Initializing the character frequency map and maximum frequency + m = new HashMap<>(); + max = 0; + + // Populating the character frequency map and update the maximum frequency + for (char c : s.toCharArray()) { + m.put(c, m.getOrDefault(c, 0) + 1); + max = Math.max(max, m.get(c)); } - // Returning the grouped anagrams as a list of lists - return new ArrayList<>(m.values()); + // Initializing the final answer string + jawab = ""; + + // Iterating over frequencies in descending order + for (int i = max; i > 0; i--) { + + // Iterating over characters in the frequency map + for (char c : m.keySet()) { + + // Appending the character to the answer string for its corresponding frequency + if (m.get(c) == i) { + for (int d = 0; d < i; d++) { + jawab += c; + } + } + } + } + + // Returning the final answer string + return jawab; } } -``` +``` \ No newline at end of file From 117c87ee463dc1f899c9bd910fba0e98b435e33c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 7 Feb 2024 10:25:58 +0530 Subject: [PATCH 122/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4925f2a..68f7d5b 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ My approach ensured that the characters in the result string are sorted based on Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $ O(max * u)$ +- Time complexity : $O(max * u)$ $max$ : maximum frequency From 16e78d94300da8c040bcaa3a73ed67d914ff9a30 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 7 Feb 2024 10:28:16 +0530 Subject: [PATCH 123/300] Create Daily 07-02-24.md --- 2024 February/Daily 07-02-24.md | 83 +++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 2024 February/Daily 07-02-24.md diff --git a/2024 February/Daily 07-02-24.md b/2024 February/Daily 07-02-24.md new file mode 100644 index 0000000..df6d7fb --- /dev/null +++ b/2024 February/Daily 07-02-24.md @@ -0,0 +1,83 @@ +## Today's 07-02-24 [Problem Link](https://leetcode.com/problems/sort-characters-by-frequency/description/?envType=daily-question&envId=2024-02-07) +## 451. Sort Characters By Frequency + +# Intuition + +The intuition behind my code is to sort the characters in a given string based on their frequency. To achieve this, I utilized a HashMap to store the frequency of each character in the input string. The maximum frequency is tracked to later iterate through frequencies and build the final answer string. + +# Approach + +**Constructed Frequency Map :** +- A HashMap (`m`) is initialized to store the frequency of each character. +- The input string is iterated, and for each character, its frequency in the map is updated. +- The maximum frequency (`max`) is maintained to determine the order of frequencies in the final result. + +**Sorted by Frequency :** +- Initialized an empty string (`jawab`) to store the final result. +- Iterated through frequencies in descending order (from the maximum frequency to 1). +- For each frequency, iterated through characters in the frequency map. +- Appended each character to the answer string the number of times equal to its frequency. + +**Returned the Result :** +- The final answer string is returned. + +My approach ensured that the characters in the result string are sorted based on their frequency, with characters having higher frequencies appearing first. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(max * u)$ + +$max$ : maximum frequency + +$u$ : number of unique characters in the input string +- Space complexity : $O(u)$ + + +# Code +``` +class Solution { + + // Static variables to store character frequency map, maximum frequency, and the final answer + static HashMap m; + static int max; + static String jawab; + + // Method to sort characters in a string based on their frequency + public String frequencySort(String s) { + + // Initializing the character frequency map and maximum frequency + m = new HashMap<>(); + max = 0; + + // Populating the character frequency map and update the maximum frequency + for (char c : s.toCharArray()) { + m.put(c, m.getOrDefault(c, 0) + 1); + max = Math.max(max, m.get(c)); + } + + // Initializing the final answer string + jawab = ""; + + // Iterating over frequencies in descending order + for (int i = max; i > 0; i--) { + + // Iterating over characters in the frequency map + for (char c : m.keySet()) { + + // Appending the character to the answer string for its corresponding frequency + if (m.get(c) == i) { + for (int d = 0; d < i; d++) { + jawab += c; + } + } + } + } + + // Returning the final answer string + return jawab; + } +} + +``` \ No newline at end of file From ab543dd55ed33a2a10040b148b7479c65d43a147 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 8 Feb 2024 11:39:30 +0530 Subject: [PATCH 124/300] Update README.md --- README.md | 104 +++++++++++++++++++++++++----------------------------- 1 file changed, 48 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 68f7d5b..578d9fe 100644 --- a/README.md +++ b/README.md @@ -4,86 +4,78 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 07-02-24 [Problem Link](https://leetcode.com/problems/sort-characters-by-frequency/description/?envType=daily-question&envId=2024-02-07) -## 451. Sort Characters By Frequency +## Today's 08-02-24 [Problem Link](https://leetcode.com/problems/perfect-squares/description/?envType=daily-question&envId=2024-02-08) +## 279. Perfect Squares + # Intuition -The intuition behind my code is to sort the characters in a given string based on their frequency. To achieve this, I utilized a HashMap to store the frequency of each character in the input string. The maximum frequency is tracked to later iterate through frequencies and build the final answer string. +This problem requires finding the minimum number of perfect squares that sum up to a given number n. Dynamic programming is a suitable approach, where I iteratively build the solution by considering optimal solutions to subproblems. My key was to break down the problem into smaller parts and leverage the solutions to those parts. # Approach -**Constructed Frequency Map :** -- A HashMap (`m`) is initialized to store the frequency of each character. -- The input string is iterated, and for each character, its frequency in the map is updated. -- The maximum frequency (`max`) is maintained to determine the order of frequencies in the final result. +**Dynamic Programming Array (gp) :** +- Created a dynamic programming array `gp` of size `n+1` to store the minimum number of perfect squares needed for each value from 0 to n. +- Initialized all values in the array to a large number (`n`) to represent an initial state. + +**Base Cases :** +- Set `gp[0]` to 0 because 0 is already a perfect square (no additional squares needed). +- Set `gp[1]` to 1 because 1 is a perfect square itself (only one square needed). + +**Filled Iteratively :** +- Iterated from 2 to `n`, considering each number as the target. +- For each target number `i`, iterated over all possible perfect squares less than or equal to i to find the minimum number of squares needed. + +**Updated Minimum Squares :** +- For each perfect square `s`, updated the minimum number of squares needed for `i` as `gp[i] = Math.min(gp[i], gp[i - s*s] + 1)`. -**Sorted by Frequency :** -- Initialized an empty string (`jawab`) to store the final result. -- Iterated through frequencies in descending order (from the maximum frequency to 1). -- For each frequency, iterated through characters in the frequency map. -- Appended each character to the answer string the number of times equal to its frequency. +**Result :** +- After completing the iteration, `gp[n]` contained the minimum number of perfect squares needed for the given number `n`. -**Returned the Result :** -- The final answer string is returned. -My approach ensured that the characters in the result string are sorted based on their frequency, with characters having higher frequencies appearing first. +My approach built the solution for larger numbers based on optimal solutions for smaller subproblems. I considered all possible combinations of perfect squares, ensuring an optimal and efficient solution. The final result is the minimum number of perfect squares needed to represent the target number `n`. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(max * u)$ +- Time complexity : $O(n * \sqrt{n})$ -$max$ : maximum frequency -$u$ : number of unique characters in the input string -- Space complexity : $O(u)$ +- Space complexity : $O(n)$ # Code ``` class Solution { - // Static variables to store character frequency map, maximum frequency, and the final answer - static HashMap m; - static int max; - static String jawab; - - // Method to sort characters in a string based on their frequency - public String frequencySort(String s) { - - // Initializing the character frequency map and maximum frequency - m = new HashMap<>(); - max = 0; - - // Populating the character frequency map and update the maximum frequency - for (char c : s.toCharArray()) { - m.put(c, m.getOrDefault(c, 0) + 1); - max = Math.max(max, m.get(c)); - } - - // Initializing the final answer string - jawab = ""; - - // Iterating over frequencies in descending order - for (int i = max; i > 0; i--) { - - // Iterating over characters in the frequency map - for (char c : m.keySet()) { - - // Appending the character to the answer string for its corresponding frequency - if (m.get(c) == i) { - for (int d = 0; d < i; d++) { - jawab += c; - } - } + // Declaring an array to store the minimum number of perfect squares needed for each value + static int[] gp; + + // Function to calculate the minimum number of perfect squares needed for a given number n + public int numSquares(int n) { + + // Initializing the array with size (n+1) and fill it with 'n' + gp = new int[n+1]; + Arrays.fill(gp, n); + + // Base cases + gp[0] = 0; // Zero is already a perfect square, so no additional squares needed + gp[1] = 1; // One is a perfect square itself, so only one square needed + + // Iterating from 2 to n to fill the dp array + for( int i = 2; i <= n; i++){ + + // Iterating over all possible perfect squares less than or equal to i + for( int s = 1; s*s <= i; s++){ + + // Updating the minimum number of squares needed for i + gp[i] = Math.min(gp[i], gp[i - s*s] + 1); } } - - // Returning the final answer string - return jawab; + + // Returning the minimum number of perfect squares needed for the given number n + return gp[n]; } } - ``` \ No newline at end of file From 53811e6e270c2f8b9384ee71d95a12f894d1aa1e Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 8 Feb 2024 11:41:17 +0530 Subject: [PATCH 125/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 578d9fe..0405581 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ This is my attempt to make the coding experience easier for you guys so that you # Intuition -This problem requires finding the minimum number of perfect squares that sum up to a given number n. Dynamic programming is a suitable approach, where I iteratively build the solution by considering optimal solutions to subproblems. My key was to break down the problem into smaller parts and leverage the solutions to those parts. +This problem required finding the minimum number of perfect squares that sum up to a given number n. Dynamic programming was the suitable approach, where I iteratively built the solution by considering optimal solutions to subproblems. My key was to break down the problem into smaller parts and leverage the solutions to those parts. # Approach From 1b25a2eeb64dee5c1576d899f23b1a748b15a6d0 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 8 Feb 2024 11:42:24 +0530 Subject: [PATCH 126/300] Create Daily 08-02-24.md --- 2024 February/Daily 08-02-24.md | 75 +++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 2024 February/Daily 08-02-24.md diff --git a/2024 February/Daily 08-02-24.md b/2024 February/Daily 08-02-24.md new file mode 100644 index 0000000..ce80e4c --- /dev/null +++ b/2024 February/Daily 08-02-24.md @@ -0,0 +1,75 @@ +## Today's 08-02-24 [Problem Link](https://leetcode.com/problems/perfect-squares/description/?envType=daily-question&envId=2024-02-08) +## 279. Perfect Squares + + +# Intuition + +This problem required finding the minimum number of perfect squares that sum up to a given number n. Dynamic programming was the suitable approach, where I iteratively built the solution by considering optimal solutions to subproblems. My key was to break down the problem into smaller parts and leverage the solutions to those parts. + +# Approach + +**Dynamic Programming Array (gp) :** +- Created a dynamic programming array `gp` of size `n+1` to store the minimum number of perfect squares needed for each value from 0 to n. +- Initialized all values in the array to a large number (`n`) to represent an initial state. + +**Base Cases :** +- Set `gp[0]` to 0 because 0 is already a perfect square (no additional squares needed). +- Set `gp[1]` to 1 because 1 is a perfect square itself (only one square needed). + +**Filled Iteratively :** +- Iterated from 2 to `n`, considering each number as the target. +- For each target number `i`, iterated over all possible perfect squares less than or equal to i to find the minimum number of squares needed. + +**Updated Minimum Squares :** +- For each perfect square `s`, updated the minimum number of squares needed for `i` as `gp[i] = Math.min(gp[i], gp[i - s*s] + 1)`. + +**Result :** +- After completing the iteration, `gp[n]` contained the minimum number of perfect squares needed for the given number `n`. + + +My approach built the solution for larger numbers based on optimal solutions for smaller subproblems. I considered all possible combinations of perfect squares, ensuring an optimal and efficient solution. The final result is the minimum number of perfect squares needed to represent the target number `n`. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(n * \sqrt{n})$ + + +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + + // Declaring an array to store the minimum number of perfect squares needed for each value + static int[] gp; + + // Function to calculate the minimum number of perfect squares needed for a given number n + public int numSquares(int n) { + + // Initializing the array with size (n+1) and fill it with 'n' + gp = new int[n+1]; + Arrays.fill(gp, n); + + // Base cases + gp[0] = 0; // Zero is already a perfect square, so no additional squares needed + gp[1] = 1; // One is a perfect square itself, so only one square needed + + // Iterating from 2 to n to fill the dp array + for( int i = 2; i <= n; i++){ + ` + // Iterating over all possible perfect squares less than or equal to i + for( int s = 1; s*s <= i; s++){ + + // Updating the minimum number of squares needed for i + gp[i] = Math.min(gp[i], gp[i - s*s] + 1); + } + } + + // Returning the minimum number of perfect squares needed for the given number n + return gp[n]; + } +} +``` \ No newline at end of file From 93a3819f9cc688f858b9263b164de748a39c71fc Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 9 Feb 2024 10:41:14 +0530 Subject: [PATCH 127/300] Update README.md --- README.md | 106 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 64 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 0405581..e728bee 100644 --- a/README.md +++ b/README.md @@ -4,44 +4,47 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 08-02-24 [Problem Link](https://leetcode.com/problems/perfect-squares/description/?envType=daily-question&envId=2024-02-08) -## 279. Perfect Squares +## Today's 09-02-24 [Problem Link](https://leetcode.com/problems/largest-divisible-subset/description/?envType=daily-question&envId=2024-02-09) +## 368. Largest Divisible Subset # Intuition -This problem required finding the minimum number of perfect squares that sum up to a given number n. Dynamic programming was the suitable approach, where I iteratively built the solution by considering optimal solutions to subproblems. My key was to break down the problem into smaller parts and leverage the solutions to those parts. +This problem aimed to find the largest divisible subset from a given array of integers. A divisible subset is a set of integers where every pair `(nums[i], nums[j])` satisfies `nums[i] % nums[j] == 0` or `nums[j] % nums[i] == 0`. The goal is to return the largest possible subset. # Approach -**Dynamic Programming Array (gp) :** -- Created a dynamic programming array `gp` of size `n+1` to store the minimum number of perfect squares needed for each value from 0 to n. -- Initialized all values in the array to a large number (`n`) to represent an initial state. +**Sort** : Sorted the given array `nums` in ascending order. Sorting helped in efficiently checking divisibility relationships between elements. -**Base Cases :** -- Set `gp[0]` to 0 because 0 is already a perfect square (no additional squares needed). -- Set `gp[1]` to 1 because 1 is a perfect square itself (only one square needed). +**Dynamic Programming** : +- Initialized three arrays: + - `khtm`: Array to store the length of the divisible subset ending at each index. + - `pichla`: Array to store the index of the previous element in the divisible subset. + - `jawab`: ArrayList to store the result, i.e., the largest divisible subset. -**Filled Iteratively :** -- Iterated from 2 to `n`, considering each number as the target. -- For each target number `i`, iterated over all possible perfect squares less than or equal to i to find the minimum number of squares needed. +- Initialized all elements of `khtm` to 1, as the minimum length of a subset is 1. +- Initialized all elements of `pichla` to -1, indicating no previous element initially. +- Used a nested loop to iterate through each pair of elements and update `khtm` and `pichla` based on the divisibility relationship. -**Updated Minimum Squares :** -- For each perfect square `s`, updated the minimum number of squares needed for `i` as `gp[i] = Math.min(gp[i], gp[i - s*s] + 1)`. +**Identified Maximum Length** : +- Kept track of the maximum length `sbsebra` and its corresponding index `in` during the dynamic programming phase. -**Result :** -- After completing the iteration, `gp[n]` contained the minimum number of perfect squares needed for the given number `n`. +**Reconstructed Subset** : +- Reconstructed the largest divisible subset using the information stored in the `pichla` array. +**Returned the Result** : +- Return the final result, i.e., the largest divisible subset. -My approach built the solution for larger numbers based on optimal solutions for smaller subproblems. I considered all possible combinations of perfect squares, ensuring an optimal and efficient solution. The final result is the minimum number of perfect squares needed to represent the target number `n`. +My dynamic programming approach efficiently identified the length of the largest divisible subset ending at each index and uses this information to reconstruct the subset. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + # Complexity -- Time complexity : $O(n * \sqrt{n})$ +- Time complexity : $O(n log n + n^2)$ $\equiv$ $O(n^2)$ - +$n$ : length of the input array nums - Space complexity : $O(n)$ @@ -49,33 +52,52 @@ Keep Solving.:) ``` class Solution { - // Declaring an array to store the minimum number of perfect squares needed for each value - static int[] gp; + // Static variables to store the result, lengths, and previous index of the largest divisible subset + static ArrayList jawab; + static int[] khtm; + static int[] pichla; - // Function to calculate the minimum number of perfect squares needed for a given number n - public int numSquares(int n) { - - // Initializing the array with size (n+1) and fill it with 'n' - gp = new int[n+1]; - Arrays.fill(gp, n); + // Main function to find the largest divisible subset + public List largestDivisibleSubset(int[] nums) { + // Sorting the array in ascending order + Arrays.sort(nums); - // Base cases - gp[0] = 0; // Zero is already a perfect square, so no additional squares needed - gp[1] = 1; // One is a perfect square itself, so only one square needed - - // Iterating from 2 to n to fill the dp array - for( int i = 2; i <= n; i++){ - - // Iterating over all possible perfect squares less than or equal to i - for( int s = 1; s*s <= i; s++){ - - // Updating the minimum number of squares needed for i - gp[i] = Math.min(gp[i], gp[i - s*s] + 1); + // Initializing the result arraylist and length arrays + jawab = new ArrayList<>(); + khtm = new int[nums.length]; + Arrays.fill(khtm, 1); // Initializing all lengths to 1 + pichla = new int[nums.length]; + Arrays.fill(pichla, -1); // Initializing all previous indices to -1 + + // Variables to keep track of the maximum length and its corresponding index + int sbsebra = 0; + int in = -1; + + // Dynamic programming approach to find the largest divisible subset + for (int i = 0; i < nums.length; i++) { + for (int j = i - 1; j >= 0; j--) { + // If the current number is divisible by the previous number + // and adding it forms a larger subset, updating the length and previous index + if (nums[i] % nums[j] == 0 && khtm[i] < 1 + khtm[j]) { + khtm[i] = 1 + khtm[j]; + pichla[i] = j; + } + } + // Updating the maximum length and its corresponding index + if (sbsebra < khtm[i]) { + sbsebra = khtm[i]; + in = i; } } - - // Returning the minimum number of perfect squares needed for the given number n - return gp[n]; + + // Reconstructing the subset using the previous index information + while (in != -1) { + jawab.add(nums[in]); + in = pichla[in]; + } + + // Returning the result + return jawab; } } ``` \ No newline at end of file From a81ab043fb196b4d22a0dbb56026ff0a00c317ad Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 9 Feb 2024 10:42:47 +0530 Subject: [PATCH 128/300] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e728bee..6cd25b9 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ This problem aimed to find the largest divisible subset from a given array of in - Initialized all elements of `khtm` to 1, as the minimum length of a subset is 1. - Initialized all elements of `pichla` to -1, indicating no previous element initially. -- Used a nested loop to iterate through each pair of elements and update `khtm` and `pichla` based on the divisibility relationship. +- Used a nested loop to iterate through each pair of elements and updated `khtm` and `pichla` based on the divisibility relationship. **Identified Maximum Length** : - Kept track of the maximum length `sbsebra` and its corresponding index `in` during the dynamic programming phase. @@ -33,9 +33,9 @@ This problem aimed to find the largest divisible subset from a given array of in - Reconstructed the largest divisible subset using the information stored in the `pichla` array. **Returned the Result** : -- Return the final result, i.e., the largest divisible subset. +- Returned the final result, i.e., the largest divisible subset. -My dynamic programming approach efficiently identified the length of the largest divisible subset ending at each index and uses this information to reconstruct the subset. +My dynamic programming approach efficiently identified the length of the largest divisible subset ending at each index and used this information to reconstruct the subset. --- Have a look at the code , still have any confusion then please let me know in the comments From 19de28c93e5039b34efc40a713f4e0f3abdcc13c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 9 Feb 2024 10:43:16 +0530 Subject: [PATCH 129/300] Create Daily 09-02-24.md --- 2024 February/Daily 09-02-24.md | 97 +++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 2024 February/Daily 09-02-24.md diff --git a/2024 February/Daily 09-02-24.md b/2024 February/Daily 09-02-24.md new file mode 100644 index 0000000..bbb2ff3 --- /dev/null +++ b/2024 February/Daily 09-02-24.md @@ -0,0 +1,97 @@ +## Today's 09-02-24 [Problem Link](https://leetcode.com/problems/largest-divisible-subset/description/?envType=daily-question&envId=2024-02-09) +## 368. Largest Divisible Subset + + +# Intuition + +This problem aimed to find the largest divisible subset from a given array of integers. A divisible subset is a set of integers where every pair `(nums[i], nums[j])` satisfies `nums[i] % nums[j] == 0` or `nums[j] % nums[i] == 0`. The goal is to return the largest possible subset. + +# Approach + +**Sort** : Sorted the given array `nums` in ascending order. Sorting helped in efficiently checking divisibility relationships between elements. + +**Dynamic Programming** : +- Initialized three arrays: + - `khtm`: Array to store the length of the divisible subset ending at each index. + - `pichla`: Array to store the index of the previous element in the divisible subset. + - `jawab`: ArrayList to store the result, i.e., the largest divisible subset. + +- Initialized all elements of `khtm` to 1, as the minimum length of a subset is 1. +- Initialized all elements of `pichla` to -1, indicating no previous element initially. +- Used a nested loop to iterate through each pair of elements and updated `khtm` and `pichla` based on the divisibility relationship. + +**Identified Maximum Length** : +- Kept track of the maximum length `sbsebra` and its corresponding index `in` during the dynamic programming phase. + +**Reconstructed Subset** : +- Reconstructed the largest divisible subset using the information stored in the `pichla` array. + +**Returned the Result** : +- Returned the final result, i.e., the largest divisible subset. + +My dynamic programming approach efficiently identified the length of the largest divisible subset ending at each index and used this information to reconstruct the subset. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(n log n + n^2)$ $\equiv$ $O(n^2)$ + +$n$ : length of the input array nums +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + + // Static variables to store the result, lengths, and previous index of the largest divisible subset + static ArrayList jawab; + static int[] khtm; + static int[] pichla; + + // Main function to find the largest divisible subset + public List largestDivisibleSubset(int[] nums) { + // Sorting the array in ascending order + Arrays.sort(nums); + + // Initializing the result arraylist and length arrays + jawab = new ArrayList<>(); + khtm = new int[nums.length]; + Arrays.fill(khtm, 1); // Initializing all lengths to 1 + pichla = new int[nums.length]; + Arrays.fill(pichla, -1); // Initializing all previous indices to -1 + + // Variables to keep track of the maximum length and its corresponding index + int sbsebra = 0; + int in = -1; + + // Dynamic programming approach to find the largest divisible subset + for (int i = 0; i < nums.length; i++) { + for (int j = i - 1; j >= 0; j--) { + // If the current number is divisible by the previous number + // and adding it forms a larger subset, updating the length and previous index + if (nums[i] % nums[j] == 0 && khtm[i] < 1 + khtm[j]) { + khtm[i] = 1 + khtm[j]; + pichla[i] = j; + } + } + // Updating the maximum length and its corresponding index + if (sbsebra < khtm[i]) { + sbsebra = khtm[i]; + in = i; + } + } + + // Reconstructing the subset using the previous index information + while (in != -1) { + jawab.add(nums[in]); + in = pichla[in]; + } + + // Returning the result + return jawab; + } +} +``` \ No newline at end of file From c7a65025e6f9f82871be7b8d9828fde65943f7f5 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 9 Feb 2024 10:53:08 +0530 Subject: [PATCH 130/300] Daily 09-02-24 --- 2024 February/Daily 09-02-24.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/2024 February/Daily 09-02-24.md b/2024 February/Daily 09-02-24.md index bbb2ff3..c0d5cb9 100644 --- a/2024 February/Daily 09-02-24.md +++ b/2024 February/Daily 09-02-24.md @@ -11,7 +11,7 @@ This problem aimed to find the largest divisible subset from a given array of in **Sort** : Sorted the given array `nums` in ascending order. Sorting helped in efficiently checking divisibility relationships between elements. **Dynamic Programming** : -- Initialized three arrays: +- Initialized three arrays : - `khtm`: Array to store the length of the divisible subset ending at each index. - `pichla`: Array to store the index of the previous element in the divisible subset. - `jawab`: ArrayList to store the result, i.e., the largest divisible subset. diff --git a/README.md b/README.md index 6cd25b9..25005c2 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ This problem aimed to find the largest divisible subset from a given array of in **Sort** : Sorted the given array `nums` in ascending order. Sorting helped in efficiently checking divisibility relationships between elements. **Dynamic Programming** : -- Initialized three arrays: +- Initialized three arrays : - `khtm`: Array to store the length of the divisible subset ending at each index. - `pichla`: Array to store the index of the previous element in the divisible subset. - `jawab`: ArrayList to store the result, i.e., the largest divisible subset. From 8af82b71b67271729f53acbb9cd8c3a02f6f4e24 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 10 Feb 2024 10:53:36 +0530 Subject: [PATCH 131/300] Update README.md --- README.md | 113 +++++++++++++++++++++++------------------------------- 1 file changed, 49 insertions(+), 64 deletions(-) diff --git a/README.md b/README.md index 25005c2..b4b272a 100644 --- a/README.md +++ b/README.md @@ -4,100 +4,85 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 09-02-24 [Problem Link](https://leetcode.com/problems/largest-divisible-subset/description/?envType=daily-question&envId=2024-02-09) -## 368. Largest Divisible Subset +## Today's 10-02-24 [Problem Link](https://leetcode.com/problems/palindromic-substrings/description/) +## 647. Palindromic Substrings +[My previous answer](https://leetcode.com/problems/palindromic-substrings/solutions/4025719/simple-approach/?envType=daily-question&envId=2024-02-10) + # Intuition -This problem aimed to find the largest divisible subset from a given array of integers. A divisible subset is a set of integers where every pair `(nums[i], nums[j])` satisfies `nums[i] % nums[j] == 0` or `nums[j] % nums[i] == 0`. The goal is to return the largest possible subset. +The task was to find and count palindromic substrings in a given string. A palindromic substring is one that reads the same backward as forward. # Approach -**Sort** : Sorted the given array `nums` in ascending order. Sorting helped in efficiently checking divisibility relationships between elements. +**Initialized the Count Variable :** Started with a count variable to keep track of the total number of palindromic substrings. + +**Looped Through Characters :** +- Iterated through each character in the string. -**Dynamic Programming** : -- Initialized three arrays : - - `khtm`: Array to store the length of the divisible subset ending at each index. - - `pichla`: Array to store the index of the previous element in the divisible subset. - - `jawab`: ArrayList to store the result, i.e., the largest divisible subset. +**Considered Two Cases:** + - **Case 1 :** Palindromic substrings with odd length. + - Visualization : Place both index fingers at position 'i' and expand them outward, checking for palindromes. + - **Case 2:** Palindromic substrings with even length. + - Visualization : Place the left index finger at position 'i' and the right index finger at 'i+1', then expand them outward, checking for palindromes. -- Initialized all elements of `khtm` to 1, as the minimum length of a subset is 1. -- Initialized all elements of `pichla` to -1, indicating no previous element initially. -- Used a nested loop to iterate through each pair of elements and updated `khtm` and `pichla` based on the divisibility relationship. +**Implemented the Helper Function :** +- Created a helper function to check and count palindromic substrings expanding from the given indices. -**Identified Maximum Length** : -- Kept track of the maximum length `sbsebra` and its corresponding index `in` during the dynamic programming phase. +**While Loop for Expansion :** +- Inside the helper function, used a while loop to continue expanding the indices until the string ends or the index fingers reach different characters. -**Reconstructed Subset** : -- Reconstructed the largest divisible subset using the information stored in the `pichla` array. +**Incremented the Count:** +- Incremented the count for each valid palindromic substring found. -**Returned the Result** : -- Returned the final result, i.e., the largest divisible subset. +**Returned the Final Count:** +- Returned the final count as the result. -My dynamic programming approach efficiently identified the length of the largest divisible subset ending at each index and used this information to reconstruct the subset. +My approach efficiently counted all palindromic substrings by expanding around each character in the string. My checking function ensured that all possible palindromic substrings are considered. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(n log n + n^2)$ $\equiv$ $O(n^2)$ +- Time complexity : $O(l^2)$ -$n$ : length of the input array nums -- Space complexity : $O(n)$ +l : length of the input string. +- Space complexity : $O(l)$ # Code ``` class Solution { + // Function to count palindromic substrings in the given string + public static int countSubstrings(String s) { + int count = 0; + + // Looping through each character in the string + for (int i = 0; i < s.length(); i++) { + // Counting palindromic substrings with odd length + count += checksides(i, i, s); // Visualization : Place both index fingers at position 'i' and expand them outward - // Static variables to store the result, lengths, and previous index of the largest divisible subset - static ArrayList jawab; - static int[] khtm; - static int[] pichla; - - // Main function to find the largest divisible subset - public List largestDivisibleSubset(int[] nums) { - // Sorting the array in ascending order - Arrays.sort(nums); - - // Initializing the result arraylist and length arrays - jawab = new ArrayList<>(); - khtm = new int[nums.length]; - Arrays.fill(khtm, 1); // Initializing all lengths to 1 - pichla = new int[nums.length]; - Arrays.fill(pichla, -1); // Initializing all previous indices to -1 - - // Variables to keep track of the maximum length and its corresponding index - int sbsebra = 0; - int in = -1; - - // Dynamic programming approach to find the largest divisible subset - for (int i = 0; i < nums.length; i++) { - for (int j = i - 1; j >= 0; j--) { - // If the current number is divisible by the previous number - // and adding it forms a larger subset, updating the length and previous index - if (nums[i] % nums[j] == 0 && khtm[i] < 1 + khtm[j]) { - khtm[i] = 1 + khtm[j]; - pichla[i] = j; - } - } - // Updating the maximum length and its corresponding index - if (sbsebra < khtm[i]) { - sbsebra = khtm[i]; - in = i; - } + // Counting palindromic substrings with even length + count += checksides(i, i + 1, s); // Visualization : Place left index finger at position 'i' and right index finger at 'i+1', then expand them outward } - // Reconstructing the subset using the previous index information - while (in != -1) { - jawab.add(nums[in]); - in = pichla[in]; + return count; + } + + // Function to check and count palindromic substrings expanding from the given indices + static int checksides(int left, int right, String s) { + int c = 0; + + // Keep incrementing until the string ends or index fingers reach different characters + while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { + c++; + left--; + right++; } - // Returning the result - return jawab; + return c; // Returning the count of palindromic substrings } } ``` \ No newline at end of file From 68d116b3ff165a2658479d1782bfed9a38131df4 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 10 Feb 2024 10:54:54 +0530 Subject: [PATCH 132/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b4b272a..315de62 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ The task was to find and count palindromic substrings in a given string. A palin - **Case 1 :** Palindromic substrings with odd length. - Visualization : Place both index fingers at position 'i' and expand them outward, checking for palindromes. - **Case 2:** Palindromic substrings with even length. - - Visualization : Place the left index finger at position 'i' and the right index finger at 'i+1', then expand them outward, checking for palindromes. + - Visualization : Place the left index finger at position 'i' and the right index finger at 'i+1', then expand them outward, checking for palindromes. **Implemented the Helper Function :** - Created a helper function to check and count palindromic substrings expanding from the given indices. From e926deb9886e1fe3689b7521b41bc10dcf4f7e60 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 10 Feb 2024 10:56:18 +0530 Subject: [PATCH 133/300] Create Daily 10-02-24.md --- 2024 February/Daily 10-02-24.md | 82 +++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 2024 February/Daily 10-02-24.md diff --git a/2024 February/Daily 10-02-24.md b/2024 February/Daily 10-02-24.md new file mode 100644 index 0000000..90f9ff6 --- /dev/null +++ b/2024 February/Daily 10-02-24.md @@ -0,0 +1,82 @@ +## Today's 10-02-24 [Problem Link](https://leetcode.com/problems/palindromic-substrings/description/) +## 647. Palindromic Substrings + + +[My previous answer](https://leetcode.com/problems/palindromic-substrings/solutions/4025719/simple-approach/?envType=daily-question&envId=2024-02-10) + +# Intuition + +The task was to find and count palindromic substrings in a given string. A palindromic substring is one that reads the same backward as forward. + +# Approach + +**Initialized the Count Variable :** Started with a count variable to keep track of the total number of palindromic substrings. + +**Looped Through Characters :** +- Iterated through each character in the string. + +**Considered Two Cases:** + - **Case 1 :** Palindromic substrings with odd length. + - Visualization : Place both index fingers at position 'i' and expand them outward, checking for palindromes. + - **Case 2:** Palindromic substrings with even length. + - Visualization : Place the left index finger at position 'i' and the right index finger at 'i+1', then expand them outward, checking for palindromes. + +**Implemented the Helper Function :** +- Created a helper function to check and count palindromic substrings expanding from the given indices. + +**While Loop for Expansion :** +- Inside the helper function, used a while loop to continue expanding the indices until the string ends or the index fingers reach different characters. + +**Incremented the Count:** +- Incremented the count for each valid palindromic substring found. + +**Returned the Final Count:** +- Returned the final count as the result. + +My approach efficiently counted all palindromic substrings by expanding around each character in the string. My checking function ensured that all possible palindromic substrings are considered. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(l^2)$ + +l : length of the input string. +- Space complexity : $O(l)$ + + +# Code +``` +class Solution { + // Function to count palindromic substrings in the given string + public static int countSubstrings(String s) { + int count = 0; + + // Looping through each character in the string + for (int i = 0; i < s.length(); i++) { + // Counting palindromic substrings with odd length + count += checksides(i, i, s); // Visualization : Place both index fingers at position 'i' and expand them outward + + // Counting palindromic substrings with even length + count += checksides(i, i + 1, s); // Visualization : Place left index finger at position 'i' and right index finger at 'i+1', then expand them outward + } + + return count; + } + + // Function to check and count palindromic substrings expanding from the given indices + static int checksides(int left, int right, String s) { + int c = 0; + + // Keep incrementing until the string ends or index fingers reach different characters + while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { + c++; + left--; + right++; + } + + return c; // Returning the count of palindromic substrings + } +} +``` \ No newline at end of file From 6680d17bf5971eb45aa7bac8d812fe0cca3b5d5d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 10 Feb 2024 11:08:32 +0530 Subject: [PATCH 134/300] Daily 10-02-24 --- 2024 February/Daily 10-02-24.md | 6 +++--- README.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/2024 February/Daily 10-02-24.md b/2024 February/Daily 10-02-24.md index 90f9ff6..9514a15 100644 --- a/2024 February/Daily 10-02-24.md +++ b/2024 February/Daily 10-02-24.md @@ -15,7 +15,7 @@ The task was to find and count palindromic substrings in a given string. A palin **Looped Through Characters :** - Iterated through each character in the string. -**Considered Two Cases:** +**Considered Two Cases :** - **Case 1 :** Palindromic substrings with odd length. - Visualization : Place both index fingers at position 'i' and expand them outward, checking for palindromes. - **Case 2:** Palindromic substrings with even length. @@ -27,10 +27,10 @@ The task was to find and count palindromic substrings in a given string. A palin **While Loop for Expansion :** - Inside the helper function, used a while loop to continue expanding the indices until the string ends or the index fingers reach different characters. -**Incremented the Count:** +**Incremented the Count :** - Incremented the count for each valid palindromic substring found. -**Returned the Final Count:** +**Returned the Final Count :** - Returned the final count as the result. My approach efficiently counted all palindromic substrings by expanding around each character in the string. My checking function ensured that all possible palindromic substrings are considered. diff --git a/README.md b/README.md index 315de62..4000144 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ The task was to find and count palindromic substrings in a given string. A palin **Looped Through Characters :** - Iterated through each character in the string. -**Considered Two Cases:** +**Considered Two Cases :** - **Case 1 :** Palindromic substrings with odd length. - Visualization : Place both index fingers at position 'i' and expand them outward, checking for palindromes. - **Case 2:** Palindromic substrings with even length. @@ -33,10 +33,10 @@ The task was to find and count palindromic substrings in a given string. A palin **While Loop for Expansion :** - Inside the helper function, used a while loop to continue expanding the indices until the string ends or the index fingers reach different characters. -**Incremented the Count:** +**Incremented the Count :** - Incremented the count for each valid palindromic substring found. -**Returned the Final Count:** +**Returned the Final Count :** - Returned the final count as the result. My approach efficiently counted all palindromic substrings by expanding around each character in the string. My checking function ensured that all possible palindromic substrings are considered. From c220194452ef305d112d9c035c84baf0a8204130 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 11 Feb 2024 12:03:33 +0530 Subject: [PATCH 135/300] Update README.md --- README.md | 114 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 66 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 4000144..344aaec 100644 --- a/README.md +++ b/README.md @@ -4,85 +4,103 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 10-02-24 [Problem Link](https://leetcode.com/problems/palindromic-substrings/description/) -## 647. Palindromic Substrings - - -[My previous answer](https://leetcode.com/problems/palindromic-substrings/solutions/4025719/simple-approach/?envType=daily-question&envId=2024-02-10) +## Today's 11-02-24 [Problem Link](https://leetcode.com/problems/cherry-pickup-ii/description/?envType=daily-question&envId=2024-02-11) +## 1463. Cherry Pickup II # Intuition -The task was to find and count palindromic substrings in a given string. A palindromic substring is one that reads the same backward as forward. +The goal was to find the maximum number of cherries that two robots can collect while starting from the top row and moving towards the bottom row in a grid. # Approach -**Initialized the Count Variable :** Started with a count variable to keep track of the total number of palindromic substrings. - -**Looped Through Characters :** -- Iterated through each character in the string. - -**Considered Two Cases :** - - **Case 1 :** Palindromic substrings with odd length. - - Visualization : Place both index fingers at position 'i' and expand them outward, checking for palindromes. - - **Case 2:** Palindromic substrings with even length. - - Visualization : Place the left index finger at position 'i' and the right index finger at 'i+1', then expand them outward, checking for palindromes. +**Initialized the Memoization Array (`m`) :** +- Created a 3D memoization array to store intermediate results. +- The memoization array was used to avoid redundant calculations during recursive calls. -**Implemented the Helper Function :** -- Created a helper function to check and count palindromic substrings expanding from the given indices. +**Recursive Cherry-Picking :** +- Defined a recursive function (`cherryPick`) to explore all possible paths of both robots. +- Base Cases : + - If the current row is at the bottom of the grid, returned 0. + - If either robot goes out of bounds, returned 0. + - If the result for the current state is already memoized, returned the memoized value. +- Calculated the cherries collected in the current row based on the positions of both robots. +- Recursively explored all the possible movements for both robots in the next row. +- Updated the memoization array with the maximum cherries collected for the current state. -**While Loop for Expansion :** -- Inside the helper function, used a while loop to continue expanding the indices until the string ends or the index fingers reach different characters. +**Started the Recursive Process :** +- Called the recursive function with the initial positions of both robots at the top row. -**Incremented the Count :** -- Incremented the count for each valid palindromic substring found. +**Returned the Maximum Cherries :** +- The final result is the maximum cherries that can be collected by both robots. -**Returned the Final Count :** -- Returned the final count as the result. - -My approach efficiently counted all palindromic substrings by expanding around each character in the string. My checking function ensured that all possible palindromic substrings are considered. +My approach used recursion with memoization to explore all possible paths of the two robots, considering their movements in the grid. The memoization array helped optimizing the algorithm by avoiding redundant calculations and improving overall efficiency. The final result represented the maximum cherries that can be collected by both robots. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(l^2)$ +- Time complexity : $O(9^m)$ -l : length of the input string. -- Space complexity : $O(l)$ +$m$ : number of rows + +$n$ : number of columns +- Space complexity : $O(m * n^2).$ # Code ``` class Solution { - // Function to count palindromic substrings in the given string - public static int countSubstrings(String s) { - int count = 0; - // Looping through each character in the string - for (int i = 0; i < s.length(); i++) { - // Counting palindromic substrings with odd length - count += checksides(i, i, s); // Visualization : Place both index fingers at position 'i' and expand them outward + // Memoization array to store intermediate results + static int[][][] m; + + public int cherryPickup(int[][] grid) { + + // Initializing the memoization array with dimensions based on the grid + m = new int[grid.length][grid[0].length][grid[0].length]; - // Counting palindromic substrings with even length - count += checksides(i, i + 1, s); // Visualization : Place left index finger at position 'i' and right index finger at 'i+1', then expand them outward + // Filling the memoization array with -1 + for (int[][] a : m){ + Arrays.stream(a).forEach(b -> Arrays.fill(b, -1)); } - return count; + // Starting the recursive cherry-picking process from the top row and both robots + return cherryPick(grid, 0, 0, grid[0].length - 1); } - // Function to check and count palindromic substrings expanding from the given indices - static int checksides(int left, int right, String s) { - int c = 0; + // Recursive helper function to find the maximum cherries collected + private int cherryPick(int[][] grid, int x, int y1, int y2) { + + // Base case : we have reached the bottom of the grid + if (x == grid.length){ + return 0; + } + + // Base case : robots are out of bounds + if (y1 < 0 || y1 == grid[0].length || y2 < 0 || y2 == grid[0].length){ + return 0; + } - // Keep incrementing until the string ends or index fingers reach different characters - while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { - c++; - left--; - right++; + // Checking if the result is already memoized + if (m[x][y1][y2] != -1){ + return m[x][y1][y2]; } - return c; // Returning the count of palindromic substrings + // Collecting cherries in the current row + int r = grid[x][y1] + (y1 == y2 ? 0 : grid[x][y2]); + + // Trying all possible movements for both robots in the next row + for (int u = -1; u <= 1; u++){ + for (int v = -1; v <= 1; v++){ + // Updating the memoization array with the maximum cherries + m[x][y1][y2] = Math.max(m[x][y1][y2], r + cherryPick(grid, x + 1, y1 + u, y2 + v)); + } + } + + // Returning the maximum cherries collected for the current state + return m[x][y1][y2]; } } + ``` \ No newline at end of file From ec79d6fc2b78fd80dfca36c4cfbd799af915009d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 11 Feb 2024 12:05:26 +0530 Subject: [PATCH 136/300] Create Daily 11-02-24.md --- 2024 February/Daily 11-02-24.md | 100 ++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 2024 February/Daily 11-02-24.md diff --git a/2024 February/Daily 11-02-24.md b/2024 February/Daily 11-02-24.md new file mode 100644 index 0000000..6586ca0 --- /dev/null +++ b/2024 February/Daily 11-02-24.md @@ -0,0 +1,100 @@ +## Today's 11-02-24 [Problem Link](https://leetcode.com/problems/cherry-pickup-ii/description/?envType=daily-question&envId=2024-02-11) +## 1463. Cherry Pickup II + +# Intuition + +The goal was to find the maximum number of cherries that two robots can collect while starting from the top row and moving towards the bottom row in a grid. + +# Approach + +**Initialized the Memoization Array (`m`) :** +- Created a 3D memoization array to store intermediate results. +- The memoization array was used to avoid redundant calculations during recursive calls. + +**Recursive Cherry-Picking :** +- Defined a recursive function (`cherryPick`) to explore all possible paths of both robots. +- Base Cases : + - If the current row is at the bottom of the grid, returned 0. + - If either robot goes out of bounds, returned 0. + - If the result for the current state is already memoized, returned the memoized value. +- Calculated the cherries collected in the current row based on the positions of both robots. +- Recursively explored all the possible movements for both robots in the next row. +- Updated the memoization array with the maximum cherries collected for the current state. + +**Started the Recursive Process :** +- Called the recursive function with the initial positions of both robots at the top row. + +**Returned the Maximum Cherries :** +- The final result is the maximum cherries that can be collected by both robots. + +My approach used recursion with memoization to explore all possible paths of the two robots, considering their movements in the grid. The memoization array helped optimizing the algorithm by avoiding redundant calculations and improving overall efficiency. The final result represented the maximum cherries that can be collected by both robots. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(9^m)$ + +$m$ : number of rows + +$n$ : number of columns +- Space complexity : $O(m * n^2).$ + + +# Code +``` +class Solution { + + // Memoization array to store intermediate results + static int[][][] m; + + public int cherryPickup(int[][] grid) { + + // Initializing the memoization array with dimensions based on the grid + m = new int[grid.length][grid[0].length][grid[0].length]; + + // Filling the memoization array with -1 + for (int[][] a : m){ + Arrays.stream(a).forEach(b -> Arrays.fill(b, -1)); + } + + // Starting the recursive cherry-picking process from the top row and both robots + return cherryPick(grid, 0, 0, grid[0].length - 1); + } + + // Recursive helper function to find the maximum cherries collected + private int cherryPick(int[][] grid, int x, int y1, int y2) { + + // Base case : we have reached the bottom of the grid + if (x == grid.length){ + return 0; + } + + // Base case : robots are out of bounds + if (y1 < 0 || y1 == grid[0].length || y2 < 0 || y2 == grid[0].length){ + return 0; + } + + // Checking if the result is already memoized + if (m[x][y1][y2] != -1){ + return m[x][y1][y2]; + } + + // Collecting cherries in the current row + int r = grid[x][y1] + (y1 == y2 ? 0 : grid[x][y2]); + + // Trying all possible movements for both robots in the next row + for (int u = -1; u <= 1; u++){ + for (int v = -1; v <= 1; v++){ + // Updating the memoization array with the maximum cherries + m[x][y1][y2] = Math.max(m[x][y1][y2], r + cherryPick(grid, x + 1, y1 + u, y2 + v)); + } + } + + // Returning the maximum cherries collected for the current state + return m[x][y1][y2]; + } +} + +``` \ No newline at end of file From ebe6068fcde037a7ce44680d743bda5503eaa105 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 12 Feb 2024 11:00:13 +0530 Subject: [PATCH 137/300] Update README.md --- README.md | 112 +++++++++++++++++++----------------------------------- 1 file changed, 39 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index 344aaec..c97de20 100644 --- a/README.md +++ b/README.md @@ -4,103 +4,69 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 11-02-24 [Problem Link](https://leetcode.com/problems/cherry-pickup-ii/description/?envType=daily-question&envId=2024-02-11) -## 1463. Cherry Pickup II +## Today's 12-02-24 [Problem Link](https://leetcode.com/problems/majority-element/description/) +## 169. Majority Element # Intuition -The goal was to find the maximum number of cherries that two robots can collect while starting from the top row and moving towards the bottom row in a grid. +This problem is designed to find the majority element in an array using the Boyer-Moore Voting Algorithm. + +The majority element is defined as the element that appears more than ⌊n/2⌋ times, where n is the length of the array. This algorithm efficiently identifies the majority element in a single pass through the array. # Approach -**Initialized the Memoization Array (`m`) :** -- Created a 3D memoization array to store intermediate results. -- The memoization array was used to avoid redundant calculations during recursive calls. -**Recursive Cherry-Picking :** -- Defined a recursive function (`cherryPick`) to explore all possible paths of both robots. -- Base Cases : - - If the current row is at the bottom of the grid, returned 0. - - If either robot goes out of bounds, returned 0. - - If the result for the current state is already memoized, returned the memoized value. -- Calculated the cherries collected in the current row based on the positions of both robots. -- Recursively explored all the possible movements for both robots in the next row. -- Updated the memoization array with the maximum cherries collected for the current state. +- Initialized two variables : + - `a` : Represented the potential majority element. + - `c` : Represented a counter for tracking the occurrences of the potential majority element. + +- Iterated through the given array `nums`. + +- Inside the loop : + - If the counter `c` is 0, updated the potential majority element `a` to the current element `n`. + - Updated the counter `c` based on whether the current element `n` is equal to the potential majority element `a`. If equal, incremented `c`; otherwise, decremented `c`. -**Started the Recursive Process :** -- Called the recursive function with the initial positions of both robots at the top row. +- After the loop, the variable `a` contains the potential majority element. -**Returned the Maximum Cherries :** -- The final result is the maximum cherries that can be collected by both robots. +- Returned the potential majority element `a` as the final result. -My approach used recursion with memoization to explore all possible paths of the two robots, considering their movements in the grid. The memoization array helped optimizing the algorithm by avoiding redundant calculations and improving overall efficiency. The final result represented the maximum cherries that can be collected by both robots. +The Boyer-Moore Voting Algorithm ensured that if a majority element exists in the array, it will be correctly identified, and if no majority element exists, the algorithm may still return a candidate (though it may not necessarily be the majority element --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity -- Time complexity : $O(9^m)$ +- Time complexity : $O(n)$ -$m$ : number of rows - -$n$ : number of columns -- Space complexity : $O(m * n^2).$ +$n$ : length of the input array `nums`. +- Space complexity : $O(1)$ # Code ``` class Solution { - // Memoization array to store intermediate results - static int[][][] m; + // Method to find the majority element in an array + public int majorityElement(int[] nums) { - public int cherryPickup(int[][] grid) { - - // Initializing the memoization array with dimensions based on the grid - m = new int[grid.length][grid[0].length][grid[0].length]; + // Variable to store the potential majority element + Integer a = null; - // Filling the memoization array with -1 - for (int[][] a : m){ - Arrays.stream(a).forEach(b -> Arrays.fill(b, -1)); - } - - // Starting the recursive cherry-picking process from the top row and both robots - return cherryPick(grid, 0, 0, grid[0].length - 1); - } - - // Recursive helper function to find the maximum cherries collected - private int cherryPick(int[][] grid, int x, int y1, int y2) { - - // Base case : we have reached the bottom of the grid - if (x == grid.length){ - return 0; - } - - // Base case : robots are out of bounds - if (y1 < 0 || y1 == grid[0].length || y2 < 0 || y2 == grid[0].length){ - return 0; - } - - // Checking if the result is already memoized - if (m[x][y1][y2] != -1){ - return m[x][y1][y2]; - } - - // Collecting cherries in the current row - int r = grid[x][y1] + (y1 == y2 ? 0 : grid[x][y2]); - - // Trying all possible movements for both robots in the next row - for (int u = -1; u <= 1; u++){ - for (int v = -1; v <= 1; v++){ - // Updating the memoization array with the maximum cherries - m[x][y1][y2] = Math.max(m[x][y1][y2], r + cherryPick(grid, x + 1, y1 + u, y2 + v)); - } - } - - // Returning the maximum cherries collected for the current state - return m[x][y1][y2]; + // Counter to keep track of the occurrences of the potential majority element + int c = 0; + + // Iterating through the array + for (int n : nums) { + // If the counter is 0, updating the potential majority element to the current element + if (c == 0) + a = n; + + // Updating the counter based on whether the current element is equal to the potential majority element + c += n == a ? 1 : -1; } + + // Returning the potential majority element + return a; + } } - ``` \ No newline at end of file From 8992cfe9fa34e9a59e03aceaa7075611e8b21d5d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 12 Feb 2024 11:04:27 +0530 Subject: [PATCH 138/300] Daily 12*02=24 --- 2024 February/Daily 12-02-24.md | 66 +++++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 2024 February/Daily 12-02-24.md diff --git a/2024 February/Daily 12-02-24.md b/2024 February/Daily 12-02-24.md new file mode 100644 index 0000000..d725ab5 --- /dev/null +++ b/2024 February/Daily 12-02-24.md @@ -0,0 +1,66 @@ +## Today's 12*02=24 [Problem Link](https://leetcode.com/problems/majority-element/description/) +## 169. Majority Element + +# Intuition + +This problem is designed to find the majority element in an array using the Boyer-Moore Voting Algorithm. + +The majority element is defined as the element that appears more than ⌊n/2⌋ times, where n is the length of the array. This algorithm efficiently identifies the majority element in a single pass through the array. + +# Approach + + +- Initialized two variables : + - `a` : Represented the potential majority element. + - `c` : Represented a counter for tracking the occurrences of the potential majority element. + +- Iterated through the given array `nums`. + +- Inside the loop : + - If the counter `c` is 0, updated the potential majority element `a` to the current element `n`. + - Updated the counter `c` based on whether the current element `n` is equal to the potential majority element `a`. If equal, incremented `c`; otherwise, decremented `c`. + +- After the loop, the variable `a` contains the potential majority element. + +- Returned the potential majority element `a` as the final result. + +The Boyer-Moore Voting Algorithm ensured that if a majority element exists in the array, it will be correctly identified, and if no majority element exists, the algorithm may still return a candidate (though it may not necessarily be the majority element + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the input array `nums`. +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + + // Method to find the majority element in an array + public int majorityElement(int[] nums) { + + // Variable to store the potential majority element + Integer a = null; + + // Counter to keep track of the occurrences of the potential majority element + int c = 0; + + // Iterating through the array + for (int n : nums) { + // If the counter is 0, updating the potential majority element to the current element + if (c == 0) + a = n; + + // Updating the counter based on whether the current element is equal to the potential majority element + c += n == a ? 1 : -1; + } + + // Returning the potential majority element + return a; + } +} +``` \ No newline at end of file diff --git a/README.md b/README.md index c97de20..58497de 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 12-02-24 [Problem Link](https://leetcode.com/problems/majority-element/description/) +## Today's 12*02=24 [Problem Link](https://leetcode.com/problems/majority-element/description/) ## 169. Majority Element # Intuition From 84ea5ef26565e020678dd8c8b97499b899601054 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 13 Feb 2024 13:38:30 +0530 Subject: [PATCH 139/300] Update README.md --- README.md | 98 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 57 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 58497de..13354f0 100644 --- a/README.md +++ b/README.md @@ -4,69 +4,85 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 12*02=24 [Problem Link](https://leetcode.com/problems/majority-element/description/) -## 169. Majority Element +## Today's 13-02-24 [Problem Link](https://leetcode.com/problems/find-first-palindromic-string-in-the-array/description/?envType=daily-question&envId=2024-02-13) +## 2108. Find First Palindromic String in the Array # Intuition -This problem is designed to find the majority element in an array using the Boyer-Moore Voting Algorithm. +The goal of this problem is to find the first palindrome in an array of words. A palindrome is a string that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). -The majority element is defined as the element that appears more than ⌊n/2⌋ times, where n is the length of the array. This algorithm efficiently identifies the majority element in a single pass through the array. +My intuition was to iterate through each word in the array and check if it is a palindrome using a helper method. # Approach +- Method ``firstPalindrome` : + - This method took an array of words as input. + - It iterated through each word in the array using a for-each loop. + - For each word, it called the `isPalin` method to check if the word is a palindrome. + - If a palindrome is found, the method immediately returned that word. + - If no palindrome is found in the entire array, it returned an empty string. -- Initialized two variables : - - `a` : Represented the potential majority element. - - `c` : Represented a counter for tracking the occurrences of the potential majority element. +- Method `isPalin` : + - This static method checked if a given string is a palindrome. + - It initialized two pointers (`l` and `r`) at the beginning and end of the string, respectively. + - It iterated while `l` is less than `r`. + - Within the loop, it compared characters at positions `l` and `r`. + - If the characters are not equal, the string is not a palindrome, and the method returned `false`. + - If the characters are equal, it incremented `l` and decremented `r` to check the next pair of characters. + - If the loop completed without returning `false`, the string is a palindrome, and the method `returned` true. -- Iterated through the given array `nums`. -- Inside the loop : - - If the counter `c` is 0, updated the potential majority element `a` to the current element `n`. - - Updated the counter `c` based on whether the current element `n` is equal to the potential majority element `a`. If equal, incremented `c`; otherwise, decremented `c`. - -- After the loop, the variable `a` contains the potential majority element. - -- Returned the potential majority element `a` as the final result. - -The Boyer-Moore Voting Algorithm ensured that if a majority element exists in the array, it will be correctly identified, and if no majority element exists, the algorithm may still return a candidate (though it may not necessarily be the majority element +Overall, my approach involved iterating through the array of words and checking each word for palindromic properties using the `isPalin` method. The first palindrome encountered is returned, or an empty string is returned if no palindrome is found in the array. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(N*M)$ -$n$ : length of the input array `nums`. -- Space complexity : $O(1)$ +$N$ : number of words + +$M$ : maximum length of a word +- Space complexity : $o(1)$ # Code ``` class Solution { + // This method finds the first palindrome in the given array of words + public String firstPalindrome(String[] words) { + + // Iterating through each word in the array + for (String s : words) { + // Checking if the current word is a palindrome using the isPalin method + if (isPalin(s)) { + // If it is a palindrome, returning the word + return s; + } + } + // If no palindrome is found, returning an empty string + return ""; + } - // Method to find the majority element in an array - public int majorityElement(int[] nums) { - - // Variable to store the potential majority element - Integer a = null; - - // Counter to keep track of the occurrences of the potential majority element - int c = 0; - - // Iterating through the array - for (int n : nums) { - // If the counter is 0, updating the potential majority element to the current element - if (c == 0) - a = n; - - // Updating the counter based on whether the current element is equal to the potential majority element - c += n == a ? 1 : -1; + // This method checks if the given string is a palindrome + static boolean isPalin(String s) { + // Initializing two pointers, one at the beginning and one at the end of the string + int l = 0; + int r = s.length() - 1; + + // Continuing checking characters from both ends towards the center + while (l < r) { + // If characters at the current positions are not equal, the string is not a palindrome + if (s.charAt(l) != s.charAt(r)) { + return false; + } + // Moving the pointers towards the center + l++; + r--; + } + // If the loop completes, the string is a palindrome + return true; } - - // Returning the potential majority element - return a; - } } ``` \ No newline at end of file From 5f0324348f4f340e5f475c3d41d443064ad6e90e Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 13 Feb 2024 13:39:48 +0530 Subject: [PATCH 140/300] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 13354f0..b466ea7 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ My intuition was to iterate through each word in the array and check if it is a # Approach -- Method ``firstPalindrome` : +- Method `firstPalindrome` : - This method took an array of words as input. - It iterated through each word in the array using a for-each loop. - For each word, it called the `isPalin` method to check if the word is a palindrome. @@ -36,6 +36,7 @@ Overall, my approach involved iterating through the array of words and checking --- Have a look at the code , still have any confusion then please let me know in the comments + Keep Solving.:) # Complexity From d1f3f02cbaccc858d9b8330849c157682d10d888 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 13 Feb 2024 13:40:13 +0530 Subject: [PATCH 141/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b466ea7..af10623 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ Keep Solving.:) $N$ : number of words $M$ : maximum length of a word -- Space complexity : $o(1)$ +- Space complexity : $O(1)$ # Code From 6d1785d841737a7b156b597495d562765b88d2f9 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 13 Feb 2024 13:40:42 +0530 Subject: [PATCH 142/300] Create Daily 13-02-24.md --- 2024 February/Daily 13-02-24.md | 83 +++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 2024 February/Daily 13-02-24.md diff --git a/2024 February/Daily 13-02-24.md b/2024 February/Daily 13-02-24.md new file mode 100644 index 0000000..6c1f815 --- /dev/null +++ b/2024 February/Daily 13-02-24.md @@ -0,0 +1,83 @@ +## Today's 13-02-24 [Problem Link](https://leetcode.com/problems/find-first-palindromic-string-in-the-array/description/?envType=daily-question&envId=2024-02-13) +## 2108. Find First Palindromic String in the Array + +# Intuition + +The goal of this problem is to find the first palindrome in an array of words. A palindrome is a string that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). + +My intuition was to iterate through each word in the array and check if it is a palindrome using a helper method. + +# Approach + +- Method `firstPalindrome` : + - This method took an array of words as input. + - It iterated through each word in the array using a for-each loop. + - For each word, it called the `isPalin` method to check if the word is a palindrome. + - If a palindrome is found, the method immediately returned that word. + - If no palindrome is found in the entire array, it returned an empty string. + +- Method `isPalin` : + - This static method checked if a given string is a palindrome. + - It initialized two pointers (`l` and `r`) at the beginning and end of the string, respectively. + - It iterated while `l` is less than `r`. + - Within the loop, it compared characters at positions `l` and `r`. + - If the characters are not equal, the string is not a palindrome, and the method returned `false`. + - If the characters are equal, it incremented `l` and decremented `r` to check the next pair of characters. + - If the loop completed without returning `false`, the string is a palindrome, and the method `returned` true. + + +Overall, my approach involved iterating through the array of words and checking each word for palindromic properties using the `isPalin` method. The first palindrome encountered is returned, or an empty string is returned if no palindrome is found in the array. + +--- +Have a look at the code , still have any confusion then please let me know in the comments + +Keep Solving.:) + +# Complexity +- Time complexity : $O(N*M)$ + +$N$ : number of words + +$M$ : maximum length of a word +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + // This method finds the first palindrome in the given array of words + public String firstPalindrome(String[] words) { + + // Iterating through each word in the array + for (String s : words) { + // Checking if the current word is a palindrome using the isPalin method + if (isPalin(s)) { + // If it is a palindrome, returning the word + return s; + } + } + // If no palindrome is found, returning an empty string + return ""; + } + + // This method checks if the given string is a palindrome + static boolean isPalin(String s) { + // Initializing two pointers, one at the beginning and one at the end of the string + int l = 0; + int r = s.length() - 1; + + // Continuing checking characters from both ends towards the center + while (l < r) { + // If characters at the current positions are not equal, the string is not a palindrome + if (s.charAt(l) != s.charAt(r)) { + return false; + } + // Moving the pointers towards the center + l++; + r--; + } + // If the loop completes, the string is a palindrome + return true; + } +} +``` \ No newline at end of file From 47d01074a075e099101b71f3e2f0318871ebccd8 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 14 Feb 2024 11:45:53 +0530 Subject: [PATCH 143/300] Update README.md --- README.md | 90 ++++++++++++++++++++++--------------------------------- 1 file changed, 35 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index af10623..024cb55 100644 --- a/README.md +++ b/README.md @@ -4,35 +4,18 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 13-02-24 [Problem Link](https://leetcode.com/problems/find-first-palindromic-string-in-the-array/description/?envType=daily-question&envId=2024-02-13) -## 2108. Find First Palindromic String in the Array +## Today's 14-02-24 [Problem Link](https://leetcode.com/problems/rearrange-array-elements-by-sign/description/) +## 2149. Rearrange Array Elements by Sign # Intuition -The goal of this problem is to find the first palindrome in an array of words. A palindrome is a string that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). - -My intuition was to iterate through each word in the array and check if it is a palindrome using a helper method. +Separate positive and negative, then update original. # Approach -- Method `firstPalindrome` : - - This method took an array of words as input. - - It iterated through each word in the array using a for-each loop. - - For each word, it called the `isPalin` method to check if the word is a palindrome. - - If a palindrome is found, the method immediately returned that word. - - If no palindrome is found in the entire array, it returned an empty string. - -- Method `isPalin` : - - This static method checked if a given string is a palindrome. - - It initialized two pointers (`l` and `r`) at the beginning and end of the string, respectively. - - It iterated while `l` is less than `r`. - - Within the loop, it compared characters at positions `l` and `r`. - - If the characters are not equal, the string is not a palindrome, and the method returned `false`. - - If the characters are equal, it incremented `l` and decremented `r` to check the next pair of characters. - - If the loop completed without returning `false`, the string is a palindrome, and the method `returned` true. - +- I stored the positive and negative in separate arrays in order of there occurence. -Overall, my approach involved iterating through the array of words and checking each word for palindromic properties using the `isPalin` method. The first palindrome encountered is returned, or an empty string is returned if no palindrome is found in the array. +- Then simply updated the original 'nums' array by updating alternately with positive and negative numbers. --- Have a look at the code , still have any confusion then please let me know in the comments @@ -40,50 +23,47 @@ Have a look at the code , still have any confusion then please let me know in th Keep Solving.:) # Complexity -- Time complexity : $O(N*M)$ +- Time complexity : $O(l)$ -$N$ : number of words -$M$ : maximum length of a word -- Space complexity : $O(1)$ +- Space complexity : $O(2*(l/2))$ = $O(l)$ +$l$ is the length of array # Code ``` class Solution { - // This method finds the first palindrome in the given array of words - public String firstPalindrome(String[] words) { - - // Iterating through each word in the array - for (String s : words) { - // Checking if the current word is a palindrome using the isPalin method - if (isPalin(s)) { - // If it is a palindrome, returning the word - return s; + public int[] rearrangeArray(int[] nums) { + + int p[] = new int[nums.length/2]; // to store positive numbers + int ip = 0; // to maintain current added index + int n[] = new int[nums.length/2]; // to store positive numbers + int in = 0; // to maintain current added index + + for( int i = 0; i < nums.length; i++){ + if( nums[i] > 0){ + p[ip++] = nums[i]; + + } + else{ + n[in++] = nums[i]; } } - // If no palindrome is found, returning an empty string - return ""; - } + ip = 0; // resetting value to update 'nums' from these values + in = 0; // resetting value to update 'nums' from these values + + //System.out.println(Arrays.toString(p)); + //System.out.println(Arrays.toString(n)); - // This method checks if the given string is a palindrome - static boolean isPalin(String s) { - // Initializing two pointers, one at the beginning and one at the end of the string - int l = 0; - int r = s.length() - 1; - - // Continuing checking characters from both ends towards the center - while (l < r) { - // If characters at the current positions are not equal, the string is not a palindrome - if (s.charAt(l) != s.charAt(r)) { - return false; + for( int i = 0; i < nums.length; i++){ // updating 'nums' with its positive and negative numbers adding alternately + if( i % 2 == 0){ // for even index starting with first one, add positive numbers + nums[i] = p[ip++]; + } + else{ // else add negative numbers + nums[i] = n[in++]; } - // Moving the pointers towards the center - l++; - r--; } - // If the loop completes, the string is a palindrome - return true; + return nums; } } -``` \ No newline at end of file +``` From 40bd54f323c5b0b6f2a2dc7a060c68e4f3b43d8f Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 14 Feb 2024 11:49:15 +0530 Subject: [PATCH 144/300] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 024cb55..57968c8 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +# बसंत पंचमी की हार्दिक शुभकामनाएं। + # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. @@ -9,7 +11,7 @@ This is my attempt to make the coding experience easier for you guys so that you # Intuition -Separate positive and negative, then update original. +Separated the positive and negative, then update original. # Approach From 19bd114497f1422759c0c83671f704887d4e9e5f Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 14 Feb 2024 11:51:50 +0530 Subject: [PATCH 145/300] Update README.md --- README.md | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/README.md b/README.md index 57968c8..fd670be 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,61 @@ # बसंत पंचमी की हार्दिक शुभकामनाएं। +# I'm bowing to the goddess of knowledge without whom I'm nothing. +# Leetcode Daily Challenge Solutions + +This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. + +## Always here to assist you guys. + +## Today's 14-02-24 [Problem Link](https://leetcode.com/problems/rearrange-array-elements-by-sign/description/) +## 2149. Rearrange Array Elements by Sign + +# Intuition + +Separated the positive and negative, then update original. + +# Approach + +- I stored the positive and negative in separate arrays in order of there occurence. + +- Then simply updated the original 'nums' array by updating alternately with positive and negative numbers. +--- +Have a look at the code , still have any confusion then please let me know in the comments + +Keep Solving.:) + +# Complexity +- Time complexity : $O(l)$ + + +- Space complexity : $O(2*(l/2))$ = $O(l)$ + +$l$ is the length of array + +# Code +``` +class Solution { + public int[] rearrangeArray(int[] nums) { + + int p[] = new int[nums.length/2]; // to store positive numbers + int ip = 0; // to maintain current added index + int n[] = new int[nums.length/2]; // to store positive numbers + int in = 0; // to maintain current added index + + for( int i = 0; i < nums.length; i++){ + if( nums[i] > 0){ + p[ip++] = nums[i]; + + } + else{ + n[in++] = nums[i]; + } + } + ip = 0; // resetting value to update 'nums' from these values + in = 0; // resetting value to update 'nums' from these values + + //System.out.println(A# बसंत पंचमी की हार्दिक शुभकामनाएं। +# I'm bowing to the goddess of knowledge without whom I'm nothing. # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. @@ -69,3 +125,18 @@ class Solution { } } ``` +rrays.toString(p)); + //System.out.println(Arrays.toString(n)); + + for( int i = 0; i < nums.length; i++){ // updating 'nums' with its positive and negative numbers adding alternately + if( i % 2 == 0){ // for even index starting with first one, add positive numbers + nums[i] = p[ip++]; + } + else{ // else add negative numbers + nums[i] = n[in++]; + } + } + return nums; + } +} +``` From eae00889b1b8a12fbfd5d71485915802ef9c2e74 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 14 Feb 2024 11:57:23 +0530 Subject: [PATCH 146/300] Update README.md --- README.md | 71 ------------------------------------------------------- 1 file changed, 71 deletions(-) diff --git a/README.md b/README.md index fd670be..c6f4ce5 100644 --- a/README.md +++ b/README.md @@ -32,62 +32,6 @@ Keep Solving.:) $l$ is the length of array -# Code -``` -class Solution { - public int[] rearrangeArray(int[] nums) { - - int p[] = new int[nums.length/2]; // to store positive numbers - int ip = 0; // to maintain current added index - int n[] = new int[nums.length/2]; // to store positive numbers - int in = 0; // to maintain current added index - - for( int i = 0; i < nums.length; i++){ - if( nums[i] > 0){ - p[ip++] = nums[i]; - - } - else{ - n[in++] = nums[i]; - } - } - ip = 0; // resetting value to update 'nums' from these values - in = 0; // resetting value to update 'nums' from these values - - //System.out.println(A# बसंत पंचमी की हार्दिक शुभकामनाएं। -# I'm bowing to the goddess of knowledge without whom I'm nothing. -# Leetcode Daily Challenge Solutions - -This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. - -## Always here to assist you guys. - -## Today's 14-02-24 [Problem Link](https://leetcode.com/problems/rearrange-array-elements-by-sign/description/) -## 2149. Rearrange Array Elements by Sign - -# Intuition - -Separated the positive and negative, then update original. - -# Approach - -- I stored the positive and negative in separate arrays in order of there occurence. - -- Then simply updated the original 'nums' array by updating alternately with positive and negative numbers. - ---- -Have a look at the code , still have any confusion then please let me know in the comments - -Keep Solving.:) - -# Complexity -- Time complexity : $O(l)$ - - -- Space complexity : $O(2*(l/2))$ = $O(l)$ - -$l$ is the length of array - # Code ``` class Solution { @@ -125,18 +69,3 @@ class Solution { } } ``` -rrays.toString(p)); - //System.out.println(Arrays.toString(n)); - - for( int i = 0; i < nums.length; i++){ // updating 'nums' with its positive and negative numbers adding alternately - if( i % 2 == 0){ // for even index starting with first one, add positive numbers - nums[i] = p[ip++]; - } - else{ // else add negative numbers - nums[i] = n[in++]; - } - } - return nums; - } -} -``` From 62e1becafb8811803e897b3b7f42091a8492fbd1 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 14 Feb 2024 11:58:29 +0530 Subject: [PATCH 147/300] Create Daily 14-02-24 --- 2024 February/Daily 14-02-24 | 68 ++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 2024 February/Daily 14-02-24 diff --git a/2024 February/Daily 14-02-24 b/2024 February/Daily 14-02-24 new file mode 100644 index 0000000..65dea86 --- /dev/null +++ b/2024 February/Daily 14-02-24 @@ -0,0 +1,68 @@ +# बसंत पंचमी की हार्दिक शुभकामनाएं। +# I'm bowing to the goddess of knowledge without whom I'm nothing. + +## Always here to assist you guys. + +## Today's 14-02-24 [Problem Link](https://leetcode.com/problems/rearrange-array-elements-by-sign/description/) +## 2149. Rearrange Array Elements by Sign + +# Intuition + +Separated the positive and negative, then update original. + +# Approach + +- I stored the positive and negative in separate arrays in order of there occurence. + +- Then simply updated the original 'nums' array by updating alternately with positive and negative numbers. + +--- +Have a look at the code , still have any confusion then please let me know in the comments + +Keep Solving.:) + +# Complexity +- Time complexity : $O(l)$ + + +- Space complexity : $O(2*(l/2))$ = $O(l)$ + +$l$ is the length of array + +# Code +``` +class Solution { + public int[] rearrangeArray(int[] nums) { + + int p[] = new int[nums.length/2]; // to store positive numbers + int ip = 0; // to maintain current added index + int n[] = new int[nums.length/2]; // to store positive numbers + int in = 0; // to maintain current added index + + for( int i = 0; i < nums.length; i++){ + if( nums[i] > 0){ + p[ip++] = nums[i]; + + } + else{ + n[in++] = nums[i]; + } + } + ip = 0; // resetting value to update 'nums' from these values + in = 0; // resetting value to update 'nums' from these values + + //System.out.println(Arrays.toString(p)); + //System.out.println(Arrays.toString(n)); + + for( int i = 0; i < nums.length; i++){ // updating 'nums' with its positive and negative numbers adding alternately + if( i % 2 == 0){ // for even index starting with first one, add positive numbers + nums[i] = p[ip++]; + } + else{ // else add negative numbers + nums[i] = n[in++]; + } + } + return nums; + } +} +``` From 52cccc0f83a8475ec55e742117b592206bc63f8b Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 14 Feb 2024 11:59:22 +0530 Subject: [PATCH 148/300] Delete 2024 February/Daily 14-02-24 --- 2024 February/Daily 14-02-24 | 68 ------------------------------------ 1 file changed, 68 deletions(-) delete mode 100644 2024 February/Daily 14-02-24 diff --git a/2024 February/Daily 14-02-24 b/2024 February/Daily 14-02-24 deleted file mode 100644 index 65dea86..0000000 --- a/2024 February/Daily 14-02-24 +++ /dev/null @@ -1,68 +0,0 @@ -# बसंत पंचमी की हार्दिक शुभकामनाएं। -# I'm bowing to the goddess of knowledge without whom I'm nothing. - -## Always here to assist you guys. - -## Today's 14-02-24 [Problem Link](https://leetcode.com/problems/rearrange-array-elements-by-sign/description/) -## 2149. Rearrange Array Elements by Sign - -# Intuition - -Separated the positive and negative, then update original. - -# Approach - -- I stored the positive and negative in separate arrays in order of there occurence. - -- Then simply updated the original 'nums' array by updating alternately with positive and negative numbers. - ---- -Have a look at the code , still have any confusion then please let me know in the comments - -Keep Solving.:) - -# Complexity -- Time complexity : $O(l)$ - - -- Space complexity : $O(2*(l/2))$ = $O(l)$ - -$l$ is the length of array - -# Code -``` -class Solution { - public int[] rearrangeArray(int[] nums) { - - int p[] = new int[nums.length/2]; // to store positive numbers - int ip = 0; // to maintain current added index - int n[] = new int[nums.length/2]; // to store positive numbers - int in = 0; // to maintain current added index - - for( int i = 0; i < nums.length; i++){ - if( nums[i] > 0){ - p[ip++] = nums[i]; - - } - else{ - n[in++] = nums[i]; - } - } - ip = 0; // resetting value to update 'nums' from these values - in = 0; // resetting value to update 'nums' from these values - - //System.out.println(Arrays.toString(p)); - //System.out.println(Arrays.toString(n)); - - for( int i = 0; i < nums.length; i++){ // updating 'nums' with its positive and negative numbers adding alternately - if( i % 2 == 0){ // for even index starting with first one, add positive numbers - nums[i] = p[ip++]; - } - else{ // else add negative numbers - nums[i] = n[in++]; - } - } - return nums; - } -} -``` From ed30b9f20f0da595a32f00ca76f26adfc840145b Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Wed, 14 Feb 2024 12:00:12 +0530 Subject: [PATCH 149/300] Create Daily 14-02-24.md --- 2024 February/Daily 14-02-24.md | 67 +++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 2024 February/Daily 14-02-24.md diff --git a/2024 February/Daily 14-02-24.md b/2024 February/Daily 14-02-24.md new file mode 100644 index 0000000..6ce29dc --- /dev/null +++ b/2024 February/Daily 14-02-24.md @@ -0,0 +1,67 @@ +# बसंत पंचमी की हार्दिक शुभकामनाएं। +# I'm bowing to the goddess of knowledge without whom I'm nothing. +## Always here to assist you guys. + +## Today's 14-02-24 [Problem Link](https://leetcode.com/problems/rearrange-array-elements-by-sign/description/) +## 2149. Rearrange Array Elements by Sign + +# Intuition + +Separated the positive and negative, then update original. + +# Approach + +- I stored the positive and negative in separate arrays in order of there occurence. + +- Then simply updated the original 'nums' array by updating alternately with positive and negative numbers. + +--- +Have a look at the code , still have any confusion then please let me know in the comments + +Keep Solving.:) + +# Complexity +- Time complexity : $O(l)$ + + +- Space complexity : $O(2*(l/2))$ = $O(l)$ + +$l$ is the length of array + +# Code +``` +class Solution { + public int[] rearrangeArray(int[] nums) { + + int p[] = new int[nums.length/2]; // to store positive numbers + int ip = 0; // to maintain current added index + int n[] = new int[nums.length/2]; // to store positive numbers + int in = 0; // to maintain current added index + + for( int i = 0; i < nums.length; i++){ + if( nums[i] > 0){ + p[ip++] = nums[i]; + + } + else{ + n[in++] = nums[i]; + } + } + ip = 0; // resetting value to update 'nums' from these values + in = 0; // resetting value to update 'nums' from these values + + //System.out.println(Arrays.toString(p)); + //System.out.println(Arrays.toString(n)); + + for( int i = 0; i < nums.length; i++){ // updating 'nums' with its positive and negative numbers adding alternately + if( i % 2 == 0){ // for even index starting with first one, add positive numbers + nums[i] = p[ip++]; + } + else{ // else add negative numbers + nums[i] = n[in++]; + } + } + return nums; + } +} +``` From b2b9ca10d23844c76cdedfcf6be1f8387554fe8b Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 15 Feb 2024 10:26:29 +0530 Subject: [PATCH 150/300] Update README.md --- README.md | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c6f4ce5..20887aa 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. +<<<<<<< Updated upstream ## Today's 14-02-24 [Problem Link](https://leetcode.com/problems/rearrange-array-elements-by-sign/description/) ## 2149. Rearrange Array Elements by Sign @@ -18,22 +19,55 @@ Separated the positive and negative, then update original. - I stored the positive and negative in separate arrays in order of there occurence. - Then simply updated the original 'nums' array by updating alternately with positive and negative numbers. +======= +## Today's 15-02-24 [Problem Link](https://leetcode.com/problems/find-polygon-with-the-largest-perimeter/description/?envType=daily-question&envId=2024-02-15) +## 2971. Find Polygon With the Largest Perimeter + +# Intuition + +The problem required finding the largest perimeter of a triangle from an array of integers. The perimeter of a triangle is the sum of its three sides. To maximize the perimeter, I to considered the largest possible combination of three sides from the given array. + +# Approach + +**Sorted the Array** +- To consider the largest sides, I started by sorting the array in ascending order. + +**Cumulative Sums** : +- Created an array (`h`) to store cumulative sums of the sorted elements. The cumulative sum represents the sum of all elements up to the current index. + +**Iterated Through the Array** : +- Iterated through the sorted array, starting from the third element, as I need at least three elements to form a triangle. +- For each element at index `i`, checked if the sum of the two smaller elements (`h[i-1]`) is greater than the current element (`nums[i]`). +- If true, updated the `perimeter` with the maximum value between the current perimeter and the cumulative sum at index `i`. + +**Return Result** : +- If a valid perimeter is found, returned the maximum perimeter; otherwise, returned -1. + +My approach ensured that I consider the largest sides to maximize the perimeter of a valid triangle. Sorting the array helped in identifying the larger sides efficiently, and cumulative sums provided a quick way to calculate the sum of elements up to a certain index. +>>>>>>> Stashed changes --- Have a look at the code , still have any confusion then please let me know in the comments - Keep Solving.:) # Complexity +<<<<<<< Updated upstream - Time complexity : $O(l)$ - Space complexity : $O(2*(l/2))$ = $O(l)$ +======= +- Time complexity : $O(n*logn)$ + +$n$ : number of elements in the array. +- Space complexity : $O(n)$ +>>>>>>> Stashed changes $l$ is the length of array # Code ``` +<<<<<<< Updated upstream class Solution { public int[] rearrangeArray(int[] nums) { @@ -66,6 +100,46 @@ class Solution { } } return nums; +======= +import java.util.Arrays; + +public class Solution { + + // Method to find the largest perimeter from an array of integers + public static long largestPerimeter(int[] nums) { + + // Sorting the array in ascending order + Arrays.sort(nums); + + // Variable to store the perimeter + long perimeter = 0; + + // Array to store cumulative sums of sorted elements + long[] h = new long[nums.length]; + h[0] = nums[0]; + + // Calculating cumulative sums + for (int i = 1; i < nums.length; i++) { + h[i] = h[i - 1] + nums[i]; + } + + // Iterating through the array to find the largest perimeter + for (int i = 2; i < nums.length; i++) { + if (h[i - 1] > nums[i]) { + // If the sum of the two smaller sides is greater than the largest side + // then updating the perimeter with the current sum + perimeter = Math.max(perimeter, h[i]); + } + } + + // If no valid perimeter is found, returning -1 + if (perimeter == 0) { + return -1; + } + + // Returning the largest perimeter + return perimeter; +>>>>>>> Stashed changes } } ``` From 5460e9d5317597ecb6ca496b953ff06a753924f6 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Thu, 15 Feb 2024 10:27:17 +0530 Subject: [PATCH 151/300] Update README.md --- README.md | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/README.md b/README.md index 20887aa..aab84f8 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,8 @@ -# बसंत पंचमी की हार्दिक शुभकामनाएं। -# I'm bowing to the goddess of knowledge without whom I'm nothing. # Leetcode Daily Challenge Solutions - This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. ## Always here to assist you guys. -<<<<<<< Updated upstream -## Today's 14-02-24 [Problem Link](https://leetcode.com/problems/rearrange-array-elements-by-sign/description/) -## 2149. Rearrange Array Elements by Sign - -# Intuition - -Separated the positive and negative, then update original. - -# Approach - -- I stored the positive and negative in separate arrays in order of there occurence. - -- Then simply updated the original 'nums' array by updating alternately with positive and negative numbers. -======= ## Today's 15-02-24 [Problem Link](https://leetcode.com/problems/find-polygon-with-the-largest-perimeter/description/?envType=daily-question&envId=2024-02-15) ## 2971. Find Polygon With the Largest Perimeter From 088885fb7f6359f353a3e80a287123b3c7a74f39 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Thu, 15 Feb 2024 10:36:22 +0530 Subject: [PATCH 152/300] Update README.md --- README.md | 40 ---------------------------------------- 1 file changed, 40 deletions(-) diff --git a/README.md b/README.md index aab84f8..2fb8dfe 100644 --- a/README.md +++ b/README.md @@ -34,12 +34,6 @@ Have a look at the code , still have any confusion then please let me know in th Keep Solving.:) # Complexity -<<<<<<< Updated upstream -- Time complexity : $O(l)$ - - -- Space complexity : $O(2*(l/2))$ = $O(l)$ -======= - Time complexity : $O(n*logn)$ $n$ : number of elements in the array. @@ -50,40 +44,6 @@ $l$ is the length of array # Code ``` -<<<<<<< Updated upstream -class Solution { - public int[] rearrangeArray(int[] nums) { - - int p[] = new int[nums.length/2]; // to store positive numbers - int ip = 0; // to maintain current added index - int n[] = new int[nums.length/2]; // to store positive numbers - int in = 0; // to maintain current added index - - for( int i = 0; i < nums.length; i++){ - if( nums[i] > 0){ - p[ip++] = nums[i]; - - } - else{ - n[in++] = nums[i]; - } - } - ip = 0; // resetting value to update 'nums' from these values - in = 0; // resetting value to update 'nums' from these values - - //System.out.println(Arrays.toString(p)); - //System.out.println(Arrays.toString(n)); - - for( int i = 0; i < nums.length; i++){ // updating 'nums' with its positive and negative numbers adding alternately - if( i % 2 == 0){ // for even index starting with first one, add positive numbers - nums[i] = p[ip++]; - } - else{ // else add negative numbers - nums[i] = n[in++]; - } - } - return nums; -======= import java.util.Arrays; public class Solution { From bd1ad33e384cb7cc7a98eb15620452d9878b02cb Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 15 Feb 2024 10:37:15 +0530 Subject: [PATCH 153/300] Update README.md --- README.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 2fb8dfe..b7856c1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Leetcode Daily Challenge Solutions + This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. ## Always here to assist you guys. @@ -27,7 +28,6 @@ The problem required finding the largest perimeter of a triangle from an array o - If a valid perimeter is found, returned the maximum perimeter; otherwise, returned -1. My approach ensured that I consider the largest sides to maximize the perimeter of a valid triangle. Sorting the array helped in identifying the larger sides efficiently, and cumulative sums provided a quick way to calculate the sum of elements up to a certain index. ->>>>>>> Stashed changes --- Have a look at the code , still have any confusion then please let me know in the comments @@ -38,9 +38,7 @@ Keep Solving.:) $n$ : number of elements in the array. - Space complexity : $O(n)$ ->>>>>>> Stashed changes -$l$ is the length of array # Code ``` @@ -82,7 +80,6 @@ public class Solution { // Returning the largest perimeter return perimeter; ->>>>>>> Stashed changes } } -``` +``` \ No newline at end of file From 23bfca8da921e4a3c49ec9daf19254b91f6c1829 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 15 Feb 2024 10:38:26 +0530 Subject: [PATCH 154/300] Create Daily 15-02-24.md --- 2024 February/Daily 15-02-24.md | 79 +++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 2024 February/Daily 15-02-24.md diff --git a/2024 February/Daily 15-02-24.md b/2024 February/Daily 15-02-24.md new file mode 100644 index 0000000..c3c7ceb --- /dev/null +++ b/2024 February/Daily 15-02-24.md @@ -0,0 +1,79 @@ +## Today's 15-02-24 [Problem Link](https://leetcode.com/problems/find-polygon-with-the-largest-perimeter/description/?envType=daily-question&envId=2024-02-15) +## 2971. Find Polygon With the Largest Perimeter + +# Intuition + +The problem required finding the largest perimeter of a triangle from an array of integers. The perimeter of a triangle is the sum of its three sides. To maximize the perimeter, I to considered the largest possible combination of three sides from the given array. + +# Approach + +**Sorted the Array** +- To consider the largest sides, I started by sorting the array in ascending order. + +**Cumulative Sums** : +- Created an array (`h`) to store cumulative sums of the sorted elements. The cumulative sum represents the sum of all elements up to the current index. + +**Iterated Through the Array** : +- Iterated through the sorted array, starting from the third element, as I need at least three elements to form a triangle. +- For each element at index `i`, checked if the sum of the two smaller elements (`h[i-1]`) is greater than the current element (`nums[i]`). +- If true, updated the `perimeter` with the maximum value between the current perimeter and the cumulative sum at index `i`. + +**Return Result** : +- If a valid perimeter is found, returned the maximum perimeter; otherwise, returned -1. + +My approach ensured that I consider the largest sides to maximize the perimeter of a valid triangle. Sorting the array helped in identifying the larger sides efficiently, and cumulative sums provided a quick way to calculate the sum of elements up to a certain index. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(n*logn)$ + +$n$ : number of elements in the array. +- Space complexity : $O(n)$ + + +# Code +``` +import java.util.Arrays; + +public class Solution { + + // Method to find the largest perimeter from an array of integers + public static long largestPerimeter(int[] nums) { + + // Sorting the array in ascending order + Arrays.sort(nums); + + // Variable to store the perimeter + long perimeter = 0; + + // Array to store cumulative sums of sorted elements + long[] h = new long[nums.length]; + h[0] = nums[0]; + + // Calculating cumulative sums + for (int i = 1; i < nums.length; i++) { + h[i] = h[i - 1] + nums[i]; + } + + // Iterating through the array to find the largest perimeter + for (int i = 2; i < nums.length; i++) { + if (h[i - 1] > nums[i]) { + // If the sum of the two smaller sides is greater than the largest side + // then updating the perimeter with the current sum + perimeter = Math.max(perimeter, h[i]); + } + } + + // If no valid perimeter is found, returning -1 + if (perimeter == 0) { + return -1; + } + + // Returning the largest perimeter + return perimeter; + } +} +``` \ No newline at end of file From 02273502679aea73a78bd384870e7e10bc934656 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 16 Feb 2024 14:17:27 +0530 Subject: [PATCH 155/300] Update README.md --- README.md | 101 +++++++++++++++++++++++++++--------------------------- 1 file changed, 51 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index b7856c1..2d04217 100644 --- a/README.md +++ b/README.md @@ -4,82 +4,83 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 15-02-24 [Problem Link](https://leetcode.com/problems/find-polygon-with-the-largest-perimeter/description/?envType=daily-question&envId=2024-02-15) -## 2971. Find Polygon With the Largest Perimeter +## Today's 16-02-24 [Problem Link](https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/description/?envType=daily-question&envId=2024-02-16) +## 1481. Least Number of Unique Integers after K Removals # Intuition -The problem required finding the largest perimeter of a triangle from an array of integers. The perimeter of a triangle is the sum of its three sides. To maximize the perimeter, I to considered the largest possible combination of three sides from the given array. +The goal is to find the least number of unique integers in an array after removing 'k' elements. # Approach -**Sorted the Array** -- To consider the largest sides, I started by sorting the array in ascending order. -**Cumulative Sums** : -- Created an array (`h`) to store cumulative sums of the sorted elements. The cumulative sum represents the sum of all elements up to the current index. +- Created a HashMap to store the frequency of each number in the array. -**Iterated Through the Array** : -- Iterated through the sorted array, starting from the third element, as I need at least three elements to form a triangle. -- For each element at index `i`, checked if the sum of the two smaller elements (`h[i-1]`) is greater than the current element (`nums[i]`). -- If true, updated the `perimeter` with the maximum value between the current perimeter and the cumulative sum at index `i`. +- Populated the HashMap with the frequency of each number. -**Return Result** : -- If a valid perimeter is found, returned the maximum perimeter; otherwise, returned -1. +- Created a Priority Queue (min-heap) with the values (frequencies) from the HashMap. -My approach ensured that I consider the largest sides to maximize the perimeter of a valid triangle. Sorting the array helped in identifying the larger sides efficiently, and cumulative sums provided a quick way to calculate the sum of elements up to a certain index. +- Iterated through the Priority Queue and decremented 'k' by the frequency of each element until 'k' becomes zero. + +- If 'k' is negative after the loop, it means more elements were removed than necessary. Returned the remaining number of unique integers plus one. + +- If 'k' is zero or positive after the loop, returned the remaining number of unique integers. + +My code efficiently found the solution by using a HashMap to store frequencies and a Priority Queue to process the frequencies in ascending order. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(n*logn)$ +- Time complexity : $O(N + N*log N + K*log N)$ ${\equiv}$ $$O( N *log N )$$ -$n$ : number of elements in the array. -- Space complexity : $O(n)$ +$N$ : number of unique elements in the array + +$K$ : given +- Space complexity : $O(N)$ # Code ``` -import java.util.Arrays; +import java.util.HashMap; +import java.util.PriorityQueue; +import java.util.Queue; -public class Solution { - - // Method to find the largest perimeter from an array of integers - public static long largestPerimeter(int[] nums) { - - // Sorting the array in ascending order - Arrays.sort(nums); - - // Variable to store the perimeter - long perimeter = 0; - - // Array to store cumulative sums of sorted elements - long[] h = new long[nums.length]; - h[0] = nums[0]; +class Solution { + + // HashMap to store the frequency of each number in the array + HashMap m; + // Priority Queue to store the frequencies in ascending order + Queue mH; + + // Method to find the least number of unique integers after removing 'k' elements + public int findLeastNumOfUniqueInts(int[] arr, int k) { - // Calculating cumulative sums - for (int i = 1; i < nums.length; i++) { - h[i] = h[i - 1] + nums[i]; + // Initializing the HashMap + m = new HashMap<>(); + // Populating the HashMap with the frequency of each number in the array + for (int n : arr) { + m.put(n, m.getOrDefault(n, 0) + 1); } - - // Iterating through the array to find the largest perimeter - for (int i = 2; i < nums.length; i++) { - if (h[i - 1] > nums[i]) { - // If the sum of the two smaller sides is greater than the largest side - // then updating the perimeter with the current sum - perimeter = Math.max(perimeter, h[i]); - } + + // Initializing the Priority Queue with the values (frequencies) from the HashMap + mH = new PriorityQueue<>(m.values()); + + // Continuing removing the smallest frequencies until 'k' becomes zero + while (k > 0) { + k -= mH.poll(); } - - // If no valid perimeter is found, returning -1 - if (perimeter == 0) { - return -1; + + // If 'k' is negative, it means more elements were removed than necessary + // In this case, returning the remaining number of unique integers plus one + if (k < 0) { + return mH.size() + 1; + } else { + // If 'k' is zero or positive, returning the remaining number of unique integers + return mH.size(); } - - // Returning the largest perimeter - return perimeter; } } + ``` \ No newline at end of file From 63369055122a6b4be674595ea89b1672a9566a57 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 16 Feb 2024 14:18:48 +0530 Subject: [PATCH 156/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2d04217..623e808 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Have a look at the code , still have any confusion then please let me know in th Keep Solving.:) # Complexity -- Time complexity : $O(N + N*log N + K*log N)$ ${\equiv}$ $$O( N *log N )$$ +- Time complexity : $O(N + N*log N + K*log N)$ ${\equiv}$ $O( N *log N )$ $N$ : number of unique elements in the array From ddcaf644a5a24ad5534f6c7c175ef55ad03df62c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 16 Feb 2024 14:22:42 +0530 Subject: [PATCH 157/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 623e808..f6d5a1f 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Have a look at the code , still have any confusion then please let me know in th Keep Solving.:) # Complexity -- Time complexity : $O(N + N*log N + K*log N)$ ${\equiv}$ $O( N *log N )$ +- Time complexity : $O(N + N*log N + K*log N) {\equiv} O( N *log N )$ $N$ : number of unique elements in the array From 934360dd1af03dad6f02801edd7e25330181da54 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 16 Feb 2024 14:24:59 +0530 Subject: [PATCH 158/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f6d5a1f..623e808 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Have a look at the code , still have any confusion then please let me know in th Keep Solving.:) # Complexity -- Time complexity : $O(N + N*log N + K*log N) {\equiv} O( N *log N )$ +- Time complexity : $O(N + N*log N + K*log N)$ ${\equiv}$ $O( N *log N )$ $N$ : number of unique elements in the array From d8bdeb66af4c88879233ec9a577d9c9290e5f67a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 16 Feb 2024 14:25:41 +0530 Subject: [PATCH 159/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 623e808..784bc38 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Have a look at the code , still have any confusion then please let me know in th Keep Solving.:) # Complexity -- Time complexity : $O(N + N*log N + K*log N)$ ${\equiv}$ $O( N *log N )$ +- Time complexity : $O( N *log N )$ $N$ : number of unique elements in the array From 4b1e3894d84c697a8d10b56b0a8aa79672f16161 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 16 Feb 2024 22:30:01 +0530 Subject: [PATCH 160/300] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 784bc38..6492012 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,6 @@ Keep Solving.:) $N$ : number of unique elements in the array -$K$ : given - Space complexity : $O(N)$ From f3d23a35aa0b39928dd47dad23af7de5b4da8cff Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 16 Feb 2024 22:30:35 +0530 Subject: [PATCH 161/300] Create Daily 16-02-24.md --- 2024 February/Daily 16-02-24.md | 79 +++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 2024 February/Daily 16-02-24.md diff --git a/2024 February/Daily 16-02-24.md b/2024 February/Daily 16-02-24.md new file mode 100644 index 0000000..3bd6d39 --- /dev/null +++ b/2024 February/Daily 16-02-24.md @@ -0,0 +1,79 @@ +## Today's 16-02-24 [Problem Link](https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/description/?envType=daily-question&envId=2024-02-16) +## 1481. Least Number of Unique Integers after K Removals + +# Intuition + +The goal is to find the least number of unique integers in an array after removing 'k' elements. + +# Approach + + +- Created a HashMap to store the frequency of each number in the array. + +- Populated the HashMap with the frequency of each number. + +- Created a Priority Queue (min-heap) with the values (frequencies) from the HashMap. + +- Iterated through the Priority Queue and decremented 'k' by the frequency of each element until 'k' becomes zero. + +- If 'k' is negative after the loop, it means more elements were removed than necessary. Returned the remaining number of unique integers plus one. + +- If 'k' is zero or positive after the loop, returned the remaining number of unique integers. + +My code efficiently found the solution by using a HashMap to store frequencies and a Priority Queue to process the frequencies in ascending order. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O( N *log N )$ + +$N$ : number of unique elements in the array + +- Space complexity : $O(N)$ + + +# Code +``` +import java.util.HashMap; +import java.util.PriorityQueue; +import java.util.Queue; + +class Solution { + + // HashMap to store the frequency of each number in the array + HashMap m; + // Priority Queue to store the frequencies in ascending order + Queue mH; + + // Method to find the least number of unique integers after removing 'k' elements + public int findLeastNumOfUniqueInts(int[] arr, int k) { + + // Initializing the HashMap + m = new HashMap<>(); + // Populating the HashMap with the frequency of each number in the array + for (int n : arr) { + m.put(n, m.getOrDefault(n, 0) + 1); + } + + // Initializing the Priority Queue with the values (frequencies) from the HashMap + mH = new PriorityQueue<>(m.values()); + + // Continuing removing the smallest frequencies until 'k' becomes zero + while (k > 0) { + k -= mH.poll(); + } + + // If 'k' is negative, it means more elements were removed than necessary + // In this case, returning the remaining number of unique integers plus one + if (k < 0) { + return mH.size() + 1; + } else { + // If 'k' is zero or positive, returning the remaining number of unique integers + return mH.size(); + } + } +} + +``` \ No newline at end of file From 3dd88a7ffaf27786a86d28ce9938c96b2a88a32e Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 17 Feb 2024 12:15:32 +0530 Subject: [PATCH 162/300] Update README.md --- README.md | 109 +++++++++++++++++++++++++++++------------------------- 1 file changed, 59 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 6492012..7ce4dc7 100644 --- a/README.md +++ b/README.md @@ -4,82 +4,91 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 16-02-24 [Problem Link](https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/description/?envType=daily-question&envId=2024-02-16) -## 1481. Least Number of Unique Integers after K Removals +## Today's 17-02-24 [Problem Link](https://leetcode.com/problems/furthest-building-you-can-reach/description/?envType=daily-question&envId=2024-02-17) +## 1642. Furthest Building You Can Reach # Intuition -The goal is to find the least number of unique integers in an array after removing 'k' elements. +This problem involved finding the furthest building that can be reached with a given number of bricks and ladders. To maximize the distance, I wanted to use ladders for the steepest climbs and save bricks for smaller climbs. # Approach +**Priority Queue for Heights Difference :** +- Used a priority queue (min-heap) to keep track of the differences in heights between consecutive buildings. +- This helped in efficiently selecting the steepest climbs. -- Created a HashMap to store the frequency of each number in the array. +**Iterated Through Buildings :** +- Iterated through the buildings, calculating the height difference between consecutive ones. +- If the difference is non-positive, moved to the next building as no resources are needed for descending. -- Populated the HashMap with the frequency of each number. +**Used Ladders for Steeper Climbs :** +- If the height difference is positive, added it to the priority queue. +- If the size of the priority queue exceeded the number of ladders available, it means I need to use bricks. Polled out the smallest height difference from the queue and subtracted it from available bricks. -- Created a Priority Queue (min-heap) with the values (frequencies) from the HashMap. +**Checked Brick Availability :** +- After subtracting the bricks, if the bricks become negative, returned the current index as it indicated that the remaining buildings cannot be reached with the available resources. -- Iterated through the Priority Queue and decremented 'k' by the frequency of each element until 'k' becomes zero. +**Retured the Furthest Reachable Building :** +- If the iteration completed without returning, all buildings can be reached. Returned the index of the last building. -- If 'k' is negative after the loop, it means more elements were removed than necessary. Returned the remaining number of unique integers plus one. - -- If 'k' is zero or positive after the loop, returned the remaining number of unique integers. - -My code efficiently found the solution by using a HashMap to store frequencies and a Priority Queue to process the frequencies in ascending order. +My approach ensured efficient utilization of ladders for steeper climbs and used bricks only when necessary, allowing for the furthest possible reach with the given resources. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity -- Time complexity : $O( N *log N )$ +- Time complexity : $O(n*logk)$ -$N$ : number of unique elements in the array +$n$ : length of `heights` array -- Space complexity : $O(N)$ +$k$ : number of ladders ( given ) +- Space complexity : $O(k)$ # Code ``` -import java.util.HashMap; -import java.util.PriorityQueue; -import java.util.Queue; - class Solution { - // HashMap to store the frequency of each number in the array - HashMap m; - // Priority Queue to store the frequencies in ascending order - Queue mH; - - // Method to find the least number of unique integers after removing 'k' elements - public int findLeastNumOfUniqueInts(int[] arr, int k) { + // Priority Queue to store the height differences + static Queue mH; + + // Variable to store the current height difference + static int antr; + + // Main method to find the furthest building + public int furthestBuilding(int[] heights, int bricks, int ladders) { - // Initializing the HashMap - m = new HashMap<>(); - // Populating the HashMap with the frequency of each number in the array - for (int n : arr) { - m.put(n, m.getOrDefault(n, 0) + 1); - } - - // Initializing the Priority Queue with the values (frequencies) from the HashMap - mH = new PriorityQueue<>(m.values()); - - // Continuing removing the smallest frequencies until 'k' becomes zero - while (k > 0) { - k -= mH.poll(); - } - - // If 'k' is negative, it means more elements were removed than necessary - // In this case, returning the remaining number of unique integers plus one - if (k < 0) { - return mH.size() + 1; - } else { - // If 'k' is zero or positive, returning the remaining number of unique integers - return mH.size(); + // Initializing the priority queue + mH = new PriorityQueue<>(); + + // Iterating through the heights array + for (int i = 0; i < heights.length - 1; i++) { + + // Calculating the height difference between consecutive buildings + antr = heights[i + 1] - heights[i]; + + // If the height difference is non-positive, continuing to the next iteration + if (antr <= 0) { + continue; + } + + // Adding the height difference to the priority queue + mH.offer(antr); + + // If the size of the priority queue exceeds the number of ladders available, + // subtracting the smallest height difference from bricks + if (mH.size() > ladders) { + bricks -= mH.poll(); + } + + // If bricks become negative, returning the current index + if (bricks < 0) { + return i; + } } + + // If all buildings can be reached, returning the last index + return heights.length - 1; } } - ``` \ No newline at end of file From f436c586e419acd77418ce2c6330cd5649757257 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 17 Feb 2024 12:16:53 +0530 Subject: [PATCH 163/300] Create Daily 17-02-24.md --- 2024 February/Daily 17-02-24.md | 88 +++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 2024 February/Daily 17-02-24.md diff --git a/2024 February/Daily 17-02-24.md b/2024 February/Daily 17-02-24.md new file mode 100644 index 0000000..f6c819b --- /dev/null +++ b/2024 February/Daily 17-02-24.md @@ -0,0 +1,88 @@ +## Today's 17-02-24 [Problem Link](https://leetcode.com/problems/furthest-building-you-can-reach/description/?envType=daily-question&envId=2024-02-17) +## 1642. Furthest Building You Can Reach + +# Intuition + +This problem involved finding the furthest building that can be reached with a given number of bricks and ladders. To maximize the distance, I wanted to use ladders for the steepest climbs and save bricks for smaller climbs. + +# Approach + +**Priority Queue for Heights Difference :** +- Used a priority queue (min-heap) to keep track of the differences in heights between consecutive buildings. +- This helped in efficiently selecting the steepest climbs. + +**Iterated Through Buildings :** +- Iterated through the buildings, calculating the height difference between consecutive ones. +- If the difference is non-positive, moved to the next building as no resources are needed for descending. + +**Used Ladders for Steeper Climbs :** +- If the height difference is positive, added it to the priority queue. +- If the size of the priority queue exceeded the number of ladders available, it means I need to use bricks. Polled out the smallest height difference from the queue and subtracted it from available bricks. + +**Checked Brick Availability :** +- After subtracting the bricks, if the bricks become negative, returned the current index as it indicated that the remaining buildings cannot be reached with the available resources. + +**Retured the Furthest Reachable Building :** +- If the iteration completed without returning, all buildings can be reached. Returned the index of the last building. + +My approach ensured efficient utilization of ladders for steeper climbs and used bricks only when necessary, allowing for the furthest possible reach with the given resources. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(n*logk)$ + +$n$ : length of `heights` array + +$k$ : number of ladders ( given ) +- Space complexity : $O(k)$ + + +# Code +``` +class Solution { + + // Priority Queue to store the height differences + static Queue mH; + + // Variable to store the current height difference + static int antr; + + // Main method to find the furthest building + public int furthestBuilding(int[] heights, int bricks, int ladders) { + + // Initializing the priority queue + mH = new PriorityQueue<>(); + + // Iterating through the heights array + for (int i = 0; i < heights.length - 1; i++) { + + // Calculating the height difference between consecutive buildings + antr = heights[i + 1] - heights[i]; + + // If the height difference is non-positive, continuing to the next iteration + if (antr <= 0) { + continue; + } + + // Adding the height difference to the priority queue + mH.offer(antr); + + // If the size of the priority queue exceeds the number of ladders available, + // subtracting the smallest height difference from bricks + if (mH.size() > ladders) { + bricks -= mH.poll(); + } + + // If bricks become negative, returning the current index + if (bricks < 0) { + return i; + } + } + + // If all buildings can be reached, returning the last index + return heights.length - 1; + } +} +``` \ No newline at end of file From e29eaba9104a471cf7cc1af590d1724224bb1171 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 18 Feb 2024 12:01:51 +0530 Subject: [PATCH 164/300] Update README.md --- README.md | 149 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 90 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 7ce4dc7..002c4e2 100644 --- a/README.md +++ b/README.md @@ -4,91 +4,122 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 17-02-24 [Problem Link](https://leetcode.com/problems/furthest-building-you-can-reach/description/?envType=daily-question&envId=2024-02-17) -## 1642. Furthest Building You Can Reach +## Today's 18-02-24 [Problem Link](https://leetcode.com/problems/meeting-rooms-iii/description/?envType=daily-question&envId=2024-02-18) +## 2402. Meeting Rooms III # Intuition -This problem involved finding the furthest building that can be reached with a given number of bricks and ladders. To maximize the distance, I wanted to use ladders for the steepest climbs and save bricks for smaller climbs. + +- To efficiently track the availability of rooms, I can use a priority queue to manage occupied rooms based on their end times. +- Additionally, I can use another priority queue to keep track of available room IDs. +- Sorting the meetings based on their start times will ensure that I process the meetings in chronological order. # Approach -**Priority Queue for Heights Difference :** -- Used a priority queue (min-heap) to keep track of the differences in heights between consecutive buildings. -- This helped in efficiently selecting the steepest climbs. - -**Iterated Through Buildings :** -- Iterated through the buildings, calculating the height difference between consecutive ones. -- If the difference is non-positive, moved to the next building as no resources are needed for descending. - -**Used Ladders for Steeper Climbs :** -- If the height difference is positive, added it to the priority queue. -- If the size of the priority queue exceeded the number of ladders available, it means I need to use bricks. Polled out the smallest height difference from the queue and subtracted it from available bricks. -**Checked Brick Availability :** -- After subtracting the bricks, if the bricks become negative, returned the current index as it indicated that the remaining buildings cannot be reached with the available resources. +- I initialized an array to store the count of meetings booked for each room (`meetingCount`). +- Sorted the meetings based on their start times. +- Initialized a priority queue (`occupiedRooms`) to store occupied rooms based on end times. +- Initialized another priority queue (`availableRoomIds`) to store available room IDs. +- Populated the `availableRoomIds` priority queue with the initial room IDs. +- Processed each meeting in chronological order: + - Moved meetings ending before the current meeting to available rooms from `occupiedRooms`. + - If no available rooms, scheduled the meeting in the room with the earliest end time from `occupiedRooms`. + - Otherwise, scheduled the meeting in an available room from `availableRoomIds`. +- Updated the `meetingCount` array with the count of meetings booked for each room. +- Found the room with the maximum booked meetings and return its index. -**Retured the Furthest Reachable Building :** -- If the iteration completed without returning, all buildings can be reached. Returned the index of the last building. - -My approach ensured efficient utilization of ladders for steeper climbs and used bricks only when necessary, allowing for the furthest possible reach with the given resources. +My approach ensured efficient tracking of occupied and available rooms, allowing for the determination of the most frequently booked room. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + # Complexity -- Time complexity : $O(n*logk)$ +- Time complexity : $O(m*logm)$ -$n$ : length of `heights` array - -$k$ : number of ladders ( given ) -- Space complexity : $O(k)$ +$m$ : number of meetings +- Space complexity : $O(m)$ # Code ``` +import java.util.Arrays; +import java.util.PriorityQueue; +import java.util.Queue; + +// Defining a class to represent a meeting with endTime and roomId +class Meeting { + public long endTime; + public int roomId; + + public Meeting(long endTime, int roomId) { + this.endTime = endTime; + this.roomId = roomId; + } +} + +// Class for meeting scheduling and finding the most booked room class Solution { - // Priority Queue to store the height differences - static Queue mH; + static Queue occupiedRooms; + static Queue availableRoomIds; - // Variable to store the current height difference - static int antr; + // Method to find the most booked room + public int mostBooked(int numberOfRooms, int[][] meetings) { - // Main method to find the furthest building - public int furthestBuilding(int[] heights, int bricks, int ladders) { - - // Initializing the priority queue - mH = new PriorityQueue<>(); - - // Iterating through the heights array - for (int i = 0; i < heights.length - 1; i++) { - - // Calculating the height difference between consecutive buildings - antr = heights[i + 1] - heights[i]; - - // If the height difference is non-positive, continuing to the next iteration - if (antr <= 0) { - continue; + // Array to store the count of meetings booked for each room + int[] meetingCount = new int[numberOfRooms]; + + // Sorting meetings based on start time + Arrays.sort(meetings, (a, b) -> a[0] - b[0]); + + // Priority queue to store occupied rooms based on end time + occupiedRooms = new PriorityQueue<>((a, b) -> + a.endTime == b.endTime ? Integer.compare(a.roomId, b.roomId) : Long.compare(a.endTime, b.endTime)); + + // Priority queue to store available room IDs + availableRoomIds = new PriorityQueue<>(); + + // Initializing available room IDs + for (int i = 0; i < numberOfRooms; ++i) { + availableRoomIds.offer(i); + } + + // Processing each meeting + for (int[] meeting : meetings) { + final int start = meeting[0]; + final int end = meeting[1]; + + // Moving meetings ending before the current meeting to available rooms + while (!occupiedRooms.isEmpty() && occupiedRooms.peek().endTime <= start) { + availableRoomIds.offer(occupiedRooms.poll().roomId); } - - // Adding the height difference to the priority queue - mH.offer(antr); - - // If the size of the priority queue exceeds the number of ladders available, - // subtracting the smallest height difference from bricks - if (mH.size() > ladders) { - bricks -= mH.poll(); + + // If no available room, scheduling the meeting in the room with the earliest end time + if (availableRoomIds.isEmpty()) { + Meeting prevMeeting = occupiedRooms.poll(); + ++meetingCount[prevMeeting.roomId]; + occupiedRooms.offer(new Meeting(prevMeeting.endTime + (end - start), prevMeeting.roomId)); + } + else { + // Scheduling the meeting in an available room + final int roomId = availableRoomIds.poll(); + ++meetingCount[roomId]; + occupiedRooms.offer(new Meeting(end, roomId)); } - - // If bricks become negative, returning the current index - if (bricks < 0) { - return i; + } + + // Finding the room with the maximum booked meetings + int maxIndex = 0; + for (int i = 0; i < numberOfRooms; ++i) { + if (meetingCount[i] > meetingCount[maxIndex]) { + maxIndex = i; } } - - // If all buildings can be reached, returning the last index - return heights.length - 1; + + return maxIndex; } } + ``` \ No newline at end of file From 75718e0383cdb60f039246cb8028cc6be8d1ea63 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 18 Feb 2024 12:02:48 +0530 Subject: [PATCH 165/300] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 002c4e2..9df1b7b 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,7 @@ This is my attempt to make the coding experience easier for you guys so that you My approach ensured efficient tracking of occupied and available rooms, allowing for the determination of the most frequently booked room. --- -Have a look at the code , still have any confusion then please let me know in the comments -Keep Solving.:) +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity - Time complexity : $O(m*logm)$ From 7ca6229faf07ad80f876c2fc44ad2aaee275df08 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 18 Feb 2024 12:03:38 +0530 Subject: [PATCH 166/300] Create Daily 18-02-24.md --- 2024 February/Daily 18-02-24.md | 118 ++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 2024 February/Daily 18-02-24.md diff --git a/2024 February/Daily 18-02-24.md b/2024 February/Daily 18-02-24.md new file mode 100644 index 0000000..66841ce --- /dev/null +++ b/2024 February/Daily 18-02-24.md @@ -0,0 +1,118 @@ +## Today's 18-02-24 [Problem Link](https://leetcode.com/problems/meeting-rooms-iii/description/?envType=daily-question&envId=2024-02-18) +## 2402. Meeting Rooms III + +# Intuition + + +- To efficiently track the availability of rooms, I can use a priority queue to manage occupied rooms based on their end times. +- Additionally, I can use another priority queue to keep track of available room IDs. +- Sorting the meetings based on their start times will ensure that I process the meetings in chronological order. + +# Approach + + +- I initialized an array to store the count of meetings booked for each room (`meetingCount`). +- Sorted the meetings based on their start times. +- Initialized a priority queue (`occupiedRooms`) to store occupied rooms based on end times. +- Initialized another priority queue (`availableRoomIds`) to store available room IDs. +- Populated the `availableRoomIds` priority queue with the initial room IDs. +- Processed each meeting in chronological order: + - Moved meetings ending before the current meeting to available rooms from `occupiedRooms`. + - If no available rooms, scheduled the meeting in the room with the earliest end time from `occupiedRooms`. + - Otherwise, scheduled the meeting in an available room from `availableRoomIds`. +- Updated the `meetingCount` array with the count of meetings booked for each room. +- Found the room with the maximum booked meetings and return its index. + +My approach ensured efficient tracking of occupied and available rooms, allowing for the determination of the most frequently booked room. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O(m*logm)$ + +$m$ : number of meetings +- Space complexity : $O(m)$ + + +# Code +``` +import java.util.Arrays; +import java.util.PriorityQueue; +import java.util.Queue; + +// Defining a class to represent a meeting with endTime and roomId +class Meeting { + public long endTime; + public int roomId; + + public Meeting(long endTime, int roomId) { + this.endTime = endTime; + this.roomId = roomId; + } +} + +// Class for meeting scheduling and finding the most booked room +class Solution { + + static Queue occupiedRooms; + static Queue availableRoomIds; + + // Method to find the most booked room + public int mostBooked(int numberOfRooms, int[][] meetings) { + + // Array to store the count of meetings booked for each room + int[] meetingCount = new int[numberOfRooms]; + + // Sorting meetings based on start time + Arrays.sort(meetings, (a, b) -> a[0] - b[0]); + + // Priority queue to store occupied rooms based on end time + occupiedRooms = new PriorityQueue<>((a, b) -> + a.endTime == b.endTime ? Integer.compare(a.roomId, b.roomId) : Long.compare(a.endTime, b.endTime)); + + // Priority queue to store available room IDs + availableRoomIds = new PriorityQueue<>(); + + // Initializing available room IDs + for (int i = 0; i < numberOfRooms; ++i) { + availableRoomIds.offer(i); + } + + // Processing each meeting + for (int[] meeting : meetings) { + final int start = meeting[0]; + final int end = meeting[1]; + + // Moving meetings ending before the current meeting to available rooms + while (!occupiedRooms.isEmpty() && occupiedRooms.peek().endTime <= start) { + availableRoomIds.offer(occupiedRooms.poll().roomId); + } + + // If no available room, scheduling the meeting in the room with the earliest end time + if (availableRoomIds.isEmpty()) { + Meeting prevMeeting = occupiedRooms.poll(); + ++meetingCount[prevMeeting.roomId]; + occupiedRooms.offer(new Meeting(prevMeeting.endTime + (end - start), prevMeeting.roomId)); + } + else { + // Scheduling the meeting in an available room + final int roomId = availableRoomIds.poll(); + ++meetingCount[roomId]; + occupiedRooms.offer(new Meeting(end, roomId)); + } + } + + // Finding the room with the maximum booked meetings + int maxIndex = 0; + for (int i = 0; i < numberOfRooms; ++i) { + if (meetingCount[i] > meetingCount[maxIndex]) { + maxIndex = i; + } + } + + return maxIndex; + } +} + +``` \ No newline at end of file From 5ab66d30d4f45b39d07266b1d369772f24f5eaa1 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 19 Feb 2024 10:22:42 +0530 Subject: [PATCH 167/300] Update README.md --- README.md | 124 ++++++++++++++---------------------------------------- 1 file changed, 31 insertions(+), 93 deletions(-) diff --git a/README.md b/README.md index 9df1b7b..a7478b2 100644 --- a/README.md +++ b/README.md @@ -4,121 +4,59 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 18-02-24 [Problem Link](https://leetcode.com/problems/meeting-rooms-iii/description/?envType=daily-question&envId=2024-02-18) -## 2402. Meeting Rooms III +## Today's 19-02-24 [Problem Link](https://leetcode.com/problems/power-of-two/description/?envType=daily-question&envId=2024-02-19) +## 231. Power of Twov # Intuition - -- To efficiently track the availability of rooms, I can use a priority queue to manage occupied rooms based on their end times. -- Additionally, I can use another priority queue to keep track of available room IDs. -- Sorting the meetings based on their start times will ensure that I process the meetings in chronological order. +The `isPowerOfTwo` method checks if a given number `n` is a power of two. If `n` is 1, it directly returns `true` as 1 is a power of two. Otherwise, I will call my helper method `recurse` to perform a recursive check. # Approach +- Base Case : If `n` is equal to 1, returned `true` as 1 is a power of two. +- Recursive Case : If `n` is not 1, called my `recurse` method to handle the recursive check. +- My Helper Method (`recurse`) : + - If `n` is 2, returned `true` as 2 is a power of two. + - If `n` is less than 2 or not divisible by 2, returned `false` as it is not a power of two. + - Recursively called the `recurse` method with `n/2`. -- I initialized an array to store the count of meetings booked for each room (`meetingCount`). -- Sorted the meetings based on their start times. -- Initialized a priority queue (`occupiedRooms`) to store occupied rooms based on end times. -- Initialized another priority queue (`availableRoomIds`) to store available room IDs. -- Populated the `availableRoomIds` priority queue with the initial room IDs. -- Processed each meeting in chronological order: - - Moved meetings ending before the current meeting to available rooms from `occupiedRooms`. - - If no available rooms, scheduled the meeting in the room with the earliest end time from `occupiedRooms`. - - Otherwise, scheduled the meeting in an available room from `availableRoomIds`. -- Updated the `meetingCount` array with the count of meetings booked for each room. -- Found the room with the maximum booked meetings and return its index. - -My approach ensured efficient tracking of occupied and available rooms, allowing for the determination of the most frequently booked room. +My approach utilized recursion to repeatedly check if the given number is divisible by 2 until reaching the base case of 2, which is a power of two. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(m*logm)$ +- Time complexity : $O(logn)$ -$m$ : number of meetings -- Space complexity : $O(m)$ +$n$ : given number +- Space complexity : $O(logn)$ # Code ``` -import java.util.Arrays; -import java.util.PriorityQueue; -import java.util.Queue; - -// Defining a class to represent a meeting with endTime and roomId -class Meeting { - public long endTime; - public int roomId; - - public Meeting(long endTime, int roomId) { - this.endTime = endTime; - this.roomId = roomId; - } -} - -// Class for meeting scheduling and finding the most booked room class Solution { - - static Queue occupiedRooms; - static Queue availableRoomIds; - // Method to find the most booked room - public int mostBooked(int numberOfRooms, int[][] meetings) { - - // Array to store the count of meetings booked for each room - int[] meetingCount = new int[numberOfRooms]; - - // Sorting meetings based on start time - Arrays.sort(meetings, (a, b) -> a[0] - b[0]); - - // Priority queue to store occupied rooms based on end time - occupiedRooms = new PriorityQueue<>((a, b) -> - a.endTime == b.endTime ? Integer.compare(a.roomId, b.roomId) : Long.compare(a.endTime, b.endTime)); - - // Priority queue to store available room IDs - availableRoomIds = new PriorityQueue<>(); - - // Initializing available room IDs - for (int i = 0; i < numberOfRooms; ++i) { - availableRoomIds.offer(i); - } - - // Processing each meeting - for (int[] meeting : meetings) { - final int start = meeting[0]; - final int end = meeting[1]; - - // Moving meetings ending before the current meeting to available rooms - while (!occupiedRooms.isEmpty() && occupiedRooms.peek().endTime <= start) { - availableRoomIds.offer(occupiedRooms.poll().roomId); - } - - // If no available room, scheduling the meeting in the room with the earliest end time - if (availableRoomIds.isEmpty()) { - Meeting prevMeeting = occupiedRooms.poll(); - ++meetingCount[prevMeeting.roomId]; - occupiedRooms.offer(new Meeting(prevMeeting.endTime + (end - start), prevMeeting.roomId)); - } - else { - // Scheduling the meeting in an available room - final int roomId = availableRoomIds.poll(); - ++meetingCount[roomId]; - occupiedRooms.offer(new Meeting(end, roomId)); - } + // Method to check if a number is a power of two + public boolean isPowerOfTwo(int n) { + // If n is 1, it is a power of two + if (n == 1) { + return true; } + // Otherwise, checking recursively + return recurse(n); + } - // Finding the room with the maximum booked meetings - int maxIndex = 0; - for (int i = 0; i < numberOfRooms; ++i) { - if (meetingCount[i] > meetingCount[maxIndex]) { - maxIndex = i; - } + // Recursive method to check if a number is a power of two + static boolean recurse(int n) { + // If n is 2, it is a power of two + if (n == 2) { + return true; + } else if (n < 2 || n % 2 != 0) { + // If n is less than 2 or not divisible by 2, it is not a power of two + return false; } - - return maxIndex; + // Recursively checking with n/2 + return recurse(n / 2); } } - ``` \ No newline at end of file From 066d08aabdafee8e95589d6b5f41982b93461422 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 19 Feb 2024 10:23:42 +0530 Subject: [PATCH 168/300] Create Daily 19-02-24.md --- 2024 February/Daily 19-02-24.md | 56 +++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 2024 February/Daily 19-02-24.md diff --git a/2024 February/Daily 19-02-24.md b/2024 February/Daily 19-02-24.md new file mode 100644 index 0000000..1eeaad8 --- /dev/null +++ b/2024 February/Daily 19-02-24.md @@ -0,0 +1,56 @@ +## Today's 19-02-24 [Problem Link](https://leetcode.com/problems/power-of-two/description/?envType=daily-question&envId=2024-02-19) +## 231. Power of Twov + +# Intuition + +The `isPowerOfTwo` method checks if a given number `n` is a power of two. If `n` is 1, it directly returns `true` as 1 is a power of two. Otherwise, I will call my helper method `recurse` to perform a recursive check. + +# Approach + +- Base Case : If `n` is equal to 1, returned `true` as 1 is a power of two. +- Recursive Case : If `n` is not 1, called my `recurse` method to handle the recursive check. +- My Helper Method (`recurse`) : + - If `n` is 2, returned `true` as 2 is a power of two. + - If `n` is less than 2 or not divisible by 2, returned `false` as it is not a power of two. + - Recursively called the `recurse` method with `n/2`. + +My approach utilized recursion to repeatedly check if the given number is divisible by 2 until reaching the base case of 2, which is a power of two. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O(logn)$ + +$n$ : given number +- Space complexity : $O(logn)$ + + +# Code +``` +class Solution { + + // Method to check if a number is a power of two + public boolean isPowerOfTwo(int n) { + // If n is 1, it is a power of two + if (n == 1) { + return true; + } + // Otherwise, checking recursively + return recurse(n); + } + + // Recursive method to check if a number is a power of two + static boolean recurse(int n) { + // If n is 2, it is a power of two + if (n == 2) { + return true; + } else if (n < 2 || n % 2 != 0) { + // If n is less than 2 or not divisible by 2, it is not a power of two + return false; + } + // Recursively checking with n/2 + return recurse(n / 2); + } +} +``` \ No newline at end of file From ee6885601c16661df5ded5f39a337bd4325c3dcd Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 19 Feb 2024 12:11:29 +0530 Subject: [PATCH 169/300] Update Daily 19-02-24.md --- 2024 February/Daily 19-02-24.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/2024 February/Daily 19-02-24.md b/2024 February/Daily 19-02-24.md index 1eeaad8..58ab21b 100644 --- a/2024 February/Daily 19-02-24.md +++ b/2024 February/Daily 19-02-24.md @@ -1,5 +1,5 @@ ## Today's 19-02-24 [Problem Link](https://leetcode.com/problems/power-of-two/description/?envType=daily-question&envId=2024-02-19) -## 231. Power of Twov +## 231. Power of Two # Intuition From 16658b9b982d96ee11bac289191760e4d5ec4159 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 19 Feb 2024 12:11:32 +0530 Subject: [PATCH 170/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a7478b2..0ac8027 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. ## Today's 19-02-24 [Problem Link](https://leetcode.com/problems/power-of-two/description/?envType=daily-question&envId=2024-02-19) -## 231. Power of Twov +## 231. Power of Two # Intuition From cde3097de97d884c22b0444e7e35d7c76297c72a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 20 Feb 2024 10:43:09 +0530 Subject: [PATCH 171/300] Update README.md --- README.md | 63 +++++++++++++++++++++++++++---------------------------- 1 file changed, 31 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 0ac8027..174bddc 100644 --- a/README.md +++ b/README.md @@ -4,59 +4,58 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 19-02-24 [Problem Link](https://leetcode.com/problems/power-of-two/description/?envType=daily-question&envId=2024-02-19) -## 231. Power of Two +## Today's 20-02-24 [Problem Link](https://leetcode.com/problems/missing-number/description/?envType=daily-question&envId=2024-02-20) +## 268. Missing Number # Intuition -The `isPowerOfTwo` method checks if a given number `n` is a power of two. If `n` is 1, it directly returns `true` as 1 is a power of two. Otherwise, I will call my helper method `recurse` to perform a recursive check. +The given task is to find the missing number in an array. # Approach -- Base Case : If `n` is equal to 1, returned `true` as 1 is a power of two. -- Recursive Case : If `n` is not 1, called my `recurse` method to handle the recursive check. -- My Helper Method (`recurse`) : - - If `n` is 2, returned `true` as 2 is a power of two. - - If `n` is less than 2 or not divisible by 2, returned `false` as it is not a power of two. - - Recursively called the `recurse` method with `n/2`. +- Cumulative Sum Calculation : + - A cumulative sum (`jor`) is maintained to keep track of the sum of elements in the array. This sum is calculated by iterating through each element in the array and adding it to the cumulative sum. -My approach utilized recursion to repeatedly check if the given number is divisible by 2 until reaching the base case of 2, which is a power of two. +- Expected Sum Calculation : + - The expected sum (`supposedSum`) is calculated based on the assumption that the array contains all numbers from 0 to `nums.length`. The formula used is `(nums.length * (nums.length + 1)) / 2`, representing the sum of an arithmetic series. + +- Finding the Missing Number : + - The missing number is determined by subtracting the cumulative sum (`jor`) from the expected sum (`supposedSum`). The result is then returned as the missing number in the array. + +My approach leverages the concept of arithmetic series to efficiently identify the missing element in the array. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(logn)$ +- Time complexity : $O(n)$ -$n$ : given number -- Space complexity : $O(logn)$ +$n$ : length of the input array `nums` +- Space complexity : $O(1)$ # Code ``` class Solution { - // Method to check if a number is a power of two - public boolean isPowerOfTwo(int n) { - // If n is 1, it is a power of two - if (n == 1) { - return true; - } - // Otherwise, checking recursively - return recurse(n); - } + // Static variable to store the cumulative sum + static int jor; - // Recursive method to check if a number is a power of two - static boolean recurse(int n) { - // If n is 2, it is a power of two - if (n == 2) { - return true; - } else if (n < 2 || n % 2 != 0) { - // If n is less than 2 or not divisible by 2, it is not a power of two - return false; + // Method to find the missing number in the array + public int missingNumber(int[] nums) { + // Initializing the cumulative sum to 0 + jor = 0; + + // Calculating the cumulative sum of the array elements + for (int i : nums) { + jor += i; } - // Recursively checking with n/2 - return recurse(n / 2); + + // Calculating the expected sum of all numbers from 0 to nums.length + int supposedSum = (nums.length * (nums.length + 1)) / 2; + + // Returning the difference between the expected sum and the actual sum + return supposedSum - jor; } } ``` \ No newline at end of file From 752199ea5d0b500aa1c69c42b536c3c506d1423a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 20 Feb 2024 10:44:38 +0530 Subject: [PATCH 172/300] Create Daily 20-02-24.md --- 2024 February/Daily 20-02-24.md | 55 +++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 2024 February/Daily 20-02-24.md diff --git a/2024 February/Daily 20-02-24.md b/2024 February/Daily 20-02-24.md new file mode 100644 index 0000000..78a256b --- /dev/null +++ b/2024 February/Daily 20-02-24.md @@ -0,0 +1,55 @@ +## Today's 20-02-24 [Problem Link](https://leetcode.com/problems/missing-number/description/?envType=daily-question&envId=2024-02-20) +## 268. Missing Number + +# Intuition + +The given task is to find the missing number in an array. + +# Approach + +- Cumulative Sum Calculation : + - A cumulative sum (`jor`) is maintained to keep track of the sum of elements in the array. This sum is calculated by iterating through each element in the array and adding it to the cumulative sum. + +- Expected Sum Calculation : + - The expected sum (`supposedSum`) is calculated based on the assumption that the array contains all numbers from 0 to `nums.length`. The formula used is `(nums.length * (nums.length + 1)) / 2`, representing the sum of an arithmetic series. + +- Finding the Missing Number : + - The missing number is determined by subtracting the cumulative sum (`jor`) from the expected sum (`supposedSum`). The result is then returned as the missing number in the array. + +My approach leverages the concept of arithmetic series to efficiently identify the missing element in the array. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the input array `nums` +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + + // Static variable to store the cumulative sum + static int jor; + + // Method to find the missing number in the array + public int missingNumber(int[] nums) { + // Initializing the cumulative sum to 0 + jor = 0; + + // Calculating the cumulative sum of the array elements + for (int i : nums) { + jor += i; + } + + // Calculating the expected sum of all numbers from 0 to nums.length + int supposedSum = (nums.length * (nums.length + 1)) / 2; + + // Returning the difference between the expected sum and the actual sum + return supposedSum - jor; + } +} +``` \ No newline at end of file From ffca9df6c960591ce3d7a63ffac186cef1d715f4 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 21 Feb 2024 12:43:16 +0530 Subject: [PATCH 173/300] Update README.md --- README.md | 60 +++++++++++++++++++++++++++---------------------------- 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 174bddc..8372bf2 100644 --- a/README.md +++ b/README.md @@ -4,58 +4,56 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 20-02-24 [Problem Link](https://leetcode.com/problems/missing-number/description/?envType=daily-question&envId=2024-02-20) -## 268. Missing Number +## Today's 21-02-24 [Problem Link](https://leetcode.com/problems/bitwise-and-of-numbers-range/description/?envType=daily-question&envId=2024-02-21) +## 201. Bitwise AND of Numbers Range # Intuition -The given task is to find the missing number in an array. +The goal of this problem is to calculate the bitwise AND of all the numbers in the given range [left, right]. + +Bitwise AND operation results in 1 only if both corresponding bits are 1. As we move from left to right in a binary representation of numbers, the common prefix of all numbers contributes to the result. Any differing bits will result in a 0 after the AND operation. # Approach -- Cumulative Sum Calculation : - - A cumulative sum (`jor`) is maintained to keep track of the sum of elements in the array. This sum is calculated by iterating through each element in the array and adding it to the cumulative sum. - -- Expected Sum Calculation : - - The expected sum (`supposedSum`) is calculated based on the assumption that the array contains all numbers from 0 to `nums.length`. The formula used is `(nums.length * (nums.length + 1)) / 2`, representing the sum of an arithmetic series. - -- Finding the Missing Number : - - The missing number is determined by subtracting the cumulative sum (`jor`) from the expected sum (`supposedSum`). The result is then returned as the missing number in the array. +- Initialized a variable `rs` (right shift) to 0 to keep track of the number of right shifts needed. +- Used a loop to continue right-shifting both `left` and `right` until they become equal. +- In each iteration, right shifted both `left` and `right` by 1 bit and incremented the `rs` counter. +- After the loop, performed a left shift on the final value of `left` by the count of right shifts (`rs`). +- Returned the result. -My approach leverages the concept of arithmetic series to efficiently identify the missing element in the array. +My idea was to identify the common prefix of all numbers in the range by iteratively right-shifting until `left` and `right` become equal. The count of right shifts is then used to left shift the common prefix to obtain the final result. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(logN)$ -$n$ : length of the input array `nums` +$N$ : maximum value between `left` and `right` - Space complexity : $O(1)$ # Code ``` class Solution { - - // Static variable to store the cumulative sum - static int jor; - - // Method to find the missing number in the array - public int missingNumber(int[] nums) { - // Initializing the cumulative sum to 0 - jor = 0; - - // Calculating the cumulative sum of the array elements - for (int i : nums) { - jor += i; - } - // Calculating the expected sum of all numbers from 0 to nums.length - int supposedSum = (nums.length * (nums.length + 1)) / 2; + // Method to perform bitwise AND operation on a range of numbers + public int rangeBitwiseAnd(int left, int right) { + + // Initializing a variable to track the number of right shifts + int rs = 0; + + // Continuing the loop until left and right become equal + while (left != right) { + // Right shifting both left and right by 1 bit + left >>= 1; + right >>= 1; + // Incrementing the count of right shifts + rs++; + } - // Returning the difference between the expected sum and the actual sum - return supposedSum - jor; + // Performing left shift on the final value of 'left' by the count of right shifts + return left << rs; } } ``` \ No newline at end of file From 7faed88195c04aa92a85605e87250566eabd1c93 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 21 Feb 2024 12:44:49 +0530 Subject: [PATCH 174/300] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8372bf2..c6b285e 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,9 @@ This is my attempt to make the coding experience easier for you guys so that you # Intuition -The goal of this problem is to calculate the bitwise AND of all the numbers in the given range [left, right]. +- The goal of this problem is to calculate the bitwise AND of all the numbers in the given range [left, right]. -Bitwise AND operation results in 1 only if both corresponding bits are 1. As we move from left to right in a binary representation of numbers, the common prefix of all numbers contributes to the result. Any differing bits will result in a 0 after the AND operation. +- Bitwise AND operation results in 1 only if both corresponding bits are 1. As we move from left to right in a binary representation of numbers, the common prefix of all numbers contributes to the result. Any differing bits will result in a 0 after the AND operation. # Approach From bb8bdbb289a9402e1306dcdd62da54d864eabf4a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 21 Feb 2024 12:45:16 +0530 Subject: [PATCH 175/300] Create Daily 21-02-24.md --- 2024 February/Daily 21-02-24.md | 53 +++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 2024 February/Daily 21-02-24.md diff --git a/2024 February/Daily 21-02-24.md b/2024 February/Daily 21-02-24.md new file mode 100644 index 0000000..2d14c5c --- /dev/null +++ b/2024 February/Daily 21-02-24.md @@ -0,0 +1,53 @@ +## Today's 21-02-24 [Problem Link](https://leetcode.com/problems/bitwise-and-of-numbers-range/description/?envType=daily-question&envId=2024-02-21) +## 201. Bitwise AND of Numbers Range + +# Intuition + +- The goal of this problem is to calculate the bitwise AND of all the numbers in the given range [left, right]. + +- Bitwise AND operation results in 1 only if both corresponding bits are 1. As we move from left to right in a binary representation of numbers, the common prefix of all numbers contributes to the result. Any differing bits will result in a 0 after the AND operation. + +# Approach + +- Initialized a variable `rs` (right shift) to 0 to keep track of the number of right shifts needed. +- Used a loop to continue right-shifting both `left` and `right` until they become equal. +- In each iteration, right shifted both `left` and `right` by 1 bit and incremented the `rs` counter. +- After the loop, performed a left shift on the final value of `left` by the count of right shifts (`rs`). +- Returned the result. + +My idea was to identify the common prefix of all numbers in the range by iteratively right-shifting until `left` and `right` become equal. The count of right shifts is then used to left shift the common prefix to obtain the final result. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O(logN)$ + +$N$ : maximum value between `left` and `right` +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + + // Method to perform bitwise AND operation on a range of numbers + public int rangeBitwiseAnd(int left, int right) { + + // Initializing a variable to track the number of right shifts + int rs = 0; + + // Continuing the loop until left and right become equal + while (left != right) { + // Right shifting both left and right by 1 bit + left >>= 1; + right >>= 1; + // Incrementing the count of right shifts + rs++; + } + + // Performing left shift on the final value of 'left' by the count of right shifts + return left << rs; + } +} +``` \ No newline at end of file From 3d2d09ac6e8a76ff0c8c896973dc07a2578f6258 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 22 Feb 2024 12:29:36 +0530 Subject: [PATCH 176/300] Update README.md --- README.md | 68 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index c6b285e..28d4c1f 100644 --- a/README.md +++ b/README.md @@ -4,56 +4,66 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 21-02-24 [Problem Link](https://leetcode.com/problems/bitwise-and-of-numbers-range/description/?envType=daily-question&envId=2024-02-21) -## 201. Bitwise AND of Numbers Range +## Today's 22+02=24 [Problem Link](https://leetcode.com/problems/find-the-town-judge/description/?envType=daily-question&envId=2024-02-22) +## 997. Find the Town Judge # Intuition -- The goal of this problem is to calculate the bitwise AND of all the numbers in the given range [left, right]. - -- Bitwise AND operation results in 1 only if both corresponding bits are 1. As we move from left to right in a binary representation of numbers, the common prefix of all numbers contributes to the result. Any differing bits will result in a 0 after the AND operation. +This problem aims to find the judge in a town based on trust relationships between the people. The judge is someone who is trusted by everyone else but does not trust anyone. # Approach -- Initialized a variable `rs` (right shift) to 0 to keep track of the number of right shifts needed. -- Used a loop to continue right-shifting both `left` and `right` until they become equal. -- In each iteration, right shifted both `left` and `right` by 1 bit and incremented the `rs` counter. -- After the loop, performed a left shift on the final value of `left` by the count of right shifts (`rs`). -- Returned the result. -My idea was to identify the common prefix of all numbers in the range by iteratively right-shifting until `left` and `right` become equal. The count of right shifts is then used to left shift the common prefix to obtain the final result. +**Initialized the Trust Counts Array :** Created an array to store the trust counts for each person. The array `a` will have a size of `n+1` to accommodate indices from 1 to n. + +**Updated the Trust Counts :** Iterated through the trust array and updated the trust counts in the array. Decreased the count for the person making the trust (outgoing trust) and increased the count for the person receiving the trust (incoming trust). + +**Found the Judge :** Iterated through the people (from 1 to n) and checked if a person has incoming trusts equal to (n - 1). If found, that person is considered the judge since the judge is trusted by everyone else and does not trust anyone. + +**Result :** If a judge is found, returned the person's index. If no judge is found, returned -1. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(logN)$ +- Time complexity : $O(N+E)$ -$N$ : maximum value between `left` and `right` -- Space complexity : $O(1)$ +$N$ : number of people +$E$ : number of trust relationships +- Space complexity : $O(N)$ # Code ``` class Solution { - // Method to perform bitwise AND operation on a range of numbers - public int rangeBitwiseAnd(int left, int right) { - - // Initializing a variable to track the number of right shifts - int rs = 0; - - // Continuing the loop until left and right become equal - while (left != right) { - // Right shifting both left and right by 1 bit - left >>= 1; - right >>= 1; - // Incrementing the count of right shifts - rs++; + // Creating a static array to store the trust counts for each person. + static int[] a; + + // Method to find the judge + public int findJudge(int n, int[][] trust) { + + // Initializing the array to store trust counts + a = new int[n + 1]; + + // Iterating through the trust array and update the trust counts in the array + for (int[] t : trust) { + // Decreasing the count for the person making the trust (outgoing trust) + a[t[0]]--; + // Increasing the count for the person receiving the trust (incoming trust) + a[t[1]]++; + } + + // Iterating through the people (1 to n) to find the judge + for (int i = 1; i <= n; i++) { + // If a person has incoming trusts equal to (n - 1), they are considered as the judge + if (a[i] == n - 1) { + return i; + } } - // Performing left shift on the final value of 'left' by the count of right shifts - return left << rs; + // If no judge is found, returning -1 + return -1; } } ``` \ No newline at end of file From 3110d59e2b5bcf9d0dfeeb8ffaa08d2f4beeccbf Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 22 Feb 2024 12:30:20 +0530 Subject: [PATCH 177/300] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 28d4c1f..227f2af 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ Have a look at the code , still have any confusion then please let me know in th - Time complexity : $O(N+E)$ $N$ : number of people + $E$ : number of trust relationships - Space complexity : $O(N)$ From bc37d9ac13c80ee3c99ced572e93ab6f7708be94 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 22 Feb 2024 12:30:52 +0530 Subject: [PATCH 178/300] Create Daily 22+02=24.md --- 2024 February/Daily 22+02=24.md | 64 +++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 2024 February/Daily 22+02=24.md diff --git a/2024 February/Daily 22+02=24.md b/2024 February/Daily 22+02=24.md new file mode 100644 index 0000000..8b79de2 --- /dev/null +++ b/2024 February/Daily 22+02=24.md @@ -0,0 +1,64 @@ +## Today's 22+02=24 [Problem Link](https://leetcode.com/problems/find-the-town-judge/description/?envType=daily-question&envId=2024-02-22) +## 997. Find the Town Judge + +# Intuition + +This problem aims to find the judge in a town based on trust relationships between the people. The judge is someone who is trusted by everyone else but does not trust anyone. + +# Approach + + +**Initialized the Trust Counts Array :** Created an array to store the trust counts for each person. The array `a` will have a size of `n+1` to accommodate indices from 1 to n. + +**Updated the Trust Counts :** Iterated through the trust array and updated the trust counts in the array. Decreased the count for the person making the trust (outgoing trust) and increased the count for the person receiving the trust (incoming trust). + +**Found the Judge :** Iterated through the people (from 1 to n) and checked if a person has incoming trusts equal to (n - 1). If found, that person is considered the judge since the judge is trusted by everyone else and does not trust anyone. + +**Result :** If a judge is found, returned the person's index. If no judge is found, returned -1. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O(N+E)$ + +$N$ : number of people + +$E$ : number of trust relationships +- Space complexity : $O(N)$ + + +# Code +``` +class Solution { + + // Creating a static array to store the trust counts for each person. + static int[] a; + + // Method to find the judge + public int findJudge(int n, int[][] trust) { + + // Initializing the array to store trust counts + a = new int[n + 1]; + + // Iterating through the trust array and update the trust counts in the array + for (int[] t : trust) { + // Decreasing the count for the person making the trust (outgoing trust) + a[t[0]]--; + // Increasing the count for the person receiving the trust (incoming trust) + a[t[1]]++; + } + + // Iterating through the people (1 to n) to find the judge + for (int i = 1; i <= n; i++) { + // If a person has incoming trusts equal to (n - 1), they are considered as the judge + if (a[i] == n - 1) { + return i; + } + } + + // If no judge is found, returning -1 + return -1; + } +} +``` \ No newline at end of file From e906308103f1a8b5e50345ff818135111c42815c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 23 Feb 2024 10:32:34 +0530 Subject: [PATCH 179/300] Update README.md --- README.md | 111 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 80 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 227f2af..6174466 100644 --- a/README.md +++ b/README.md @@ -4,66 +4,115 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 22+02=24 [Problem Link](https://leetcode.com/problems/find-the-town-judge/description/?envType=daily-question&envId=2024-02-22) -## 997. Find the Town Judge +## Today's 23-02-24 [Problem Link](https://leetcode.com/problems/cheapest-flights-within-k-stops/description/?envType=daily-question&envId=2024-02-23) +## 787. Cheapest Flights Within K Stops # Intuition -This problem aims to find the judge in a town based on trust relationships between the people. The judge is someone who is trusted by everyone else but does not trust anyone. +This problem involves finding the cheapest price to travel from a source city to a destination city with a constraint on the maximum number of stops allowed. This can be solved using Dijkstra's algorithm, which is a graph search algorithm that finds the shortest paths between nodes in a graph. # Approach +**Initialized the Graph :** + - Created an adjacency list to represent the graph, where each node contained a list of neighboring nodes and their corresponding weights. -**Initialized the Trust Counts Array :** Created an array to store the trust counts for each person. The array `a` will have a size of `n+1` to accommodate indices from 1 to n. +**Initialized the Data Structures :** + - Created a priority queue (minHeap) to store information about the current distance, current node, and remaining stops. + - Initialized a 2D array (`dist`) to store the minimum distances from the source to each node with a specific number of stops remaining. -**Updated the Trust Counts :** Iterated through the trust array and updated the trust counts in the array. Decreased the count for the person making the trust (outgoing trust) and increased the count for the person receiving the trust (incoming trust). +**Dijkstra's Algorithm :** + - Initialized the distance from the source to itself with the maximum number of stops allowed to be 0. + - Added the source node to the priority queue with the initial distance. + - Performed the main loop of Dijkstra's algorithm : + - Popped the node with the minimum distance from the priority queue. + - If the current node is the destination, returned the minimum cost. + - If the remaining stops are 0, skipped to the next iteration. + - Relaxation step : Updated the distances to neighbors and added them to the priority queue if a shorter path is found. -**Found the Judge :** Iterated through the people (from 1 to n) and checked if a person has incoming trusts equal to (n - 1). If found, that person is considered the judge since the judge is trusted by everyone else and does not trust anyone. - -**Result :** If a judge is found, returned the person's index. If no judge is found, returned -1. +**Result :** + - If the destination is not reachable within the allowed stops, returned -1. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(N+E)$ +- Time complexity : $O((V + E) * log(V))$ -$N$ : number of people +$V$ : number of nodes +$E$ : number of edges in the graph -$E$ : number of trust relationships -- Space complexity : $O(N)$ +- Space complexity : $ O(V + E)$ # Code ``` class Solution { - // Creating a static array to store the trust counts for each person. - static int[] a; + // Static variables for graph, minHeap, and distance matrix + static List>[] graph; + static Queue minHeap; + static int[][] dist; - // Method to find the judge - public int findJudge(int n, int[][] trust) { + // Main function to find the cheapest price using Dijkstra's algorithm + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { - // Initializing the array to store trust counts - a = new int[n + 1]; - - // Iterating through the trust array and update the trust counts in the array - for (int[] t : trust) { - // Decreasing the count for the person making the trust (outgoing trust) - a[t[0]]--; - // Increasing the count for the person receiving the trust (incoming trust) - a[t[1]]++; + // Initializing the graph as an adjacency list + graph = new List[n]; + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + // Populating the graph with flight information + for (int[] flight : flights) { + int u = flight[0]; + int v = flight[1]; + int w = flight[2]; + graph[u].add(new Pair<>(v, w)); } - // Iterating through the people (1 to n) to find the judge - for (int i = 1; i <= n; i++) { - // If a person has incoming trusts equal to (n - 1), they are considered as the judge - if (a[i] == n - 1) { - return i; + // Initializing the minHeap with a custom comparator for Dijkstra's algorithm + minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + + // Initializing the distance matrix with maximum values + dist = new int[graph.length][k + 2]; + for (int[] row : dist) + Arrays.fill(row, Integer.MAX_VALUE); + + // Setting the distance from source to source with k stops remaining to 0 + dist[src][k + 1] = 0; + minHeap.offer(new int[]{dist[src][k + 1], src, k + 1}); + + // Calling the helper function to perform Dijkstra's algorithm + return helperDijkstra(src, dst, k); + } + + // Helper function for Dijkstra's algorithm + private static int helperDijkstra(int src, int dst, int k) { + // Main loop for Dijkstra's algorithm + while (!minHeap.isEmpty()) { + int d = minHeap.peek()[0]; + int u = minHeap.peek()[1]; + int stops = minHeap.poll()[2]; + + // If the destination is reached, returning the minimum cost + if (u == dst) + return d; + + // If no more stops allowed, skipping to the next iteration + if (stops == 0) + continue; + + // Relaxation step - update distances to neighbors + for (Pair pair : graph[u]) { + int v = pair.getKey(); + int w = pair.getValue(); + if (d + w < dist[v][stops - 1]) { + dist[v][stops - 1] = d + w; + minHeap.offer(new int[]{dist[v][stops - 1], v, stops - 1}); + } } } - // If no judge is found, returning -1 + // If the destination is not reachable within allowed stops, returning -1 return -1; } } From 1e90df3dcb020f97714cd82cf8ed86c798b5d495 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 23 Feb 2024 10:33:05 +0530 Subject: [PATCH 180/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6174466..b41a477 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Have a look at the code , still have any confusion then please let me know in th $V$ : number of nodes $E$ : number of edges in the graph -- Space complexity : $ O(V + E)$ +- Space complexity : $O(V + E)$ # Code From 5b70958e5b419f47304626239a75376d8a3374c6 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 23 Feb 2024 10:33:48 +0530 Subject: [PATCH 181/300] Create Daily 23-02-24.md --- 2024 February/Daily 23-02-24.md | 113 ++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 2024 February/Daily 23-02-24.md diff --git a/2024 February/Daily 23-02-24.md b/2024 February/Daily 23-02-24.md new file mode 100644 index 0000000..875048a --- /dev/null +++ b/2024 February/Daily 23-02-24.md @@ -0,0 +1,113 @@ +## Today's 23-02-24 [Problem Link](https://leetcode.com/problems/cheapest-flights-within-k-stops/description/?envType=daily-question&envId=2024-02-23) +## 787. Cheapest Flights Within K Stops + +# Intuition + +This problem involves finding the cheapest price to travel from a source city to a destination city with a constraint on the maximum number of stops allowed. This can be solved using Dijkstra's algorithm, which is a graph search algorithm that finds the shortest paths between nodes in a graph. + +# Approach + +**Initialized the Graph :** + - Created an adjacency list to represent the graph, where each node contained a list of neighboring nodes and their corresponding weights. + +**Initialized the Data Structures :** + - Created a priority queue (minHeap) to store information about the current distance, current node, and remaining stops. + - Initialized a 2D array (`dist`) to store the minimum distances from the source to each node with a specific number of stops remaining. + +**Dijkstra's Algorithm :** + - Initialized the distance from the source to itself with the maximum number of stops allowed to be 0. + - Added the source node to the priority queue with the initial distance. + - Performed the main loop of Dijkstra's algorithm : + - Popped the node with the minimum distance from the priority queue. + - If the current node is the destination, returned the minimum cost. + - If the remaining stops are 0, skipped to the next iteration. + - Relaxation step : Updated the distances to neighbors and added them to the priority queue if a shorter path is found. + +**Result :** + - If the destination is not reachable within the allowed stops, returned -1. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O((V + E) * log(V))$ + +$V$ : number of nodes +$E$ : number of edges in the graph + +- Space complexity : $O(V + E)$ + + +# Code +``` +class Solution { + + // Static variables for graph, minHeap, and distance matrix + static List>[] graph; + static Queue minHeap; + static int[][] dist; + + // Main function to find the cheapest price using Dijkstra's algorithm + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { + + // Initializing the graph as an adjacency list + graph = new List[n]; + for (int i = 0; i < n; i++) + graph[i] = new ArrayList<>(); + + // Populating the graph with flight information + for (int[] flight : flights) { + int u = flight[0]; + int v = flight[1]; + int w = flight[2]; + graph[u].add(new Pair<>(v, w)); + } + + // Initializing the minHeap with a custom comparator for Dijkstra's algorithm + minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + + // Initializing the distance matrix with maximum values + dist = new int[graph.length][k + 2]; + for (int[] row : dist) + Arrays.fill(row, Integer.MAX_VALUE); + + // Setting the distance from source to source with k stops remaining to 0 + dist[src][k + 1] = 0; + minHeap.offer(new int[]{dist[src][k + 1], src, k + 1}); + + // Calling the helper function to perform Dijkstra's algorithm + return helperDijkstra(src, dst, k); + } + + // Helper function for Dijkstra's algorithm + private static int helperDijkstra(int src, int dst, int k) { + // Main loop for Dijkstra's algorithm + while (!minHeap.isEmpty()) { + int d = minHeap.peek()[0]; + int u = minHeap.peek()[1]; + int stops = minHeap.poll()[2]; + + // If the destination is reached, returning the minimum cost + if (u == dst) + return d; + + // If no more stops allowed, skipping to the next iteration + if (stops == 0) + continue; + + // Relaxation step - update distances to neighbors + for (Pair pair : graph[u]) { + int v = pair.getKey(); + int w = pair.getValue(); + if (d + w < dist[v][stops - 1]) { + dist[v][stops - 1] = d + w; + minHeap.offer(new int[]{dist[v][stops - 1], v, stops - 1}); + } + } + } + + // If the destination is not reachable within allowed stops, returning -1 + return -1; + } +} +``` \ No newline at end of file From 61f5252966539bace996de09ab0f9cbaa11ce1eb Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 24 Feb 2024 10:39:23 +0530 Subject: [PATCH 182/300] Update README.md --- README.md | 190 +++++++++++++++++++++++++++++------------------------- 1 file changed, 102 insertions(+), 88 deletions(-) diff --git a/README.md b/README.md index b41a477..d7941bf 100644 --- a/README.md +++ b/README.md @@ -4,116 +4,130 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 23-02-24 [Problem Link](https://leetcode.com/problems/cheapest-flights-within-k-stops/description/?envType=daily-question&envId=2024-02-23) -## 787. Cheapest Flights Within K Stops +## Today's 24-02-24 [Problem Link](https://leetcode.com/problems/find-all-people-with-secret/description/?envType=daily-question&envId=2024-02-24) +## 2092. Find All People With Secret # Intuition -This problem involves finding the cheapest price to travel from a source city to a destination city with a constraint on the maximum number of stops allowed. This can be solved using Dijkstra's algorithm, which is a graph search algorithm that finds the shortest paths between nodes in a graph. +**Disjoint Set** : I utilized the Disjoint Set (Union-Find) data structure to manage connected components. + +**Union by Rank** : Optimized union operations by merging sets based on their ranks. + +**Path Compression** : Enhanced find operations with path compression to shorten the path to the root. # Approach -**Initialized the Graph :** - - Created an adjacency list to represent the graph, where each node contained a list of neighboring nodes and their corresponding weights. +**Initialized the Disjoint Set** : I created a Disjoint Set to represent individual sets for each element. + +**Connected Initial Person** : Connected the specified initial person to the root of the disjoint set. + +**Organized the Meetings** : I sorted meetings by time using a TreeMap to process them chronologically. -**Initialized the Data Structures :** - - Created a priority queue (minHeap) to store information about the current distance, current node, and remaining stops. - - Initialized a 2D array (`dist`) to store the minimum distances from the source to each node with a specific number of stops remaining. +**Processed Meetings** : For each meeting, connected people in the disjoint set and reset unconnected nodes. -**Dijkstra's Algorithm :** - - Initialized the distance from the source to itself with the maximum number of stops allowed to be 0. - - Added the source node to the priority queue with the initial distance. - - Performed the main loop of Dijkstra's algorithm : - - Popped the node with the minimum distance from the priority queue. - - If the current node is the destination, returned the minimum cost. - - If the remaining stops are 0, skipped to the next iteration. - - Relaxation step : Updated the distances to neighbors and added them to the priority queue if a shorter path is found. +**Find Connected People** : Identified all people connected to the root of the disjoint set. -**Result :** - - If the destination is not reachable within the allowed stops, returned -1. +**Result** : Provided the list of people connected to the specified initial person. + +My approach ensured efficient management of connected components, enabling the identification of individuals connected to a given starting point. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) - # Complexity -- Time complexity : $O((V + E) * log(V))$ +- Time complexity : $O(m * log n)$ -$V$ : number of nodes -$E$ : number of edges in the graph - -- Space complexity : $O(V + E)$ +$m$ : number of meetings +$n$ : number of peoples +- Space complexity : $O(n + m)$ # Code ``` +// Implementation of Disjoint Set (Union-Find) data structure +class DisjointSet { + private int[] parent; + private int[] rank; + + // Constructor to initialize the disjoint set with individual sets for each element + public DisjointSet(int size) { + parent = new int[size]; + rank = new int[size]; + for (int i = 0; i < size; ++i) + parent[i] = i; + } + + // Union operation with rank optimization to merge sets + public void unionByRank(int u, int v) { + final int rootU = find(u); + final int rootV = find(v); + if (rootU == rootV) + return; + if (rank[rootU] < rank[rootV]) { + parent[rootU] = rootV; + } else if (rank[rootU] > rank[rootV]) { + parent[rootV] = rootU; + } else { + parent[rootU] = rootV; + ++rank[rootV]; + } + } + + // Find operation to determine the root of the set to which an element belongs + public boolean isConnected(int u, int v) { + return find(u) == find(v); + } + + // Resetting the parent of a node, useful for disconnecting nodes from a set + public void resetNode(int u) { + parent[u] = u; + } + + // Recursive find operation with path compression for efficient set determination + private int find(int u) { + return parent[u] == u ? u : (parent[u] = find(parent[u])); + } +} + +// Solution class that utilizes the DisjointSet to find all people connected to a specific person class Solution { - // Static variables for graph, minHeap, and distance matrix - static List>[] graph; - static Queue minHeap; - static int[][] dist; - - // Main function to find the cheapest price using Dijkstra's algorithm - public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { - - // Initializing the graph as an adjacency list - graph = new List[n]; - for (int i = 0; i < n; i++) - graph[i] = new ArrayList<>(); - - // Populating the graph with flight information - for (int[] flight : flights) { - int u = flight[0]; - int v = flight[1]; - int w = flight[2]; - graph[u].add(new Pair<>(v, w)); - } - - // Initializing the minHeap with a custom comparator for Dijkstra's algorithm - minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); - - // Initializing the distance matrix with maximum values - dist = new int[graph.length][k + 2]; - for (int[] row : dist) - Arrays.fill(row, Integer.MAX_VALUE); - - // Setting the distance from source to source with k stops remaining to 0 - dist[src][k + 1] = 0; - minHeap.offer(new int[]{dist[src][k + 1], src, k + 1}); - - // Calling the helper function to perform Dijkstra's algorithm - return helperDijkstra(src, dst, k); + // Method to find all people connected to a specific person based on meeting times + public List findAllPeople(int numOfPeople, int[][] meetings, int initialPerson) { + List result = new ArrayList<>(); + DisjointSet disjointSet = new DisjointSet(numOfPeople); + TreeMap>> timeToPairs = new TreeMap<>(); + + // Connecting the initial person to the root of the disjoint set + disjointSet.unionByRank(0, initialPerson); + + // Organizing meetings based on time + for (int[] meeting : meetings) { + timeToPairs.putIfAbsent(meeting[2], new ArrayList<>()); + timeToPairs.get(meeting[2]).add(new Pair<>(meeting[0], meeting[1])); } - // Helper function for Dijkstra's algorithm - private static int helperDijkstra(int src, int dst, int k) { - // Main loop for Dijkstra's algorithm - while (!minHeap.isEmpty()) { - int d = minHeap.peek()[0]; - int u = minHeap.peek()[1]; - int stops = minHeap.poll()[2]; - - // If the destination is reached, returning the minimum cost - if (u == dst) - return d; - - // If no more stops allowed, skipping to the next iteration - if (stops == 0) - continue; - - // Relaxation step - update distances to neighbors - for (Pair pair : graph[u]) { - int v = pair.getKey(); - int w = pair.getValue(); - if (d + w < dist[v][stops - 1]) { - dist[v][stops - 1] = d + w; - minHeap.offer(new int[]{dist[v][stops - 1], v, stops - 1}); - } - } - } - - // If the destination is not reachable within allowed stops, returning -1 - return -1; + // Processing meetings and connect people in the disjoint set + for (List> pairs : timeToPairs.values()) { + Set connectedPeople = new HashSet<>(); + for (Pair pair : pairs) { + final int personX = pair.getKey(); + final int personY = pair.getValue(); + disjointSet.unionByRank(personX, personY); + connectedPeople.add(personX); + connectedPeople.add(personY); + } + // Resetting nodes not connected to the root of the set + for (final int person : connectedPeople) + if (!disjointSet.isConnected(person, 0)) + disjointSet.resetNode(person); } + + // Finding all people connected to the root of the disjoint set + for (int i = 0; i < numOfPeople; ++i) + if (disjointSet.isConnected(i, 0)) + result.add(i); + + return result; + } } ``` \ No newline at end of file From d43afc8e0203c46629738721ccb0674751e63945 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 24 Feb 2024 10:57:46 +0530 Subject: [PATCH 183/300] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d7941bf..e5aaa40 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ Have a look at the code , still have any confusion then please let me know in th - Time complexity : $O(m * log n)$ $m$ : number of meetings + $n$ : number of peoples - Space complexity : $O(n + m)$ From 9e12116ec0089e46ef6e32dc2dfdd981d5e1e3a1 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 24 Feb 2024 10:58:16 +0530 Subject: [PATCH 184/300] Create Daily 24-02-24.md --- 2024 February/Daily 24-02-24.md | 128 ++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 2024 February/Daily 24-02-24.md diff --git a/2024 February/Daily 24-02-24.md b/2024 February/Daily 24-02-24.md new file mode 100644 index 0000000..f71617c --- /dev/null +++ b/2024 February/Daily 24-02-24.md @@ -0,0 +1,128 @@ +## Today's 24-02-24 [Problem Link](https://leetcode.com/problems/find-all-people-with-secret/description/?envType=daily-question&envId=2024-02-24) +## 2092. Find All People With Secret + +# Intuition + +**Disjoint Set** : I utilized the Disjoint Set (Union-Find) data structure to manage connected components. + +**Union by Rank** : Optimized union operations by merging sets based on their ranks. + +**Path Compression** : Enhanced find operations with path compression to shorten the path to the root. + +# Approach + +**Initialized the Disjoint Set** : I created a Disjoint Set to represent individual sets for each element. + +**Connected Initial Person** : Connected the specified initial person to the root of the disjoint set. + +**Organized the Meetings** : I sorted meetings by time using a TreeMap to process them chronologically. + +**Processed Meetings** : For each meeting, connected people in the disjoint set and reset unconnected nodes. + +**Find Connected People** : Identified all people connected to the root of the disjoint set. + +**Result** : Provided the list of people connected to the specified initial person. + +My approach ensured efficient management of connected components, enabling the identification of individuals connected to a given starting point. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(m * log n)$ + +$m$ : number of meetings + +$n$ : number of peoples +- Space complexity : $O(n + m)$ + + +# Code +``` +// Implementation of Disjoint Set (Union-Find) data structure +class DisjointSet { + private int[] parent; + private int[] rank; + + // Constructor to initialize the disjoint set with individual sets for each element + public DisjointSet(int size) { + parent = new int[size]; + rank = new int[size]; + for (int i = 0; i < size; ++i) + parent[i] = i; + } + + // Union operation with rank optimization to merge sets + public void unionByRank(int u, int v) { + final int rootU = find(u); + final int rootV = find(v); + if (rootU == rootV) + return; + if (rank[rootU] < rank[rootV]) { + parent[rootU] = rootV; + } else if (rank[rootU] > rank[rootV]) { + parent[rootV] = rootU; + } else { + parent[rootU] = rootV; + ++rank[rootV]; + } + } + + // Find operation to determine the root of the set to which an element belongs + public boolean isConnected(int u, int v) { + return find(u) == find(v); + } + + // Resetting the parent of a node, useful for disconnecting nodes from a set + public void resetNode(int u) { + parent[u] = u; + } + + // Recursive find operation with path compression for efficient set determination + private int find(int u) { + return parent[u] == u ? u : (parent[u] = find(parent[u])); + } +} + +// Solution class that utilizes the DisjointSet to find all people connected to a specific person +class Solution { + + // Method to find all people connected to a specific person based on meeting times + public List findAllPeople(int numOfPeople, int[][] meetings, int initialPerson) { + List result = new ArrayList<>(); + DisjointSet disjointSet = new DisjointSet(numOfPeople); + TreeMap>> timeToPairs = new TreeMap<>(); + + // Connecting the initial person to the root of the disjoint set + disjointSet.unionByRank(0, initialPerson); + + // Organizing meetings based on time + for (int[] meeting : meetings) { + timeToPairs.putIfAbsent(meeting[2], new ArrayList<>()); + timeToPairs.get(meeting[2]).add(new Pair<>(meeting[0], meeting[1])); + } + + // Processing meetings and connect people in the disjoint set + for (List> pairs : timeToPairs.values()) { + Set connectedPeople = new HashSet<>(); + for (Pair pair : pairs) { + final int personX = pair.getKey(); + final int personY = pair.getValue(); + disjointSet.unionByRank(personX, personY); + connectedPeople.add(personX); + connectedPeople.add(personY); + } + // Resetting nodes not connected to the root of the set + for (final int person : connectedPeople) + if (!disjointSet.isConnected(person, 0)) + disjointSet.resetNode(person); + } + + // Finding all people connected to the root of the disjoint set + for (int i = 0; i < numOfPeople; ++i) + if (disjointSet.isConnected(i, 0)) + result.add(i); + + return result; + } +} +``` \ No newline at end of file From a429ae32a0628ad5b2be96736f930fc5921cab3a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 27 Feb 2024 20:02:11 +0530 Subject: [PATCH 185/300] Update README.md --- README.md | 177 ++++++++++++++++++++++-------------------------------- 1 file changed, 72 insertions(+), 105 deletions(-) diff --git a/README.md b/README.md index e5aaa40..a8eb59b 100644 --- a/README.md +++ b/README.md @@ -4,131 +4,98 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 24-02-24 [Problem Link](https://leetcode.com/problems/find-all-people-with-secret/description/?envType=daily-question&envId=2024-02-24) -## 2092. Find All People With Secret +## Today's 27-02-24 [Problem Link](https://leetcode.com/problems/diameter-of-binary-tree/description/?envType=daily-question&envId=2024-02-27) +## 543. Diameter of Binary Tree # Intuition -**Disjoint Set** : I utilized the Disjoint Set (Union-Find) data structure to manage connected components. - -**Union by Rank** : Optimized union operations by merging sets based on their ranks. - -**Path Compression** : Enhanced find operations with path compression to shorten the path to the root. +The problem is to find the diameter of a binary tree, where the diameter is defined as the length of the longest path between any two nodes in a tree. The path may or may not pass through the root. # Approach -**Initialized the Disjoint Set** : I created a Disjoint Set to represent individual sets for each element. - -**Connected Initial Person** : Connected the specified initial person to the root of the disjoint set. - -**Organized the Meetings** : I sorted meetings by time using a TreeMap to process them chronologically. - -**Processed Meetings** : For each meeting, connected people in the disjoint set and reset unconnected nodes. +My code defined a `Solution` class with a static variable `maxDiameter` to store the maximum diameter encountered during traversal. -**Find Connected People** : Identified all people connected to the root of the disjoint set. +**Diameter Calculation Method (`diameterOfBinaryTree`) :** + - This method is the entry point for calculating the diameter of the binary tree. + - It resetted the `maxDiameter` variable to 0 before each calculation. + - Called the `calculateMaxDepth` method to perform the traversal and update the `maxDiameter`. + - Returned the final calculated diameter. -**Result** : Provided the list of people connected to the specified initial person. - -My approach ensured efficient management of connected components, enabling the identification of individuals connected to a given starting point. +**Depth Calculation Method (`calculateMaxDepth`) :** + - This method recursively calculated the maximum depth of the binary tree. + - Base Case : If the current node is null, return 0. + - Recursively calculated the maximum depth of the left and right subtrees. + - Updated `maxDiameter` if the sum of left and right depths is greater than the current `maxDiameter`. + - Returned the current node's depth (1 plus the maximum of left and right depths). --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(m * log n)$ +- Time complexity : $O(n)$ -$m$ : number of meetings - -$n$ : number of peoples -- Space complexity : $O(n + m)$ +$n$ : number of nodes in the binary tree +- Space complexity : $O(h)$ +$h$ : height of the binary tree # Code ``` -// Implementation of Disjoint Set (Union-Find) data structure -class DisjointSet { - private int[] parent; - private int[] rank; - - // Constructor to initialize the disjoint set with individual sets for each element - public DisjointSet(int size) { - parent = new int[size]; - rank = new int[size]; - for (int i = 0; i < size; ++i) - parent[i] = i; - } - - // Union operation with rank optimization to merge sets - public void unionByRank(int u, int v) { - final int rootU = find(u); - final int rootV = find(v); - if (rootU == rootV) - return; - if (rank[rootU] < rank[rootV]) { - parent[rootU] = rootV; - } else if (rank[rootU] > rank[rootV]) { - parent[rootV] = rootU; - } else { - parent[rootU] = rootV; - ++rank[rootV]; - } - } - - // Find operation to determine the root of the set to which an element belongs - public boolean isConnected(int u, int v) { - return find(u) == find(v); - } - - // Resetting the parent of a node, useful for disconnecting nodes from a set - public void resetNode(int u) { - parent[u] = u; - } - - // Recursive find operation with path compression for efficient set determination - private int find(int u) { - return parent[u] == u ? u : (parent[u] = find(parent[u])); - } -} - -// Solution class that utilizes the DisjointSet to find all people connected to a specific person +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ + +// Solution class for calculating the diameter of a binary tree. class Solution { - - // Method to find all people connected to a specific person based on meeting times - public List findAllPeople(int numOfPeople, int[][] meetings, int initialPerson) { - List result = new ArrayList<>(); - DisjointSet disjointSet = new DisjointSet(numOfPeople); - TreeMap>> timeToPairs = new TreeMap<>(); - - // Connecting the initial person to the root of the disjoint set - disjointSet.unionByRank(0, initialPerson); - - // Organizing meetings based on time - for (int[] meeting : meetings) { - timeToPairs.putIfAbsent(meeting[2], new ArrayList<>()); - timeToPairs.get(meeting[2]).add(new Pair<>(meeting[0], meeting[1])); + + // Static variable to store the maximum diameter. + static int maxDiameter = 0; + + /** + * Calculates the diameter of the binary tree. + * + * @param root The root of the binary tree. + * @return The diameter of the binary tree. + */ + public int diameterOfBinaryTree(TreeNode root) { + // Resetting the static variable before each calculation. + maxDiameter = 0; + calculateMaxDepth(root); + return maxDiameter; } - // Processing meetings and connect people in the disjoint set - for (List> pairs : timeToPairs.values()) { - Set connectedPeople = new HashSet<>(); - for (Pair pair : pairs) { - final int personX = pair.getKey(); - final int personY = pair.getValue(); - disjointSet.unionByRank(personX, personY); - connectedPeople.add(personX); - connectedPeople.add(personY); - } - // Resetting nodes not connected to the root of the set - for (final int person : connectedPeople) - if (!disjointSet.isConnected(person, 0)) - disjointSet.resetNode(person); + /** + * Calculates the maximum depth of the binary tree. + * + * @param node The current node in the binary tree. + * @return The maximum depth of the binary tree. + */ + static int calculateMaxDepth(TreeNode node) { + // Base case: if the node is null, return 0. + if (node == null) { + return 0; + } + + // Recursively calculating the maximum depth of the left and right subtrees. + int leftDepth = calculateMaxDepth(node.left); + int rightDepth = calculateMaxDepth(node.right); + + // Updating the maximum diameter if needed. + maxDiameter = Math.max(maxDiameter, leftDepth + rightDepth); + + // Returning the current node's depth. + return 1 + Math.max(leftDepth, rightDepth); } - - // Finding all people connected to the root of the disjoint set - for (int i = 0; i < numOfPeople; ++i) - if (disjointSet.isConnected(i, 0)) - result.add(i); - - return result; - } } ``` \ No newline at end of file From 801d62c187909ed6e265f4c0d1cf8f234c51eed0 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 27 Feb 2024 20:03:21 +0530 Subject: [PATCH 186/300] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a8eb59b..cf147d7 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. +### Sorry for past two days as I was offline completely. Now I'll remain regular. Thanks for your pateince. + ## Today's 27-02-24 [Problem Link](https://leetcode.com/problems/diameter-of-binary-tree/description/?envType=daily-question&envId=2024-02-27) ## 543. Diameter of Binary Tree From 250369bb68e9e88e9807d4992f3f3cafb731a01b Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 28 Feb 2024 14:28:46 +0530 Subject: [PATCH 187/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cf147d7..0516211 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -### Sorry for past two days as I was offline completely. Now I'll remain regular. Thanks for your pateince. +### Sorry for past two days as I was offline completely. Now I'll remain regular. Thanks for your patience. ## Today's 27-02-24 [Problem Link](https://leetcode.com/problems/diameter-of-binary-tree/description/?envType=daily-question&envId=2024-02-27) ## 543. Diameter of Binary Tree From 4652d0c61899c26f1ca068dff0baaaa2136f1add Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 28 Feb 2024 14:46:50 +0530 Subject: [PATCH 188/300] Update README.md --- README.md | 109 ++++++++++++++++++++++++------------------------------ 1 file changed, 48 insertions(+), 61 deletions(-) diff --git a/README.md b/README.md index 0516211..47f3530 100644 --- a/README.md +++ b/README.md @@ -4,41 +4,35 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -### Sorry for past two days as I was offline completely. Now I'll remain regular. Thanks for your patience. - -## Today's 27-02-24 [Problem Link](https://leetcode.com/problems/diameter-of-binary-tree/description/?envType=daily-question&envId=2024-02-27) -## 543. Diameter of Binary Tree +## Today's 28-02-24 [Problem Link](https://leetcode.com/problems/find-bottom-left-tree-value/description/?envType=daily-question&envId=2024-02-28) +## 513. Find Bottom Left Tree Value # Intuition -The problem is to find the diameter of a binary tree, where the diameter is defined as the length of the longest path between any two nodes in a tree. The path may or may not pass through the root. +To find the leftmost value in the bottom row of a binary tree, I can perform a level order traversal (BFS) of the tree. During the traversal, I keep updating a variable to store the leftmost node at each level. Once the traversal is complete, the variable will contain the leftmost node in the bottom row. # Approach -My code defined a `Solution` class with a static variable `maxDiameter` to store the maximum diameter encountered during traversal. - -**Diameter Calculation Method (`diameterOfBinaryTree`) :** - - This method is the entry point for calculating the diameter of the binary tree. - - It resetted the `maxDiameter` variable to 0 before each calculation. - - Called the `calculateMaxDepth` method to perform the traversal and update the `maxDiameter`. - - Returned the final calculated diameter. - -**Depth Calculation Method (`calculateMaxDepth`) :** - - This method recursively calculated the maximum depth of the binary tree. - - Base Case : If the current node is null, return 0. - - Recursively calculated the maximum depth of the left and right subtrees. - - Updated `maxDiameter` if the sum of left and right depths is greater than the current `maxDiameter`. - - Returned the current node's depth (1 plus the maximum of left and right depths). +- I initialized a variable (`leftMost`) to store the leftmost node. +- Used a queue to perform level order traversal. +- Enqueued the root of the tree. +- While the queue is not empty : + - Dequeued a node and update `leftMost` with its value. + - Enqueued the right child if it exists. + - Enqueued the left child if it exists. +- After the traversal, `leftMost` will contain the leftmost node in the bottom row. +- Returned the value of the leftmost node. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(N)$ -$n$ : number of nodes in the binary tree -- Space complexity : $O(h)$ +$N$ : number of nodes in the binary tree + +- Space complexity : $O(1)$ -$h$ : height of the binary tree # Code ``` @@ -57,47 +51,40 @@ $h$ : height of the binary tree * } * } */ - -// Solution class for calculating the diameter of a binary tree. class Solution { - // Static variable to store the maximum diameter. - static int maxDiameter = 0; - - /** - * Calculates the diameter of the binary tree. - * - * @param root The root of the binary tree. - * @return The diameter of the binary tree. - */ - public int diameterOfBinaryTree(TreeNode root) { - // Resetting the static variable before each calculation. - maxDiameter = 0; - calculateMaxDepth(root); - return maxDiameter; - } - - /** - * Calculates the maximum depth of the binary tree. - * - * @param node The current node in the binary tree. - * @return The maximum depth of the binary tree. - */ - static int calculateMaxDepth(TreeNode node) { - // Base case: if the node is null, return 0. - if (node == null) { - return 0; + // Static variable to store the leftmost node + static TreeNode leftMost; + + // Queue to perform level order traversal + static Queue q; + + // Method to find the leftmost value in the bottom row of the binary tree + public int findBottomLeftValue(TreeNode root) { + + // Initializing the leftMost and queue + leftMost = null; + q = new LinkedList<>(); + q.offer(root); + + // Performing level order traversal + while (!q.isEmpty()) { + // Retrieving the front node of the queue and update leftMost + leftMost = q.poll(); + + // Enqueueing the right child if it exists + if (leftMost.right != null) { + q.offer(leftMost.right); + } + + // Enqueueing the left child if it exists + if (leftMost.left != null) { + q.offer(leftMost.left); + } } - - // Recursively calculating the maximum depth of the left and right subtrees. - int leftDepth = calculateMaxDepth(node.left); - int rightDepth = calculateMaxDepth(node.right); - - // Updating the maximum diameter if needed. - maxDiameter = Math.max(maxDiameter, leftDepth + rightDepth); - - // Returning the current node's depth. - return 1 + Math.max(leftDepth, rightDepth); + + // Returning the value of the leftmost node in the bottom row + return leftMost.val; } } ``` \ No newline at end of file From 5ea26a52bf0cb00008ee10de27fb3fe860409677 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 28 Feb 2024 14:48:33 +0530 Subject: [PATCH 189/300] Create Daily 28-02-24.md --- 2024 February/Daily 28-02-24.md | 84 +++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 2024 February/Daily 28-02-24.md diff --git a/2024 February/Daily 28-02-24.md b/2024 February/Daily 28-02-24.md new file mode 100644 index 0000000..48c960e --- /dev/null +++ b/2024 February/Daily 28-02-24.md @@ -0,0 +1,84 @@ +## Today's 28-02-24 [Problem Link](https://leetcode.com/problems/find-bottom-left-tree-value/description/?envType=daily-question&envId=2024-02-28) +## 513. Find Bottom Left Tree Value + +# Intuition + +To find the leftmost value in the bottom row of a binary tree, I can perform a level order traversal (BFS) of the tree. During the traversal, I keep updating a variable to store the leftmost node at each level. Once the traversal is complete, the variable will contain the leftmost node in the bottom row. + +# Approach + +- I initialized a variable (`leftMost`) to store the leftmost node. +- Used a queue to perform level order traversal. +- Enqueued the root of the tree. +- While the queue is not empty : + - Dequeued a node and update `leftMost` with its value. + - Enqueued the right child if it exists. + - Enqueued the left child if it exists. +- After the traversal, `leftMost` will contain the leftmost node in the bottom row. +- Returned the value of the leftmost node. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O(N)$ + +$N$ : number of nodes in the binary tree + +- Space complexity : $O(1)$ + + +# Code +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + // Static variable to store the leftmost node + static TreeNode leftMost; + + // Queue to perform level order traversal + static Queue q; + + // Method to find the leftmost value in the bottom row of the binary tree + public int findBottomLeftValue(TreeNode root) { + + // Initializing the leftMost and queue + leftMost = null; + q = new LinkedList<>(); + q.offer(root); + + // Performing level order traversal + while (!q.isEmpty()) { + // Retrieving the front node of the queue and update leftMost + leftMost = q.poll(); + + // Enqueueing the right child if it exists + if (leftMost.right != null) { + q.offer(leftMost.right); + } + + // Enqueueing the left child if it exists + if (leftMost.left != null) { + q.offer(leftMost.left); + } + } + + // Returning the value of the leftmost node in the bottom row + return leftMost.val; + } +} +``` \ No newline at end of file From 9c3d7c02bf8f829eec04e2f6feb5260db372dc97 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 29 Feb 2024 09:45:51 +0530 Subject: [PATCH 190/300] Update README.md --- README.md | 128 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 88 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 47f3530..172aa51 100644 --- a/README.md +++ b/README.md @@ -4,34 +4,47 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 28-02-24 [Problem Link](https://leetcode.com/problems/find-bottom-left-tree-value/description/?envType=daily-question&envId=2024-02-28) -## 513. Find Bottom Left Tree Value +## Today's 29-02-24 [Problem Link](https://leetcode.com/problems/even-odd-tree/description/?envType=daily-question&envId=2024-02-29) +## 1609. Even Odd Tree # Intuition -To find the leftmost value in the bottom row of a binary tree, I can perform a level order traversal (BFS) of the tree. During the traversal, I keep updating a variable to store the leftmost node at each level. Once the traversal is complete, the variable will contain the leftmost node in the bottom row. +The problem requires determining whether a binary tree is an "Even-Odd Tree." An Even-Odd Tree is a binary tree where : + +- The values at each level alternate between odd and even. +- For each level, the values are strictly increasing from left to right. + +The task is to check if the given binary tree adheres to these conditions. # Approach -- I initialized a variable (`leftMost`) to store the leftmost node. -- Used a queue to perform level order traversal. -- Enqueued the root of the tree. -- While the queue is not empty : - - Dequeued a node and update `leftMost` with its value. - - Enqueued the right child if it exists. - - Enqueued the left child if it exists. -- After the traversal, `leftMost` will contain the leftmost node in the bottom row. -- Returned the value of the leftmost node. +To solve this problem, I can use a level-order traversal (breadth-first search) of the binary tree. I will maintain a queue to process nodes level by level. At each level, I just need to check if the conditions for an Even-Odd Tree are satisfied. ---- -Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +**Initialize the queue and level flag :** I started by adding the root node to the queue and set the initial level flag to even. + +**Level-Order Traversal :** Used a loop to process each level of the tree. Inside the loop: + - Checked if the current level is valid using a helper function. + - Toggled the level flag (odd to even or even to odd) for the next level. + - Continued until the queue is empty. +**Helper Function (isValidLevel) :** This function is responsible for checking if the current level adheres to the Even-Odd Tree conditions. It performed the following steps : + - Initialized the previous value based on whether the level is odd or even. + - Iterated through the nodes at the current level. + - Checked if the values violate the conditions (e.g., odd values on even levels, even values on odd levels). + - Updated the previous value for the next iteration. + - Enqueued the left and right children if they exist. + +**Result :** If all levels passed the validation, returned true, indicating that the binary tree is an Even-Odd Tree; otherwise, returned false. + +My approach ensured a systematic examination of each level, verifying the required conditions at each step. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:)v # Complexity - Time complexity : $O(N)$ $N$ : number of nodes in the binary tree - -- Space complexity : $O(1)$ +- Space complexity : $O(N/2)$ ${\equiv}$ $O(N)$ # Code @@ -51,40 +64,75 @@ $N$ : number of nodes in the binary tree * } * } */ + class Solution { - - // Static variable to store the leftmost node - static TreeNode leftMost; - - // Queue to perform level order traversal + + // Global queue to perform level-order traversal static Queue q; - // Method to find the leftmost value in the bottom row of the binary tree - public int findBottomLeftValue(TreeNode root) { - - // Initializing the leftMost and queue - leftMost = null; + // Flag to keep track of odd or even level + static boolean oddlevel; + + public boolean isEvenOddTree(TreeNode root) { + // Checking if the root is null + if (root == null) { + return false; + } + + // Initializing the queue with the root q = new LinkedList<>(); q.offer(root); - // Performing level order traversal + // Starting with even level + oddlevel = false; + + // Performing level-order traversal while (!q.isEmpty()) { - // Retrieving the front node of the queue and update leftMost - leftMost = q.poll(); - - // Enqueueing the right child if it exists - if (leftMost.right != null) { - q.offer(leftMost.right); + // Checking if the level is valid + if (!isValidLevel()) { + return false; } - - // Enqueueing the left child if it exists - if (leftMost.left != null) { - q.offer(leftMost.left); + + // Toggle to the next level + oddlevel = !oddlevel; + } + + // If all levels are valid, returning true + return true; + } + + // Helper function to check if the current level is valid + static boolean isValidLevel() { + // Initialize the previous value based on odd or even level + int prevValue = oddlevel ? Integer.MAX_VALUE : Integer.MIN_VALUE; + + // Iterating through the current level + for (int s = q.size(); s > 0; s--) { + // Polling the front of the queue + TreeNode t = q.poll(); + + // Checking if the value violates the conditions based on odd or even level + if (oddlevel && (t.val % 2 != 0 || t.val >= prevValue)) { + return false; + } + if (!oddlevel && (t.val % 2 == 0 || t.val <= prevValue)) { + return false; + } + + // Updating the previous value + prevValue = t.val; + + // Enqueuing the left and right children if they exist + if (t.left != null) { + q.offer(t.left); + } + if (t.right != null) { + q.offer(t.right); } } - - // Returning the value of the leftmost node in the bottom row - return leftMost.val; + + // The level is valid + return true; } } ``` \ No newline at end of file From 71da4da80d5d032e9179b700d109739cbda3cc7d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 29 Feb 2024 09:46:55 +0530 Subject: [PATCH 191/300] Create Daily 29-02-24.md --- 2024 February/Daily 29-02-24.md | 132 ++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 2024 February/Daily 29-02-24.md diff --git a/2024 February/Daily 29-02-24.md b/2024 February/Daily 29-02-24.md new file mode 100644 index 0000000..9974c5a --- /dev/null +++ b/2024 February/Daily 29-02-24.md @@ -0,0 +1,132 @@ +## Today's 29-02-24 [Problem Link](https://leetcode.com/problems/even-odd-tree/description/?envType=daily-question&envId=2024-02-29) +## 1609. Even Odd Tree + +# Intuition + +The problem requires determining whether a binary tree is an "Even-Odd Tree." An Even-Odd Tree is a binary tree where : + +- The values at each level alternate between odd and even. +- For each level, the values are strictly increasing from left to right. + +The task is to check if the given binary tree adheres to these conditions. + +# Approach + +To solve this problem, I can use a level-order traversal (breadth-first search) of the binary tree. I will maintain a queue to process nodes level by level. At each level, I just need to check if the conditions for an Even-Odd Tree are satisfied. + +**Initialize the queue and level flag :** I started by adding the root node to the queue and set the initial level flag to even. + +**Level-Order Traversal :** Used a loop to process each level of the tree. Inside the loop: + - Checked if the current level is valid using a helper function. + - Toggled the level flag (odd to even or even to odd) for the next level. + - Continued until the queue is empty. + +**Helper Function (isValidLevel) :** This function is responsible for checking if the current level adheres to the Even-Odd Tree conditions. It performed the following steps : + - Initialized the previous value based on whether the level is odd or even. + - Iterated through the nodes at the current level. + - Checked if the values violate the conditions (e.g., odd values on even levels, even values on odd levels). + - Updated the previous value for the next iteration. + - Enqueued the left and right children if they exist. + +**Result :** If all levels passed the validation, returned true, indicating that the binary tree is an Even-Odd Tree; otherwise, returned false. + +My approach ensured a systematic examination of each level, verifying the required conditions at each step. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:)v +# Complexity +- Time complexity : $O(N)$ + +$N$ : number of nodes in the binary tree +- Space complexity : $O(N/2)$ ${\equiv}$ $O(N)$ + + +# Code +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ + +class Solution { + + // Global queue to perform level-order traversal + static Queue q; + + // Flag to keep track of odd or even level + static boolean oddlevel; + + public boolean isEvenOddTree(TreeNode root) { + // Checking if the root is null + if (root == null) { + return false; + } + + // Initializing the queue with the root + q = new LinkedList<>(); + q.offer(root); + + // Starting with even level + oddlevel = false; + + // Performing level-order traversal + while (!q.isEmpty()) { + // Checking if the level is valid + if (!isValidLevel()) { + return false; + } + + // Toggle to the next level + oddlevel = !oddlevel; + } + + // If all levels are valid, returning true + return true; + } + + // Helper function to check if the current level is valid + static boolean isValidLevel() { + // Initialize the previous value based on odd or even level + int prevValue = oddlevel ? Integer.MAX_VALUE : Integer.MIN_VALUE; + + // Iterating through the current level + for (int s = q.size(); s > 0; s--) { + // Polling the front of the queue + TreeNode t = q.poll(); + + // Checking if the value violates the conditions based on odd or even level + if (oddlevel && (t.val % 2 != 0 || t.val >= prevValue)) { + return false; + } + if (!oddlevel && (t.val % 2 == 0 || t.val <= prevValue)) { + return false; + } + + // Updating the previous value + prevValue = t.val; + + // Enqueuing the left and right children if they exist + if (t.left != null) { + q.offer(t.left); + } + if (t.right != null) { + q.offer(t.right); + } + } + + // The level is valid + return true; + } +} +``` \ No newline at end of file From 5ba01015aa1f445386358fd3e1db2d77eae950fb Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 1 Mar 2024 12:00:04 +0530 Subject: [PATCH 192/300] Update README.md --- README.md | 148 ++++++++++++++++++------------------------------------ 1 file changed, 48 insertions(+), 100 deletions(-) diff --git a/README.md b/README.md index 172aa51..e90e400 100644 --- a/README.md +++ b/README.md @@ -4,135 +4,83 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 29-02-24 [Problem Link](https://leetcode.com/problems/even-odd-tree/description/?envType=daily-question&envId=2024-02-29) -## 1609. Even Odd Tree +## Today's 01-03-24 [Problem Link](https://leetcode.com/problems/maximum-odd-binary-number/description/?envType=daily-question&envId=2024-03-01) +## 2864. Maximum Odd Binary Number # Intuition -The problem requires determining whether a binary tree is an "Even-Odd Tree." An Even-Odd Tree is a binary tree where : +The goal of the code is to find the maximum odd binary number based on the input binary string `s`. The approach involves counting the number of '1's in the input string and constructing a new binary string accordingly. -- The values at each level alternate between odd and even. -- For each level, the values are strictly increasing from left to right. - -The task is to check if the given binary tree adheres to these conditions. # Approach -To solve this problem, I can use a level-order traversal (breadth-first search) of the binary tree. I will maintain a queue to process nodes level by level. At each level, I just need to check if the conditions for an Even-Odd Tree are satisfied. - -**Initialize the queue and level flag :** I started by adding the root node to the queue and set the initial level flag to even. -**Level-Order Traversal :** Used a loop to process each level of the tree. Inside the loop: - - Checked if the current level is valid using a helper function. - - Toggled the level flag (odd to even or even to odd) for the next level. - - Continued until the queue is empty. +**Counted '1's :** + - Initialized a static variable `ones` to count the number of '1's. + - Iterated through each character in the input string `s`. + - If the character is '1', incremented the `ones` count. -**Helper Function (isValidLevel) :** This function is responsible for checking if the current level adheres to the Even-Odd Tree conditions. It performed the following steps : - - Initialized the previous value based on whether the level is odd or even. - - Iterated through the nodes at the current level. - - Checked if the values violate the conditions (e.g., odd values on even levels, even values on odd levels). - - Updated the previous value for the next iteration. - - Enqueued the left and right children if they exist. +**Constructed the Result String :** + - Initialized an empty string `jawab` to store the result. + - Added ('1's - 1) times '1' to the result string. + - Added ('0's - 1) times '0' to the result string. + - If there is at least one '1' in the input string, added a final '1' to the result. -**Result :** If all levels passed the validation, returned true, indicating that the binary tree is an Even-Odd Tree; otherwise, returned false. +**Result :** + - The constructed string `jawab` represents the maximum odd binary number. + - Returned the result string. -My approach ensured a systematic examination of each level, verifying the required conditions at each step. +My code ensures that the resulting binary number is odd by including a final '1' in the string. The approach efficiently constructs the result based on the count of '1's in the input string. --- -Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:)v +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(N)$ +- Time complexity : $O(s)$ -$N$ : number of nodes in the binary tree -- Space complexity : $O(N/2)$ ${\equiv}$ $O(N)$ +$s$ : length of the input string +- Space complexity : $O(s)$ # Code ``` -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ - class Solution { - - // Global queue to perform level-order traversal - static Queue q; - - // Flag to keep track of odd or even level - static boolean oddlevel; - public boolean isEvenOddTree(TreeNode root) { - // Checking if the root is null - if (root == null) { - return false; - } - - // Initializing the queue with the root - q = new LinkedList<>(); - q.offer(root); - - // Starting with even level - oddlevel = false; - - // Performing level-order traversal - while (!q.isEmpty()) { - // Checking if the level is valid - if (!isValidLevel()) { - return false; + // Static variable to count the number of '1's in the input string + static int ones; + + // Method to find the maximum odd binary number + public String maximumOddBinaryNumber(String s) { + + // Initializing the count of '1's + ones = 0; + + // Counting the number of '1's in the input string + for (char c : s.toCharArray()) { + if (c == '1') { + ones++; } - - // Toggle to the next level - oddlevel = !oddlevel; } - // If all levels are valid, returning true - return true; - } - - // Helper function to check if the current level is valid - static boolean isValidLevel() { - // Initialize the previous value based on odd or even level - int prevValue = oddlevel ? Integer.MAX_VALUE : Integer.MIN_VALUE; - - // Iterating through the current level - for (int s = q.size(); s > 0; s--) { - // Polling the front of the queue - TreeNode t = q.poll(); + // Initializing an empty string to store the result + String jawab = ""; - // Checking if the value violates the conditions based on odd or even level - if (oddlevel && (t.val % 2 != 0 || t.val >= prevValue)) { - return false; - } - if (!oddlevel && (t.val % 2 == 0 || t.val <= prevValue)) { - return false; - } + // Adding '1's to the result string (ones - 1) times + for (int i = 0; i < ones - 1; i++) { + jawab += '1'; + } - // Updating the previous value - prevValue = t.val; + // Adding '0's to the result string (s.length() - ones) times + for (int i = 0; i < s.length() - ones; i++) { + jawab += '0'; + } - // Enqueuing the left and right children if they exist - if (t.left != null) { - q.offer(t.left); - } - if (t.right != null) { - q.offer(t.right); - } + // If there is at least one '1' in the input string, adding a final '1' + if (ones > 0) { + jawab += '1'; } - // The level is valid - return true; + // Returning the result string + return jawab; } } ``` \ No newline at end of file From 1eb32b12a67140099ee161a3d8a6e62da1456593 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 1 Mar 2024 12:01:24 +0530 Subject: [PATCH 193/300] Create Daily 01-03-24.md --- 2024 March/Daily 01-03-24.md | 80 ++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 2024 March/Daily 01-03-24.md diff --git a/2024 March/Daily 01-03-24.md b/2024 March/Daily 01-03-24.md new file mode 100644 index 0000000..517dca3 --- /dev/null +++ b/2024 March/Daily 01-03-24.md @@ -0,0 +1,80 @@ +## Today's 01-03-24 [Problem Link](https://leetcode.com/problems/maximum-odd-binary-number/description/?envType=daily-question&envId=2024-03-01) +## 2864. Maximum Odd Binary Number + +# Intuition + +The goal of the code is to find the maximum odd binary number based on the input binary string `s`. The approach involves counting the number of '1's in the input string and constructing a new binary string accordingly. + + +# Approach + + +**Counted '1's :** + - Initialized a static variable `ones` to count the number of '1's. + - Iterated through each character in the input string `s`. + - If the character is '1', incremented the `ones` count. + +**Constructed the Result String :** + - Initialized an empty string `jawab` to store the result. + - Added ('1's - 1) times '1' to the result string. + - Added ('0's - 1) times '0' to the result string. + - If there is at least one '1' in the input string, added a final '1' to the result. + +**Result :** + - The constructed string `jawab` represents the maximum odd binary number. + - Returned the result string. + +My code ensures that the resulting binary number is odd by including a final '1' in the string. The approach efficiently constructs the result based on the count of '1's in the input string. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(s)$ + +$s$ : length of the input string +- Space complexity : $O(s)$ + + +# Code +``` +class Solution { + + // Static variable to count the number of '1's in the input string + static int ones; + + // Method to find the maximum odd binary number + public String maximumOddBinaryNumber(String s) { + + // Initializing the count of '1's + ones = 0; + + // Counting the number of '1's in the input string + for (char c : s.toCharArray()) { + if (c == '1') { + ones++; + } + } + + // Initializing an empty string to store the result + String jawab = ""; + + // Adding '1's to the result string (ones - 1) times + for (int i = 0; i < ones - 1; i++) { + jawab += '1'; + } + + // Adding '0's to the result string (s.length() - ones) times + for (int i = 0; i < s.length() - ones; i++) { + jawab += '0'; + } + + // If there is at least one '1' in the input string, adding a final '1' + if (ones > 0) { + jawab += '1'; + } + + // Returning the result string + return jawab; + } +} +``` \ No newline at end of file From c221e417ba93aeb7c72c3518f20c14bcc22e7381 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 2 Mar 2024 17:38:00 +0530 Subject: [PATCH 194/300] Update README.md --- README.md | 97 ++++++++++++++++++++++++++----------------------------- 1 file changed, 45 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index e90e400..dcc88a1 100644 --- a/README.md +++ b/README.md @@ -4,83 +4,76 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 01-03-24 [Problem Link](https://leetcode.com/problems/maximum-odd-binary-number/description/?envType=daily-question&envId=2024-03-01) -## 2864. Maximum Odd Binary Number +## Today's 02-03-24 [Problem Link](https://leetcode.com/problems/squares-of-a-sorted-array/description/?envType=daily-question&envId=2024-03-02) +## 977. Squares of a Sorted Array # Intuition -The goal of the code is to find the maximum odd binary number based on the input binary string `s`. The approach involves counting the number of '1's in the input string and constructing a new binary string accordingly. - +The given code aims to calculate the sorted squares of an array of integers. It uses a two-pointer approach to efficiently process the input array and produce the result array containing the squares in sorted order. # Approach +- Initialize variables: + - `size`: Get the size of the input array. + - `result`: Initialize an array to store the sorted squares. + - `index`: Initialize an index to populate the result array in reverse order. + +- Two-pointer traversal : + - Use two pointers, `left` starting from the beginning and `right` starting from the end of the array. + - Compare the absolute values of elements at `left` and `right` pointers. -**Counted '1's :** - - Initialized a static variable `ones` to count the number of '1's. - - Iterated through each character in the input string `s`. - - If the character is '1', incremented the `ones` count. +- Square and store : + - If the absolute value at `left` is greater, square it and store it in the `result` array at the specified `index`. + - If the absolute value at `right` is greater, square it and store it in the `result` array at the specified `index`. -**Constructed the Result String :** - - Initialized an empty string `jawab` to store the result. - - Added ('1's - 1) times '1' to the result string. - - Added ('0's - 1) times '0' to the result string. - - If there is at least one '1' in the input string, added a final '1' to the result. +- Move pointers : + - Adjust the pointers (`left` or `right`) based on the comparison. -**Result :** - - The constructed string `jawab` represents the maximum odd binary number. - - Returned the result string. +- Repeat until traversal is complete. -My code ensures that the resulting binary number is odd by including a final '1' in the string. The approach efficiently constructs the result based on the count of '1's in the input string. +- Return the `result` array containing the sorted squares. + +My approach ensures that the result array is populated with sorted squares in a time-efficient manner, utilizing the two-pointer technique. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + # Complexity -- Time complexity : $O(s)$ +- Time complexity : $O(N)$ -$s$ : length of the input string -- Space complexity : $O(s)$ +$N$ : size of the input array +- Space complexity : $O(N)$ # Code ``` class Solution { - - // Static variable to count the number of '1's in the input string - static int ones; - // Method to find the maximum odd binary number - public String maximumOddBinaryNumber(String s) { + // Method to calculate sorted squares of input numbers + public int[] sortedSquares(int[] nums) { + // Getting the size of the input array + final int size = nums.length; - // Initializing the count of '1's - ones = 0; - - // Counting the number of '1's in the input string - for (char c : s.toCharArray()) { - if (c == '1') { - ones++; + // Initializing an array to store the result + int[] result = new int[size]; + + // Initializing an index for storing results in reverse order + int index = size - 1; + + // Looping through the input array using two pointers (left and right) + for (int left = 0, right = size - 1; left <= right;) { + // Comparing the absolute values of numbers at left and right pointers + if (Math.abs(nums[left]) > Math.abs(nums[right])) { + // If the absolute value at left is greater, squaring it and storing in result + result[index--] = nums[left] * nums[left++]; + } else { + // If the absolute value at right is greater, squaring it and storing in result + result[index--] = nums[right] * nums[right--]; } } - // Initializing an empty string to store the result - String jawab = ""; - - // Adding '1's to the result string (ones - 1) times - for (int i = 0; i < ones - 1; i++) { - jawab += '1'; - } - - // Adding '0's to the result string (s.length() - ones) times - for (int i = 0; i < s.length() - ones; i++) { - jawab += '0'; - } - - // If there is at least one '1' in the input string, adding a final '1' - if (ones > 0) { - jawab += '1'; - } - - // Returning the result string - return jawab; + // Returning the array containing sorted squares + return result; } } ``` \ No newline at end of file From 57eb012bc0cb9eea05cdc49a77e8b64dfb8dc9b4 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 2 Mar 2024 17:39:10 +0530 Subject: [PATCH 195/300] Create Daily 02-03-24.md --- 2024 March/Daily 02-03-24.md | 73 ++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 2024 March/Daily 02-03-24.md diff --git a/2024 March/Daily 02-03-24.md b/2024 March/Daily 02-03-24.md new file mode 100644 index 0000000..05995bf --- /dev/null +++ b/2024 March/Daily 02-03-24.md @@ -0,0 +1,73 @@ +## Today's 02-03-24 [Problem Link](https://leetcode.com/problems/squares-of-a-sorted-array/description/?envType=daily-question&envId=2024-03-02) +## 977. Squares of a Sorted Array + +# Intuition + +The given code aims to calculate the sorted squares of an array of integers. It uses a two-pointer approach to efficiently process the input array and produce the result array containing the squares in sorted order. + +# Approach + +- Initialize variables: + - `size`: Get the size of the input array. + - `result`: Initialize an array to store the sorted squares. + - `index`: Initialize an index to populate the result array in reverse order. + +- Two-pointer traversal : + - Use two pointers, `left` starting from the beginning and `right` starting from the end of the array. + - Compare the absolute values of elements at `left` and `right` pointers. + +- Square and store : + - If the absolute value at `left` is greater, square it and store it in the `result` array at the specified `index`. + - If the absolute value at `right` is greater, square it and store it in the `result` array at the specified `index`. + +- Move pointers : + - Adjust the pointers (`left` or `right`) based on the comparison. + +- Repeat until traversal is complete. + +- Return the `result` array containing the sorted squares. + +My approach ensures that the result array is populated with sorted squares in a time-efficient manner, utilizing the two-pointer technique. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O(N)$ + +$N$ : size of the input array +- Space complexity : $O(N)$ + + +# Code +``` +class Solution { + + // Method to calculate sorted squares of input numbers + public int[] sortedSquares(int[] nums) { + // Getting the size of the input array + final int size = nums.length; + + // Initializing an array to store the result + int[] result = new int[size]; + + // Initializing an index for storing results in reverse order + int index = size - 1; + + // Looping through the input array using two pointers (left and right) + for (int left = 0, right = size - 1; left <= right;) { + // Comparing the absolute values of numbers at left and right pointers + if (Math.abs(nums[left]) > Math.abs(nums[right])) { + // If the absolute value at left is greater, squaring it and storing in result + result[index--] = nums[left] * nums[left++]; + } else { + // If the absolute value at right is greater, squaring it and storing in result + result[index--] = nums[right] * nums[right--]; + } + } + + // Returning the array containing sorted squares + return result; + } +} +``` \ No newline at end of file From dee1cbca93a38f6b007a1aab69e6af059413f76d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 3 Mar 2024 09:34:33 +0530 Subject: [PATCH 196/300] Update README.md --- README.md | 93 ++++++++++++++++++++++++++----------------------------- 1 file changed, 44 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index dcc88a1..79230d7 100644 --- a/README.md +++ b/README.md @@ -4,76 +4,71 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 02-03-24 [Problem Link](https://leetcode.com/problems/squares-of-a-sorted-array/description/?envType=daily-question&envId=2024-03-02) -## 977. Squares of a Sorted Array +## Today's 03=03-24 [Problem Link](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/?envType=daily-question&envId=2024-03-03) +## 19. Remove Nth Node From End of List # Intuition -The given code aims to calculate the sorted squares of an array of integers. It uses a two-pointer approach to efficiently process the input array and produce the result array containing the squares in sorted order. +The goal is to remove the Nth node from the end of a singly-linked list. # Approach -- Initialize variables: - - `size`: Get the size of the input array. - - `result`: Initialize an array to store the sorted squares. - - `index`: Initialize an index to populate the result array in reverse order. +- I initialized two pointers, `l` and `skip`, both pointing to the head of the linked list. +- Moved the `skip` pointer N nodes ahead. If it becomes null during this process, it means the length of the linked list is exactly N. In this case, return `head.next` as we need to remove the head. +- Moved both pointers until the `skip` pointer reaches the end of the linked list. +- Updated the `next` pointer of the node pointed by `l` to skip the Nth node from the end. +- Returned the modified head of the linked list.. -- Two-pointer traversal : - - Use two pointers, `left` starting from the beginning and `right` starting from the end of the array. - - Compare the absolute values of elements at `left` and `right` pointers. - -- Square and store : - - If the absolute value at `left` is greater, square it and store it in the `result` array at the specified `index`. - - If the absolute value at `right` is greater, square it and store it in the `result` array at the specified `index`. - -- Move pointers : - - Adjust the pointers (`left` or `right`) based on the comparison. - -- Repeat until traversal is complete. - -- Return the `result` array containing the sorted squares. - -My approach ensures that the result array is populated with sorted squares in a time-efficient manner, utilizing the two-pointer technique. +My approach utilized two pointers to efficiently find and remove the Nth node from the end of the linked list. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) - # Complexity - Time complexity : $O(N)$ -$N$ : size of the input array -- Space complexity : $O(N)$ + +- Space complexity : $o(1)$ # Code ``` +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ class Solution { - - // Method to calculate sorted squares of input numbers - public int[] sortedSquares(int[] nums) { - // Getting the size of the input array - final int size = nums.length; - - // Initializing an array to store the result - int[] result = new int[size]; - - // Initializing an index for storing results in reverse order - int index = size - 1; - - // Looping through the input array using two pointers (left and right) - for (int left = 0, right = size - 1; left <= right;) { - // Comparing the absolute values of numbers at left and right pointers - if (Math.abs(nums[left]) > Math.abs(nums[right])) { - // If the absolute value at left is greater, squaring it and storing in result - result[index--] = nums[left] * nums[left++]; - } else { - // If the absolute value at right is greater, squaring it and storing in result - result[index--] = nums[right] * nums[right--]; + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode l = head; // Initializing a pointer 'l' to the head of the linked list + ListNode skip = head; // Initializing a pointer 'skip' to the head of the linked list to track the skipped parts + + // Moving 'skip' pointer n nodes ahead + for (int i = 0; i < n; i++) { + skip = skip.next; + + // If 'skip' becomes null, it means the length of the linked list is exactly n, + // and I need to remove the head. Return head.next in this case. + if (skip == null) { + return head.next; } } - // Returning the array containing sorted squares - return result; + // Move both pointers until 'skip' reaches the end of the linked list + while (skip.next != null) { + skip = skip.next; + l = l.next; + } + + // Removing the nth node from the end by updating the 'next' pointer of the node before it + l.next = l.next.next; + + // Returning the modified head of the linked list + return head; } } ``` \ No newline at end of file From e03f28d33599351a527e08b77c10de66f700d0f2 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 3 Mar 2024 09:35:10 +0530 Subject: [PATCH 197/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 79230d7..2b55180 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Have a look at the code , still have any confusion then please let me know in th - Time complexity : $O(N)$ -- Space complexity : $o(1)$ +- Space complexity : $O(1)$ # Code From 485eabb1161a5976636bc8422a8af2b955075be0 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 3 Mar 2024 09:35:34 +0530 Subject: [PATCH 198/300] Create Daily 03-03-24.md --- 2024 March/Daily 03-03-24.md | 68 ++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 2024 March/Daily 03-03-24.md diff --git a/2024 March/Daily 03-03-24.md b/2024 March/Daily 03-03-24.md new file mode 100644 index 0000000..5f6d42d --- /dev/null +++ b/2024 March/Daily 03-03-24.md @@ -0,0 +1,68 @@ +## Today's 03=03-24 [Problem Link](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/?envType=daily-question&envId=2024-03-03) +## 19. Remove Nth Node From End of List + +# Intuition + +The goal is to remove the Nth node from the end of a singly-linked list. + +# Approach + +- I initialized two pointers, `l` and `skip`, both pointing to the head of the linked list. +- Moved the `skip` pointer N nodes ahead. If it becomes null during this process, it means the length of the linked list is exactly N. In this case, return `head.next` as we need to remove the head. +- Moved both pointers until the `skip` pointer reaches the end of the linked list. +- Updated the `next` pointer of the node pointed by `l` to skip the Nth node from the end. +- Returned the modified head of the linked list.. + +My approach utilized two pointers to efficiently find and remove the Nth node from the end of the linked list. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(N)$ + + +- Space complexity : $O(1)$ + + +# Code +``` +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode l = head; // Initializing a pointer 'l' to the head of the linked list + ListNode skip = head; // Initializing a pointer 'skip' to the head of the linked list to track the skipped parts + + // Moving 'skip' pointer n nodes ahead + for (int i = 0; i < n; i++) { + skip = skip.next; + + // If 'skip' becomes null, it means the length of the linked list is exactly n, + // and I need to remove the head. Return head.next in this case. + if (skip == null) { + return head.next; + } + } + + // Move both pointers until 'skip' reaches the end of the linked list + while (skip.next != null) { + skip = skip.next; + l = l.next; + } + + // Removing the nth node from the end by updating the 'next' pointer of the node before it + l.next = l.next.next; + + // Returning the modified head of the linked list + return head; + } +} +``` \ No newline at end of file From 0e0bda4e9c5173980faefb595605addf716df6d2 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 4 Mar 2024 10:13:32 +0530 Subject: [PATCH 199/300] Update README.md --- README.md | 86 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 44 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 2b55180..63fc08f 100644 --- a/README.md +++ b/README.md @@ -4,71 +4,73 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 03=03-24 [Problem Link](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/?envType=daily-question&envId=2024-03-03) -## 19. Remove Nth Node From End of List +## Today's 04-03-24 [Problem Link](https://leetcode.com/problems/bag-of-tokens/description/?envType=daily-question&envId=2024-03-04) +## 948. Bag of Tokens # Intuition -The goal is to remove the Nth node from the end of a singly-linked list. +The goal of this algorithm is to calculate the maximum score that can be obtained from a bag of tokens, given the initial power. The idea is to strategically play the tokens to maximize the score. # Approach -- I initialized two pointers, `l` and `skip`, both pointing to the head of the linked list. -- Moved the `skip` pointer N nodes ahead. If it becomes null during this process, it means the length of the linked list is exactly N. In this case, return `head.next` as we need to remove the head. -- Moved both pointers until the `skip` pointer reaches the end of the linked list. -- Updated the `next` pointer of the node pointed by `l` to skip the Nth node from the end. -- Returned the modified head of the linked list.. +**Sorting** : I sorted the array of tokens in ascending order. This allowed me to consider the smallest tokens first, making the algorithm more efficient. -My approach utilized two pointers to efficiently find and remove the Nth node from the end of the linked list. +**Two Pointers** : Used two pointers, `leftIndex` and `rightIndex`, initially pointing to the smallest and largest tokens, respectively. + +**Token Play Loop** : Iterated through the tokens while considering the available power and the current score. Play tokens in a way to maximize the score : + + - Played the smallest face up (increment `leftIndex`) if there's enough power. + + - Updated the maximum score if needed. + + - Played the largest face down (decrement `rightIndex`) if there's still score to be used. + +**Result** : The final result is the maximum score obtained from the bag of tokens. + +My algorithm ensured efficient utilization of power and strategic playing of tokens to achieve the maximum possible score.x --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + # Complexity -- Time complexity : $O(N)$ +- Time complexity: -- Space complexity : $O(1)$ +- Space complexity: # Code ``` -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ class Solution { - public ListNode removeNthFromEnd(ListNode head, int n) { - ListNode l = head; // Initializing a pointer 'l' to the head of the linked list - ListNode skip = head; // Initializing a pointer 'skip' to the head of the linked list to track the skipped parts + + // Method to calculate the maximum score for a given set of tokens and initial power + public int bagOfTokensScore(int[] tokens, int power) { + int maxScore = 0; // Variable to store the maximum score + int currentScore = 0; // Variable to track the current score + int leftIndex = 0; // Index of the smallest token + int rightIndex = tokens.length - 1; // Index of the largest token - // Moving 'skip' pointer n nodes ahead - for (int i = 0; i < n; i++) { - skip = skip.next; + Arrays.sort(tokens); // Sorting the tokens in ascending order + + // Iterating through the tokens while considering the power and score + while (leftIndex <= rightIndex && (power >= tokens[leftIndex] || currentScore > 0)) { + // Playing the smallest face up as long as there is enough power + while (leftIndex <= rightIndex && power >= tokens[leftIndex]) { + power -= tokens[leftIndex++]; + ++currentScore; + } + // Updating the maximum score + maxScore = Math.max(maxScore, currentScore); - // If 'skip' becomes null, it means the length of the linked list is exactly n, - // and I need to remove the head. Return head.next in this case. - if (skip == null) { - return head.next; + // Playing the largest face down if there's still score to be used + if (leftIndex <= rightIndex && currentScore > 0) { + power += tokens[rightIndex--]; + --currentScore; } } - // Move both pointers until 'skip' reaches the end of the linked list - while (skip.next != null) { - skip = skip.next; - l = l.next; - } - - // Removing the nth node from the end by updating the 'next' pointer of the node before it - l.next = l.next.next; - - // Returning the modified head of the linked list - return head; + // Returning the calculated maximum score + return maxScore; } } ``` \ No newline at end of file From 2ea3302304e0fa052b16c898c6dfa41162a02217 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 4 Mar 2024 10:15:16 +0530 Subject: [PATCH 200/300] Update README.md --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index 63fc08f..273c020 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,14 @@ +# 🌟 Today is 4 🌟 + +A very auspicious day for me. Some dates are etched in the heart, and for me, 4 is that magical day. Words fall short in expressing the depth of gratitude I feel towards the divine for this profound emotion. + +📖 It's a humble request to all you amazing souls reading my repository : + +Life is a journey filled with highs and lows, moments of joy and instances of pain. Embrace every facet, for each contributes to the beautiful tapestry of existence. Remember who you are and maintain unwavering faith in yourself, just as I do. + +🚀 Enjoy exploring my solution and keep the coding spirit alive! Happy coding! ✨ + + # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. From 4b7f0f3e861b8ff9cb5b30773c52885a420bfc23 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 4 Mar 2024 10:15:58 +0530 Subject: [PATCH 201/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 273c020..5c88f91 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ A very auspicious day for me. Some dates are etched in the heart, and for me, 4 Life is a journey filled with highs and lows, moments of joy and instances of pain. Embrace every facet, for each contributes to the beautiful tapestry of existence. Remember who you are and maintain unwavering faith in yourself, just as I do. -🚀 Enjoy exploring my solution and keep the coding spirit alive! Happy coding! ✨ +🚀 Enjoy exploring my solution and keep the coding spirit alive! Happy coding ! ✨ # Leetcode Daily Challenge Solutions From 018efd6e866162b9b461179f47ab8e8d00475a66 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 4 Mar 2024 10:16:24 +0530 Subject: [PATCH 202/300] Create Daily 04-03-24.md --- 2024 March/Daily 04-03-24.md | 80 ++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 2024 March/Daily 04-03-24.md diff --git a/2024 March/Daily 04-03-24.md b/2024 March/Daily 04-03-24.md new file mode 100644 index 0000000..910f561 --- /dev/null +++ b/2024 March/Daily 04-03-24.md @@ -0,0 +1,80 @@ +# 🌟 Today is 4 🌟 + +A very auspicious day for me. Some dates are etched in the heart, and for me, 4 is that magical day. Words fall short in expressing the depth of gratitude I feel towards the divine for this profound emotion. + +📖 It's a humble request to all you amazing souls reading my repository : + +Life is a journey filled with highs and lows, moments of joy and instances of pain. Embrace every facet, for each contributes to the beautiful tapestry of existence. Remember who you are and maintain unwavering faith in yourself, just as I do. + +🚀 Enjoy exploring my solution and keep the coding spirit alive! Happy coding ! ✨ + +## Today's 04-03-24 [Problem Link](https://leetcode.com/problems/bag-of-tokens/description/?envType=daily-question&envId=2024-03-04) +## 948. Bag of Tokens + +# Intuition + +The goal of this algorithm is to calculate the maximum score that can be obtained from a bag of tokens, given the initial power. The idea is to strategically play the tokens to maximize the score. + +# Approach + +**Sorting** : I sorted the array of tokens in ascending order. This allowed me to consider the smallest tokens first, making the algorithm more efficient. + +**Two Pointers** : Used two pointers, `leftIndex` and `rightIndex`, initially pointing to the smallest and largest tokens, respectively. + +**Token Play Loop** : Iterated through the tokens while considering the available power and the current score. Play tokens in a way to maximize the score : + + - Played the smallest face up (increment `leftIndex`) if there's enough power. + + - Updated the maximum score if needed. + + - Played the largest face down (decrement `rightIndex`) if there's still score to be used. + +**Result** : The final result is the maximum score obtained from the bag of tokens. + +My algorithm ensured efficient utilization of power and strategic playing of tokens to achieve the maximum possible score.x + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity: + + +- Space complexity: + + +# Code +``` +class Solution { + + // Method to calculate the maximum score for a given set of tokens and initial power + public int bagOfTokensScore(int[] tokens, int power) { + int maxScore = 0; // Variable to store the maximum score + int currentScore = 0; // Variable to track the current score + int leftIndex = 0; // Index of the smallest token + int rightIndex = tokens.length - 1; // Index of the largest token + + Arrays.sort(tokens); // Sorting the tokens in ascending order + + // Iterating through the tokens while considering the power and score + while (leftIndex <= rightIndex && (power >= tokens[leftIndex] || currentScore > 0)) { + // Playing the smallest face up as long as there is enough power + while (leftIndex <= rightIndex && power >= tokens[leftIndex]) { + power -= tokens[leftIndex++]; + ++currentScore; + } + // Updating the maximum score + maxScore = Math.max(maxScore, currentScore); + + // Playing the largest face down if there's still score to be used + if (leftIndex <= rightIndex && currentScore > 0) { + power += tokens[rightIndex--]; + --currentScore; + } + } + + // Returning the calculated maximum score + return maxScore; + } +} +``` \ No newline at end of file From 1b72e21e2df944cb05160d653e336b8b28641189 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 5 Mar 2024 16:20:49 +0530 Subject: [PATCH 203/300] Update README.md --- README.md | 100 ++++++++++++++++++++++-------------------------------- 1 file changed, 41 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 5c88f91..828e65e 100644 --- a/README.md +++ b/README.md @@ -1,87 +1,69 @@ -# 🌟 Today is 4 🌟 - -A very auspicious day for me. Some dates are etched in the heart, and for me, 4 is that magical day. Words fall short in expressing the depth of gratitude I feel towards the divine for this profound emotion. - -📖 It's a humble request to all you amazing souls reading my repository : - -Life is a journey filled with highs and lows, moments of joy and instances of pain. Embrace every facet, for each contributes to the beautiful tapestry of existence. Remember who you are and maintain unwavering faith in yourself, just as I do. - -🚀 Enjoy exploring my solution and keep the coding spirit alive! Happy coding ! ✨ - - # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. ## Always here to assist you guys. -## Today's 04-03-24 [Problem Link](https://leetcode.com/problems/bag-of-tokens/description/?envType=daily-question&envId=2024-03-04) -## 948. Bag of Tokens +## Today's 05-03-24 [Problem Link](https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/description/?envType=daily-question&envId=2024-03-05) +## 1750. Minimum Length of String After Deleting Similar Ends # Intuition -The goal of this algorithm is to calculate the maximum score that can be obtained from a bag of tokens, given the initial power. The idea is to strategically play the tokens to maximize the score. +The goal is to find the minimum length of a string after repeatedly removing the same character from both ends until the string is no longer symmetric. # Approach -**Sorting** : I sorted the array of tokens in ascending order. This allowed me to consider the smallest tokens first, making the algorithm more efficient. - -**Two Pointers** : Used two pointers, `leftIndex` and `rightIndex`, initially pointing to the smallest and largest tokens, respectively. - -**Token Play Loop** : Iterated through the tokens while considering the available power and the current score. Play tokens in a way to maximize the score : +- I initialized two pointers, `leftIdx` and `rightIdx`, at the beginning and end of the string, respectively. +- Used a while loop to iterate while `leftIdx` is less than `rightIdx` and the characters at these indices are equal. +- Inside the loop : + - Stored the current character at `leftIdx` in the variable `currentChar`. + - Moved `leftIdx` to the right until a different character is encountered. + - Moved `rightIdx` to the left until a different character is encountered. +- Calculated and return the length of the remaining string by subtracting `leftIdx` from `rightIdx` and adding 1. - - Played the smallest face up (increment `leftIndex`) if there's enough power. - - - Updated the maximum score if needed. - - - Played the largest face down (decrement `rightIndex`) if there's still score to be used. - -**Result** : The final result is the maximum score obtained from the bag of tokens. - -My algorithm ensured efficient utilization of power and strategic playing of tokens to achieve the maximum possible score.x +My algorithm efficiently reduced the length of the string by removing symmetric characters from both ends until no more symmetric characters are found. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity: +- Time complexity : $O(s)$ - -- Space complexity: +$s$ : length of the input string +- Space complexity : $O(1)$ # Code ``` class Solution { - // Method to calculate the maximum score for a given set of tokens and initial power - public int bagOfTokensScore(int[] tokens, int power) { - int maxScore = 0; // Variable to store the maximum score - int currentScore = 0; // Variable to track the current score - int leftIndex = 0; // Index of the smallest token - int rightIndex = tokens.length - 1; // Index of the largest token - - Arrays.sort(tokens); // Sorting the tokens in ascending order - - // Iterating through the tokens while considering the power and score - while (leftIndex <= rightIndex && (power >= tokens[leftIndex] || currentScore > 0)) { - // Playing the smallest face up as long as there is enough power - while (leftIndex <= rightIndex && power >= tokens[leftIndex]) { - power -= tokens[leftIndex++]; - ++currentScore; - } - // Updating the maximum score - maxScore = Math.max(maxScore, currentScore); - - // Playing the largest face down if there's still score to be used - if (leftIndex <= rightIndex && currentScore > 0) { - power += tokens[rightIndex--]; - --currentScore; - } - } - - // Returning the calculated maximum score - return maxScore; + // Method to find the minimum length + public int minimumLength(String s) { + // Initialize two pointers, leftIdx and rightIdx + int leftIdx = 0; + int rightIdx = s.length() - 1; + + // Iterating while the leftIdx is less than rightIdx and characters at these indices are equal + while (leftIdx < rightIdx && s.charAt(leftIdx) == s.charAt(rightIdx)) { + + // Storing the current character + final char currentChar = s.charAt(leftIdx); + + // Moving leftIdx to the right until a different character is encountered + while (leftIdx <= rightIdx && s.charAt(leftIdx) == currentChar){ + leftIdx++; + } + + // Moving rightIdx to the left until a different character is encountered + while (leftIdx <= rightIdx && s.charAt(rightIdx) == currentChar){ + rightIdx--; + } + } + + // Returning the calculated minimum length + return rightIdx - leftIdx + 1; + } } + ``` \ No newline at end of file From 1245630737685e79d995864e78d777333897692a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 5 Mar 2024 16:22:03 +0530 Subject: [PATCH 204/300] Create Daily 05-03-24.md --- 2024 March/Daily 05-03-24.md | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 2024 March/Daily 05-03-24.md diff --git a/2024 March/Daily 05-03-24.md b/2024 March/Daily 05-03-24.md new file mode 100644 index 0000000..750b705 --- /dev/null +++ b/2024 March/Daily 05-03-24.md @@ -0,0 +1,63 @@ +## Today's 05-03-24 [Problem Link](https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/description/?envType=daily-question&envId=2024-03-05) +## 1750. Minimum Length of String After Deleting Similar Ends + +# Intuition + +The goal is to find the minimum length of a string after repeatedly removing the same character from both ends until the string is no longer symmetric. + +# Approach + +- I initialized two pointers, `leftIdx` and `rightIdx`, at the beginning and end of the string, respectively. +- Used a while loop to iterate while `leftIdx` is less than `rightIdx` and the characters at these indices are equal. +- Inside the loop : + - Stored the current character at `leftIdx` in the variable `currentChar`. + - Moved `leftIdx` to the right until a different character is encountered. + - Moved `rightIdx` to the left until a different character is encountered. +- Calculated and return the length of the remaining string by subtracting `leftIdx` from `rightIdx` and adding 1. + +My algorithm efficiently reduced the length of the string by removing symmetric characters from both ends until no more symmetric characters are found. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O(s)$ + +$s$ : length of the input string +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + + // Method to find the minimum length + public int minimumLength(String s) { + // Initialize two pointers, leftIdx and rightIdx + int leftIdx = 0; + int rightIdx = s.length() - 1; + + // Iterating while the leftIdx is less than rightIdx and characters at these indices are equal + while (leftIdx < rightIdx && s.charAt(leftIdx) == s.charAt(rightIdx)) { + + // Storing the current character + final char currentChar = s.charAt(leftIdx); + + // Moving leftIdx to the right until a different character is encountered + while (leftIdx <= rightIdx && s.charAt(leftIdx) == currentChar){ + leftIdx++; + } + + // Moving rightIdx to the left until a different character is encountered + while (leftIdx <= rightIdx && s.charAt(rightIdx) == currentChar){ + rightIdx--; + } + + } + + // Returning the calculated minimum length + return rightIdx - leftIdx + 1; + } +} + +``` \ No newline at end of file From c97b1e3a74c4c50f4d4a4765ff15016ac6f72fad Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 6 Mar 2024 09:10:06 +0530 Subject: [PATCH 205/300] Update README.md --- README.md | 107 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 65 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 828e65e..f5003a7 100644 --- a/README.md +++ b/README.md @@ -4,66 +4,89 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 05-03-24 [Problem Link](https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/description/?envType=daily-question&envId=2024-03-05) -## 1750. Minimum Length of String After Deleting Similar Ends +## Today's 06-03-24 [Problem Link](https://leetcode.com/problems/linked-list-cycle/description/?envType=daily-question&envId=2024-03-06) +## 141. Linked List Cycle # Intuition -The goal is to find the minimum length of a string after repeatedly removing the same character from both ends until the string is no longer symmetric. +The goal is to determine whether a given linked list has a cycle or not. A cycle in a linked list occurs when a node points to a previously visited node, creating a loop in the structure. # Approach -- I initialized two pointers, `leftIdx` and `rightIdx`, at the beginning and end of the string, respectively. -- Used a while loop to iterate while `leftIdx` is less than `rightIdx` and the characters at these indices are equal. -- Inside the loop : - - Stored the current character at `leftIdx` in the variable `currentChar`. - - Moved `leftIdx` to the right until a different character is encountered. - - Moved `rightIdx` to the left until a different character is encountered. -- Calculated and return the length of the remaining string by subtracting `leftIdx` from `rightIdx` and adding 1. +**Edge Case Check :** + - Checked if the given linked list is empty (head is null). If it is, returned `false` as there can't be a cycle in an empty list. -My algorithm efficiently reduced the length of the string by removing symmetric characters from both ends until no more symmetric characters are found. +**HashSet for Visited Nodes :** + - Initialized a HashSet (`visitedNodes`) to keep track of visited nodes. + - Added the head of the linked list to the HashSet. + +**Traverse the Linked List:** + - Used a while loop to traverse the linked list. + - At each step, checked if the next node is already present in the HashSet. If it is, there is a cycle, so return `true`. + - If the next node is not in the HashSet, added it to the HashSet. + - Moved to the next node in the linked list. + +**Result :** + - If the loop completes without finding a cycle, returned `false`. + +My approach utilized a HashSet to efficiently detect cycles in a linked list. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) - # Complexity -- Time complexity : $O(s)$ +- Time complexity : $O(N)$ -$s$ : length of the input string -- Space complexity : $O(1)$ +$N$ : number of nodes in the linked list +- Space complexity : $O(N)$ # Code ``` -class Solution { - - // Method to find the minimum length - public int minimumLength(String s) { - // Initialize two pointers, leftIdx and rightIdx - int leftIdx = 0; - int rightIdx = s.length() - 1; +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ - // Iterating while the leftIdx is less than rightIdx and characters at these indices are equal - while (leftIdx < rightIdx && s.charAt(leftIdx) == s.charAt(rightIdx)) { - - // Storing the current character - final char currentChar = s.charAt(leftIdx); - - // Moving leftIdx to the right until a different character is encountered - while (leftIdx <= rightIdx && s.charAt(leftIdx) == currentChar){ - leftIdx++; - } +public class Solution { + + // Function to check if a linked list has a cycle + public boolean hasCycle(ListNode head) { + + // Checking if the head is null (empty list) + if (head == null) { + return false; + } + + // HashSet to store visited nodes + HashSet visitedNodes = new HashSet<>(); + + // Adding the head to the HashSet + visitedNodes.add(head); - // Moving rightIdx to the left until a different character is encountered - while (leftIdx <= rightIdx && s.charAt(rightIdx) == currentChar){ - rightIdx--; - } - + // Looping through the linked list + while (head != null) { + + // Checking if the next node is already in the HashSet (indicating a cycle) + if (visitedNodes.contains(head.next)) { + return true; + } + + // Adding the next node to the HashSet + visitedNodes.add(head.next); + + // Moving to the next node in the linked list + head = head.next; + } + + // If the loop completes without finding a cycle, returning false + return false; } - - // Returning the calculated minimum length - return rightIdx - leftIdx + 1; - } } - ``` \ No newline at end of file From 1f6a8432931abcdc8ddb1488b99aa1b4a9477c1d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 6 Mar 2024 09:11:00 +0530 Subject: [PATCH 206/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f5003a7..f05dd89 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ The goal is to determine whether a given linked list has a cycle or not. A cycle - Initialized a HashSet (`visitedNodes`) to keep track of visited nodes. - Added the head of the linked list to the HashSet. -**Traverse the Linked List:** +**Traversed the Linked List :** - Used a while loop to traverse the linked list. - At each step, checked if the next node is already present in the HashSet. If it is, there is a cycle, so return `true`. - If the next node is not in the HashSet, added it to the HashSet. From 7173c17955f7af8a14dc9baeb14010bd9e986f27 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 6 Mar 2024 09:11:25 +0530 Subject: [PATCH 207/300] Create Daily 06-03-24.md --- 2024 March/Daily 06-03-24.md | 86 ++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 2024 March/Daily 06-03-24.md diff --git a/2024 March/Daily 06-03-24.md b/2024 March/Daily 06-03-24.md new file mode 100644 index 0000000..66ed839 --- /dev/null +++ b/2024 March/Daily 06-03-24.md @@ -0,0 +1,86 @@ +## Today's 06-03-24 [Problem Link](https://leetcode.com/problems/linked-list-cycle/description/?envType=daily-question&envId=2024-03-06) +## 141. Linked List Cycle + +# Intuition + +The goal is to determine whether a given linked list has a cycle or not. A cycle in a linked list occurs when a node points to a previously visited node, creating a loop in the structure. + +# Approach + +**Edge Case Check :** + - Checked if the given linked list is empty (head is null). If it is, returned `false` as there can't be a cycle in an empty list. + +**HashSet for Visited Nodes :** + - Initialized a HashSet (`visitedNodes`) to keep track of visited nodes. + - Added the head of the linked list to the HashSet. + +**Traversed the Linked List :** + - Used a while loop to traverse the linked list. + - At each step, checked if the next node is already present in the HashSet. If it is, there is a cycle, so return `true`. + - If the next node is not in the HashSet, added it to the HashSet. + - Moved to the next node in the linked list. + +**Result :** + - If the loop completes without finding a cycle, returned `false`. + +My approach utilized a HashSet to efficiently detect cycles in a linked list. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(N)$ + +$N$ : number of nodes in the linked list +- Space complexity : $O(N)$ + + +# Code +``` +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ + +public class Solution { + + // Function to check if a linked list has a cycle + public boolean hasCycle(ListNode head) { + + // Checking if the head is null (empty list) + if (head == null) { + return false; + } + + // HashSet to store visited nodes + HashSet visitedNodes = new HashSet<>(); + + // Adding the head to the HashSet + visitedNodes.add(head); + + // Looping through the linked list + while (head != null) { + + // Checking if the next node is already in the HashSet (indicating a cycle) + if (visitedNodes.contains(head.next)) { + return true; + } + + // Adding the next node to the HashSet + visitedNodes.add(head.next); + + // Moving to the next node in the linked list + head = head.next; + } + + // If the loop completes without finding a cycle, returning false + return false; + } +} +``` \ No newline at end of file From d012da712b252cfd1efc0e210a10f37cf820b30f Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 7 Mar 2024 10:01:24 +0530 Subject: [PATCH 208/300] Update README.md --- README.md | 94 ++++++++++++++++++++++--------------------------------- 1 file changed, 38 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index f05dd89..49ce953 100644 --- a/README.md +++ b/README.md @@ -4,89 +4,71 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 06-03-24 [Problem Link](https://leetcode.com/problems/linked-list-cycle/description/?envType=daily-question&envId=2024-03-06) -## 141. Linked List Cycle +## Today's 07-03-24 [Problem Link](https://leetcode.com/problems/middle-of-the-linked-list/description/?envType=daily-question&envId=2024-03-07) +## 876. Middle of the Linked List # Intuition -The goal is to determine whether a given linked list has a cycle or not. A cycle in a linked list occurs when a node points to a previously visited node, creating a loop in the structure. +We are given a singly-linked list and need to find its middle node. # Approach -**Edge Case Check :** - - Checked if the given linked list is empty (head is null). If it is, returned `false` as there can't be a cycle in an empty list. - -**HashSet for Visited Nodes :** - - Initialized a HashSet (`visitedNodes`) to keep track of visited nodes. - - Added the head of the linked list to the HashSet. - -**Traversed the Linked List :** - - Used a while loop to traverse the linked list. - - At each step, checked if the next node is already present in the HashSet. If it is, there is a cycle, so return `true`. - - If the next node is not in the HashSet, added it to the HashSet. - - Moved to the next node in the linked list. - -**Result :** - - If the loop completes without finding a cycle, returned `false`. - -My approach utilized a HashSet to efficiently detect cycles in a linked list. +To find the middle node, I followed these steps : +- I calculated the length of the linked list using a helper function. +- Traversed the linked list to find the middle node. +- Returned the middle node. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(N)$ +- Time complexity : $O(n)$ -$N$ : number of nodes in the linked list -- Space complexity : $O(N)$ +$n$ : number of nodes in the linked list +- Space complexity : $O(1)$ # Code ``` /** * Definition for singly-linked list. - * class ListNode { + * public class ListNode { * int val; * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ - -public class Solution { - - // Function to check if a linked list has a cycle - public boolean hasCycle(ListNode head) { +class Solution { + // Function to find the middle node of a linked list + public ListNode middleNode(ListNode head) { - // Checking if the head is null (empty list) - if (head == null) { - return false; - } + // Calculating the length of the linked list + int l = length(head); + int i = 0; - // HashSet to store visited nodes - HashSet visitedNodes = new HashSet<>(); + // Traversing to the middle node + while( i < l/2){ + head = head.next; + i++; + } - // Adding the head to the HashSet - visitedNodes.add(head); + // Returning the middle node + return head; + } - // Looping through the linked list - while (head != null) { - - // Checking if the next node is already in the HashSet (indicating a cycle) - if (visitedNodes.contains(head.next)) { - return true; - } - - // Adding the next node to the HashSet - visitedNodes.add(head.next); - - // Moving to the next node in the linked list - head = head.next; + // Function to calculate the length of a linked list + static int length(ListNode h){ + int l = 0; + + // Traversing the linked list and count the nodes + while( h != null){ + l++; + h = h.next; } - // If the loop completes without finding a cycle, returning false - return false; + // Returning the length + return l; } } ``` \ No newline at end of file From 72d2719c17d38a474fc449666e0a0cff503ff9e6 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 7 Mar 2024 10:02:15 +0530 Subject: [PATCH 209/300] Create Daily 07-03-24.md --- 2024 March/Daily 07-03-24.md | 68 ++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 2024 March/Daily 07-03-24.md diff --git a/2024 March/Daily 07-03-24.md b/2024 March/Daily 07-03-24.md new file mode 100644 index 0000000..a6419d0 --- /dev/null +++ b/2024 March/Daily 07-03-24.md @@ -0,0 +1,68 @@ +## Today's 07-03-24 [Problem Link](https://leetcode.com/problems/middle-of-the-linked-list/description/?envType=daily-question&envId=2024-03-07) +## 876. Middle of the Linked List + +# Intuition + +We are given a singly-linked list and need to find its middle node. + +# Approach + +To find the middle node, I followed these steps : +- I calculated the length of the linked list using a helper function. +- Traversed the linked list to find the middle node. +- Returned the middle node. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : number of nodes in the linked list +- Space complexity : $O(1)$ + + +# Code +``` +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + // Function to find the middle node of a linked list + public ListNode middleNode(ListNode head) { + + // Calculating the length of the linked list + int l = length(head); + int i = 0; + + // Traversing to the middle node + while( i < l/2){ + head = head.next; + i++; + } + + // Returning the middle node + return head; + } + + // Function to calculate the length of a linked list + static int length(ListNode h){ + int l = 0; + + // Traversing the linked list and count the nodes + while( h != null){ + l++; + h = h.next; + } + + // Returning the length + return l; + } +} +``` \ No newline at end of file From 7524d5d6505f2027d7ab3702a44fb95716df68cf Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 8 Mar 2024 10:56:54 +0530 Subject: [PATCH 210/300] Update README.md --- README.md | 95 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 52 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 49ce953..3cd5a86 100644 --- a/README.md +++ b/README.md @@ -1,74 +1,83 @@ +# 🔱 Embracing the cosmic energy this Mahashivratri ! Wishing everyone a day filled with devotion, introspection, and coding adventures. Let the blessings of Lord Shiva guide our paths in the coding realm. 🖥️🕉️ #Mahashivratri #CodeWithDevotion #GitHubDiaries + # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. ## Always here to assist you guys. -## Today's 07-03-24 [Problem Link](https://leetcode.com/problems/middle-of-the-linked-list/description/?envType=daily-question&envId=2024-03-07) -## 876. Middle of the Linked List +## Today's 08-03-24 [Problem Link](https://leetcode.com/problems/count-elements-with-maximum-frequency/description/?envType=daily-question&envId=2024-03-08) +## 3005. Count Elements With Maximum Frequency # Intuition -We are given a singly-linked list and need to find its middle node. +- I will utilize a HashMap to efficiently store and update the frequency of each element in the input array. + +- Keep track of the maximum frequency encountered during the traversal. # Approach -To find the middle node, I followed these steps : -- I calculated the length of the linked list using a helper function. -- Traversed the linked list to find the middle node. -- Returned the middle node. +- I initialized a HashMap (m) to store the frequency of each element and a variable (max) to track the maximum frequency. + +- Traversed through the input array (nums) : + - For each element, updated its frequency in the HashMap. + - Updated the maximum frequency (max) if a higher frequency is encountered. + +- Iterated through the keys of the HashMap : + - For each key, if its frequency is equal to the maximum frequency (max), added its frequency to the final answer (jawab). + +- The final result (jawab) is the sum of frequencies of elements with the maximum frequency. + +My approach efficiently identified elements with the maximum frequency in the given array. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(N)$ -$n$ : number of nodes in the linked list -- Space complexity : $O(1)$ +$N$ : number of elements in the input array `nums` +$u$ : number of unique elements in the input array `nums` +- Space complexity : $O(u)$ # Code ``` -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ class Solution { - // Function to find the middle node of a linked list - public ListNode middleNode(ListNode head) { + + // Method to find the maximum frequency elements in an array + public int maxFrequencyElements(int[] nums) { + // HashMap to store the frequency of each element + HashMap m = new HashMap<>(); - // Calculating the length of the linked list - int l = length(head); - int i = 0; + // Variable to track the maximum frequency + int max = 0; - // Traversing to the middle node - while( i < l/2){ - head = head.next; - i++; - } - - // Returning the middle node - return head; - } + // Looping through the array to count the frequency of each element + for (int i : nums) { + // If the element is not present in the HashMap, adding it with a default frequency of 0 + m.putIfAbsent(i, 0); + + // Updating the frequency of the element in the HashMap + m.put(i, m.getOrDefault(i, 0) + 1); + + // Updating the maximum frequency + max = Math.max(max, m.get(i)); + } - // Function to calculate the length of a linked list - static int length(ListNode h){ - int l = 0; + // Variable to store the final answer + int jawab = 0; - // Traversing the linked list and count the nodes - while( h != null){ - l++; - h = h.next; + // Looping through the keys of the HashMap to find elements with the maximum frequency + for (int k : m.keySet()) { + // If the frequency of the element is equal to the maximum frequency, adding it to the answer + if (m.get(k) == max) { + jawab += m.get(k); + } } - // Returning the length - return l; + // Returning the final answer + return jawab; } } ``` \ No newline at end of file From e9cbf736ea324bb5c5dca0e5417347f0c84389f8 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 8 Mar 2024 10:57:42 +0530 Subject: [PATCH 211/300] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3cd5a86..64cbe5e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ -# 🔱 Embracing the cosmic energy this Mahashivratri ! Wishing everyone a day filled with devotion, introspection, and coding adventures. Let the blessings of Lord Shiva guide our paths in the coding realm. 🖥️🕉️ #Mahashivratri #CodeWithDevotion #GitHubDiaries +# 🔱 Embracing the cosmic energy this Mahashivratri ! +## Wishing everyone a day filled with devotion, introspection, and coding adventures. Let the blessings of Lord Shiva guide our paths in the coding realm. 🖥️🕉️ #Mahashivratri #CodeWithDevotion #GitHubDiaries # Leetcode Daily Challenge Solutions From f06631b39e812ab62e6f67803bcad3daea215c0c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 8 Mar 2024 10:59:59 +0530 Subject: [PATCH 212/300] Create Daily 08-03-24.md --- 2024 March/Daily 08-03-24.md | 79 ++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 2024 March/Daily 08-03-24.md diff --git a/2024 March/Daily 08-03-24.md b/2024 March/Daily 08-03-24.md new file mode 100644 index 0000000..3d55d42 --- /dev/null +++ b/2024 March/Daily 08-03-24.md @@ -0,0 +1,79 @@ +# 🔱 Embracing the cosmic energy this Mahashivratri ! +## Wishing everyone a day filled with devotion, introspection, and coding adventures. Let the blessings of Lord Shiva guide our paths in the coding realm. 🖥️🕉️ #Mahashivratri #CodeWithDevotion #GitHubDiaries + + +## Today's 08-03-24 [Problem Link](https://leetcode.com/problems/count-elements-with-maximum-frequency/description/?envType=daily-question&envId=2024-03-08) +## 3005. Count Elements With Maximum Frequency + +# Intuition + +- I will utilize a HashMap to efficiently store and update the frequency of each element in the input array. + +- Keep track of the maximum frequency encountered during the traversal. + +# Approach + +- I initialized a HashMap (m) to store the frequency of each element and a variable (max) to track the maximum frequency. + +- Traversed through the input array (nums) : + - For each element, updated its frequency in the HashMap. + - Updated the maximum frequency (max) if a higher frequency is encountered. + +- Iterated through the keys of the HashMap : + - For each key, if its frequency is equal to the maximum frequency (max), added its frequency to the final answer (jawab). + +- The final result (jawab) is the sum of frequencies of elements with the maximum frequency. + +My approach efficiently identified elements with the maximum frequency in the given array. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O(N)$ + +$N$ : number of elements in the input array `nums` +$u$ : number of unique elements in the input array `nums` +- Space complexity : $O(u)$ + + +# Code +``` +class Solution { + + // Method to find the maximum frequency elements in an array + public int maxFrequencyElements(int[] nums) { + // HashMap to store the frequency of each element + HashMap m = new HashMap<>(); + + // Variable to track the maximum frequency + int max = 0; + + // Looping through the array to count the frequency of each element + for (int i : nums) { + // If the element is not present in the HashMap, adding it with a default frequency of 0 + m.putIfAbsent(i, 0); + + // Updating the frequency of the element in the HashMap + m.put(i, m.getOrDefault(i, 0) + 1); + + // Updating the maximum frequency + max = Math.max(max, m.get(i)); + } + + // Variable to store the final answer + int jawab = 0; + + // Looping through the keys of the HashMap to find elements with the maximum frequency + for (int k : m.keySet()) { + // If the frequency of the element is equal to the maximum frequency, adding it to the answer + if (m.get(k) == max) { + jawab += m.get(k); + } + } + + // Returning the final answer + return jawab; + } +} +``` \ No newline at end of file From a027799589f291f5fa5e605429ff5f38e46ed19c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 9 Mar 2024 10:44:53 +0530 Subject: [PATCH 213/300] Update README.md --- README.md | 106 +++++++++++++++++++++++++++++------------------------- 1 file changed, 58 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 64cbe5e..3c9aaa7 100644 --- a/README.md +++ b/README.md @@ -1,84 +1,94 @@ -# 🔱 Embracing the cosmic energy this Mahashivratri ! -## Wishing everyone a day filled with devotion, introspection, and coding adventures. Let the blessings of Lord Shiva guide our paths in the coding realm. 🖥️🕉️ #Mahashivratri #CodeWithDevotion #GitHubDiaries - # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. ## Always here to assist you guys. -## Today's 08-03-24 [Problem Link](https://leetcode.com/problems/count-elements-with-maximum-frequency/description/?envType=daily-question&envId=2024-03-08) -## 3005. Count Elements With Maximum Frequency +## Today's 09-03-24 [Problem Link](https://leetcode.com/problems/minimum-common-value/description/?envType=daily-question&envId=2024-03-09) +## 2540. Minimum Common Value # Intuition -- I will utilize a HashMap to efficiently store and update the frequency of each element in the input array. - -- Keep track of the maximum frequency encountered during the traversal. +The goal is to find the common element between two arrays, and the approach involves using a HashSet to efficiently check for common elements. My algorithm first determines which array is larger and populates the HashSet with elements from the smaller array. Then, it iterates through the larger array to find the common element by checking HashSet membership. Once found, the common element is returned. # Approach -- I initialized a HashMap (m) to store the frequency of each element and a variable (max) to track the maximum frequency. +**Initialized the Variables :** + - Initialized `common` to -1 to store the common element. + - Initialized `n1IsLarge` to false to track which array is larger. + +**Determined Larger Array :** + - Checked if the length of `nums1` is greater than the length of `nums2`. + - Set `n1IsLarge` to true if `nums1` is larger. -- Traversed through the input array (nums) : - - For each element, updated its frequency in the HashMap. - - Updated the maximum frequency (max) if a higher frequency is encountered. +**Created HashSet :** + - Created a HashSet `h` to store elements of the smaller array. -- Iterated through the keys of the HashMap : - - For each key, if its frequency is equal to the maximum frequency (max), added its frequency to the final answer (jawab). +**Populated the HashSet :** + - If `n1IsLarge` is true, iterated through `nums2` and added elements to HashSet `h`. + - If `n1IsLarge` is false, iterated through `nums1` and added elements to HashSet `h`. -- The final result (jawab) is the sum of frequencies of elements with the maximum frequency. +**Found Common Element :** + - Iterated through the larger array. + - If the current element is present in HashSet `h`, set `common` to that element and broke the loop. -My approach efficiently identified elements with the maximum frequency in the given array. +**Result :** + - Returned the value of `common`, which represents the common element. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) - # Complexity -- Time complexity : $O(N)$ +- Time complexity : $O(m + n)$ -$N$ : number of elements in the input array `nums` -$u$ : number of unique elements in the input array `nums` -- Space complexity : $O(u)$ +$m$ : length of smaller array +$n$ : length of larger array +- Space complexity : $O(m)$ # Code ``` class Solution { - - // Method to find the maximum frequency elements in an array - public int maxFrequencyElements(int[] nums) { - // HashMap to store the frequency of each element - HashMap m = new HashMap<>(); + + public int getCommon(int[] nums1, int[] nums2) { + int common = -1; + boolean n1IsLarge = false; + + // Determining which array is larger + if (nums1.length > nums2.length) { + n1IsLarge = true; + } - // Variable to track the maximum frequency - int max = 0; + HashSet h = new HashSet<>(); - // Looping through the array to count the frequency of each element - for (int i : nums) { - // If the element is not present in the HashMap, adding it with a default frequency of 0 - m.putIfAbsent(i, 0); + // Populating the HashSet with the elements of the smaller array + if (n1IsLarge) { + for (int i : nums2) { + h.add(i); + } - // Updating the frequency of the element in the HashMap - m.put(i, m.getOrDefault(i, 0) + 1); + // Finding the common element + for (int i = 0; i < nums1.length; i++) { + if (h.contains(nums1[i])) { + common = nums1[i]; + break; + } + } + } + else { + for (int i : nums1) { + h.add(i); + } - // Updating the maximum frequency - max = Math.max(max, m.get(i)); - } - - // Variable to store the final answer - int jawab = 0; - - // Looping through the keys of the HashMap to find elements with the maximum frequency - for (int k : m.keySet()) { - // If the frequency of the element is equal to the maximum frequency, adding it to the answer - if (m.get(k) == max) { - jawab += m.get(k); + // Finding the common element + for (int i = 0; i < nums2.length; i++) { + if (h.contains(nums2[i])) { + common = nums2[i]; + break; + } } } - // Returning the final answer - return jawab; + return common; } } ``` \ No newline at end of file From d526f79269f10d615aa63ee9f66b13d73db9da18 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 9 Mar 2024 10:45:46 +0530 Subject: [PATCH 214/300] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3c9aaa7..767cf72 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ This is my attempt to make the coding experience easier for you guys so that you # Intuition -The goal is to find the common element between two arrays, and the approach involves using a HashSet to efficiently check for common elements. My algorithm first determines which array is larger and populates the HashSet with elements from the smaller array. Then, it iterates through the larger array to find the common element by checking HashSet membership. Once found, the common element is returned. +The goal is to find the common element between two arrays, and my approach involves using a HashSet to efficiently check for common elements. My algorithm first determines which array is larger and populates the HashSet with elements from the smaller array. Then, it iterates through the larger array to find the common element by checking HashSet membership. Once found, the common element is returned. # Approach @@ -41,6 +41,8 @@ Have a look at the code , still have any confusion then please let me know in th - Time complexity : $O(m + n)$ $m$ : length of smaller array + + $n$ : length of larger array - Space complexity : $O(m)$ From 41a22b640acb668762d105426ec2abd943292646 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 9 Mar 2024 10:46:22 +0530 Subject: [PATCH 215/300] Create Daily 09-03-24.md --- 2024 March/Daily 09-03-24.md | 90 ++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 2024 March/Daily 09-03-24.md diff --git a/2024 March/Daily 09-03-24.md b/2024 March/Daily 09-03-24.md new file mode 100644 index 0000000..6ec6489 --- /dev/null +++ b/2024 March/Daily 09-03-24.md @@ -0,0 +1,90 @@ +## Today's 09-03-24 [Problem Link](https://leetcode.com/problems/minimum-common-value/description/?envType=daily-question&envId=2024-03-09) +## 2540. Minimum Common Value + +# Intuition + +The goal is to find the common element between two arrays, and my approach involves using a HashSet to efficiently check for common elements. My algorithm first determines which array is larger and populates the HashSet with elements from the smaller array. Then, it iterates through the larger array to find the common element by checking HashSet membership. Once found, the common element is returned. + +# Approach + +**Initialized the Variables :** + - Initialized `common` to -1 to store the common element. + - Initialized `n1IsLarge` to false to track which array is larger. + +**Determined Larger Array :** + - Checked if the length of `nums1` is greater than the length of `nums2`. + - Set `n1IsLarge` to true if `nums1` is larger. + +**Created HashSet :** + - Created a HashSet `h` to store elements of the smaller array. + +**Populated the HashSet :** + - If `n1IsLarge` is true, iterated through `nums2` and added elements to HashSet `h`. + - If `n1IsLarge` is false, iterated through `nums1` and added elements to HashSet `h`. + +**Found Common Element :** + - Iterated through the larger array. + - If the current element is present in HashSet `h`, set `common` to that element and broke the loop. + +**Result :** + - Returned the value of `common`, which represents the common element. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(m + n)$ + +$m$ : length of smaller array + + +$n$ : length of larger array +- Space complexity : $O(m)$ + + +# Code +``` +class Solution { + + public int getCommon(int[] nums1, int[] nums2) { + int common = -1; + boolean n1IsLarge = false; + + // Determining which array is larger + if (nums1.length > nums2.length) { + n1IsLarge = true; + } + + HashSet h = new HashSet<>(); + + // Populating the HashSet with the elements of the smaller array + if (n1IsLarge) { + for (int i : nums2) { + h.add(i); + } + + // Finding the common element + for (int i = 0; i < nums1.length; i++) { + if (h.contains(nums1[i])) { + common = nums1[i]; + break; + } + } + } + else { + for (int i : nums1) { + h.add(i); + } + + // Finding the common element + for (int i = 0; i < nums2.length; i++) { + if (h.contains(nums2[i])) { + common = nums2[i]; + break; + } + } + } + + return common; + } +} +``` \ No newline at end of file From af39a42a5642efb59b5aa19607063ff01dc00c9f Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 10 Mar 2024 23:16:33 +0530 Subject: [PATCH 216/300] Update README.md --- README.md | 103 ++++++++++++++++++++---------------------------------- 1 file changed, 38 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index 767cf72..fc1907b 100644 --- a/README.md +++ b/README.md @@ -4,93 +4,66 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 09-03-24 [Problem Link](https://leetcode.com/problems/minimum-common-value/description/?envType=daily-question&envId=2024-03-09) -## 2540. Minimum Common Value +## Today's 10-03-24 [Problem Link](https://leetcode.com/problems/intersection-of-two-arrays/description/?envType=daily-question&envId=2024-03-10) +## 349. Intersection of Two Arrays # Intuition -The goal is to find the common element between two arrays, and my approach involves using a HashSet to efficiently check for common elements. My algorithm first determines which array is larger and populates the HashSet with elements from the smaller array. Then, it iterates through the larger array to find the common element by checking HashSet membership. Once found, the common element is returned. +The goal is to find the intersection of two arrays, `nums1` and `nums2`. The code uses a set to efficiently check for common elements between the arrays. # Approach -**Initialized the Variables :** - - Initialized `common` to -1 to store the common element. - - Initialized `n1IsLarge` to false to track which array is larger. +**List Initialization :** + - Initialized an empty list (`ans`) to store the elements of the intersection. -**Determined Larger Array :** - - Checked if the length of `nums1` is greater than the length of `nums2`. - - Set `n1IsLarge` to true if `nums1` is larger. +**Set Conversion :** + - Converted the first array (`nums1`) to a set (`set`) for efficient element lookup. -**Created HashSet :** - - Created a HashSet `h` to store elements of the smaller array. +**Intersection Check :** + - Iterated through each element (`num`) in the second array (`nums2`). + - Checked if the current element is present in the set (`set`). + - If present, removed the element from the set and add it to the `ans` list. -**Populated the HashSet :** - - If `n1IsLarge` is true, iterated through `nums2` and added elements to HashSet `h`. - - If `n1IsLarge` is false, iterated through `nums1` and added elements to HashSet `h`. - -**Found Common Element :** - - Iterated through the larger array. - - If the current element is present in HashSet `h`, set `common` to that element and broke the loop. - -**Result :** - - Returned the value of `common`, which represents the common element. +**Array Conversion :** + - Converted the list of intersection elements (`ans`) to an integer array. +**Return :** + - Returned the final integer array containing the intersection. + - --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + # Complexity - Time complexity : $O(m + n)$ -$m$ : length of smaller array +$n$ : length of first array -$n$ : length of larger array -- Space complexity : $O(m)$ +$m$ : length of second array +- Space complexity : $O(n)$ # Code ``` class Solution { + + public int[] intersection(int[] nums1, int[] nums2) { + // Creating a list to store the intersection elements. + List ans = new ArrayList<>(); - public int getCommon(int[] nums1, int[] nums2) { - int common = -1; - boolean n1IsLarge = false; - - // Determining which array is larger - if (nums1.length > nums2.length) { - n1IsLarge = true; - } - - HashSet h = new HashSet<>(); - - // Populating the HashSet with the elements of the smaller array - if (n1IsLarge) { - for (int i : nums2) { - h.add(i); - } - - // Finding the common element - for (int i = 0; i < nums1.length; i++) { - if (h.contains(nums1[i])) { - common = nums1[i]; - break; - } - } - } - else { - for (int i : nums1) { - h.add(i); - } - - // Finding the common element - for (int i = 0; i < nums2.length; i++) { - if (h.contains(nums2[i])) { - common = nums2[i]; - break; - } - } - } - - return common; - } + // Converting nums1 to a set for faster lookup. + Set set = Arrays.stream(nums1).boxed().collect(Collectors.toSet()); + + // Iterating through each element in nums2. + for (final int num : nums2) + // Checking if the element is present in the set (intersection). + if (set.remove(num)) + // Adding the common element to the result list. + ans.add(num); + + // Converting the list to an array and return it. + return ans.stream().mapToInt(Integer::intValue).toArray(); + } } + ``` \ No newline at end of file From d2e9ce48f5ee7157477634ef949c5c0e0c72afa5 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 10 Mar 2024 23:17:25 +0530 Subject: [PATCH 217/300] Create Daily 10-03-24.md --- 2024 March/Daily 10-03-24.md | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 2024 March/Daily 10-03-24.md diff --git a/2024 March/Daily 10-03-24.md b/2024 March/Daily 10-03-24.md new file mode 100644 index 0000000..4df2146 --- /dev/null +++ b/2024 March/Daily 10-03-24.md @@ -0,0 +1,63 @@ +## Today's 10-03-24 [Problem Link](https://leetcode.com/problems/intersection-of-two-arrays/description/?envType=daily-question&envId=2024-03-10) +## 349. Intersection of Two Arrays + +# Intuition + +The goal is to find the intersection of two arrays, `nums1` and `nums2`. The code uses a set to efficiently check for common elements between the arrays. + +# Approach + +**List Initialization :** + - Initialized an empty list (`ans`) to store the elements of the intersection. + +**Set Conversion :** + - Converted the first array (`nums1`) to a set (`set`) for efficient element lookup. + +**Intersection Check :** + - Iterated through each element (`num`) in the second array (`nums2`). + - Checked if the current element is present in the set (`set`). + - If present, removed the element from the set and add it to the `ans` list. + +**Array Conversion :** + - Converted the list of intersection elements (`ans`) to an integer array. + +**Return :** + - Returned the final integer array containing the intersection. + - +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O(m + n)$ + +$n$ : length of first array + + +$m$ : length of second array +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + + public int[] intersection(int[] nums1, int[] nums2) { + // Creating a list to store the intersection elements. + List ans = new ArrayList<>(); + + // Converting nums1 to a set for faster lookup. + Set set = Arrays.stream(nums1).boxed().collect(Collectors.toSet()); + + // Iterating through each element in nums2. + for (final int num : nums2) + // Checking if the element is present in the set (intersection). + if (set.remove(num)) + // Adding the common element to the result list. + ans.add(num); + + // Converting the list to an array and return it. + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} + +``` \ No newline at end of file From 657212202701b97702d03b5d8f551dc4d260d3e5 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 11 Mar 2024 09:24:55 +0530 Subject: [PATCH 218/300] Update README.md --- README.md | 113 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 72 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index fc1907b..3fcd510 100644 --- a/README.md +++ b/README.md @@ -4,66 +4,97 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 10-03-24 [Problem Link](https://leetcode.com/problems/intersection-of-two-arrays/description/?envType=daily-question&envId=2024-03-10) -## 349. Intersection of Two Arrays +## Today's 11-03-24 [Problem Link](https://leetcode.com/problems/custom-sort-string/description/?envType=daily-question&envId=2024-03-11) +## 791. Custom Sort String # Intuition -The goal is to find the intersection of two arrays, `nums1` and `nums2`. The code uses a set to efficiently check for common elements between the arrays. +My given code implements a custom sort string function using a HashSet and a HashMap. # Approach -**List Initialization :** - - Initialized an empty list (`ans`) to store the elements of the intersection. +**Initialization :** + - Created a HashSet `h` to store characters in the given order. + - Created a HashMap `m` to store characters and their counts in the input string. + - Initialized an empty string `jawab` to store the final result. -**Set Conversion :** - - Converted the first array (`nums1`) to a set (`set`) for efficient element lookup. +**Processed Order Characters :** + - Iterated through each character in the given order. + - If the character is present in the input string (`m.containsKey(c)`), appended it to the result string `jawab` based on its count. -**Intersection Check :** - - Iterated through each element (`num`) in the second array (`nums2`). - - Checked if the current element is present in the set (`set`). - - If present, removed the element from the set and add it to the `ans` list. +**Processed Remaining Characters :** + - Iterated through each character in the input string. + - If the character is not in the given order (`!h.contains(c)`), added it to the order, and append it to the result string `jawab` based on its count. -**Array Conversion :** - - Converted the list of intersection elements (`ans`) to an integer array. +**Result :** + - The final result string `jawab` contained the custom-sorted string based on the given order. + +My approach ensured that the characters are processed according to the specified order, and the resulting string follows the custom sorting criteria. -**Return :** - - Returned the final integer array containing the intersection. - - --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(m + n)$ +- Time complexity : $O( O + S + N )$ -$n$ : length of first array - - -$m$ : length of second array -- Space complexity : $O(n)$ +$O$ : length of the order string +$S$ : length of the input string +$N$ : total number of characters in the input string +- Space complexity : $O( O + S + N )$ # Code ``` +// This is a Java implementation of a custom sort string function. +// I used a HashSet and a HashMap to process the order and input string. + class Solution { - - public int[] intersection(int[] nums1, int[] nums2) { - // Creating a list to store the intersection elements. - List ans = new ArrayList<>(); - - // Converting nums1 to a set for faster lookup. - Set set = Arrays.stream(nums1).boxed().collect(Collectors.toSet()); - - // Iterating through each element in nums2. - for (final int num : nums2) - // Checking if the element is present in the set (intersection). - if (set.remove(num)) - // Adding the common element to the result list. - ans.add(num); - - // Converting the list to an array and return it. - return ans.stream().mapToInt(Integer::intValue).toArray(); - } -} + // HashSet to store characters in the given order + static HashSet h; + // HashMap to store characters and their counts in the input string + static HashMap m; + // String to store the final result + static String jawab; + + // Function to custom sort the input string based on the given order + public String customSortString(String order, String s) { + // Initializing the HashSet with the order characters + h = new HashSet<>(); + for (char c : order.toCharArray()) { + h.add(c); + } + + // Initializing the HashMap with characters and their counts in the input string + m = new HashMap<>(); + for (char c : s.toCharArray()) { + m.put(c, m.getOrDefault(c, 0) + 1); + } + + // Initializing the result string + jawab = ""; + + // Processing characters in the given order and append them to the result string + for (char c : order.toCharArray()) { + if (m.containsKey(c)) { + for (int i = 0; i < m.get(c); i++) { + jawab += c; + } + } + } + + // Processing remaining characters in the input string and append them to the result string + for (char c : s.toCharArray()) { + if (!h.contains(c)) { + h.add(c); + for (int i = 0; i < m.get(c); i++) { + jawab += c; + } + } + } + + // Returning the final result string + return jawab; + } +} ``` \ No newline at end of file From 7a02aed863c558627ef20457e03b8f2cb275be12 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 11 Mar 2024 09:25:35 +0530 Subject: [PATCH 219/300] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3fcd510..3452e08 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,9 @@ Have a look at the code , still have any confusion then please let me know in th - Time complexity : $O( O + S + N )$ $O$ : length of the order string + $S$ : length of the input string + $N$ : total number of characters in the input string - Space complexity : $O( O + S + N )$ From 8fb79ac6ccee610e38d1cd200e8078bd308b447a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 11 Mar 2024 09:26:00 +0530 Subject: [PATCH 220/300] Create Daily 11-03-24.md --- 2024 March/Daily 11-03-24.md | 96 ++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 2024 March/Daily 11-03-24.md diff --git a/2024 March/Daily 11-03-24.md b/2024 March/Daily 11-03-24.md new file mode 100644 index 0000000..c5e75aa --- /dev/null +++ b/2024 March/Daily 11-03-24.md @@ -0,0 +1,96 @@ +## Today's 11-03-24 [Problem Link](https://leetcode.com/problems/custom-sort-string/description/?envType=daily-question&envId=2024-03-11) +## 791. Custom Sort String + +# Intuition + +My given code implements a custom sort string function using a HashSet and a HashMap. + +# Approach + +**Initialization :** + - Created a HashSet `h` to store characters in the given order. + - Created a HashMap `m` to store characters and their counts in the input string. + - Initialized an empty string `jawab` to store the final result. + +**Processed Order Characters :** + - Iterated through each character in the given order. + - If the character is present in the input string (`m.containsKey(c)`), appended it to the result string `jawab` based on its count. + +**Processed Remaining Characters :** + - Iterated through each character in the input string. + - If the character is not in the given order (`!h.contains(c)`), added it to the order, and append it to the result string `jawab` based on its count. + +**Result :** + - The final result string `jawab` contained the custom-sorted string based on the given order. + +My approach ensured that the characters are processed according to the specified order, and the resulting string follows the custom sorting criteria. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) + +# Complexity +- Time complexity : $O( O + S + N )$ + +$O$ : length of the order string + +$S$ : length of the input string + +$N$ : total number of characters in the input string +- Space complexity : $O( O + S + N )$ + + +# Code +``` +// This is a Java implementation of a custom sort string function. +// I used a HashSet and a HashMap to process the order and input string. + +class Solution { + + // HashSet to store characters in the given order + static HashSet h; + // HashMap to store characters and their counts in the input string + static HashMap m; + // String to store the final result + static String jawab; + + // Function to custom sort the input string based on the given order + public String customSortString(String order, String s) { + // Initializing the HashSet with the order characters + h = new HashSet<>(); + for (char c : order.toCharArray()) { + h.add(c); + } + + // Initializing the HashMap with characters and their counts in the input string + m = new HashMap<>(); + for (char c : s.toCharArray()) { + m.put(c, m.getOrDefault(c, 0) + 1); + } + + // Initializing the result string + jawab = ""; + + // Processing characters in the given order and append them to the result string + for (char c : order.toCharArray()) { + if (m.containsKey(c)) { + for (int i = 0; i < m.get(c); i++) { + jawab += c; + } + } + } + + // Processing remaining characters in the input string and append them to the result string + for (char c : s.toCharArray()) { + if (!h.contains(c)) { + h.add(c); + for (int i = 0; i < m.get(c); i++) { + jawab += c; + } + } + } + + // Returning the final result string + return jawab; + } +} +``` \ No newline at end of file From 8e8bd82f849fa8dd43ce9fbbef376ddcf8fdd5ad Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 12 Mar 2024 09:07:05 +0530 Subject: [PATCH 221/300] Update README.md --- README.md | 133 ++++++++++++++++++++++++++---------------------------- 1 file changed, 64 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index 3452e08..7a7bdb6 100644 --- a/README.md +++ b/README.md @@ -4,99 +4,94 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 11-03-24 [Problem Link](https://leetcode.com/problems/custom-sort-string/description/?envType=daily-question&envId=2024-03-11) -## 791. Custom Sort String +## Today's 12-03-24 [Problem Link](https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/description/?envType=daily-question&envId=2024-03-12) +## 1171. Remove Zero Sum Consecutive Nodes from Linked List # Intuition -My given code implements a custom sort string function using a HashSet and a HashMap. +The goal of my algorithm should be to remove zero-sum sublists from a given linked list. # Approach +My approach involves using a dummy node and a HashMap to keep track of the prefix sum and the corresponding nodes. + **Initialization :** - - Created a HashSet `h` to store characters in the given order. - - Created a HashMap `m` to store characters and their counts in the input string. - - Initialized an empty string `jawab` to store the final result. + - Created a dummy node with a value of 0 and set it as the head. + - Initialized a HashMap to store the prefix sum and corresponding nodes, starting with a prefix sum of 0 pointing to the dummy node. + - Set the initial prefix sum variable to 0. -**Processed Order Characters :** - - Iterated through each character in the given order. - - If the character is present in the input string (`m.containsKey(c)`), appended it to the result string `jawab` based on its count. +**Populated the HashMap :** + - Traversed the linked list, updating the prefix sum as we iterate. + - Stored the current prefix sum and the corresponding node in the HashMap. -**Processed Remaining Characters :** - - Iterated through each character in the input string. - - If the character is not in the given order (`!h.contains(c)`), added it to the order, and append it to the result string `jawab` based on its count. +**Removed Zero-Sum Sublists :** + - Reset the prefix sum variable to 0. + - Traversed the linked list again. + - Updated the next pointers of nodes to remove zero-sum sublists by pointing them to the next node after the corresponding prefix sum in the HashMap. -**Result :** - - The final result string `jawab` contained the custom-sorted string based on the given order. +**Result :** + - Returned the modified list starting from the dummy node's next. -My approach ensured that the characters are processed according to the specified order, and the resulting string follows the custom sorting criteria. +My approach efficiently handled the removal of zero-sum sublists by leveraging the HashMap to keep track of the prefix sums and their corresponding nodes. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) - # Complexity -- Time complexity : $O( O + S + N )$ +- Time complexity : $O(N)$ -$O$ : length of the order string - -$S$ : length of the input string - -$N$ : total number of characters in the input string -- Space complexity : $O( O + S + N )$ +$N$ : number of nodes in the linked list +- Space complexity : $O(N)$ # Code ``` -// This is a Java implementation of a custom sort string function. -// I used a HashSet and a HashMap to process the order and input string. - +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ class Solution { - - // HashSet to store characters in the given order - static HashSet h; - // HashMap to store characters and their counts in the input string - static HashMap m; - // String to store the final result - static String jawab; - - // Function to custom sort the input string based on the given order - public String customSortString(String order, String s) { - // Initializing the HashSet with the order characters - h = new HashSet<>(); - for (char c : order.toCharArray()) { - h.add(c); - } - - // Initializing the HashMap with characters and their counts in the input string + + // Static variables to store the map, the current node, and the prefix sum + static Map m; + static ListNode t; + static int prefixJor; + + // Function to remove zero-sum sublists + public ListNode removeZeroSumSublists(ListNode head) { + + // Creating a dummy node with value 0 and set it as the head + t = new ListNode(0, head); + + // Initializing the map with prefix sum 0 pointing to the dummy node m = new HashMap<>(); - for (char c : s.toCharArray()) { - m.put(c, m.getOrDefault(c, 0) + 1); + m.put(0, t); + + // Initializing the prefix sum variable + prefixJor = 0; + + // Populating the map with prefix sum and corresponding nodes + for (ListNode node = t; node != null; node = node.next) { + prefixJor += node.val; + m.put(prefixJor, node); } - - // Initializing the result string - jawab = ""; - - // Processing characters in the given order and append them to the result string - for (char c : order.toCharArray()) { - if (m.containsKey(c)) { - for (int i = 0; i < m.get(c); i++) { - jawab += c; - } - } + + // Resetting prefix sum + prefixJor = 0; + + // Updating the next pointers to remove zero-sum sublists + for (ListNode node = t; node != null; node = node.next) { + prefixJor += node.val; + node.next = m.get(prefixJor).next; } - - // Processing remaining characters in the input string and append them to the result string - for (char c : s.toCharArray()) { - if (!h.contains(c)) { - h.add(c); - for (int i = 0; i < m.get(c); i++) { - jawab += c; - } - } - } - - // Returning the final result string - return jawab; + + // Returning the modified list starting from the dummy node's next + return t.next; } } ``` \ No newline at end of file From f3af35489c2a86672bdb623babf7536a1c120592 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 12 Mar 2024 09:08:11 +0530 Subject: [PATCH 222/300] Update README.md --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 7a7bdb6..21e4eef 100644 --- a/README.md +++ b/README.md @@ -13,24 +13,24 @@ The goal of my algorithm should be to remove zero-sum sublists from a given link # Approach -My approach involves using a dummy node and a HashMap to keep track of the prefix sum and the corresponding nodes. +My approach involved using a dummy node and a HashMap to keep track of the prefix sum and the corresponding nodes. **Initialization :** - - Created a dummy node with a value of 0 and set it as the head. - - Initialized a HashMap to store the prefix sum and corresponding nodes, starting with a prefix sum of 0 pointing to the dummy node. - - Set the initial prefix sum variable to 0. +- Created a dummy node with a value of 0 and set it as the head. +- Initialized a HashMap to store the prefix sum and corresponding nodes, starting with a prefix sum of 0 pointing to the dummy node. +- Set the initial prefix sum variable to 0. **Populated the HashMap :** - - Traversed the linked list, updating the prefix sum as we iterate. - - Stored the current prefix sum and the corresponding node in the HashMap. +- Traversed the linked list, updating the prefix sum as we iterate. +- Stored the current prefix sum and the corresponding node in the HashMap. **Removed Zero-Sum Sublists :** - - Reset the prefix sum variable to 0. - - Traversed the linked list again. - - Updated the next pointers of nodes to remove zero-sum sublists by pointing them to the next node after the corresponding prefix sum in the HashMap. +- Reset the prefix sum variable to 0. +- Traversed the linked list again. +- Updated the next pointers of nodes to remove zero-sum sublists by pointing them to the next node after the corresponding prefix sum in the HashMap. **Result :** - - Returned the modified list starting from the dummy node's next. +- Returned the modified list starting from the dummy node's next. My approach efficiently handled the removal of zero-sum sublists by leveraging the HashMap to keep track of the prefix sums and their corresponding nodes. From d544b2b666343ecebc3c589e0b2779a666109eb1 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 12 Mar 2024 09:08:55 +0530 Subject: [PATCH 223/300] Create Daily 12-03-24.md --- 2024 March/Daily 12-03-24.md | 91 ++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 2024 March/Daily 12-03-24.md diff --git a/2024 March/Daily 12-03-24.md b/2024 March/Daily 12-03-24.md new file mode 100644 index 0000000..1145b30 --- /dev/null +++ b/2024 March/Daily 12-03-24.md @@ -0,0 +1,91 @@ +## Today's 12-03-24 [Problem Link](https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/description/?envType=daily-question&envId=2024-03-12) +## 1171. Remove Zero Sum Consecutive Nodes from Linked List + +# Intuition + +The goal of my algorithm should be to remove zero-sum sublists from a given linked list. + +# Approach + +My approach involved using a dummy node and a HashMap to keep track of the prefix sum and the corresponding nodes. + +**Initialization :** +- Created a dummy node with a value of 0 and set it as the head. +- Initialized a HashMap to store the prefix sum and corresponding nodes, starting with a prefix sum of 0 pointing to the dummy node. +- Set the initial prefix sum variable to 0. + +**Populated the HashMap :** +- Traversed the linked list, updating the prefix sum as we iterate. +- Stored the current prefix sum and the corresponding node in the HashMap. + +**Removed Zero-Sum Sublists :** +- Reset the prefix sum variable to 0. +- Traversed the linked list again. +- Updated the next pointers of nodes to remove zero-sum sublists by pointing them to the next node after the corresponding prefix sum in the HashMap. + +**Result :** +- Returned the modified list starting from the dummy node's next. + +My approach efficiently handled the removal of zero-sum sublists by leveraging the HashMap to keep track of the prefix sums and their corresponding nodes. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(N)$ + +$N$ : number of nodes in the linked list +- Space complexity : $O(N)$ + + +# Code +``` +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + + // Static variables to store the map, the current node, and the prefix sum + static Map m; + static ListNode t; + static int prefixJor; + + // Function to remove zero-sum sublists + public ListNode removeZeroSumSublists(ListNode head) { + + // Creating a dummy node with value 0 and set it as the head + t = new ListNode(0, head); + + // Initializing the map with prefix sum 0 pointing to the dummy node + m = new HashMap<>(); + m.put(0, t); + + // Initializing the prefix sum variable + prefixJor = 0; + + // Populating the map with prefix sum and corresponding nodes + for (ListNode node = t; node != null; node = node.next) { + prefixJor += node.val; + m.put(prefixJor, node); + } + + // Resetting prefix sum + prefixJor = 0; + + // Updating the next pointers to remove zero-sum sublists + for (ListNode node = t; node != null; node = node.next) { + prefixJor += node.val; + node.next = m.get(prefixJor).next; + } + + // Returning the modified list starting from the dummy node's next + return t.next; + } +} +``` \ No newline at end of file From 4cd06522b386e2cb3e1f6c2e4cfc497fffa84993 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 13 Mar 2024 09:41:51 +0530 Subject: [PATCH 224/300] Update README.md --- README.md | 97 +++++++++++++++++-------------------------------------- 1 file changed, 30 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index 21e4eef..00ccf31 100644 --- a/README.md +++ b/README.md @@ -4,94 +4,57 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 12-03-24 [Problem Link](https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/description/?envType=daily-question&envId=2024-03-12) -## 1171. Remove Zero Sum Consecutive Nodes from Linked List +## Today's 13-03-24 [Problem Link](https://leetcode.com/problems/find-the-pivot-integer/description/?envType=daily-question&envId=2024-03-13) +## 2485. Find the Pivot Integer # Intuition -The goal of my algorithm should be to remove zero-sum sublists from a given linked list. +The goal of the `pivotInteger` function is to find a pivot integer 'x' for a given integer 'n', where the sum of integers from 1 to 'x' is equal to the sum of integers from 'x + 1' to 'n'. # Approach -My approach involved using a dummy node and a HashMap to keep track of the prefix sum and the corresponding nodes. +The derivation involves solving a quadratic equation based on the summation of arithmetic series. The key steps are as follows: -**Initialization :** -- Created a dummy node with a value of 0 and set it as the head. -- Initialized a HashMap to store the prefix sum and corresponding nodes, starting with a prefix sum of 0 pointing to the dummy node. -- Set the initial prefix sum variable to 0. +**Summation Equation** : \(1 + 2 + ... + x = x + ... + n\) -**Populated the HashMap :** -- Traversed the linked list, updating the prefix sum as we iterate. -- Stored the current prefix sum and the corresponding node in the HashMap. +**Quadratic Equation** : \((1 + x) \times \frac{x}{2} = (x + n) \times \frac{n - x + 1}{2}\) -**Removed Zero-Sum Sublists :** -- Reset the prefix sum variable to 0. -- Traversed the linked list again. -- Updated the next pointers of nodes to remove zero-sum sublists by pointing them to the next node after the corresponding prefix sum in the HashMap. +**Simplify and Solved** : Manipulated the equation to get \(2 * x^2 = n^2 + n\) and solved for 'x'. -**Result :** -- Returned the modified list starting from the dummy node's next. +**Calculated and Checked** : Calculated 'y' as \(\frac{n^2 + n}{2}\) and find the square root 'x'. Check if \(x^2\) equals 'y'. -My approach efficiently handled the removal of zero-sum sublists by leveraging the HashMap to keep track of the prefix sums and their corresponding nodes. +**Result** : Returned 'x' if it's a perfect square; otherwise, return -1. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(N)$ +- Time complexity : $O(1)$ -$N$ : number of nodes in the linked list -- Space complexity : $O(N)$ + +- Space complexity : $O(1)$ # Code ``` -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ class Solution { + public int pivotInteger(int n) { + + /* Sum of the series: 1 + 2 + ... + x = x + ... + n + Equation derivation : + (1 + x) * x / 2 = (x + n) * (n - x + 1) / 2 + Simplifying : + x + x^2 = nx - x^2 + x + n^2 - nx + n + 2 * x^2 = n^2 + n + Solving for x: + x = sqrt((n^2 + n) / 2) + */ - // Static variables to store the map, the current node, and the prefix sum - static Map m; - static ListNode t; - static int prefixJor; - - // Function to remove zero-sum sublists - public ListNode removeZeroSumSublists(ListNode head) { - - // Creating a dummy node with value 0 and set it as the head - t = new ListNode(0, head); - - // Initializing the map with prefix sum 0 pointing to the dummy node - m = new HashMap<>(); - m.put(0, t); - - // Initializing the prefix sum variable - prefixJor = 0; - - // Populating the map with prefix sum and corresponding nodes - for (ListNode node = t; node != null; node = node.next) { - prefixJor += node.val; - m.put(prefixJor, node); - } - - // Resetting prefix sum - prefixJor = 0; - - // Updating the next pointers to remove zero-sum sublists - for (ListNode node = t; node != null; node = node.next) { - prefixJor += node.val; - node.next = m.get(prefixJor).next; - } - - // Returning the modified list starting from the dummy node's next - return t.next; - } + // Calculating values and checking for a perfect square + final int y = (n * n + n) / 2; + final int x = (int) Math.sqrt(y); + + // Returning result based on perfect square condition + return x * x == y ? x : -1; + } } ``` \ No newline at end of file From c485a6ab9bfeaf88039af1e0d509ab1ebf0d13e2 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 13 Mar 2024 09:43:06 +0530 Subject: [PATCH 225/300] Create Daily 13-03-24.md --- 2024 March/Daily 13-03-24.md | 60 ++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 2024 March/Daily 13-03-24.md diff --git a/2024 March/Daily 13-03-24.md b/2024 March/Daily 13-03-24.md new file mode 100644 index 0000000..00ccf31 --- /dev/null +++ b/2024 March/Daily 13-03-24.md @@ -0,0 +1,60 @@ +# Leetcode Daily Challenge Solutions + +This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. + +## Always here to assist you guys. + +## Today's 13-03-24 [Problem Link](https://leetcode.com/problems/find-the-pivot-integer/description/?envType=daily-question&envId=2024-03-13) +## 2485. Find the Pivot Integer + +# Intuition + +The goal of the `pivotInteger` function is to find a pivot integer 'x' for a given integer 'n', where the sum of integers from 1 to 'x' is equal to the sum of integers from 'x + 1' to 'n'. + +# Approach + +The derivation involves solving a quadratic equation based on the summation of arithmetic series. The key steps are as follows: + +**Summation Equation** : \(1 + 2 + ... + x = x + ... + n\) + +**Quadratic Equation** : \((1 + x) \times \frac{x}{2} = (x + n) \times \frac{n - x + 1}{2}\) + +**Simplify and Solved** : Manipulated the equation to get \(2 * x^2 = n^2 + n\) and solved for 'x'. + +**Calculated and Checked** : Calculated 'y' as \(\frac{n^2 + n}{2}\) and find the square root 'x'. Check if \(x^2\) equals 'y'. + +**Result** : Returned 'x' if it's a perfect square; otherwise, return -1. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(1)$ + + +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + public int pivotInteger(int n) { + + /* Sum of the series: 1 + 2 + ... + x = x + ... + n + Equation derivation : + (1 + x) * x / 2 = (x + n) * (n - x + 1) / 2 + Simplifying : + x + x^2 = nx - x^2 + x + n^2 - nx + n + 2 * x^2 = n^2 + n + Solving for x: + x = sqrt((n^2 + n) / 2) + */ + + // Calculating values and checking for a perfect square + final int y = (n * n + n) / 2; + final int x = (int) Math.sqrt(y); + + // Returning result based on perfect square condition + return x * x == y ? x : -1; + } +} +``` \ No newline at end of file From 67fdef8c6dc5f28bce668269e079f4db1a8033f7 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 13 Mar 2024 09:44:25 +0530 Subject: [PATCH 226/300] Delete Daily 13-03-24.md --- 2024 March/Daily 13-03-24.md | 60 ------------------------------------ 1 file changed, 60 deletions(-) delete mode 100644 2024 March/Daily 13-03-24.md diff --git a/2024 March/Daily 13-03-24.md b/2024 March/Daily 13-03-24.md deleted file mode 100644 index 00ccf31..0000000 --- a/2024 March/Daily 13-03-24.md +++ /dev/null @@ -1,60 +0,0 @@ -# Leetcode Daily Challenge Solutions - -This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. - -## Always here to assist you guys. - -## Today's 13-03-24 [Problem Link](https://leetcode.com/problems/find-the-pivot-integer/description/?envType=daily-question&envId=2024-03-13) -## 2485. Find the Pivot Integer - -# Intuition - -The goal of the `pivotInteger` function is to find a pivot integer 'x' for a given integer 'n', where the sum of integers from 1 to 'x' is equal to the sum of integers from 'x + 1' to 'n'. - -# Approach - -The derivation involves solving a quadratic equation based on the summation of arithmetic series. The key steps are as follows: - -**Summation Equation** : \(1 + 2 + ... + x = x + ... + n\) - -**Quadratic Equation** : \((1 + x) \times \frac{x}{2} = (x + n) \times \frac{n - x + 1}{2}\) - -**Simplify and Solved** : Manipulated the equation to get \(2 * x^2 = n^2 + n\) and solved for 'x'. - -**Calculated and Checked** : Calculated 'y' as \(\frac{n^2 + n}{2}\) and find the square root 'x'. Check if \(x^2\) equals 'y'. - -**Result** : Returned 'x' if it's a perfect square; otherwise, return -1. - ---- -Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) -# Complexity -- Time complexity : $O(1)$ - - -- Space complexity : $O(1)$ - - -# Code -``` -class Solution { - public int pivotInteger(int n) { - - /* Sum of the series: 1 + 2 + ... + x = x + ... + n - Equation derivation : - (1 + x) * x / 2 = (x + n) * (n - x + 1) / 2 - Simplifying : - x + x^2 = nx - x^2 + x + n^2 - nx + n - 2 * x^2 = n^2 + n - Solving for x: - x = sqrt((n^2 + n) / 2) - */ - - // Calculating values and checking for a perfect square - final int y = (n * n + n) / 2; - final int x = (int) Math.sqrt(y); - - // Returning result based on perfect square condition - return x * x == y ? x : -1; - } -} -``` \ No newline at end of file From 7ad69a2d150e5f235c442f23c4e6ab2a3f854fd2 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 13 Mar 2024 09:45:22 +0530 Subject: [PATCH 227/300] Create Daily 13-03-24.md --- 2024 March/Daily 13-03-24.md | 54 ++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 2024 March/Daily 13-03-24.md diff --git a/2024 March/Daily 13-03-24.md b/2024 March/Daily 13-03-24.md new file mode 100644 index 0000000..e10a1b3 --- /dev/null +++ b/2024 March/Daily 13-03-24.md @@ -0,0 +1,54 @@ +## Today's 13-03-24 [Problem Link](https://leetcode.com/problems/find-the-pivot-integer/description/?envType=daily-question&envId=2024-03-13) +## 2485. Find the Pivot Integer + +# Intuition + +The goal of the `pivotInteger` function is to find a pivot integer 'x' for a given integer 'n', where the sum of integers from 1 to 'x' is equal to the sum of integers from 'x + 1' to 'n'. + +# Approach + +The derivation involves solving a quadratic equation based on the summation of arithmetic series. The key steps are as follows: + +**Summation Equation** : \(1 + 2 + ... + x = x + ... + n\) + +**Quadratic Equation** : \((1 + x) \times \frac{x}{2} = (x + n) \times \frac{n - x + 1}{2}\) + +**Simplify and Solved** : Manipulated the equation to get \(2 * x^2 = n^2 + n\) and solved for 'x'. + +**Calculated and Checked** : Calculated 'y' as \(\frac{n^2 + n}{2}\) and find the square root 'x'. Check if \(x^2\) equals 'y'. + +**Result** : Returned 'x' if it's a perfect square; otherwise, return -1. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(1)$ + + +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + public int pivotInteger(int n) { + + /* Sum of the series: 1 + 2 + ... + x = x + ... + n + Equation derivation : + (1 + x) * x / 2 = (x + n) * (n - x + 1) / 2 + Simplifying : + x + x^2 = nx - x^2 + x + n^2 - nx + n + 2 * x^2 = n^2 + n + Solving for x: + x = sqrt((n^2 + n) / 2) + */ + + // Calculating values and checking for a perfect square + final int y = (n * n + n) / 2; + final int x = (int) Math.sqrt(y); + + // Returning result based on perfect square condition + return x * x == y ? x : -1; + } +} +``` \ No newline at end of file From e30a5821c0066206bd950cc9fe154343e171c6a1 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 13 Mar 2024 13:46:25 +0530 Subject: [PATCH 228/300] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 00ccf31..7ee6dde 100644 --- a/README.md +++ b/README.md @@ -15,13 +15,13 @@ The goal of the `pivotInteger` function is to find a pivot integer 'x' for a giv The derivation involves solving a quadratic equation based on the summation of arithmetic series. The key steps are as follows: -**Summation Equation** : \(1 + 2 + ... + x = x + ... + n\) +**Summation Equation** : $1 + 2 + ... + x = x + ... + n$ -**Quadratic Equation** : \((1 + x) \times \frac{x}{2} = (x + n) \times \frac{n - x + 1}{2}\) +**Quadratic Equation** : $(1 + x) \times \frac{x}{2} = (x + n) \times \frac{n - x + 1}{2}$ -**Simplify and Solved** : Manipulated the equation to get \(2 * x^2 = n^2 + n\) and solved for 'x'. +**Simplify and Solved** : Manipulated the equation to get $2 * x^2 = n^2 + n$ and solved for 'x'. -**Calculated and Checked** : Calculated 'y' as \(\frac{n^2 + n}{2}\) and find the square root 'x'. Check if \(x^2\) equals 'y'. +**Calculated and Checked** : Calculated 'y' as $\frac{n^2 + n}{2}$ and find the square root 'x'. Checked if $x^2$ equals 'y'. **Result** : Returned 'x' if it's a perfect square; otherwise, return -1. From e9e6a06e79e2dfc0a019aa3453d951c6d0fa6b2d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 13 Mar 2024 13:46:56 +0530 Subject: [PATCH 229/300] Update Daily 13-03-24.md --- 2024 March/Daily 13-03-24.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/2024 March/Daily 13-03-24.md b/2024 March/Daily 13-03-24.md index e10a1b3..299dbd5 100644 --- a/2024 March/Daily 13-03-24.md +++ b/2024 March/Daily 13-03-24.md @@ -9,13 +9,13 @@ The goal of the `pivotInteger` function is to find a pivot integer 'x' for a giv The derivation involves solving a quadratic equation based on the summation of arithmetic series. The key steps are as follows: -**Summation Equation** : \(1 + 2 + ... + x = x + ... + n\) +**Summation Equation** : $1 + 2 + ... + x = x + ... + n$ -**Quadratic Equation** : \((1 + x) \times \frac{x}{2} = (x + n) \times \frac{n - x + 1}{2}\) +**Quadratic Equation** : $(1 + x) \times \frac{x}{2} = (x + n) \times \frac{n - x + 1}{2}$ -**Simplify and Solved** : Manipulated the equation to get \(2 * x^2 = n^2 + n\) and solved for 'x'. +**Simplify and Solved** : Manipulated the equation to get $2 * x^2 = n^2 + n$ and solved for 'x'. -**Calculated and Checked** : Calculated 'y' as \(\frac{n^2 + n}{2}\) and find the square root 'x'. Check if \(x^2\) equals 'y'. +**Calculated and Checked** : Calculated 'y' as $\frac{n^2 + n}{2}$ and find the square root 'x'. Checked if $x^2$ equals 'y'. **Result** : Returned 'x' if it's a perfect square; otherwise, return -1. From 8159491368d8e2530ee1581723c27228a5d08698 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 14 Mar 2024 10:06:02 +0530 Subject: [PATCH 230/300] Update README.md --- README.md | 78 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 44 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 7ee6dde..0aac287 100644 --- a/README.md +++ b/README.md @@ -4,57 +4,67 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 13-03-24 [Problem Link](https://leetcode.com/problems/find-the-pivot-integer/description/?envType=daily-question&envId=2024-03-13) -## 2485. Find the Pivot Integer +## Today's 14-03-24 [Problem Link](https://leetcode.com/problems/binary-subarrays-with-sum/description/?envType=daily-question&envId=2024-03-14) +## 930. Binary Subarrays With Sum # Intuition -The goal of the `pivotInteger` function is to find a pivot integer 'x' for a given integer 'n', where the sum of integers from 1 to 'x' is equal to the sum of integers from 'x + 1' to 'n'. +To efficiently count the subarrays with the desired sum, I will utilize the concept of prefix sums. +- A prefix sum of an array at index `i` represents the sum of all elements from index 0 to `i`. +- By maintaining a prefix sum, I can determine the sum of any subarray by computing the difference between two prefix sums. # Approach -The derivation involves solving a quadratic equation based on the summation of arithmetic series. The key steps are as follows: +- Initialized the variables : `ans` to store the result, `prefix` to keep track of the prefix sum, and `count` as a HashMap to store the count of encountered prefix sums. +- Initialized the `count` HashMap with a key-value pair `(0, 1)` to indicate the prefix sum of 0 with count 1. +- Iterated through the array elements : + - Updated the `prefix` sum by adding the current element. + - Calculated the difference between the current prefix sum and the target value (`goal`). + - If the HashMap contained the calculated key, added the count associated with that key to the result. + - Updated the count of the current prefix sum in the HashMap. +- Returned the final count of subarrays with the given sum (`ans`). -**Summation Equation** : $1 + 2 + ... + x = x + ... + n$ - -**Quadratic Equation** : $(1 + x) \times \frac{x}{2} = (x + n) \times \frac{n - x + 1}{2}$ - -**Simplify and Solved** : Manipulated the equation to get $2 * x^2 = n^2 + n$ and solved for 'x'. - -**Calculated and Checked** : Calculated 'y' as $\frac{n^2 + n}{2}$ and find the square root 'x'. Checked if $x^2$ equals 'y'. - -**Result** : Returned 'x' if it's a perfect square; otherwise, return -1. +My approach efficiently counted the number of subarrays with the desired sum by utilizing prefix sums and a HashMap to keep track of prefix sum occurrences. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(1)$ +- Time complexity : $O(n)$ - -- Space complexity : $O(1)$ +$n$ : size of the input array +- Space complexity : $O(n)$ # Code ``` class Solution { - public int pivotInteger(int n) { - - /* Sum of the series: 1 + 2 + ... + x = x + ... + n - Equation derivation : - (1 + x) * x / 2 = (x + n) * (n - x + 1) / 2 - Simplifying : - x + x^2 = nx - x^2 + x + n^2 - nx + n - 2 * x^2 = n^2 + n - Solving for x: - x = sqrt((n^2 + n) / 2) - */ - - // Calculating values and checking for a perfect square - final int y = (n * n + n) / 2; - final int x = (int) Math.sqrt(y); - - // Returning result based on perfect square condition - return x * x == y ? x : -1; + + // Method to count the number of subarrays with the given sum. + public int numSubarraysWithSum(int[] nums, int goal) { + + // Initializing variables to store the result and the prefix sum. + int ans = 0; + int prefix = 0; + // Creating a HashMap to store the count of prefix sums encountered so far. + Map count = new HashMap<>(); + // Adding an initial key-value pair to indicate the prefix sum of 0 with count 1. + count.put(0, 1); + + // Iterating through the array elements. + for (final int num : nums) { + // Updating the prefix sum. + prefix += num; + // Calculating the difference between the current prefix sum and the target value. + final int key = prefix - goal; + // If the HashMap contains the key, add the count associated with that key to the result. + if (count.containsKey(key)) + ans += count.get(key); + // Updating the count of the current prefix sum in the HashMap. + count.merge(prefix, 1, Integer::sum); + } + + // Returning the final count of subarrays with the given sum. + return ans; } } ``` \ No newline at end of file From 5f07d5ed1f6313fadf8cb5361e390cdd3346c2e1 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 14 Mar 2024 10:06:51 +0530 Subject: [PATCH 231/300] Create Daily 14-03-24.md --- 2024 March/Daily 14-03-24.md | 64 ++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 2024 March/Daily 14-03-24.md diff --git a/2024 March/Daily 14-03-24.md b/2024 March/Daily 14-03-24.md new file mode 100644 index 0000000..72f1fc8 --- /dev/null +++ b/2024 March/Daily 14-03-24.md @@ -0,0 +1,64 @@ +## Today's 14-03-24 [Problem Link](https://leetcode.com/problems/binary-subarrays-with-sum/description/?envType=daily-question&envId=2024-03-14) +## 930. Binary Subarrays With Sum + +# Intuition + +To efficiently count the subarrays with the desired sum, I will utilize the concept of prefix sums. +- A prefix sum of an array at index `i` represents the sum of all elements from index 0 to `i`. +- By maintaining a prefix sum, I can determine the sum of any subarray by computing the difference between two prefix sums. + +# Approach + +- Initialized the variables : `ans` to store the result, `prefix` to keep track of the prefix sum, and `count` as a HashMap to store the count of encountered prefix sums. +- Initialized the `count` HashMap with a key-value pair `(0, 1)` to indicate the prefix sum of 0 with count 1. +- Iterated through the array elements : + - Updated the `prefix` sum by adding the current element. + - Calculated the difference between the current prefix sum and the target value (`goal`). + - If the HashMap contained the calculated key, added the count associated with that key to the result. + - Updated the count of the current prefix sum in the HashMap. +- Returned the final count of subarrays with the given sum (`ans`). + +My approach efficiently counted the number of subarrays with the desired sum by utilizing prefix sums and a HashMap to keep track of prefix sum occurrences. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : size of the input array +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + + // Method to count the number of subarrays with the given sum. + public int numSubarraysWithSum(int[] nums, int goal) { + + // Initializing variables to store the result and the prefix sum. + int ans = 0; + int prefix = 0; + // Creating a HashMap to store the count of prefix sums encountered so far. + Map count = new HashMap<>(); + // Adding an initial key-value pair to indicate the prefix sum of 0 with count 1. + count.put(0, 1); + + // Iterating through the array elements. + for (final int num : nums) { + // Updating the prefix sum. + prefix += num; + // Calculating the difference between the current prefix sum and the target value. + final int key = prefix - goal; + // If the HashMap contains the key, add the count associated with that key to the result. + if (count.containsKey(key)) + ans += count.get(key); + // Updating the count of the current prefix sum in the HashMap. + count.merge(prefix, 1, Integer::sum); + } + + // Returning the final count of subarrays with the given sum. + return ans; + } +} +``` \ No newline at end of file From 7a4c2e42471adbe7aad327dceddca3456b620c6a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 15 Mar 2024 10:16:58 +0530 Subject: [PATCH 232/300] Update README.md --- README.md | 79 +++++++++++++++++++++++++++---------------------------- 1 file changed, 39 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 0aac287..bf70c1b 100644 --- a/README.md +++ b/README.md @@ -4,67 +4,66 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 14-03-24 [Problem Link](https://leetcode.com/problems/binary-subarrays-with-sum/description/?envType=daily-question&envId=2024-03-14) -## 930. Binary Subarrays With Sum +## Today's 15-03-24 [Problem Link](https://leetcode.com/problems/product-of-array-except-self/description/?envType=daily-question&envId=2024-03-15) +## 238. Product of Array Except Self # Intuition -To efficiently count the subarrays with the desired sum, I will utilize the concept of prefix sums. -- A prefix sum of an array at index `i` represents the sum of all elements from index 0 to `i`. -- By maintaining a prefix sum, I can determine the sum of any subarray by computing the difference between two prefix sums. +Given an array `nums` of integers, we are tasked with finding an array `jawab` such that `jawab[i]` is equal to the product of all the elements of `nums` except `nums[i]`. # Approach -- Initialized the variables : `ans` to store the result, `prefix` to keep track of the prefix sum, and `count` as a HashMap to store the count of encountered prefix sums. -- Initialized the `count` HashMap with a key-value pair `(0, 1)` to indicate the prefix sum of 0 with count 1. -- Iterated through the array elements : - - Updated the `prefix` sum by adding the current element. - - Calculated the difference between the current prefix sum and the target value (`goal`). - - If the HashMap contained the calculated key, added the count associated with that key to the result. - - Updated the count of the current prefix sum in the HashMap. -- Returned the final count of subarrays with the given sum (`ans`). +**Prefix Product Calculation** : + - I first calculated the product of all elements to the left of each element `nums[i]` and stored it in the `jawab` array. + - I initialized `jawab[0] = 1` and then iterate through the array from index 1 to `nums.length - 1`. For each index `i`, `jawab[i]` is assigned the product of all elements to the left of `nums[i]`. -My approach efficiently counted the number of subarrays with the desired sum by utilizing prefix sums and a HashMap to keep track of prefix sum occurrences. +**Suffix Product Calculation** : + - I then calculated the product of all elements to the right of each element `nums[i]`, multiplying it with the corresponding value in the `jawab` array. + - I initialized a variable `s = 1` and iterated through the array from right to left (index `nums.length - 1` to 0). For each index `i`, I multiplied `jawab[i]` with `s` and updated `s` by multiplying it with `nums[i]`. + +**Final Result** : + - After both prefix and suffix products are calculated and combined, the `jawab` array contained the desired product of all elements except `nums[i]` for each index `i`. + - I returned the `jawab` array as the final result. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : size of the input array +$n$ : length of the input array - Space complexity : $O(n)$ # Code ``` class Solution { - - // Method to count the number of subarrays with the given sum. - public int numSubarraysWithSum(int[] nums, int goal) { + + // Static variable to store the result + static int[] jawab; - // Initializing variables to store the result and the prefix sum. - int ans = 0; - int prefix = 0; - // Creating a HashMap to store the count of prefix sums encountered so far. - Map count = new HashMap<>(); - // Adding an initial key-value pair to indicate the prefix sum of 0 with count 1. - count.put(0, 1); + // Method to calculate product of array except self + public int[] productExceptSelf(int[] nums) { + + // Initializing the result array + jawab = new int[nums.length]; + // Set the initial value of the first element in the result array to 1 + jawab[0] = 1; - // Iterating through the array elements. - for (final int num : nums) { - // Updating the prefix sum. - prefix += num; - // Calculating the difference between the current prefix sum and the target value. - final int key = prefix - goal; - // If the HashMap contains the key, add the count associated with that key to the result. - if (count.containsKey(key)) - ans += count.get(key); - // Updating the count of the current prefix sum in the HashMap. - count.merge(prefix, 1, Integer::sum); - } + // Calculating product of elements to the left of current element + for (int i = 1; i < nums.length; i++) { + jawab[i] = jawab[i - 1] * nums[i - 1]; + } - // Returning the final count of subarrays with the given sum. - return ans; - } + // Initializing a variable to store product of elements to the right of current element + int s = 1; + // Calculating product of elements to the right of current element and update result array + for (int i = nums.length - 1; i >= 0; i--) { + jawab[i] *= s; + s *= nums[i]; + } + + // Returning the final result array + return jawab; + } } ``` \ No newline at end of file From edfa61920e1f2786f13dc753ea22e1ac3b52987d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 15 Mar 2024 10:17:44 +0530 Subject: [PATCH 233/300] Create Daily 15-03-24.md --- 2024 March/Daily 15-03-24.md | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 2024 March/Daily 15-03-24.md diff --git a/2024 March/Daily 15-03-24.md b/2024 March/Daily 15-03-24.md new file mode 100644 index 0000000..3504251 --- /dev/null +++ b/2024 March/Daily 15-03-24.md @@ -0,0 +1,63 @@ +## Today's 15-03-24 [Problem Link](https://leetcode.com/problems/product-of-array-except-self/description/?envType=daily-question&envId=2024-03-15) +## 238. Product of Array Except Self + +# Intuition + +Given an array `nums` of integers, we are tasked with finding an array `jawab` such that `jawab[i]` is equal to the product of all the elements of `nums` except `nums[i]`. + +# Approach + +**Prefix Product Calculation** : + - I first calculated the product of all elements to the left of each element `nums[i]` and stored it in the `jawab` array. + - I initialized `jawab[0] = 1` and then iterate through the array from index 1 to `nums.length - 1`. For each index `i`, `jawab[i]` is assigned the product of all elements to the left of `nums[i]`. + +**Suffix Product Calculation** : + - I then calculated the product of all elements to the right of each element `nums[i]`, multiplying it with the corresponding value in the `jawab` array. + - I initialized a variable `s = 1` and iterated through the array from right to left (index `nums.length - 1` to 0). For each index `i`, I multiplied `jawab[i]` with `s` and updated `s` by multiplying it with `nums[i]`. + +**Final Result** : + - After both prefix and suffix products are calculated and combined, the `jawab` array contained the desired product of all elements except `nums[i]` for each index `i`. + - I returned the `jawab` array as the final result. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the input array +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + + // Static variable to store the result + static int[] jawab; + + // Method to calculate product of array except self + public int[] productExceptSelf(int[] nums) { + + // Initializing the result array + jawab = new int[nums.length]; + // Set the initial value of the first element in the result array to 1 + jawab[0] = 1; + + // Calculating product of elements to the left of current element + for (int i = 1; i < nums.length; i++) { + jawab[i] = jawab[i - 1] * nums[i - 1]; + } + + // Initializing a variable to store product of elements to the right of current element + int s = 1; + // Calculating product of elements to the right of current element and update result array + for (int i = nums.length - 1; i >= 0; i--) { + jawab[i] *= s; + s *= nums[i]; + } + + // Returning the final result array + return jawab; + } +} +``` \ No newline at end of file From f567bcd814405d9c5966eca086294e5b6b60a60f Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 16 Mar 2024 09:56:30 +0530 Subject: [PATCH 234/300] Update README.md --- README.md | 85 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 46 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index bf70c1b..4b7f0f7 100644 --- a/README.md +++ b/README.md @@ -4,66 +4,73 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 15-03-24 [Problem Link](https://leetcode.com/problems/product-of-array-except-self/description/?envType=daily-question&envId=2024-03-15) -## 238. Product of Array Except Self +## Today's 16-03-24 [Problem Link](https://leetcode.com/problems/contiguous-array/description/?envType=daily-question&envId=2024-03-16) +## 525. Contiguous Array # Intuition -Given an array `nums` of integers, we are tasked with finding an array `jawab` such that `jawab[i]` is equal to the product of all the elements of `nums` except `nums[i]`. +The problem requires finding the maximum length of a contiguous subarray with an equal number of 0s and 1s. To approach this, I can utilize the concept of a running sum. # Approach -**Prefix Product Calculation** : - - I first calculated the product of all elements to the left of each element `nums[i]` and stored it in the `jawab` array. - - I initialized `jawab[0] = 1` and then iterate through the array from index 1 to `nums.length - 1`. For each index `i`, `jawab[i]` is assigned the product of all elements to the left of `nums[i]`. +**Running Sum :** I maintained a running sum of the elements encountered so far, where I increment the sum by 1 for every 1 encountered and decrement it by 1 for every 0 encountered. -**Suffix Product Calculation** : - - I then calculated the product of all elements to the right of each element `nums[i]`, multiplying it with the corresponding value in the `jawab` array. - - I initialized a variable `s = 1` and iterated through the array from right to left (index `nums.length - 1` to 0). For each index `i`, I multiplied `jawab[i]` with `s` and updated `s` by multiplying it with `nums[i]`. +**Equal Number of 0s and 1s :** If the running sum is equal at two different indices, it implies that the number of 0s and 1s between those indices is the same. -**Final Result** : - - After both prefix and suffix products are calculated and combined, the `jawab` array contained the desired product of all elements except `nums[i]` for each index `i`. - - I returned the `jawab` array as the final result. +**Maximum Length :** I aim to maximize the length of the subarray with an equal number of 0s and 1s. + +By storing the running sum and its corresponding index in a map, I can efficiently determine the maximum length by checking if a running sum repeats. If it does, the difference between the current index and the index stored for that running sum gives the length of the subarray with equal 0s and 1s. + +Through this approach, I can efficiently find the maximum length of the required subarray. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(a)$ -$n$ : length of the input array -- Space complexity : $O(n)$ +$a$ : length of the input array +- Space complexity : $O(a)$ # Code ``` class Solution { - - // Static variable to store the result - static int[] jawab; - - // Method to calculate product of array except self - public int[] productExceptSelf(int[] nums) { - - // Initializing the result array - jawab = new int[nums.length]; - // Set the initial value of the first element in the result array to 1 - jawab[0] = 1; + + // Static variable to store the maximum length of subarray with equal number of 0s and 1s + static int maxLength; + + // Method to find the maximum length of subarray with equal number of 0s and 1s + public int findMaxLength(int[] nums) { - // Calculating product of elements to the left of current element - for (int i = 1; i < nums.length; i++) { - jawab[i] = jawab[i - 1] * nums[i - 1]; - } + // Initializing the maximum length to 0 + maxLength = 0; - // Initializing a variable to store product of elements to the right of current element - int s = 1; - // Calculating product of elements to the right of current element and update result array - for (int i = nums.length - 1; i >= 0; i--) { - jawab[i] *= s; - s *= nums[i]; - } + // Variable to keep track of the running sum + int runningSum = 0; + + // Map to store the running sum and its corresponding index + Map sumToIndex = new HashMap<>(); + + // Initializing the map with running sum 0 and index -1 + sumToIndex.put(0, -1); - // Returning the final result array - return jawab; + // Looping through the array + for (int i = 0; i < nums.length; i++) { + // Updating the running sum based on the current element + runningSum += (nums[i] == 1) ? 1 : -1; + // If the running sum is already present in the map + if (sumToIndex.containsKey(runningSum)){ + // Updating the maximum length with the difference between the current index and the index stored in the map + maxLength = Math.max(maxLength, i - sumToIndex.get(runningSum)); + } + else{ + // If the running sum is not present in the map, adding it along with its index + sumToIndex.put(runningSum, i); + } } + + // Returning the maximum length of subarray with equal number of 0s and 1s + return maxLength; + } } ``` \ No newline at end of file From 8040d0e705ac4782eb6850b5a9d8ea2da534ec24 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 16 Mar 2024 09:57:22 +0530 Subject: [PATCH 235/300] Create Daily 16-03-24.md --- 2024 March/Daily 16-03-24.md | 70 ++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 2024 March/Daily 16-03-24.md diff --git a/2024 March/Daily 16-03-24.md b/2024 March/Daily 16-03-24.md new file mode 100644 index 0000000..0418620 --- /dev/null +++ b/2024 March/Daily 16-03-24.md @@ -0,0 +1,70 @@ +## Today's 16-03-24 [Problem Link](https://leetcode.com/problems/contiguous-array/description/?envType=daily-question&envId=2024-03-16) +## 525. Contiguous Array + +# Intuition + +The problem requires finding the maximum length of a contiguous subarray with an equal number of 0s and 1s. To approach this, I can utilize the concept of a running sum. + +# Approach + +**Running Sum :** I maintained a running sum of the elements encountered so far, where I increment the sum by 1 for every 1 encountered and decrement it by 1 for every 0 encountered. + +**Equal Number of 0s and 1s :** If the running sum is equal at two different indices, it implies that the number of 0s and 1s between those indices is the same. + +**Maximum Length :** I aim to maximize the length of the subarray with an equal number of 0s and 1s. + +By storing the running sum and its corresponding index in a map, I can efficiently determine the maximum length by checking if a running sum repeats. If it does, the difference between the current index and the index stored for that running sum gives the length of the subarray with equal 0s and 1s. + +Through this approach, I can efficiently find the maximum length of the required subarray. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(a)$ + +$a$ : length of the input array +- Space complexity : $O(a)$ + + +# Code +``` +class Solution { + + // Static variable to store the maximum length of subarray with equal number of 0s and 1s + static int maxLength; + + // Method to find the maximum length of subarray with equal number of 0s and 1s + public int findMaxLength(int[] nums) { + + // Initializing the maximum length to 0 + maxLength = 0; + + // Variable to keep track of the running sum + int runningSum = 0; + + // Map to store the running sum and its corresponding index + Map sumToIndex = new HashMap<>(); + + // Initializing the map with running sum 0 and index -1 + sumToIndex.put(0, -1); + + // Looping through the array + for (int i = 0; i < nums.length; i++) { + // Updating the running sum based on the current element + runningSum += (nums[i] == 1) ? 1 : -1; + // If the running sum is already present in the map + if (sumToIndex.containsKey(runningSum)){ + // Updating the maximum length with the difference between the current index and the index stored in the map + maxLength = Math.max(maxLength, i - sumToIndex.get(runningSum)); + } + else{ + // If the running sum is not present in the map, adding it along with its index + sumToIndex.put(runningSum, i); + } + } + + // Returning the maximum length of subarray with equal number of 0s and 1s + return maxLength; + } +} +``` \ No newline at end of file From 96558134cfccc4fa4d1297f5b7febee67c21752e Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 17 Mar 2024 10:44:49 +0530 Subject: [PATCH 236/300] Update README.md --- README.md | 100 +++++++++++++++++++++++++++++------------------------- 1 file changed, 54 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 4b7f0f7..3665ff3 100644 --- a/README.md +++ b/README.md @@ -4,73 +4,81 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 16-03-24 [Problem Link](https://leetcode.com/problems/contiguous-array/description/?envType=daily-question&envId=2024-03-16) -## 525. Contiguous Array +## Today's 17-03-24 [Problem Link](https://leetcode.com/problems/insert-interval/description/?envType=daily-question&envId=2024-03-17) +## 57. Insert Interval # Intuition -The problem requires finding the maximum length of a contiguous subarray with an equal number of 0s and 1s. To approach this, I can utilize the concept of a running sum. +The goal of this code is to insert a new interval into a list of intervals while merging any overlapping intervals. # Approach -**Running Sum :** I maintained a running sum of the elements encountered so far, where I increment the sum by 1 for every 1 encountered and decrement it by 1 for every 0 encountered. +**Initialization** : +- Initialized an empty list `jawab` to store the merged intervals. -**Equal Number of 0s and 1s :** If the running sum is equal at two different indices, it implies that the number of 0s and 1s between those indices is the same. +**Iterated Over Intervals** : +- Iterated through the given list of intervals. +- Added intervals that ended before the start of the new interval directly to the result list `jawab`. -**Maximum Length :** I aim to maximize the length of the subarray with an equal number of 0s and 1s. +**Merged Overlapping Intervals** : +- While iterating, merged intervals that overlap with the new interval. +- Updated the start and end values of the new interval accordingly. -By storing the running sum and its corresponding index in a map, I can efficiently determine the maximum length by checking if a running sum repeats. If it does, the difference between the current index and the index stored for that running sum gives the length of the subarray with equal 0s and 1s. +**Added Merged Interval** : +- Added the merged new interval to the result list `jawab`. -Through this approach, I can efficiently find the maximum length of the required subarray. +**Added Remaining Intervals** : +- Added any remaining intervals from the input list to `jawab`. + +**Result** : +- Converted the ArrayList `jawab` to a 2D array and return the result. + +My approach ensures that the intervals are merged efficiently while maintaining the order of intervals. It optimizes the insertion process with a time complexity of O(n), where n is the number of intervals in the input. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(a)$ +- Time complexity : $O(n+m)$ -$a$ : length of the input array -- Space complexity : $O(a)$ +$n$ : number of intervals +$m$ : number of merged intervals +- Space complexity : $O(n+m)$ # Code ``` class Solution { - - // Static variable to store the maximum length of subarray with equal number of 0s and 1s - static int maxLength; - - // Method to find the maximum length of subarray with equal number of 0s and 1s - public int findMaxLength(int[] nums) { - - // Initializing the maximum length to 0 - maxLength = 0; - - // Variable to keep track of the running sum - int runningSum = 0; - - // Map to store the running sum and its corresponding index - Map sumToIndex = new HashMap<>(); - // Initializing the map with running sum 0 and index -1 - sumToIndex.put(0, -1); - - // Looping through the array - for (int i = 0; i < nums.length; i++) { - // Updating the running sum based on the current element - runningSum += (nums[i] == 1) ? 1 : -1; - // If the running sum is already present in the map - if (sumToIndex.containsKey(runningSum)){ - // Updating the maximum length with the difference between the current index and the index stored in the map - maxLength = Math.max(maxLength, i - sumToIndex.get(runningSum)); - } - else{ - // If the running sum is not present in the map, adding it along with its index - sumToIndex.put(runningSum, i); - } - } + static List jawab; // Declaring a static List to hold the intervals + + // Method to insert a new interval into a list of intervals + public int[][] insert(int[][] intervals, int[] newInterval) { + int n = intervals.length; + jawab = new ArrayList<>(); // Initializing the List to store the result + int i = 0; - // Returning the maximum length of subarray with equal number of 0s and 1s - return maxLength; - } + // Adding intervals before the newInterval + while (i < n && intervals[i][1] < newInterval[0]) { + jawab.add(intervals[i++]); + } + + // Merging overlapping intervals with the newInterval + while (i < n && intervals[i][0] <= newInterval[1]) { + newInterval[0] = Math.min(newInterval[0], intervals[i][0]); + newInterval[1] = Math.max(newInterval[1], intervals[i][1]); + i++; + } + + // Adding the merged newInterval + jawab.add(newInterval); + + // Adding intervals after the newInterval + while (i < n) { + jawab.add(intervals[i++]); + } + + // Converting List to 2D array and returning the result + return jawab.toArray(new int[jawab.size()][]); + } } ``` \ No newline at end of file From b5787192ab5c7f48dba1cf3b3c6a10dd36b57dca Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 17 Mar 2024 10:45:31 +0530 Subject: [PATCH 237/300] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 3665ff3..d6233dc 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ Have a look at the code , still have any confusion then please let me know in th - Time complexity : $O(n+m)$ $n$ : number of intervals + $m$ : number of merged intervals - Space complexity : $O(n+m)$ From 75407ab4ddaa69ceb40af86bd577b69eb4905656 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 17 Mar 2024 10:45:57 +0530 Subject: [PATCH 238/300] Create Daily 17-03-24.md --- 2024 March/Daily 17-03-24.md | 79 ++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 2024 March/Daily 17-03-24.md diff --git a/2024 March/Daily 17-03-24.md b/2024 March/Daily 17-03-24.md new file mode 100644 index 0000000..ee06fc4 --- /dev/null +++ b/2024 March/Daily 17-03-24.md @@ -0,0 +1,79 @@ +## Today's 17-03-24 [Problem Link](https://leetcode.com/problems/insert-interval/description/?envType=daily-question&envId=2024-03-17) +## 57. Insert Interval + +# Intuition + +The goal of this code is to insert a new interval into a list of intervals while merging any overlapping intervals. + +# Approach + +**Initialization** : +- Initialized an empty list `jawab` to store the merged intervals. + +**Iterated Over Intervals** : +- Iterated through the given list of intervals. +- Added intervals that ended before the start of the new interval directly to the result list `jawab`. + +**Merged Overlapping Intervals** : +- While iterating, merged intervals that overlap with the new interval. +- Updated the start and end values of the new interval accordingly. + +**Added Merged Interval** : +- Added the merged new interval to the result list `jawab`. + +**Added Remaining Intervals** : +- Added any remaining intervals from the input list to `jawab`. + +**Result** : +- Converted the ArrayList `jawab` to a 2D array and return the result. + +My approach ensures that the intervals are merged efficiently while maintaining the order of intervals. It optimizes the insertion process with a time complexity of O(n), where n is the number of intervals in the input. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(n+m)$ + +$n$ : number of intervals + +$m$ : number of merged intervals +- Space complexity : $O(n+m)$ + + +# Code +``` +class Solution { + + static List jawab; // Declaring a static List to hold the intervals + + // Method to insert a new interval into a list of intervals + public int[][] insert(int[][] intervals, int[] newInterval) { + int n = intervals.length; + jawab = new ArrayList<>(); // Initializing the List to store the result + int i = 0; + + // Adding intervals before the newInterval + while (i < n && intervals[i][1] < newInterval[0]) { + jawab.add(intervals[i++]); + } + + // Merging overlapping intervals with the newInterval + while (i < n && intervals[i][0] <= newInterval[1]) { + newInterval[0] = Math.min(newInterval[0], intervals[i][0]); + newInterval[1] = Math.max(newInterval[1], intervals[i][1]); + i++; + } + + // Adding the merged newInterval + jawab.add(newInterval); + + // Adding intervals after the newInterval + while (i < n) { + jawab.add(intervals[i++]); + } + + // Converting List to 2D array and returning the result + return jawab.toArray(new int[jawab.size()][]); + } +} +``` \ No newline at end of file From 93a60a08cc9460e07d88f766b0cd7ec32170f38d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 18 Mar 2024 10:33:12 +0530 Subject: [PATCH 239/300] Update README.md --- README.md | 91 ++++++++++++++++++++++--------------------------------- 1 file changed, 37 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index d6233dc..3b2ccc9 100644 --- a/README.md +++ b/README.md @@ -4,82 +4,65 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 17-03-24 [Problem Link](https://leetcode.com/problems/insert-interval/description/?envType=daily-question&envId=2024-03-17) -## 57. Insert Interval +## Today's 18-03-24 [Problem Link](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/?envType=daily-question&envId=2024-03-18) +## 452. Minimum Number of Arrows to Burst Balloons # Intuition -The goal of this code is to insert a new interval into a list of intervals while merging any overlapping intervals. - +- Sort the points based on their end coordinates to efficiently burst balloons. +- Iterate through the sorted array, updating the arrow position to burst overlapping balloons. +- Increment the arrow count whenever a new arrow is needed. # Approach -**Initialization** : -- Initialized an empty list `jawab` to store the merged intervals. -**Iterated Over Intervals** : -- Iterated through the given list of intervals. -- Added intervals that ended before the start of the new interval directly to the result list `jawab`. +**Sorted Points :** Sorted the points based on their end coordinates using a custom comparator. + +**Initialized Variables :** Initialized variables for the arrow count and current arrow position. -**Merged Overlapping Intervals** : -- While iterating, merged intervals that overlap with the new interval. -- Updated the start and end values of the new interval accordingly. +**Iterate Through Points :** Iterated through the sorted array of points. -**Added Merged Interval** : -- Added the merged new interval to the result list `jawab`. +**Checked Balloon Positions :** For each point, checked if its start coordinate is greater than the current arrow position. -**Added Remaining Intervals** : -- Added any remaining intervals from the input list to `jawab`. +**Updated Arrow Position :** If the start coordinate of the current point is greater than the current arrow position, updated the arrow position to the end coordinate of the current point. -**Result** : -- Converted the ArrayList `jawab` to a 2D array and return the result. +**Incremented Arrow Count :** Incremented the arrow count whenever a new arrow is needed to burst a balloon. -My approach ensures that the intervals are merged efficiently while maintaining the order of intervals. It optimizes the insertion process with a time complexity of O(n), where n is the number of intervals in the input. +**Result :** After iterating through all points, returned the arrow count as the minimum number of arrows needed. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(n+m)$ +- Time complexity : $O(n * logn )$ -$n$ : number of intervals - -$m$ : number of merged intervals -- Space complexity : $O(n+m)$ +$n$ : number of points +- Space complexity : $O(1)$ # Code ``` class Solution { + public int findMinArrowShots(int[][] points) { - static List jawab; // Declaring a static List to hold the intervals - - // Method to insert a new interval into a list of intervals - public int[][] insert(int[][] intervals, int[] newInterval) { - int n = intervals.length; - jawab = new ArrayList<>(); // Initializing the List to store the result - int i = 0; - - // Adding intervals before the newInterval - while (i < n && intervals[i][1] < newInterval[0]) { - jawab.add(intervals[i++]); - } - - // Merging overlapping intervals with the newInterval - while (i < n && intervals[i][0] <= newInterval[1]) { - newInterval[0] = Math.min(newInterval[0], intervals[i][0]); - newInterval[1] = Math.max(newInterval[1], intervals[i][1]); - i++; - } - - // Adding the merged newInterval - jawab.add(newInterval); - - // Adding intervals after the newInterval - while (i < n) { - jawab.add(intervals[i++]); - } - - // Converting List to 2D array and returning the result - return jawab.toArray(new int[jawab.size()][]); + // Sorting points based on their end coordinates + Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1])); + + // Initializing variables + int jawab = 1; + int teer = points[0][1]; + + // Iterating through the sorted array of points + for (int i = 1; i < points.length; ++i) { + // If the start coordinate of the current point is greater than the current arrow position + if (points[i][0] > teer) { + // Updating the current arrow position to the end coordinate of the current point + teer = points[i][1]; + // Incrementing the arrow count + jawab++; + } } + + // Returning the arrow count as the result + return jawab; + } } ``` \ No newline at end of file From 9f7e57d86157b6b7a19c7daa72241f6141ce7404 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 18 Mar 2024 10:34:59 +0530 Subject: [PATCH 240/300] Create Daily 18-03-24.md --- 2024 March/Daily 18-03-24.md | 62 ++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 2024 March/Daily 18-03-24.md diff --git a/2024 March/Daily 18-03-24.md b/2024 March/Daily 18-03-24.md new file mode 100644 index 0000000..7b36626 --- /dev/null +++ b/2024 March/Daily 18-03-24.md @@ -0,0 +1,62 @@ +## Today's 18-03-24 [Problem Link](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/?envType=daily-question&envId=2024-03-18) +## 452. Minimum Number of Arrows to Burst Balloons + +# Intuition + +- Sort the points based on their end coordinates to efficiently burst balloons. +- Iterate through the sorted array, updating the arrow position to burst overlapping balloons. +- Increment the arrow count whenever a new arrow is needed. +# Approach + + +**Sorted Points :** Sorted the points based on their end coordinates using a custom comparator. + +**Initialized Variables :** Initialized variables for the arrow count and current arrow position. + +**Iterate Through Points :** Iterated through the sorted array of points. + +**Checked Balloon Positions :** For each point, checked if its start coordinate is greater than the current arrow position. + +**Updated Arrow Position :** If the start coordinate of the current point is greater than the current arrow position, updated the arrow position to the end coordinate of the current point. + +**Incremented Arrow Count :** Incremented the arrow count whenever a new arrow is needed to burst a balloon. + +**Result :** After iterating through all points, returned the arrow count as the minimum number of arrows needed. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(n * logn )$ + +$n$ : number of points +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + public int findMinArrowShots(int[][] points) { + + // Sorting points based on their end coordinates + Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1])); + + // Initializing variables + int jawab = 1; + int teer = points[0][1]; + + // Iterating through the sorted array of points + for (int i = 1; i < points.length; ++i) { + // If the start coordinate of the current point is greater than the current arrow position + if (points[i][0] > teer) { + // Updating the current arrow position to the end coordinate of the current point + teer = points[i][1]; + // Incrementing the arrow count + jawab++; + } + } + + // Returning the arrow count as the result + return jawab; + } +} +``` \ No newline at end of file From 24e2a432626b27c68493a3c8622e5c4c3a460b19 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 19 Mar 2024 09:54:03 +0530 Subject: [PATCH 241/300] Update README.md --- README.md | 75 ++++++++++++++++++++++++++----------------------------- 1 file changed, 36 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 3b2ccc9..5430c4d 100644 --- a/README.md +++ b/README.md @@ -4,65 +4,62 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 18-03-24 [Problem Link](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/?envType=daily-question&envId=2024-03-18) -## 452. Minimum Number of Arrows to Burst Balloons +## Today's 19-03-24 [Problem Link](https://leetcode.com/problems/task-scheduler/description/?envType=daily-question&envId=2024-03-19) +## 621. Task Scheduler # Intuition -- Sort the points based on their end coordinates to efficiently burst balloons. -- Iterate through the sorted array, updating the arrow position to burst overlapping balloons. -- Increment the arrow count whenever a new arrow is needed. +The problem requires us to determine the least interval needed to execute a given set of tasks, considering a cooldown period between tasks of the same type. + # Approach +- I start by counting the frequency of each task. This allows us to identify the task with the maximum frequency. -**Sorted Points :** Sorted the points based on their end coordinates using a custom comparator. - -**Initialized Variables :** Initialized variables for the arrow count and current arrow position. - -**Iterate Through Points :** Iterated through the sorted array of points. - -**Checked Balloon Positions :** For each point, checked if its start coordinate is greater than the current arrow position. +- I calculate the total time required to execute all tasks with cooldown. This is determined by finding the maximum frequency task and accounting for the cooldown period between its executions. -**Updated Arrow Position :** If the start coordinate of the current point is greater than the current arrow position, updated the arrow position to the end coordinate of the current point. +- Next, I find the number of tasks that have the maximum frequency. This helps us understand how many tasks need to be executed with the maximum frequency. -**Incremented Arrow Count :** Incremented the arrow count whenever a new arrow is needed to burst a balloon. +- Finally, I determine the least interval by considering the maximum of either executing all tasks with cooldown or the total number of tasks. This ensures that I cover both scenarios where the cooldown is utilized and where it is not necessary. -**Result :** After iterating through all points, returned the arrow count as the minimum number of arrows needed. +By following this approach, I can efficiently calculate the least interval required to execute the tasks. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(n * logn )$ +- Time complexity : $O(t)$ -$n$ : number of points -- Space complexity : $O(1)$ +$t$ : number of tasks +- Space complexity : $O(26) = O(1)$ # Code ``` class Solution { - public int findMinArrowShots(int[][] points) { - // Sorting points based on their end coordinates - Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1])); - - // Initializing variables - int jawab = 1; - int teer = points[0][1]; - - // Iterating through the sorted array of points - for (int i = 1; i < points.length; ++i) { - // If the start coordinate of the current point is greater than the current arrow position - if (points[i][0] > teer) { - // Updating the current arrow position to the end coordinate of the current point - teer = points[i][1]; - // Incrementing the arrow count - jawab++; - } + // Static array to keep track of task frequencies + static int[] frequencies; + + public int leastInterval(char[] tasks, int n) { + + // Initializing the frequency array to keep track of task occurrences + frequencies = new int[26]; + + // Populating the frequency array by iterating through the tasks + for (char task : tasks) { + frequencies[task - 'A']++; + } + + // Finding the maximum frequency of any task + int maxFrequency = Arrays.stream(frequencies).max().getAsInt(); + + // Calculating the total time taken for executing all tasks with cooldown + int totalWithCooldown = (maxFrequency - 1) * (n + 1); + + // Calculating the number of tasks that have the maximum frequency + int numOfMaxFrequency = (int) Arrays.stream(frequencies).filter(f -> f == maxFrequency).count(); + + // Returning the maximum of either executing all tasks with cooldown or total number of tasks + return Math.max(totalWithCooldown + numOfMaxFrequency, tasks.length); } - - // Returning the arrow count as the result - return jawab; - } } ``` \ No newline at end of file From 00562bd2e801b66d9f944cc483dbd97c32cfbaec Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 19 Mar 2024 09:57:33 +0530 Subject: [PATCH 242/300] Create Daily 19-03-24.md --- 2024 March/Daily 19-03-24.md | 59 ++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 2024 March/Daily 19-03-24.md diff --git a/2024 March/Daily 19-03-24.md b/2024 March/Daily 19-03-24.md new file mode 100644 index 0000000..bb04d3f --- /dev/null +++ b/2024 March/Daily 19-03-24.md @@ -0,0 +1,59 @@ +## Today's 19-03-24 [Problem Link](https://leetcode.com/problems/task-scheduler/description/?envType=daily-question&envId=2024-03-19) +## 621. Task Scheduler + +# Intuition + +The problem requires us to determine the least interval needed to execute a given set of tasks, considering a cooldown period between tasks of the same type. + +# Approach + +- I start by counting the frequency of each task. This allows us to identify the task with the maximum frequency. + +- I calculate the total time required to execute all tasks with cooldown. This is determined by finding the maximum frequency task and accounting for the cooldown period between its executions. + +- Next, I find the number of tasks that have the maximum frequency. This helps us understand how many tasks need to be executed with the maximum frequency. + +- Finally, I determine the least interval by considering the maximum of either executing all tasks with cooldown or the total number of tasks. This ensures that I cover both scenarios where the cooldown is utilized and where it is not necessary. + +By following this approach, I can efficiently calculate the least interval required to execute the tasks. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(t)$ + +$t$ : number of tasks +- Space complexity : $O(26) = O(1)$ + + +# Code +``` +class Solution { + + // Static array to keep track of task frequencies + static int[] frequencies; + + public int leastInterval(char[] tasks, int n) { + + // Initializing the frequency array to keep track of task occurrences + frequencies = new int[26]; + + // Populating the frequency array by iterating through the tasks + for (char task : tasks) { + frequencies[task - 'A']++; + } + + // Finding the maximum frequency of any task + int maxFrequency = Arrays.stream(frequencies).max().getAsInt(); + + // Calculating the total time taken for executing all tasks with cooldown + int totalWithCooldown = (maxFrequency - 1) * (n + 1); + + // Calculating the number of tasks that have the maximum frequency + int numOfMaxFrequency = (int) Arrays.stream(frequencies).filter(f -> f == maxFrequency).count(); + + // Returning the maximum of either executing all tasks with cooldown or total number of tasks + return Math.max(totalWithCooldown + numOfMaxFrequency, tasks.length); + } +} +``` \ No newline at end of file From 3881f3243b2105d3af39362d8b30dac45c1c6367 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 21 Mar 2024 00:36:17 +0530 Subject: [PATCH 243/300] Update README.md --- README.md | 91 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 55 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 5430c4d..1f773f2 100644 --- a/README.md +++ b/README.md @@ -4,62 +4,81 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 19-03-24 [Problem Link](https://leetcode.com/problems/task-scheduler/description/?envType=daily-question&envId=2024-03-19) -## 621. Task Scheduler +## Today's 20-03-24 [Problem Link](https://leetcode.com/problems/merge-in-between-linked-lists/description/?envType=daily-question&envId=2024-03-20) +## 1669. Merge In Between Linked Lists # Intuition -The problem requires us to determine the least interval needed to execute a given set of tasks, considering a cooldown period between tasks of the same type. +The task is to merge the nodes of `head2` into `head1` between the indices `start` and `end`. # Approach -- I start by counting the frequency of each task. This allows us to identify the task with the maximum frequency. -- I calculate the total time required to execute all tasks with cooldown. This is determined by finding the maximum frequency task and accounting for the cooldown period between its executions. - -- Next, I find the number of tasks that have the maximum frequency. This helps us understand how many tasks need to be executed with the maximum frequency. - -- Finally, I determine the least interval by considering the maximum of either executing all tasks with cooldown or the total number of tasks. This ensures that I cover both scenarios where the cooldown is utilized and where it is not necessary. - -By following this approach, I can efficiently calculate the least interval required to execute the tasks. +- I initialized a pointer `beforeStartNode` to `head1`. +- Move `beforeStartNode` to the node before the `start` index by iterating `start - 1` times. +- Initialize a pointer `endNode` to the node at the `start` index (i.e., `beforeStartNode.next`). +- Move `endNode` to the node at the `end` index by iterating `end - start` times. +- Connect the node before the `start` index to the head of `head2`. +- Find the last node in `head2` by traversing till the end of the list. +- Connect the last node of `head2` to the node after the `end` index. +- Disconnect the nodes between the `start` and `end` indices from `head1`. +- Return the modified `head1` after merging `head2` between `start` and `end` indices. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(t)$ +- Time complexity : $O(n)$ -$t$ : number of tasks -- Space complexity : $O(26) = O(1)$ +$n$ : number of nodes in the list +- Space complexity : $O(1)$ # Code ``` +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ class Solution { + + // Function to merge the nodes of head2 into head1 between the indices start and end + public ListNode mergeInBetween(ListNode head1, int start, int end, ListNode head2) { - // Static array to keep track of task frequencies - static int[] frequencies; - - public int leastInterval(char[] tasks, int n) { - - // Initializing the frequency array to keep track of task occurrences - frequencies = new int[26]; + // Pointer to the node before the start index + ListNode beforeStartNode = head1; + for (int i = 0; i < start - 1; i++){ + beforeStartNode = beforeStartNode.next; + } - // Populating the frequency array by iterating through the tasks - for (char task : tasks) { - frequencies[task - 'A']++; - } + // Pointer to the node at the end index + ListNode endNode = beforeStartNode.next; + for (int i = 0; i < end - start; i++){ + endNode = endNode.next; + } - // Finding the maximum frequency of any task - int maxFrequency = Arrays.stream(frequencies).max().getAsInt(); - - // Calculating the total time taken for executing all tasks with cooldown - int totalWithCooldown = (maxFrequency - 1) * (n + 1); - - // Calculating the number of tasks that have the maximum frequency - int numOfMaxFrequency = (int) Arrays.stream(frequencies).filter(f -> f == maxFrequency).count(); - - // Returning the maximum of either executing all tasks with cooldown or total number of tasks - return Math.max(totalWithCooldown + numOfMaxFrequency, tasks.length); + // Connecting the node before the start index to the head of head2 + beforeStartNode.next = head2; + + // Finding the last node in head2 + ListNode lastNodeInHead2 = head2; + while (lastNodeInHead2.next != null){ + lastNodeInHead2 = lastNodeInHead2.next; } + + // Connecting the last node of head2 to the node after the end index + lastNodeInHead2.next = endNode.next; + + // Disconnecting the nodes between the start and end indices from head1 + endNode.next = null; + + // Returning the modified head1 after merging head2 between start and end indices + return head1; + } } ``` \ No newline at end of file From 3f8daf3494ad4f34420a98e3b360efd4101cd49e Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 21 Mar 2024 00:37:53 +0530 Subject: [PATCH 244/300] Update README.md --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 1f773f2..fba7f71 100644 --- a/README.md +++ b/README.md @@ -15,14 +15,14 @@ The task is to merge the nodes of `head2` into `head1` between the indices `star - I initialized a pointer `beforeStartNode` to `head1`. -- Move `beforeStartNode` to the node before the `start` index by iterating `start - 1` times. -- Initialize a pointer `endNode` to the node at the `start` index (i.e., `beforeStartNode.next`). -- Move `endNode` to the node at the `end` index by iterating `end - start` times. -- Connect the node before the `start` index to the head of `head2`. -- Find the last node in `head2` by traversing till the end of the list. -- Connect the last node of `head2` to the node after the `end` index. -- Disconnect the nodes between the `start` and `end` indices from `head1`. -- Return the modified `head1` after merging `head2` between `start` and `end` indices. +- Moved `beforeStartNode` to the node before the `start` index by iterating `start - 1` times. +- Initialized a pointer `endNode` to the node at the `start` index (i.e., `beforeStartNode.next`). +- Moved `endNode` to the node at the `end` index by iterating `end - start` times. +- Connected the node before the `start` index to the head of `head2`. +- Finded the last node in `head2` by traversing till the end of the list. +- Connected the last node of `head2` to the node after the `end` index. +- Disconnected the nodes between the `start` and `end` indices from `head1`. +- Returned the modified `head1` after merging `head2` between `start` and `end` indices. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) From c38b971198ab54901109aacb41236ead5edda040 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 21 Mar 2024 00:46:04 +0530 Subject: [PATCH 245/300] Create Daily 20-03-24.md --- 2024 March/Daily 20-03-24.md | 78 ++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 2024 March/Daily 20-03-24.md diff --git a/2024 March/Daily 20-03-24.md b/2024 March/Daily 20-03-24.md new file mode 100644 index 0000000..7133f20 --- /dev/null +++ b/2024 March/Daily 20-03-24.md @@ -0,0 +1,78 @@ +## Today's 20-03-24 [Problem Link](https://leetcode.com/problems/merge-in-between-linked-lists/description/?envType=daily-question&envId=2024-03-20) +## 1669. Merge In Between Linked Lists + +# Intuition + +The task is to merge the nodes of `head2` into `head1` between the indices `start` and `end`. + +# Approach + + +- I initialized a pointer `beforeStartNode` to `head1`. +- Moved `beforeStartNode` to the node before the `start` index by iterating `start - 1` times. +- Initialized a pointer `endNode` to the node at the `start` index (i.e., `beforeStartNode.next`). +- Moved `endNode` to the node at the `end` index by iterating `end - start` times. +- Connected the node before the `start` index to the head of `head2`. +- Finded the last node in `head2` by traversing till the end of the list. +- Connected the last node of `head2` to the node after the `end` index. +- Disconnected the nodes between the `start` and `end` indices from `head1`. +- Returned the modified `head1` after merging `head2` between `start` and `end` indices. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : number of nodes in the list +- Space complexity : $O(1)$ + + +# Code +``` +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + + // Function to merge the nodes of head2 into head1 between the indices start and end + public ListNode mergeInBetween(ListNode head1, int start, int end, ListNode head2) { + + // Pointer to the node before the start index + ListNode beforeStartNode = head1; + for (int i = 0; i < start - 1; i++){ + beforeStartNode = beforeStartNode.next; + } + + // Pointer to the node at the end index + ListNode endNode = beforeStartNode.next; + for (int i = 0; i < end - start; i++){ + endNode = endNode.next; + } + + // Connecting the node before the start index to the head of head2 + beforeStartNode.next = head2; + + // Finding the last node in head2 + ListNode lastNodeInHead2 = head2; + while (lastNodeInHead2.next != null){ + lastNodeInHead2 = lastNodeInHead2.next; + } + + // Connecting the last node of head2 to the node after the end index + lastNodeInHead2.next = endNode.next; + + // Disconnecting the nodes between the start and end indices from head1 + endNode.next = null; + + // Returning the modified head1 after merging head2 between start and end indices + return head1; + } +} +``` \ No newline at end of file From 4bb6ffb83828896814dff318cffcb0a795c1e613 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 22 Mar 2024 19:19:48 +0530 Subject: [PATCH 246/300] Update README.md --- README.md | 104 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 63 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index fba7f71..b984594 100644 --- a/README.md +++ b/README.md @@ -4,32 +4,30 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 20-03-24 [Problem Link](https://leetcode.com/problems/merge-in-between-linked-lists/description/?envType=daily-question&envId=2024-03-20) -## 1669. Merge In Between Linked Lists +## Today's 22-03-24 [Problem Link](https://leetcode.com/problems/palindrome-linked-list/description/?envType=daily-question&envId=2024-03-22) +## 234. Palindrome Linked List # Intuition -The task is to merge the nodes of `head2` into `head1` between the indices `start` and `end`. +To check if a linked list is a palindrome, we can use the following approach : +- Find the middle of the linked list using the slow and fast pointers technique. +- Reverse the second half of the linked list. +- Compare the first half of the original list with the reversed second half. # Approach - -- I initialized a pointer `beforeStartNode` to `head1`. -- Moved `beforeStartNode` to the node before the `start` index by iterating `start - 1` times. -- Initialized a pointer `endNode` to the node at the `start` index (i.e., `beforeStartNode.next`). -- Moved `endNode` to the node at the `end` index by iterating `end - start` times. -- Connected the node before the `start` index to the head of `head2`. -- Finded the last node in `head2` by traversing till the end of the list. -- Connected the last node of `head2` to the node after the `end` index. -- Disconnected the nodes between the `start` and `end` indices from `head1`. -- Returned the modified `head1` after merging `head2` between `start` and `end` indices. +- Initialize two pointers, slow and fast, both pointing to the head of the linked list. +- Traverse the list using the slow and fast pointers, where slow moves one step at a time and fast moves two steps at a time. By the time the fast pointer reaches the end of the list, the slow pointer will be at the middle of the list. +- Reverse the second half of the list starting from the node after the slow pointer. This can be done using a separate helper function to reverse a linked list. +- Traverse both the first and second halves of the list simultaneously and compare the values of the nodes. +- If at any point the values of the nodes don't match, return false; otherwise, if we reach the end of the list, return true. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : number of nodes in the list +$n$ : number of nodes in the list - Space complexity : $O(1)$ @@ -46,39 +44,63 @@ $n$ : number of nodes in the list * } */ class Solution { - - // Function to merge the nodes of head2 into head1 between the indices start and end - public ListNode mergeInBetween(ListNode head1, int start, int end, ListNode head2) { - // Pointer to the node before the start index - ListNode beforeStartNode = head1; - for (int i = 0; i < start - 1; i++){ - beforeStartNode = beforeStartNode.next; - } - - // Pointer to the node at the end index - ListNode endNode = beforeStartNode.next; - for (int i = 0; i < end - start; i++){ - endNode = endNode.next; + // Function to check if the linked list is a palindrome + public boolean isPalindrome(ListNode head) { + // Find the middle of the list + ListNode middle = findMiddle(head); + // Reverse the second half of the list + ListNode reversedSecondHalf = reverseList(middle); + + // Initialize pointers for traversal + ListNode p1 = head; + ListNode p2 = reversedSecondHalf; + + // Traverse both halves and compare values + while (p1 != null && p2 != null) { + // If values don't match, the list is not a palindrome + if (p1.val != p2.val) { + return false; + } + // Move pointers to next nodes + p1 = p1.next; + p2 = p2.next; } - - // Connecting the node before the start index to the head of head2 - beforeStartNode.next = head2; - // Finding the last node in head2 - ListNode lastNodeInHead2 = head2; - while (lastNodeInHead2.next != null){ - lastNodeInHead2 = lastNodeInHead2.next; + // If traversal completes without finding a mismatch, list is a palindrome + return true; + } + + // Function to find the middle of the list using slow and fast pointers + private ListNode findMiddle(ListNode head) { + ListNode slow = head; + ListNode fast = head; + + // Move slow pointer by one step and fast pointer by two steps + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; } - - // Connecting the last node of head2 to the node after the end index - lastNodeInHead2.next = endNode.next; - // Disconnecting the nodes between the start and end indices from head1 - endNode.next = null; + // Return the middle node + return slow; + } + + // Function to reverse a linked list + private ListNode reverseList(ListNode head) { + ListNode prev = null; + ListNode current = head; + + // Iterate through the list, reversing pointers + while (current != null) { + ListNode next = current.next; + current.next = prev; + prev = current; + current = next; + } - // Returning the modified head1 after merging head2 between start and end indices - return head1; + // Return the new head of the reversed list + return prev; } } ``` \ No newline at end of file From cbbb2ab564e5f554cfdfda1c44ab505f20519fb8 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 22 Mar 2024 19:23:08 +0530 Subject: [PATCH 247/300] Create Daily 22-03-24.md --- 2024 March/Daily 22-03-24.md | 100 +++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 2024 March/Daily 22-03-24.md diff --git a/2024 March/Daily 22-03-24.md b/2024 March/Daily 22-03-24.md new file mode 100644 index 0000000..236de2c --- /dev/null +++ b/2024 March/Daily 22-03-24.md @@ -0,0 +1,100 @@ +## Today's 22-03-24 [Problem Link](https://leetcode.com/problems/palindrome-linked-list/description/?envType=daily-question&envId=2024-03-22) +## 234. Palindrome Linked List + +# Intuition + +To check if a linked list is a palindrome, we can use the following approach : + +- Find the middle of the linked list using the slow and fast pointers technique. +- Reverse the second half of the linked list. +- Compare the first half of the original list with the reversed second half. +# Approach + +- Initialize two pointers, slow and fast, both pointing to the head of the linked list. +- Traverse the list using the slow and fast pointers, where slow moves one step at a time and fast moves two steps at a time. By the time the fast pointer reaches the end of the list, the slow pointer will be at the middle of the list. +- Reverse the second half of the list starting from the node after the slow pointer. This can be done using a separate helper function to reverse a linked list. +- Traverse both the first and second halves of the list simultaneously and compare the values of the nodes. +- If at any point the values of the nodes don't match, return false; otherwise, if we reach the end of the list, return true. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : number of nodes in the list +- Space complexity : $O(1)$ + + +# Code +``` +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + + // Function to check if the linked list is a palindrome + public boolean isPalindrome(ListNode head) { + // Find the middle of the list + ListNode middle = findMiddle(head); + // Reverse the second half of the list + ListNode reversedSecondHalf = reverseList(middle); + + // Initialize pointers for traversal + ListNode p1 = head; + ListNode p2 = reversedSecondHalf; + + // Traverse both halves and compare values + while (p1 != null && p2 != null) { + // If values don't match, the list is not a palindrome + if (p1.val != p2.val) { + return false; + } + // Move pointers to next nodes + p1 = p1.next; + p2 = p2.next; + } + + // If traversal completes without finding a mismatch, list is a palindrome + return true; + } + + // Function to find the middle of the list using slow and fast pointers + private ListNode findMiddle(ListNode head) { + ListNode slow = head; + ListNode fast = head; + + // Move slow pointer by one step and fast pointer by two steps + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + // Return the middle node + return slow; + } + + // Function to reverse a linked list + private ListNode reverseList(ListNode head) { + ListNode prev = null; + ListNode current = head; + + // Iterate through the list, reversing pointers + while (current != null) { + ListNode next = current.next; + current.next = prev; + prev = current; + current = next; + } + + // Return the new head of the reversed list + return prev; + } +} +``` \ No newline at end of file From 4187e3db25c49f394f9e417ce6fb411ae8932218 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 23 Mar 2024 19:04:28 +0530 Subject: [PATCH 248/300] Update README.md --- README.md | 116 +++++++++++++++++++++++++++--------------------------- 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index b984594..7f8dba1 100644 --- a/README.md +++ b/README.md @@ -4,30 +4,24 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 22-03-24 [Problem Link](https://leetcode.com/problems/palindrome-linked-list/description/?envType=daily-question&envId=2024-03-22) -## 234. Palindrome Linked List +## Today's 23-03-24 [Problem Link](https://leetcode.com/problems/reorder-list/description/?envType=daily-question&envId=2024-03-23) +## 143. Reorder List # Intuition -To check if a linked list is a palindrome, we can use the following approach : +My given code should aim to reorder a singly-linked list such that the resulting list is formed by interleaving the nodes from the first half and the reversed second half of the original list. -- Find the middle of the linked list using the slow and fast pointers technique. -- Reverse the second half of the linked list. -- Compare the first half of the original list with the reversed second half. # Approach -- Initialize two pointers, slow and fast, both pointing to the head of the linked list. -- Traverse the list using the slow and fast pointers, where slow moves one step at a time and fast moves two steps at a time. By the time the fast pointer reaches the end of the list, the slow pointer will be at the middle of the list. -- Reverse the second half of the list starting from the node after the slow pointer. This can be done using a separate helper function to reverse a linked list. -- Traverse both the first and second halves of the list simultaneously and compare the values of the nodes. -- If at any point the values of the nodes don't match, return false; otherwise, if we reach the end of the list, return true. - +- I finded the middle of the linked list. +- Reversed the second half of the list. +- Merged the first half and the reversed second half by alternating their nodes. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : number of nodes in the list +$n$ : size of linked list - Space complexity : $O(1)$ @@ -43,64 +37,70 @@ $n$ : number of nodes in the list * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ + class Solution { - - // Function to check if the linked list is a palindrome - public boolean isPalindrome(ListNode head) { - // Find the middle of the list + + // Method to reorder the given linked list + public void reorderList(ListNode head) { + + // Checking if the list is null or has only one node + if (head == null || head.next == null){ + return; + } + + // Finding the middle node of the list ListNode middle = findMiddle(head); - // Reverse the second half of the list + // Reversing the second half of the list ListNode reversedSecondHalf = reverseList(middle); - - // Initialize pointers for traversal - ListNode p1 = head; - ListNode p2 = reversedSecondHalf; - - // Traverse both halves and compare values - while (p1 != null && p2 != null) { - // If values don't match, the list is not a palindrome - if (p1.val != p2.val) { - return false; - } - // Move pointers to next nodes - p1 = p1.next; - p2 = p2.next; - } - - // If traversal completes without finding a mismatch, list is a palindrome - return true; + // Merging the first half and the reversed second half + mergeLists(head, reversedSecondHalf); } - - // Function to find the middle of the list using slow and fast pointers + + // Method to find the middle node of the list private ListNode findMiddle(ListNode head) { - ListNode slow = head; - ListNode fast = head; - - // Move slow pointer by one step and fast pointer by two steps - while (fast != null && fast.next != null) { - slow = slow.next; - fast = fast.next.next; + ListNode prev = null; + ListNode slowPtr = head; + ListNode fastPtr = head; + + // Moving slowPtr by one and fastPtr by two until fastPtr reaches the end of the list + while (fastPtr != null && fastPtr.next != null) { + prev = slowPtr; + slowPtr = slowPtr.next; + fastPtr = fastPtr.next.next; } - - // Return the middle node - return slow; + + // Disconnecting the first half from the second half + if (prev != null){ + prev.next = null; + } + + return slowPtr; // Return the middle node } - - // Function to reverse a linked list - private ListNode reverseList(ListNode head) { + + // Method to reverse a linked list + static ListNode reverseList(ListNode head) { ListNode prev = null; ListNode current = head; - - // Iterate through the list, reversing pointers + + // Reversing the list by updating pointers while (current != null) { - ListNode next = current.next; + ListNode nextNode = current.next; current.next = prev; prev = current; - current = next; + current = nextNode; + } + + return prev; // Returning the new head of the reversed list + } + + // Method to merge two linked lists by alternating their nodes + static void mergeLists(ListNode first, ListNode second) { + while (second != null) { + ListNode nextFirst = first.next; + first.next = second; + first = second; + second = nextFirst; } - - // Return the new head of the reversed list - return prev; } } ``` \ No newline at end of file From c4b40b16a586b6f0028cdb65d36508c2df180bfa Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 23 Mar 2024 19:05:25 +0530 Subject: [PATCH 249/300] Create Daily 23-03-24.md --- 2024 March/Daily 23-03-24.md | 100 +++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 2024 March/Daily 23-03-24.md diff --git a/2024 March/Daily 23-03-24.md b/2024 March/Daily 23-03-24.md new file mode 100644 index 0000000..958f283 --- /dev/null +++ b/2024 March/Daily 23-03-24.md @@ -0,0 +1,100 @@ +## Today's 23-03-24 [Problem Link](https://leetcode.com/problems/reorder-list/description/?envType=daily-question&envId=2024-03-23) +## 143. Reorder List + +# Intuition + +My given code should aim to reorder a singly-linked list such that the resulting list is formed by interleaving the nodes from the first half and the reversed second half of the original list. + +# Approach + +- I finded the middle of the linked list. +- Reversed the second half of the list. +- Merged the first half and the reversed second half by alternating their nodes. +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : size of linked list +- Space complexity : $O(1)$ + + +# Code +``` +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ + +class Solution { + + // Method to reorder the given linked list + public void reorderList(ListNode head) { + + // Checking if the list is null or has only one node + if (head == null || head.next == null){ + return; + } + + // Finding the middle node of the list + ListNode middle = findMiddle(head); + // Reversing the second half of the list + ListNode reversedSecondHalf = reverseList(middle); + // Merging the first half and the reversed second half + mergeLists(head, reversedSecondHalf); + } + + // Method to find the middle node of the list + private ListNode findMiddle(ListNode head) { + ListNode prev = null; + ListNode slowPtr = head; + ListNode fastPtr = head; + + // Moving slowPtr by one and fastPtr by two until fastPtr reaches the end of the list + while (fastPtr != null && fastPtr.next != null) { + prev = slowPtr; + slowPtr = slowPtr.next; + fastPtr = fastPtr.next.next; + } + + // Disconnecting the first half from the second half + if (prev != null){ + prev.next = null; + } + + return slowPtr; // Return the middle node + } + + // Method to reverse a linked list + static ListNode reverseList(ListNode head) { + ListNode prev = null; + ListNode current = head; + + // Reversing the list by updating pointers + while (current != null) { + ListNode nextNode = current.next; + current.next = prev; + prev = current; + current = nextNode; + } + + return prev; // Returning the new head of the reversed list + } + + // Method to merge two linked lists by alternating their nodes + static void mergeLists(ListNode first, ListNode second) { + while (second != null) { + ListNode nextFirst = first.next; + first.next = second; + first = second; + second = nextFirst; + } + } +} +``` \ No newline at end of file From 046168da2e2afc35e0e803610f341e15b708fdd6 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 24 Mar 2024 12:32:10 +0530 Subject: [PATCH 250/300] Update README.md --- README.md | 113 ++++++++++++++++-------------------------------------- 1 file changed, 32 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index 7f8dba1..156ec42 100644 --- a/README.md +++ b/README.md @@ -4,103 +4,54 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 23-03-24 [Problem Link](https://leetcode.com/problems/reorder-list/description/?envType=daily-question&envId=2024-03-23) -## 143. Reorder List +## Today's 24-03-24 [Problem Link](https://leetcode.com/problems/find-the-duplicate-number/description/?envType=daily-question&envId=2024-03-24) +## 287. Find the Duplicate Number # Intuition -My given code should aim to reorder a singly-linked list such that the resulting list is formed by interleaving the nodes from the first half and the reversed second half of the original list. +To solve this problem, I should iterate through the array `nums` and use a HashSet to keep track of the numbers we have encountered so far. # Approach -- I finded the middle of the linked list. -- Reversed the second half of the list. -- Merged the first half and the reversed second half by alternating their nodes. +- I initialized an empty HashSet `hs`. +- I iterated through each element `num` in the array `nums`. +- For each element `num`, we check if it is already present in the HashSet `hs` using the `add` method. + - If `num` is already present in `hs`, the `add` method will return `false`, indicating that `num` is a duplicate. + - In this case, I return `num` as it is the duplicate element. + - If `num` is not present in `hs`, I add it to the HashSet and continue with the next iteration. + +Finally, if no duplicate is found after iterating through the entire array, I return `-1` to indicate that no duplicates exist in the array. + --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : size of linked list -- Space complexity : $O(1)$ +$n$ : number of elements in the input array `nums` +- Space complexity : $O(n)$ # Code ``` -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ - class Solution { - - // Method to reorder the given linked list - public void reorderList(ListNode head) { - - // Checking if the list is null or has only one node - if (head == null || head.next == null){ - return; - } - - // Finding the middle node of the list - ListNode middle = findMiddle(head); - // Reversing the second half of the list - ListNode reversedSecondHalf = reverseList(middle); - // Merging the first half and the reversed second half - mergeLists(head, reversedSecondHalf); - } - - // Method to find the middle node of the list - private ListNode findMiddle(ListNode head) { - ListNode prev = null; - ListNode slowPtr = head; - ListNode fastPtr = head; - - // Moving slowPtr by one and fastPtr by two until fastPtr reaches the end of the list - while (fastPtr != null && fastPtr.next != null) { - prev = slowPtr; - slowPtr = slowPtr.next; - fastPtr = fastPtr.next.next; - } - - // Disconnecting the first half from the second half - if (prev != null){ - prev.next = null; - } - - return slowPtr; // Return the middle node - } - - // Method to reverse a linked list - static ListNode reverseList(ListNode head) { - ListNode prev = null; - ListNode current = head; - - // Reversing the list by updating pointers - while (current != null) { - ListNode nextNode = current.next; - current.next = prev; - prev = current; - current = nextNode; - } - - return prev; // Returning the new head of the reversed list - } - - // Method to merge two linked lists by alternating their nodes - static void mergeLists(ListNode first, ListNode second) { - while (second != null) { - ListNode nextFirst = first.next; - first.next = second; - first = second; - second = nextFirst; + + public int findDuplicate(int[] nums) { + // HashSet to store encountered numbers + HashSet hs = new HashSet<>(); + + // Length of the array + int length = nums.length; + + // Iterating through the array + for (int i = 0; i < length; i++) { + // If the number is already in the HashSet, it's a duplicate + if (!hs.add(nums[i])) { + return nums[i]; + } + } + + // If no duplicates found, return -1 + return -1; } - } } ``` \ No newline at end of file From bd302f98bac17816cdb304bd219224b57f21df98 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 24 Mar 2024 12:35:21 +0530 Subject: [PATCH 251/300] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 156ec42..4375c2d 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +# Wishing you all a vibrant Holika Dahan! Let the sacred fire illuminate our hearts with joy and the triumph of good over evil. 🪔✨ #HolikaDahan + # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. From dbc412fd7fa7b306379a62c02d66b047562e82d8 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 24 Mar 2024 12:36:08 +0530 Subject: [PATCH 252/300] Create Daily 24-03-24.md --- 2024 March/Daily 24-03-24.md | 53 ++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 2024 March/Daily 24-03-24.md diff --git a/2024 March/Daily 24-03-24.md b/2024 March/Daily 24-03-24.md new file mode 100644 index 0000000..10715b8 --- /dev/null +++ b/2024 March/Daily 24-03-24.md @@ -0,0 +1,53 @@ +# Wishing you all a vibrant Holika Dahan! Let the sacred fire illuminate our hearts with joy and the triumph of good over evil. 🪔✨ #HolikaDahan + +## Today's 24-03-24 [Problem Link](https://leetcode.com/problems/find-the-duplicate-number/description/?envType=daily-question&envId=2024-03-24) +## 287. Find the Duplicate Number + +# Intuition + +To solve this problem, I should iterate through the array `nums` and use a HashSet to keep track of the numbers we have encountered so far. + +# Approach + +- I initialized an empty HashSet `hs`. +- I iterated through each element `num` in the array `nums`. +- For each element `num`, we check if it is already present in the HashSet `hs` using the `add` method. + - If `num` is already present in `hs`, the `add` method will return `false`, indicating that `num` is a duplicate. + - In this case, I return `num` as it is the duplicate element. + - If `num` is not present in `hs`, I add it to the HashSet and continue with the next iteration. + +Finally, if no duplicate is found after iterating through the entire array, I return `-1` to indicate that no duplicates exist in the array. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : number of elements in the input array `nums` +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + + public int findDuplicate(int[] nums) { + // HashSet to store encountered numbers + HashSet hs = new HashSet<>(); + + // Length of the array + int length = nums.length; + + // Iterating through the array + for (int i = 0; i < length; i++) { + // If the number is already in the HashSet, it's a duplicate + if (!hs.add(nums[i])) { + return nums[i]; + } + } + + // If no duplicates found, return -1 + return -1; + } +} +``` \ No newline at end of file From 2faeb139c84bf596fdc11d93c023d5a0d43dd582 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 25 Mar 2024 08:44:43 +0530 Subject: [PATCH 253/300] Update README.md --- README.md | 69 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 4375c2d..868ba82 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,8 @@ -# Wishing you all a vibrant Holika Dahan! Let the sacred fire illuminate our hearts with joy and the triumph of good over evil. 🪔✨ #HolikaDahan +# 🎉 Happy Holi, GitHub Friends! 🌈🎨 + +## Wishing you a colorful and joyful Holi celebration! 🥳 May your coding adventures be as vibrant and delightful as the festival itself. Thanks for stopping by my repo! 💻🌟 + +## Happy Holi from me to you! 🎊🎉 # Leetcode Daily Challenge Solutions @@ -6,54 +10,53 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 24-03-24 [Problem Link](https://leetcode.com/problems/find-the-duplicate-number/description/?envType=daily-question&envId=2024-03-24) -## 287. Find the Duplicate Number +## Today's 25-03-24 [Problem Link](https://leetcode.com/problems/find-all-duplicates-in-an-array/description/?envType=daily-question&envId=2024-03-25) +## 442. Find All Duplicates in an Array # Intuition -To solve this problem, I should iterate through the array `nums` and use a HashSet to keep track of the numbers we have encountered so far. - +- My algorithm should marks encountered numbers by toggling their sign at the index corresponding to their absolute value. +- Positive values at these indices should indicate duplicate numbers. # Approach -- I initialized an empty HashSet `hs`. -- I iterated through each element `num` in the array `nums`. -- For each element `num`, we check if it is already present in the HashSet `hs` using the `add` method. - - If `num` is already present in `hs`, the `add` method will return `false`, indicating that `num` is a duplicate. - - In this case, I return `num` as it is the duplicate element. - - If `num` is not present in `hs`, I add it to the HashSet and continue with the next iteration. - -Finally, if no duplicate is found after iterating through the entire array, I return `-1` to indicate that no duplicates exist in the array. +- I iterated through each number in the array. +- Toggle the sign of the number at the index corresponding to its absolute value. +- If the number at that index is positive, it means it has been encountered before, so added the absolute value of the number to the duplicates list. +- Returned the list of duplicates. --- Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : number of elements in the input array `nums` -- Space complexity : $O(n)$ +$n$ : length of the input array +- Space complexity : $O(1)$ # Code ``` class Solution { - - public int findDuplicate(int[] nums) { - // HashSet to store encountered numbers - HashSet hs = new HashSet<>(); - - // Length of the array - int length = nums.length; - - // Iterating through the array - for (int i = 0; i < length; i++) { - // If the number is already in the HashSet, it's a duplicate - if (!hs.add(nums[i])) { - return nums[i]; - } - } - - // If no duplicates found, return -1 - return -1; + + // Method to find duplicates in an array of integers + public List findDuplicates(int[] numbers) { + + // List to store duplicates + List duplicates = new ArrayList<>(); + + // Iterating through each number in the array + for (final int number : numbers) { + // Toggling the sign of the number at the index corresponding to its absolute value + numbers[Math.abs(number) - 1] *= -1; + + // If the number at that index is positive, it means it has been encountered before + if (numbers[Math.abs(number) - 1] > 0){ + // Adding the absolute value of the number to the duplicates list + duplicates.add(Math.abs(number)); + } } + + // Returning the list of duplicates + return duplicates; + } } ``` \ No newline at end of file From 62613da6053543171f075fa54f309882c9fe67c1 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 25 Mar 2024 08:45:16 +0530 Subject: [PATCH 254/300] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 868ba82..266dcfa 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# 🎉 Happy Holi, GitHub Friends! 🌈🎨 +# 🎉 Happy Holi, GitHub Friends ! 🌈🎨 -## Wishing you a colorful and joyful Holi celebration! 🥳 May your coding adventures be as vibrant and delightful as the festival itself. Thanks for stopping by my repo! 💻🌟 +## Wishing you a colorful and joyful Holi celebration ! 🥳 May your coding adventures be as vibrant and delightful as the festival itself. Thanks for stopping by my repo ! 💻🌟 -## Happy Holi from me to you! 🎊🎉 +## Happy Holi from me to you ! 🎊🎉 # Leetcode Daily Challenge Solutions From 85df6ea78f8a2b0fa87943c4a527695a0c849d5c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 25 Mar 2024 08:46:41 +0530 Subject: [PATCH 255/300] Create Daily 25-03-24.md --- 2024 March/Daily 25-03-24.md | 56 ++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 2024 March/Daily 25-03-24.md diff --git a/2024 March/Daily 25-03-24.md b/2024 March/Daily 25-03-24.md new file mode 100644 index 0000000..f82af15 --- /dev/null +++ b/2024 March/Daily 25-03-24.md @@ -0,0 +1,56 @@ +# 🎉 Happy Holi, GitHub Friends ! 🌈🎨 + +## Wishing you a colorful and joyful Holi celebration ! 🥳 May your coding adventures be as vibrant and delightful as the festival itself. Thanks for stopping by my repo ! 💻🌟 + +## Happy Holi from me to you ! 🎊🎉 + +## Today's 25-03-24 [Problem Link](https://leetcode.com/problems/find-all-duplicates-in-an-array/description/?envType=daily-question&envId=2024-03-25) +## 442. Find All Duplicates in an Array + +# Intuition + +- My algorithm should marks encountered numbers by toggling their sign at the index corresponding to their absolute value. +- Positive values at these indices should indicate duplicate numbers. +# Approach + +- I iterated through each number in the array. +- Toggle the sign of the number at the index corresponding to its absolute value. +- If the number at that index is positive, it means it has been encountered before, so added the absolute value of the number to the duplicates list. +- Returned the list of duplicates. + +--- +Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the input array +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + + // Method to find duplicates in an array of integers + public List findDuplicates(int[] numbers) { + + // List to store duplicates + List duplicates = new ArrayList<>(); + + // Iterating through each number in the array + for (final int number : numbers) { + // Toggling the sign of the number at the index corresponding to its absolute value + numbers[Math.abs(number) - 1] *= -1; + + // If the number at that index is positive, it means it has been encountered before + if (numbers[Math.abs(number) - 1] > 0){ + // Adding the absolute value of the number to the duplicates list + duplicates.add(Math.abs(number)); + } + } + + // Returning the list of duplicates + return duplicates; + } +} +``` \ No newline at end of file From ccdde07e081db1171f275e8161871dd618886e9f Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 26 Mar 2024 13:20:20 +0530 Subject: [PATCH 256/300] Update README.md --- README.md | 68 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 36 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 266dcfa..ffc5f6a 100644 --- a/README.md +++ b/README.md @@ -10,26 +10,28 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 25-03-24 [Problem Link](https://leetcode.com/problems/find-all-duplicates-in-an-array/description/?envType=daily-question&envId=2024-03-25) -## 442. Find All Duplicates in an Array +## Today's 26-03-24 [Problem Link](https://leetcode.com/problems/first-missing-positive/description/?envType=daily-question&envId=2024-03-26) +## 41. First Missing Positive # Intuition -- My algorithm should marks encountered numbers by toggling their sign at the index corresponding to their absolute value. -- Positive values at these indices should indicate duplicate numbers. +Simply sort, then look for positive numbers. + # Approach -- I iterated through each number in the array. -- Toggle the sign of the number at the index corresponding to its absolute value. -- If the number at that index is positive, it means it has been encountered before, so added the absolute value of the number to the duplicates list. -- Returned the list of duplicates. +- Sorted the array ( used java collection sorting method which uses $$log(n)$$ time complexity so no issue) +- looked for positive numbers starting with 1, if found then searched next number ( 2, then 3, then 4...) +- as array is sorted , no issue in arrangement of numbers +- the last positive number not found will be the answer + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) ---- -Have a look at the code , still have any confusion then please let me know in the comments ... Keep Solving.:) # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(n log n)$ -$n$ : length of the input array +$n$ : length of the input array `nums` - Space complexity : $O(1)$ @@ -37,26 +39,28 @@ $n$ : length of the input array ``` class Solution { - // Method to find duplicates in an array of integers - public List findDuplicates(int[] numbers) { - - // List to store duplicates - List duplicates = new ArrayList<>(); - - // Iterating through each number in the array - for (final int number : numbers) { - // Toggling the sign of the number at the index corresponding to its absolute value - numbers[Math.abs(number) - 1] *= -1; - - // If the number at that index is positive, it means it has been encountered before - if (numbers[Math.abs(number) - 1] > 0){ - // Adding the absolute value of the number to the duplicates list - duplicates.add(Math.abs(number)); - } + // Method to find the first missing positive integer in the given array + public int firstMissingPositive(int[] nums) { + + // Initializing the variable to store the potential missing positive integer + int p = 1; + + // Sorting the array to simplify the search process + Arrays.sort(nums); + + // Iterating through the array to find the first missing positive integer + for (int i = 0; i < nums.length; i++) { + + // Checking if the current element matches the potential missing positive integer + if (nums[i] == p) { + // If it matches, incrementing the potential missing positive integer + p++; + } + } + + // Returning the first missing positive integer found + return p; } - - // Returning the list of duplicates - return duplicates; - } } + ``` \ No newline at end of file From 328c42695694fa6726c50104949dc9b026d24246 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 26 Mar 2024 13:21:51 +0530 Subject: [PATCH 257/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ffc5f6a..d5fb474 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Simply sort, then look for positive numbers. # Approach -- Sorted the array ( used java collection sorting method which uses $$log(n)$$ time complexity so no issue) +- Sorted the array ( used java collection sorting method which uses $n*log(n)$ time complexity so no issue) - looked for positive numbers starting with 1, if found then searched next number ( 2, then 3, then 4...) - as array is sorted , no issue in arrangement of numbers - the last positive number not found will be the answer From 78b50693111e5951d3a81e5a93000e01312a844e Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 26 Mar 2024 13:23:22 +0530 Subject: [PATCH 258/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d5fb474..9163c77 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Have a look at the code , still have any confusion then please let me know in th Keep Solving.:) # Complexity -- Time complexity : $O(n log n)$ +- Time complexity : $O(n*log n)$ $n$ : length of the input array `nums` - Space complexity : $O(1)$ From 3b5d5848f7134697d05ae51217aa56d79ab23240 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 26 Mar 2024 13:24:20 +0530 Subject: [PATCH 259/300] Create Daily 26-03-24.md --- 2024 March/Daily 26-03-24.md | 60 ++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 2024 March/Daily 26-03-24.md diff --git a/2024 March/Daily 26-03-24.md b/2024 March/Daily 26-03-24.md new file mode 100644 index 0000000..6bfc177 --- /dev/null +++ b/2024 March/Daily 26-03-24.md @@ -0,0 +1,60 @@ +# 🎉 Happy Holi, GitHub Friends ! 🌈🎨 + +## Wishing you a colorful and joyful Holi celebration ! 🥳 May your coding adventures be as vibrant and delightful as the festival itself. Thanks for stopping by my repo ! 💻🌟 + +## Happy Holi from me to you ! 🎊🎉 + +## Today's 26-03-24 [Problem Link](https://leetcode.com/problems/first-missing-positive/description/?envType=daily-question&envId=2024-03-26) +## 41. First Missing Positive + +# Intuition + +Simply sort, then look for positive numbers. + +# Approach + +- Sorted the array ( used java collection sorting method which uses $n*log(n)$ time complexity so no issue) +- looked for positive numbers starting with 1, if found then searched next number ( 2, then 3, then 4...) +- as array is sorted , no issue in arrangement of numbers +- the last positive number not found will be the answer + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(n*log n)$ + +$n$ : length of the input array `nums` +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + + // Method to find the first missing positive integer in the given array + public int firstMissingPositive(int[] nums) { + + // Initializing the variable to store the potential missing positive integer + int p = 1; + + // Sorting the array to simplify the search process + Arrays.sort(nums); + + // Iterating through the array to find the first missing positive integer + for (int i = 0; i < nums.length; i++) { + + // Checking if the current element matches the potential missing positive integer + if (nums[i] == p) { + // If it matches, incrementing the potential missing positive integer + p++; + } + } + + // Returning the first missing positive integer found + return p; + } +} + +``` \ No newline at end of file From 3ba3f1ed4a1ac9e5bbe4a5eafb846c7292983fb8 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 27 Mar 2024 11:41:33 +0530 Subject: [PATCH 260/300] Update README.md --- README.md | 91 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 55 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 9163c77..8113523 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,38 @@ -# 🎉 Happy Holi, GitHub Friends ! 🌈🎨 - -## Wishing you a colorful and joyful Holi celebration ! 🥳 May your coding adventures be as vibrant and delightful as the festival itself. Thanks for stopping by my repo ! 💻🌟 - -## Happy Holi from me to you ! 🎊🎉 - # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. ## Always here to assist you guys. -## Today's 26-03-24 [Problem Link](https://leetcode.com/problems/first-missing-positive/description/?envType=daily-question&envId=2024-03-26) -## 41. First Missing Positive +## Today's 27-03=24 [Problem Link](https://leetcode.com/problems/subarray-product-less-than-k/description/?envType=daily-question&envId=2024-03-27) +## 713. Subarray Product Less Than K # Intuition -Simply sort, then look for positive numbers. +The problem requires finding the number of subarrays with a product less than a given threshold `k`. I can solve this efficiently using the sliding window technique. # Approach -- Sorted the array ( used java collection sorting method which uses $n*log(n)$ time complexity so no issue) -- looked for positive numbers starting with 1, if found then searched next number ( 2, then 3, then 4...) -- as array is sorted , no issue in arrangement of numbers -- the last positive number not found will be the answer +**Initialization** : I initialized two pointers `l` and `r` to track the left and right ends of the sliding window, respectively. Initialize `guna` (product of subarrays) and `jawab` (count of valid subarrays) to 1 and 0, respectively. + +**Edge Case Handling** : If `k` is less than or equal to 1, returned 0 as there can be no subarrays with product less than `k`. + +**Sliding Window Technique** : Iterated through the array using the right pointer `r`. At each step : +- Updated `guna` by multiplying it with the current element `nums[r]`. +- If `guna` becomes greater than or equal to `k`, shrink the window from the left : + - Moved the left pointer `l` to the right and divide `guna` by `nums[l]` until `guna` is less than `k`. +- Added the count of valid subarrays (`r - l + 1`) to `jawab`. +- Moved the right pointer `r` to the next element. + +**Return** : After iterating through the array, returned the count of valid subarrays `jawab`. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) - # Complexity -- Time complexity : $O(n*log n)$ +- Time complexity : $O(N)$ -$n$ : length of the input array `nums` +$N$ : number of elements in the input array `nums` - Space complexity : $O(1)$ @@ -39,28 +40,46 @@ $n$ : length of the input array `nums` ``` class Solution { - // Method to find the first missing positive integer in the given array - public int firstMissingPositive(int[] nums) { - - // Initializing the variable to store the potential missing positive integer - int p = 1; - - // Sorting the array to simplify the search process - Arrays.sort(nums); - - // Iterating through the array to find the first missing positive integer - for (int i = 0; i < nums.length; i++) { - - // Checking if the current element matches the potential missing positive integer - if (nums[i] == p) { - // If it matches, incrementing the potential missing positive integer - p++; + // Static variables to store the product of subarrays and the count of valid subarrays + static int guna; + static int jawab; + + // Method to count the number of subarrays with product less than k + public int numSubarrayProductLessThanK(int[] nums, int k) { + + // If k is less than or equal to 1, there can be no subarrays with product less than k + if( k <= 1){ + return 0; + } + + // Initializing the product of subarrays and the count of valid subarrays + guna = 1; + jawab = 0; + + // Initializing pointers for the sliding window technique + int l = 0; // Left pointer + int r = 0; // Right pointer + + // Iterating through the array + while( r < nums.length){ + + // Multiplying the product of subarrays with the current element + guna *= nums[r]; + + // If the product becomes greater than or equal to k, shrinking the window from the left + while( guna >= k){ + guna /= nums[l++]; // Dividing the product by the element at the left pointer } + + // Adding the count of valid subarrays to the answer + jawab += r - l + 1; + + // Moving the right pointer to the next element + r++; } - - // Returning the first missing positive integer found - return p; + + // Returning the count of valid subarrays + return jawab; } } - ``` \ No newline at end of file From b4c62e2e5ce821081adeb7f3dfcd4c503814815c Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 27 Mar 2024 11:43:24 +0530 Subject: [PATCH 261/300] Create Daily 27-03-24.md --- 2024 March/Daily 27-03-24.md | 79 ++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 2024 March/Daily 27-03-24.md diff --git a/2024 March/Daily 27-03-24.md b/2024 March/Daily 27-03-24.md new file mode 100644 index 0000000..2a28718 --- /dev/null +++ b/2024 March/Daily 27-03-24.md @@ -0,0 +1,79 @@ +## Today's 27-03=24 [Problem Link](https://leetcode.com/problems/subarray-product-less-than-k/description/?envType=daily-question&envId=2024-03-27) +## 713. Subarray Product Less Than K + +# Intuition + +The problem requires finding the number of subarrays with a product less than a given threshold `k`. I can solve this efficiently using the sliding window technique. + +# Approach + +**Initialization** : I initialized two pointers `l` and `r` to track the left and right ends of the sliding window, respectively. Initialize `guna` (product of subarrays) and `jawab` (count of valid subarrays) to 1 and 0, respectively. + +**Edge Case Handling** : If `k` is less than or equal to 1, returned 0 as there can be no subarrays with product less than `k`. + +**Sliding Window Technique** : Iterated through the array using the right pointer `r`. At each step : +- Updated `guna` by multiplying it with the current element `nums[r]`. +- If `guna` becomes greater than or equal to `k`, shrink the window from the left : + - Moved the left pointer `l` to the right and divide `guna` by `nums[l]` until `guna` is less than `k`. +- Added the count of valid subarrays (`r - l + 1`) to `jawab`. +- Moved the right pointer `r` to the next element. + +**Return** : After iterating through the array, returned the count of valid subarrays `jawab`. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(N)$ + +$N$ : number of elements in the input array `nums` +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + + // Static variables to store the product of subarrays and the count of valid subarrays + static int guna; + static int jawab; + + // Method to count the number of subarrays with product less than k + public int numSubarrayProductLessThanK(int[] nums, int k) { + + // If k is less than or equal to 1, there can be no subarrays with product less than k + if( k <= 1){ + return 0; + } + + // Initializing the product of subarrays and the count of valid subarrays + guna = 1; + jawab = 0; + + // Initializing pointers for the sliding window technique + int l = 0; // Left pointer + int r = 0; // Right pointer + + // Iterating through the array + while( r < nums.length){ + + // Multiplying the product of subarrays with the current element + guna *= nums[r]; + + // If the product becomes greater than or equal to k, shrinking the window from the left + while( guna >= k){ + guna /= nums[l++]; // Dividing the product by the element at the left pointer + } + + // Adding the count of valid subarrays to the answer + jawab += r - l + 1; + + // Moving the right pointer to the next element + r++; + } + + // Returning the count of valid subarrays + return jawab; + } +} +``` \ No newline at end of file From fbe53892e8b6c310d2659699529a09317adf442b Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 28 Mar 2024 11:49:06 +0530 Subject: [PATCH 262/300] Update README.md --- README.md | 87 +++++++++++++++++++++++++------------------------------ 1 file changed, 40 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 8113523..d3ab010 100644 --- a/README.md +++ b/README.md @@ -4,81 +4,74 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 27-03=24 [Problem Link](https://leetcode.com/problems/subarray-product-less-than-k/description/?envType=daily-question&envId=2024-03-27) -## 713. Subarray Product Less Than K +## Today's 28-03-24 [Problem Link](https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/description/?envType=daily-question&envId=2024-03-28) +## 2958. Length of Longest Subarray With at Most K Frequency # Intuition -The problem requires finding the number of subarrays with a product less than a given threshold `k`. I can solve this efficiently using the sliding window technique. - +My algorithm should employ a sliding window technique to find the maximum subarray length whose sum equals a given target `k`. # Approach -**Initialization** : I initialized two pointers `l` and `r` to track the left and right ends of the sliding window, respectively. Initialize `guna` (product of subarrays) and `jawab` (count of valid subarrays) to 1 and 0, respectively. +**Initialization** : I initialized a HashMap to store the frequency of elements encountered and variables to track the start index of the subarray (`s`) and the maximum length found so far (`jawab`). + +**Iterated Through Array** : Traversed the input array `nums`. + +**Updated HashMap** : Updated the frequency of the current element in the HashMap using the `merge()` method. + +**Checked Subarray Sum** : Checked if the sum of elements from the start index to the current index equals `k`. -**Edge Case Handling** : If `k` is less than or equal to 1, returned 0 as there can be no subarrays with product less than `k`. +**Adjusted Start Index** : If the sum exceeded `k`, moved the start index forward and updated the HashMap accordingly. -**Sliding Window Technique** : Iterated through the array using the right pointer `r`. At each step : -- Updated `guna` by multiplying it with the current element `nums[r]`. -- If `guna` becomes greater than or equal to `k`, shrink the window from the left : - - Moved the left pointer `l` to the right and divide `guna` by `nums[l]` until `guna` is less than `k`. -- Added the count of valid subarrays (`r - l + 1`) to `jawab`. -- Moved the right pointer `r` to the next element. +**Updated Maximum Length** : Updated the maximum length found so far (`jawab`) using the `Math.max()` function. -**Return** : After iterating through the array, returned the count of valid subarrays `jawab`. +**Result** : Returned the maximum subarray length satisfying the condition (`jawab`). --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(N)$ +- Time complexity : $O(n)$ -$N$ : number of elements in the input array `nums` -- Space complexity : $O(1)$ +$n$ : number of elements in the array +- Space complexity : $O(u)$ +$u$ : number of unique elements in the array # Code ``` class Solution { - // Static variables to store the product of subarrays and the count of valid subarrays - static int guna; - static int jawab; - - // Method to count the number of subarrays with product less than k - public int numSubarrayProductLessThanK(int[] nums, int k) { + // Static HashMap to store the frequency of elements encountered + static HashMap m; - // If k is less than or equal to 1, there can be no subarrays with product less than k - if( k <= 1){ - return 0; - } - - // Initializing the product of subarrays and the count of valid subarrays - guna = 1; + // Static variable to store the maximum subarray length satisfying the condition + static int jawab; + + // Method to find the maximum subarray length whose sum equals k + public int maxSubarrayLength(int[] nums, int k) { + // Initializing the HashMap + m = new HashMap<>(); + // Initializing variables to track the start index of the subarray and the maximum length found so far + int s = 0; jawab = 0; - - // Initializing pointers for the sliding window technique - int l = 0; // Left pointer - int r = 0; // Right pointer - - // Iterating through the array - while( r < nums.length){ - // Multiplying the product of subarrays with the current element - guna *= nums[r]; + // Traversing the array + for (int i = 0; i < nums.length; i++) { + // Updating the frequency of the current element in the HashMap + m.merge(nums[i], 1, Integer::sum); - // If the product becomes greater than or equal to k, shrinking the window from the left - while( guna >= k){ - guna /= nums[l++]; // Dividing the product by the element at the left pointer + // Checking if the sum of elements from start index to current index equals k + while (m.get(nums[i]) == 1 + k) { + // If sum exceeds k, moving the start index forward and updating the HashMap accordingly + m.merge(nums[s], -1, Integer::sum); + s++; } - // Adding the count of valid subarrays to the answer - jawab += r - l + 1; - - // Moving the right pointer to the next element - r++; + // Updating the maximum length found so far + jawab = Math.max(jawab, i - s + 1); } - // Returning the count of valid subarrays + // Returning the maximum subarray length satisfying the condition return jawab; } } From 13f97c40818d7c471fc499b86f40608df9ffb3ed Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 28 Mar 2024 11:50:54 +0530 Subject: [PATCH 263/300] Create Daily 28-03-24.md --- 2024 March/Daily 28-03-24.md | 72 ++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 2024 March/Daily 28-03-24.md diff --git a/2024 March/Daily 28-03-24.md b/2024 March/Daily 28-03-24.md new file mode 100644 index 0000000..2b3e603 --- /dev/null +++ b/2024 March/Daily 28-03-24.md @@ -0,0 +1,72 @@ +## Today's 28-03-24 [Problem Link](https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/description/?envType=daily-question&envId=2024-03-28) +## 2958. Length of Longest Subarray With at Most K Frequency + +# Intuition + +My algorithm should employ a sliding window technique to find the maximum subarray length whose sum equals a given target `k`. +# Approach + +**Initialization** : I initialized a HashMap to store the frequency of elements encountered and variables to track the start index of the subarray (`s`) and the maximum length found so far (`jawab`). + +**Iterated Through Array** : Traversed the input array `nums`. + +**Updated HashMap** : Updated the frequency of the current element in the HashMap using the `merge()` method. + +**Checked Subarray Sum** : Checked if the sum of elements from the start index to the current index equals `k`. + +**Adjusted Start Index** : If the sum exceeded `k`, moved the start index forward and updated the HashMap accordingly. + +**Updated Maximum Length** : Updated the maximum length found so far (`jawab`) using the `Math.max()` function. + +**Result** : Returned the maximum subarray length satisfying the condition (`jawab`). + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : number of elements in the array +- Space complexity : $O(u)$ + +$u$ : number of unique elements in the array + +# Code +``` +class Solution { + + // Static HashMap to store the frequency of elements encountered + static HashMap m; + + // Static variable to store the maximum subarray length satisfying the condition + static int jawab; + + // Method to find the maximum subarray length whose sum equals k + public int maxSubarrayLength(int[] nums, int k) { + // Initializing the HashMap + m = new HashMap<>(); + // Initializing variables to track the start index of the subarray and the maximum length found so far + int s = 0; + jawab = 0; + + // Traversing the array + for (int i = 0; i < nums.length; i++) { + // Updating the frequency of the current element in the HashMap + m.merge(nums[i], 1, Integer::sum); + + // Checking if the sum of elements from start index to current index equals k + while (m.get(nums[i]) == 1 + k) { + // If sum exceeds k, moving the start index forward and updating the HashMap accordingly + m.merge(nums[s], -1, Integer::sum); + s++; + } + + // Updating the maximum length found so far + jawab = Math.max(jawab, i - s + 1); + } + + // Returning the maximum subarray length satisfying the condition + return jawab; + } +} +``` \ No newline at end of file From 9d7a51cc4a2af9669df2f1e00d781af7a615dec4 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 29 Mar 2024 11:05:52 +0530 Subject: [PATCH 264/300] Update README.md --- README.md | 101 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 56 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index d3ab010..12ccc06 100644 --- a/README.md +++ b/README.md @@ -4,27 +4,37 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 28-03-24 [Problem Link](https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/description/?envType=daily-question&envId=2024-03-28) -## 2958. Length of Longest Subarray With at Most K Frequency +## Today's 29-03-24 [Problem Link](https://leetcode.com/problems/count-subarrays-where-max-element-appears-at-least-k-times/description/?envType=daily-question&envId=2024-03-29) +## 2962. Count Subarrays Where Max Element Appears at Least K Times # Intuition -My algorithm should employ a sliding window technique to find the maximum subarray length whose sum equals a given target `k`. +My given solution should aim to count the number of subarrays in an array `arr` with at least `k` occurrences of the maximum element. + # Approach -**Initialization** : I initialized a HashMap to store the frequency of elements encountered and variables to track the start index of the subarray (`s`) and the maximum length found so far (`jawab`). - -**Iterated Through Array** : Traversed the input array `nums`. - -**Updated HashMap** : Updated the frequency of the current element in the HashMap using the `merge()` method. +**Initialization** : + - Initialized `length` as the length of `arr`. + - Initialized `maxValue` to store the maximum value in `arr`. + - Initialized `left` and `right` pointers for the sliding window approach. + - Initialized `ginti` to count occurrences of the maximum value. + - Initialized `jawab` to accumulate the count of valid subarrays. -**Checked Subarray Sum** : Checked if the sum of elements from the start index to the current index equals `k`. +**Fonded the Maximum Value** : + - Iterated through `arr` to find the maximum value, stored in `maxValue`. -**Adjusted Start Index** : If the sum exceeded `k`, moved the start index forward and updated the HashMap accordingly. +**Sliding Window Approach** : + - Initialized `left` and `right` pointers to traverse the array. + - Initialized `ginti` to track the count of occurrences of the maximum value in the current window. + - Iterated through the array using `right` pointer: + - Incremented `ginti` if `arr[right]` equals `maxValue`. + - If `ginti` becomes greater than or equal to `k` : + - Incremented `jawab` by the count of valid subarrays ending at `right`. + - Slided the window by incrementing `left` until `ginti` becomes less than `k`. + - Repeated the process until `right` reaches the end of the array. -**Updated Maximum Length** : Updated the maximum length found so far (`jawab`) using the `Math.max()` function. - -**Result** : Returned the maximum subarray length satisfying the condition (`jawab`). +**Result** : + - Returned the final count stored in `jawab`. --- Have a look at the code , still have any confusion then please let me know in the comments @@ -32,47 +42,48 @@ Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : number of elements in the array -- Space complexity : $O(u)$ +$n$ : length of the input array `arr` +- Space complexity : $O(1)$ -$u$ : number of unique elements in the array # Code ``` class Solution { + public long countSubarrays(int[] arr, int k) { + int length = arr.length; + int maxValue = Integer.MIN_VALUE; + + // Finding the maximum value in the array + for (int num : arr) { + maxValue = Math.max(maxValue, num); + } + + int left = 0, right = 0, ginti = 0; + long jawab = 0; - // Static HashMap to store the frequency of elements encountered - static HashMap m; - - // Static variable to store the maximum subarray length satisfying the condition - static int jawab; - - // Method to find the maximum subarray length whose sum equals k - public int maxSubarrayLength(int[] nums, int k) { - // Initializing the HashMap - m = new HashMap<>(); - // Initializing variables to track the start index of the subarray and the maximum length found so far - int s = 0; - jawab = 0; - - // Traversing the array - for (int i = 0; i < nums.length; i++) { - // Updating the frequency of the current element in the HashMap - m.merge(nums[i], 1, Integer::sum); - - // Checking if the sum of elements from start index to current index equals k - while (m.get(nums[i]) == 1 + k) { - // If sum exceeds k, moving the start index forward and updating the HashMap accordingly - m.merge(nums[s], -1, Integer::sum); - s++; + // Sliding window approach + while (right < length) { + // Incrementing ginti if the element is equal to the maximum value + if (arr[right] == maxValue) { + ginti++; } - - // Updating the maximum length found so far - jawab = Math.max(jawab, i - s + 1); + // Checking if ginti is greater than or equal to k + if (ginti >= k) { + // Moving the left pointer until ginti is less than k + while (ginti >= k) { + // Incrementing jawab by the ginti of valid subarrays + jawab += length - right; + // Decrementing ginti if the element at left is equal to the maximum value + if (arr[left] == maxValue) { + ginti--; + } + left++; + } + } + right++; } - - // Returning the maximum subarray length satisfying the condition return jawab; } } + ``` \ No newline at end of file From 851475d2567731fc8812e425e2785f62c1845c4e Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 29 Mar 2024 11:06:59 +0530 Subject: [PATCH 265/300] Create Daily 29-03-24.md --- 2024 March/Daily 29-03-24.md | 83 ++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 2024 March/Daily 29-03-24.md diff --git a/2024 March/Daily 29-03-24.md b/2024 March/Daily 29-03-24.md new file mode 100644 index 0000000..2ed6f5f --- /dev/null +++ b/2024 March/Daily 29-03-24.md @@ -0,0 +1,83 @@ +## Today's 29-03-24 [Problem Link](https://leetcode.com/problems/count-subarrays-where-max-element-appears-at-least-k-times/description/?envType=daily-question&envId=2024-03-29) +## 2962. Count Subarrays Where Max Element Appears at Least K Times + +# Intuition + +My given solution should aim to count the number of subarrays in an array `arr` with at least `k` occurrences of the maximum element. + +# Approach + +**Initialization** : + - Initialized `length` as the length of `arr`. + - Initialized `maxValue` to store the maximum value in `arr`. + - Initialized `left` and `right` pointers for the sliding window approach. + - Initialized `ginti` to count occurrences of the maximum value. + - Initialized `jawab` to accumulate the count of valid subarrays. + +**Fonded the Maximum Value** : + - Iterated through `arr` to find the maximum value, stored in `maxValue`. + +**Sliding Window Approach** : + - Initialized `left` and `right` pointers to traverse the array. + - Initialized `ginti` to track the count of occurrences of the maximum value in the current window. + - Iterated through the array using `right` pointer: + - Incremented `ginti` if `arr[right]` equals `maxValue`. + - If `ginti` becomes greater than or equal to `k` : + - Incremented `jawab` by the count of valid subarrays ending at `right`. + - Slided the window by incrementing `left` until `ginti` becomes less than `k`. + - Repeated the process until `right` reaches the end of the array. + +**Result** : + - Returned the final count stored in `jawab`. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the input array `arr` +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + public long countSubarrays(int[] arr, int k) { + int length = arr.length; + int maxValue = Integer.MIN_VALUE; + + // Finding the maximum value in the array + for (int num : arr) { + maxValue = Math.max(maxValue, num); + } + + int left = 0, right = 0, ginti = 0; + long jawab = 0; + + // Sliding window approach + while (right < length) { + // Incrementing ginti if the element is equal to the maximum value + if (arr[right] == maxValue) { + ginti++; + } + // Checking if ginti is greater than or equal to k + if (ginti >= k) { + // Moving the left pointer until ginti is less than k + while (ginti >= k) { + // Incrementing jawab by the ginti of valid subarrays + jawab += length - right; + // Decrementing ginti if the element at left is equal to the maximum value + if (arr[left] == maxValue) { + ginti--; + } + left++; + } + } + right++; + } + return jawab; + } +} + +``` \ No newline at end of file From 2ae44f1956115eadc31064b9dd7a2b5a27f5c897 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 30 Mar 2024 10:03:11 +0530 Subject: [PATCH 266/300] Update README.md --- README.md | 93 ++++++++++++++++++++----------------------------------- 1 file changed, 34 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 12ccc06..dee931e 100644 --- a/README.md +++ b/README.md @@ -4,37 +4,23 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 29-03-24 [Problem Link](https://leetcode.com/problems/count-subarrays-where-max-element-appears-at-least-k-times/description/?envType=daily-question&envId=2024-03-29) -## 2962. Count Subarrays Where Max Element Appears at Least K Times +## Today's 30-03-24 [Problem Link](https://leetcode.com/problems/subarrays-with-k-different-integers/description/?envType=daily-question&envId=2024-03-30) +## 992. Subarrays with K Different Integers # Intuition -My given solution should aim to count the number of subarrays in an array `arr` with at least `k` occurrences of the maximum element. - +This problem can be solved using a sliding window approach combined with hashing. # Approach -**Initialization** : - - Initialized `length` as the length of `arr`. - - Initialized `maxValue` to store the maximum value in `arr`. - - Initialized `left` and `right` pointers for the sliding window approach. - - Initialized `ginti` to count occurrences of the maximum value. - - Initialized `jawab` to accumulate the count of valid subarrays. - -**Fonded the Maximum Value** : - - Iterated through `arr` to find the maximum value, stored in `maxValue`. - -**Sliding Window Approach** : - - Initialized `left` and `right` pointers to traverse the array. - - Initialized `ginti` to track the count of occurrences of the maximum value in the current window. - - Iterated through the array using `right` pointer: - - Incremented `ginti` if `arr[right]` equals `maxValue`. - - If `ginti` becomes greater than or equal to `k` : - - Incremented `jawab` by the count of valid subarrays ending at `right`. - - Slided the window by incrementing `left` until `ginti` becomes less than `k`. - - Repeated the process until `right` reaches the end of the array. +- I defined a helper function `subarrayAtmostKdistinct` which calculates the number of subarrays with at most `k` distinct elements. +- The main function `subarraysWithKDistinct` then calculates the number of subarrays with exactly `k` distinct elements by subtracting the count of subarrays with at most `k-1` distinct elements from the count of subarrays with at most `k` distinct elements. +- I used a sliding window approach where I kept track of the frequency of elements within the current window using a hashmap. +- I iterated through the array using two pointers `start` and `end`, where `start` marks the start of the current window and `end` marks the end. +- I incremented `end` until the number of distinct elements within the window exceeded `k`. +- At each step, I updated the hashmap and calculated the count of subarrays with at most `k` distinct elements using the formula `end - start + 1`. +- I repeated this process until I reached the end of the array. -**Result** : - - Returned the final count stored in `jawab`. +By following this approach, I efficiently calculated the number of subarrays with exactly `k` distinct elements. --- Have a look at the code , still have any confusion then please let me know in the comments @@ -42,48 +28,37 @@ Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : length of the input array `arr` -- Space complexity : $O(1)$ +$n$ : length of the input array +- Space complexity : $O(k)$ - +$k$ : given # Code ``` class Solution { - public long countSubarrays(int[] arr, int k) { - int length = arr.length; - int maxValue = Integer.MIN_VALUE; - - // Finding the maximum value in the array - for (int num : arr) { - maxValue = Math.max(maxValue, num); - } + public static int subarraysWithKDistinct(int[] nums, int k) { + + return subarrayAtmostKdistinct(nums, k) - subarrayAtmostKdistinct(nums, k-1); - int left = 0, right = 0, ginti = 0; - long jawab = 0; + } - // Sliding window approach - while (right < length) { - // Incrementing ginti if the element is equal to the maximum value - if (arr[right] == maxValue) { - ginti++; - } - // Checking if ginti is greater than or equal to k - if (ginti >= k) { - // Moving the left pointer until ginti is less than k - while (ginti >= k) { - // Incrementing jawab by the ginti of valid subarrays - jawab += length - right; - // Decrementing ginti if the element at left is equal to the maximum value - if (arr[left] == maxValue) { - ginti--; - } - left++; - } + public static int subarrayAtmostKdistinct( int[] a, int k){ // this function will give number of subarrays which have at most 'k' distinct elements + int count = 0; + HashMap h = new HashMap<>(); // to store the occurences of numbers + int start = 0; // to be considered when number of distinct numbers crosses 'k' + for( int end = 0; end < a.length; end++){ + h.put( a[end], h.getOrDefault(a[end], 0) + 1); + while( h.size() > k){ + int t = h.get(a[start]); // get the number of occurences of leftmost number + h.put(a[start], t-1); // decrement it's number of occurence + if( t-1 == 0){ // if it was the last of it's kind then remove this from hashmap + h.remove(a[start]); + } + start++; // incremented the start } - right++; + count += end - start + 1; // try to visualise with {1,2,1,3,4} with k = 3 then you will get why this (end-start+1) is added : because it will give the all subarrays with distinct numbers less than or equal to 'k' } - return jawab; + return count; } -} +} ``` \ No newline at end of file From 2e7c6b4320fe69486654c59bdb30d47b2b7305ba Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 30 Mar 2024 10:03:53 +0530 Subject: [PATCH 267/300] Create Daily 30-03-24.md --- 2024 March/Daily 30-03-24.md | 58 ++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 2024 March/Daily 30-03-24.md diff --git a/2024 March/Daily 30-03-24.md b/2024 March/Daily 30-03-24.md new file mode 100644 index 0000000..a5a8e3f --- /dev/null +++ b/2024 March/Daily 30-03-24.md @@ -0,0 +1,58 @@ +## Today's 30-03-24 [Problem Link](https://leetcode.com/problems/subarrays-with-k-different-integers/description/?envType=daily-question&envId=2024-03-30) +## 992. Subarrays with K Different Integers + +# Intuition + +This problem can be solved using a sliding window approach combined with hashing. +# Approach + +- I defined a helper function `subarrayAtmostKdistinct` which calculates the number of subarrays with at most `k` distinct elements. +- The main function `subarraysWithKDistinct` then calculates the number of subarrays with exactly `k` distinct elements by subtracting the count of subarrays with at most `k-1` distinct elements from the count of subarrays with at most `k` distinct elements. +- I used a sliding window approach where I kept track of the frequency of elements within the current window using a hashmap. +- I iterated through the array using two pointers `start` and `end`, where `start` marks the start of the current window and `end` marks the end. +- I incremented `end` until the number of distinct elements within the window exceeded `k`. +- At each step, I updated the hashmap and calculated the count of subarrays with at most `k` distinct elements using the formula `end - start + 1`. +- I repeated this process until I reached the end of the array. + +By following this approach, I efficiently calculated the number of subarrays with exactly `k` distinct elements. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the input array +- Space complexity : $O(k)$ + +$k$ : given +# Code +``` +class Solution { + public static int subarraysWithKDistinct(int[] nums, int k) { + + return subarrayAtmostKdistinct(nums, k) - subarrayAtmostKdistinct(nums, k-1); + + } + + public static int subarrayAtmostKdistinct( int[] a, int k){ // this function will give number of subarrays which have at most 'k' distinct elements + int count = 0; + HashMap h = new HashMap<>(); // to store the occurences of numbers + int start = 0; // to be considered when number of distinct numbers crosses 'k' + for( int end = 0; end < a.length; end++){ + h.put( a[end], h.getOrDefault(a[end], 0) + 1); + while( h.size() > k){ + int t = h.get(a[start]); // get the number of occurences of leftmost number + h.put(a[start], t-1); // decrement it's number of occurence + if( t-1 == 0){ // if it was the last of it's kind then remove this from hashmap + h.remove(a[start]); + } + start++; // incremented the start + } + count += end - start + 1; // try to visualise with {1,2,1,3,4} with k = 3 then you will get why this (end-start+1) is added : because it will give the all subarrays with distinct numbers less than or equal to 'k' + } + return count; + } + +} +``` \ No newline at end of file From d8449471f9e50304e493869bce8b420daf72e6c4 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 31 Mar 2024 15:09:27 +0530 Subject: [PATCH 268/300] Update README.md --- README.md | 83 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 50 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index dee931e..10cca8e 100644 --- a/README.md +++ b/README.md @@ -4,23 +4,32 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 30-03-24 [Problem Link](https://leetcode.com/problems/subarrays-with-k-different-integers/description/?envType=daily-question&envId=2024-03-30) -## 992. Subarrays with K Different Integers +## Today's 31-03-24 [Problem Link](https://leetcode.com/problems/count-subarrays-with-fixed-bounds/description/?envType=daily-question&envId=2024-03-31) +## 2444. Count Subarrays With Fixed Bounds # Intuition -This problem can be solved using a sliding window approach combined with hashing. +The problem requires counting the number of subarrays within a given range [minK, maxK] where the subarray's elements are also within this range. To efficiently count these subarrays, I can iterate through the array once and keep track of the last invalid index, the last occurrence of minK, and the last occurrence of maxK. By doing so, I can determine the valid subarrays that end at each index. + # Approach -- I defined a helper function `subarrayAtmostKdistinct` which calculates the number of subarrays with at most `k` distinct elements. -- The main function `subarraysWithKDistinct` then calculates the number of subarrays with exactly `k` distinct elements by subtracting the count of subarrays with at most `k-1` distinct elements from the count of subarrays with at most `k` distinct elements. -- I used a sliding window approach where I kept track of the frequency of elements within the current window using a hashmap. -- I iterated through the array using two pointers `start` and `end`, where `start` marks the start of the current window and `end` marks the end. -- I incremented `end` until the number of distinct elements within the window exceeded `k`. -- At each step, I updated the hashmap and calculated the count of subarrays with at most `k` distinct elements using the formula `end - start + 1`. -- I repeated this process until I reached the end of the array. -By following this approach, I efficiently calculated the number of subarrays with exactly `k` distinct elements. +- Initialized variables : + - `count`: to store the count of valid subarrays. + - `lastInvalidIndex`: to keep track of the index of the last element that violates the range condition. + - `lastMinIndex`: to store the index of the last occurrence of minK. + - `lastMaxIndex`: to store the index of the last occurrence of maxK. + +- Iterated through the array `nums` : + - Updated `lastInvalidIndex` if the current element is out of the range [minK, maxK]. + - Updated `lastMinIndex` if the current element is equal to minK. + - Updated `lastMaxIndex` if the current element is equal to maxK. + - Calculated the count of valid subarrays up to the current index by taking the maximum of 0 and the difference between the minimum of `lastMinIndex` and `lastMaxIndex` and `lastInvalidIndex`. + - Added this count to the `count`. + +- Returned the total count of valid subarrays. + +By following this approach, I can efficiently count the number of valid subarrays within the given range. --- Have a look at the code , still have any confusion then please let me know in the comments @@ -28,37 +37,45 @@ Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : length of the input array -- Space complexity : $O(k)$ +$n$ : length of the input array `nums` +- Space complexity : $O(1)$ -$k$ : given + # Code ``` class Solution { - public static int subarraysWithKDistinct(int[] nums, int k) { - return subarrayAtmostKdistinct(nums, k) - subarrayAtmostKdistinct(nums, k-1); - - } + // Function to count subarrays within the given range [minK, maxK] + public long countSubarrays(int[] nums, int minK, int maxK) { + + // Variable to store the count of valid subarrays + long count = 0; + // Index of the last element that violates the range condition + int lastInvalidIndex = -1; + // Index of the last occurrence of minK + int lastMinIndex = -1; + // Index of the last occurrence of maxK + int lastMaxIndex = -1; - public static int subarrayAtmostKdistinct( int[] a, int k){ // this function will give number of subarrays which have at most 'k' distinct elements - int count = 0; - HashMap h = new HashMap<>(); // to store the occurences of numbers - int start = 0; // to be considered when number of distinct numbers crosses 'k' - for( int end = 0; end < a.length; end++){ - h.put( a[end], h.getOrDefault(a[end], 0) + 1); - while( h.size() > k){ - int t = h.get(a[start]); // get the number of occurences of leftmost number - h.put(a[start], t-1); // decrement it's number of occurence - if( t-1 == 0){ // if it was the last of it's kind then remove this from hashmap - h.remove(a[start]); - } - start++; // incremented the start + // Iterating through the array + for (int i = 0; i < nums.length; ++i) { + // Updating lastInvalidIndex if current element is out of range + if (nums[i] < minK || nums[i] > maxK) { + lastInvalidIndex = i; + } + // Updating lastMinIndex if current element is equal to minK + if (nums[i] == minK) { + lastMinIndex = i; } - count += end - start + 1; // try to visualise with {1,2,1,3,4} with k = 3 then you will get why this (end-start+1) is added : because it will give the all subarrays with distinct numbers less than or equal to 'k' + // Updating lastMaxIndex if current element is equal to maxK + if (nums[i] == maxK) { + lastMaxIndex = i; + } + // Calculating the count of valid subarrays up to the current index + count += Math.max(0, Math.min(lastMinIndex, lastMaxIndex) - lastInvalidIndex); } + // Returning the total count of valid subarrays return count; } - } ``` \ No newline at end of file From 76df4f03786755a48cc49419eb80a63f6a3d46ad Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 31 Mar 2024 15:10:10 +0530 Subject: [PATCH 269/300] Create Daily 31-03-24.md --- 2024 March/Daily 31-03-24.md | 77 ++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 2024 March/Daily 31-03-24.md diff --git a/2024 March/Daily 31-03-24.md b/2024 March/Daily 31-03-24.md new file mode 100644 index 0000000..bc3dc40 --- /dev/null +++ b/2024 March/Daily 31-03-24.md @@ -0,0 +1,77 @@ +# Leetcode Daily Challenge Solutions + +## Today's 31-03-24 [Problem Link](https://leetcode.com/problems/count-subarrays-with-fixed-bounds/description/?envType=daily-question&envId=2024-03-31) +## 2444. Count Subarrays With Fixed Bounds + +# Intuition + +The problem requires counting the number of subarrays within a given range [minK, maxK] where the subarray's elements are also within this range. To efficiently count these subarrays, I can iterate through the array once and keep track of the last invalid index, the last occurrence of minK, and the last occurrence of maxK. By doing so, I can determine the valid subarrays that end at each index. + +# Approach + + +- Initialized variables : + - `count`: to store the count of valid subarrays. + - `lastInvalidIndex`: to keep track of the index of the last element that violates the range condition. + - `lastMinIndex`: to store the index of the last occurrence of minK. + - `lastMaxIndex`: to store the index of the last occurrence of maxK. + +- Iterated through the array `nums` : + - Updated `lastInvalidIndex` if the current element is out of the range [minK, maxK]. + - Updated `lastMinIndex` if the current element is equal to minK. + - Updated `lastMaxIndex` if the current element is equal to maxK. + - Calculated the count of valid subarrays up to the current index by taking the maximum of 0 and the difference between the minimum of `lastMinIndex` and `lastMaxIndex` and `lastInvalidIndex`. + - Added this count to the `count`. + +- Returned the total count of valid subarrays. + +By following this approach, I can efficiently count the number of valid subarrays within the given range. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the input array `nums` +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + + // Function to count subarrays within the given range [minK, maxK] + public long countSubarrays(int[] nums, int minK, int maxK) { + + // Variable to store the count of valid subarrays + long count = 0; + // Index of the last element that violates the range condition + int lastInvalidIndex = -1; + // Index of the last occurrence of minK + int lastMinIndex = -1; + // Index of the last occurrence of maxK + int lastMaxIndex = -1; + + // Iterating through the array + for (int i = 0; i < nums.length; ++i) { + // Updating lastInvalidIndex if current element is out of range + if (nums[i] < minK || nums[i] > maxK) { + lastInvalidIndex = i; + } + // Updating lastMinIndex if current element is equal to minK + if (nums[i] == minK) { + lastMinIndex = i; + } + // Updating lastMaxIndex if current element is equal to maxK + if (nums[i] == maxK) { + lastMaxIndex = i; + } + // Calculating the count of valid subarrays up to the current index + count += Math.max(0, Math.min(lastMinIndex, lastMaxIndex) - lastInvalidIndex); + } + // Returning the total count of valid subarrays + return count; + } +} +``` \ No newline at end of file From 88f27dda095697cc4a657590fb88cf0726126957 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 1 Apr 2024 20:13:55 +0530 Subject: [PATCH 270/300] Update README.md --- README.md | 70 ++++++++++++++++--------------------------------------- 1 file changed, 20 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 10cca8e..38bc71a 100644 --- a/README.md +++ b/README.md @@ -4,32 +4,22 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 31-03-24 [Problem Link](https://leetcode.com/problems/count-subarrays-with-fixed-bounds/description/?envType=daily-question&envId=2024-03-31) -## 2444. Count Subarrays With Fixed Bounds +## Today's 01-04-24 [Problem Link](https://leetcode.com/problems/length-of-last-word/description/?envType=daily-question&envId=2024-04-01) +## 58. Length of Last Word # Intuition -The problem requires counting the number of subarrays within a given range [minK, maxK] where the subarray's elements are also within this range. To efficiently count these subarrays, I can iterate through the array once and keep track of the last invalid index, the last occurrence of minK, and the last occurrence of maxK. By doing so, I can determine the valid subarrays that end at each index. +To find the length of the last word in the given string, I need to identify and isolate the last word. This involves trimming any leading or trailing spaces from the string and then locating the last space character to determine where the last word begins. Once I have isolated the last word, I can calculate its length and return it. # Approach +**Trim the string** : Remove dleading and trailing spaces from the input string. -- Initialized variables : - - `count`: to store the count of valid subarrays. - - `lastInvalidIndex`: to keep track of the index of the last element that violates the range condition. - - `lastMinIndex`: to store the index of the last occurrence of minK. - - `lastMaxIndex`: to store the index of the last occurrence of maxK. +**Finded the last space index** : Determined the index of the last space character in the trimmed string. -- Iterated through the array `nums` : - - Updated `lastInvalidIndex` if the current element is out of the range [minK, maxK]. - - Updated `lastMinIndex` if the current element is equal to minK. - - Updated `lastMaxIndex` if the current element is equal to maxK. - - Calculated the count of valid subarrays up to the current index by taking the maximum of 0 and the difference between the minimum of `lastMinIndex` and `lastMaxIndex` and `lastInvalidIndex`. - - Added this count to the `count`. +**Calculated the length of the last word** : Subtracted the index of the last space from the length of the trimmed string to find the length of the last word. -- Returned the total count of valid subarrays. - -By following this approach, I can efficiently count the number of valid subarrays within the given range. +**Returned the length of the last word** : Provided the calculated length as the output. --- Have a look at the code , still have any confusion then please let me know in the comments @@ -37,45 +27,25 @@ Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : length of the input array `nums` +$n$ : length of the string - Space complexity : $O(1)$ # Code ``` class Solution { - - // Function to count subarrays within the given range [minK, maxK] - public long countSubarrays(int[] nums, int minK, int maxK) { - - // Variable to store the count of valid subarrays - long count = 0; - // Index of the last element that violates the range condition - int lastInvalidIndex = -1; - // Index of the last occurrence of minK - int lastMinIndex = -1; - // Index of the last occurrence of maxK - int lastMaxIndex = -1; - - // Iterating through the array - for (int i = 0; i < nums.length; ++i) { - // Updating lastInvalidIndex if current element is out of range - if (nums[i] < minK || nums[i] > maxK) { - lastInvalidIndex = i; - } - // Updating lastMinIndex if current element is equal to minK - if (nums[i] == minK) { - lastMinIndex = i; - } - // Updating lastMaxIndex if current element is equal to maxK - if (nums[i] == maxK) { - lastMaxIndex = i; - } - // Calculating the count of valid subarrays up to the current index - count += Math.max(0, Math.min(lastMinIndex, lastMaxIndex) - lastInvalidIndex); - } - // Returning the total count of valid subarrays - return count; + public int lengthOfLastWord(String s) { + // Trimming the string to remove leading and trailing spaces + s = s.trim(); + + // Finding the index of the last space character + int lastSpaceIndex = s.lastIndexOf(' '); + + // Calculating the length of the last word + int lengthOfLastWord = s.length() - lastSpaceIndex - 1; + + // Returning the length of the last word + return lengthOfLastWord; } } ``` \ No newline at end of file From 12546264bae224c4cc2fb4de8d19df91b2c69d75 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 1 Apr 2024 20:14:58 +0530 Subject: [PATCH 271/300] Create Daily 01-04-24.md --- 2024 April/Daily 01-04-24.md | 45 ++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 2024 April/Daily 01-04-24.md diff --git a/2024 April/Daily 01-04-24.md b/2024 April/Daily 01-04-24.md new file mode 100644 index 0000000..f75be5b --- /dev/null +++ b/2024 April/Daily 01-04-24.md @@ -0,0 +1,45 @@ +## Today's 01-04-24 [Problem Link](https://leetcode.com/problems/length-of-last-word/description/?envType=daily-question&envId=2024-04-01) +## 58. Length of Last Word + +# Intuition + +To find the length of the last word in the given string, I need to identify and isolate the last word. This involves trimming any leading or trailing spaces from the string and then locating the last space character to determine where the last word begins. Once I have isolated the last word, I can calculate its length and return it. + +# Approach + +**Trim the string** : Remove dleading and trailing spaces from the input string. + +**Finded the last space index** : Determined the index of the last space character in the trimmed string. + +**Calculated the length of the last word** : Subtracted the index of the last space from the length of the trimmed string to find the length of the last word. + +**Returned the length of the last word** : Provided the calculated length as the output. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the string +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + public int lengthOfLastWord(String s) { + // Trimming the string to remove leading and trailing spaces + s = s.trim(); + + // Finding the index of the last space character + int lastSpaceIndex = s.lastIndexOf(' '); + + // Calculating the length of the last word + int lengthOfLastWord = s.length() - lastSpaceIndex - 1; + + // Returning the length of the last word + return lengthOfLastWord; + } +} +``` \ No newline at end of file From cdc007a2df4eca7d9e8c0021ea5072271b7a0437 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 2 Apr 2024 12:57:11 +0530 Subject: [PATCH 272/300] Update README.md --- README.md | 70 ++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 49 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 38bc71a..4ad901e 100644 --- a/README.md +++ b/README.md @@ -4,22 +4,25 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 01-04-24 [Problem Link](https://leetcode.com/problems/length-of-last-word/description/?envType=daily-question&envId=2024-04-01) -## 58. Length of Last Word +## Today's 02-04-24 [Problem Link](https://leetcode.com/problems/isomorphic-strings/description/?envType=daily-question&envId=2024-04-02) +## 205. Isomorphic Strings # Intuition -To find the length of the last word in the given string, I need to identify and isolate the last word. This involves trimming any leading or trailing spaces from the string and then locating the last space character to determine where the last word begins. Once I have isolated the last word, I can calculate its length and return it. +To check if two strings are isomorphic, we need to establish a one-to-one mapping between characters in one string to characters in the other string. This mapping must preserve the order of characters and ensure that no two characters map to the same character, while allowing a character to map to itself. # Approach -**Trim the string** : Remove dleading and trailing spaces from the input string. +**Initialization** : Initialized two hash maps (`sToTMap` and `tToSMap`) to store mappings from characters in string `s` to characters in string `t`, and vice versa. + +**Iteration** : Iterated through each character in the strings `s` and `t`. + +**Mapping Check** : + - For each character pair `(sChar, tChar)`, checked if `sChar` is already mapped to a character in `t` and if `tChar` is already mapped to a character in `s`. + - If a mapping existed and the mapped characters are not equal to each other, returned `false`. + - If a mapping does not exist, established the mapping by adding the characters to their respective maps. -**Finded the last space index** : Determined the index of the last space character in the trimmed string. - -**Calculated the length of the last word** : Subtracted the index of the last space from the length of the trimmed string to find the length of the last word. - -**Returned the length of the last word** : Provided the calculated length as the output. +**Completion** : If the loop completes without returning `false`, returned `true`, indicating that the strings are isomorphic. --- Have a look at the code , still have any confusion then please let me know in the comments @@ -27,25 +30,50 @@ Keep Solving.:) # Complexity - Time complexity : $O(n)$ -$n$ : length of the string -- Space complexity : $O(1)$ +$n$ : length of the strings `s` and `t` +- Space complexity : $O(min(m, n))$ +$m$ : size of the character set # Code ``` class Solution { - public int lengthOfLastWord(String s) { - // Trimming the string to remove leading and trailing spaces - s = s.trim(); - - // Finding the index of the last space character - int lastSpaceIndex = s.lastIndexOf(' '); + public boolean isIsomorphic(String s, String t) { + + // Initializing two hash maps to store mappings + Map sToTMap = new HashMap<>(); + Map tToSMap = new HashMap<>(); - // Calculating the length of the last word - int lengthOfLastWord = s.length() - lastSpaceIndex - 1; + // Iterating through each character in the strings s and t + for (int i = 0; i < s.length(); i++) { + char sChar = s.charAt(i); + char tChar = t.charAt(i); + + // Checking if sChar is already mapped to a character in t + if (sToTMap.containsKey(sChar)) { + // If the mapped character is not equal to tChar, returning false + if (sToTMap.get(sChar) != tChar) { + return false; + } + } else { + // If sChar is not mapped, mapping it to tChar + sToTMap.put(sChar, tChar); + } + + // Checking if tChar is already mapped to a character in s + if (tToSMap.containsKey(tChar)) { + // If the mapped character is not equal to sChar, returning false + if (tToSMap.get(tChar) != sChar) { + return false; + } + } else { + // If tChar is not mapped, mapping it to sChar + tToSMap.put(tChar, sChar); + } + } - // Returning the length of the last word - return lengthOfLastWord; + // If the loop completes without returning false, returning true + return true; } } ``` \ No newline at end of file From 18993efbc4e74d8a420f00e9ed0d21215830a332 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 2 Apr 2024 12:59:15 +0530 Subject: [PATCH 273/300] Create Daily 02-04-24.md --- 2024 April/Daily 02-04-24.md | 73 ++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 2024 April/Daily 02-04-24.md diff --git a/2024 April/Daily 02-04-24.md b/2024 April/Daily 02-04-24.md new file mode 100644 index 0000000..c15c40e --- /dev/null +++ b/2024 April/Daily 02-04-24.md @@ -0,0 +1,73 @@ +## Today's 02-04-24 [Problem Link](https://leetcode.com/problems/isomorphic-strings/description/?envType=daily-question&envId=2024-04-02) +## 205. Isomorphic Strings + +# Intuition + +To check if two strings are isomorphic, we need to establish a one-to-one mapping between characters in one string to characters in the other string. This mapping must preserve the order of characters and ensure that no two characters map to the same character, while allowing a character to map to itself. + +# Approach + +**Initialization** : Initialized two hash maps (`sToTMap` and `tToSMap`) to store mappings from characters in string `s` to characters in string `t`, and vice versa. + +**Iteration** : Iterated through each character in the strings `s` and `t`. + +**Mapping Check** : + - For each character pair `(sChar, tChar)`, checked if `sChar` is already mapped to a character in `t` and if `tChar` is already mapped to a character in `s`. + - If a mapping existed and the mapped characters are not equal to each other, returned `false`. + - If a mapping does not exist, established the mapping by adding the characters to their respective maps. + +**Completion** : If the loop completes without returning `false`, returned `true`, indicating that the strings are isomorphic. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the strings `s` and `t` +- Space complexity : $O(min(m, n))$ + +$m$ : size of the character set + +# Code +``` +class Solution { + public boolean isIsomorphic(String s, String t) { + + // Initializing two hash maps to store mappings + Map sToTMap = new HashMap<>(); + Map tToSMap = new HashMap<>(); + + // Iterating through each character in the strings s and t + for (int i = 0; i < s.length(); i++) { + char sChar = s.charAt(i); + char tChar = t.charAt(i); + + // Checking if sChar is already mapped to a character in t + if (sToTMap.containsKey(sChar)) { + // If the mapped character is not equal to tChar, returning false + if (sToTMap.get(sChar) != tChar) { + return false; + } + } else { + // If sChar is not mapped, mapping it to tChar + sToTMap.put(sChar, tChar); + } + + // Checking if tChar is already mapped to a character in s + if (tToSMap.containsKey(tChar)) { + // If the mapped character is not equal to sChar, returning false + if (tToSMap.get(tChar) != sChar) { + return false; + } + } else { + // If tChar is not mapped, mapping it to sChar + tToSMap.put(tChar, sChar); + } + } + + // If the loop completes without returning false, returning true + return true; + } +} +``` \ No newline at end of file From e01fa3c591ed73dde88333c6730beedb451e1a21 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 3 Apr 2024 22:42:21 +0530 Subject: [PATCH 274/300] Update README.md --- README.md | 112 +++++++++++++++++++++++++++++------------------------- 1 file changed, 61 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 4ad901e..45434d5 100644 --- a/README.md +++ b/README.md @@ -4,76 +4,86 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 02-04-24 [Problem Link](https://leetcode.com/problems/isomorphic-strings/description/?envType=daily-question&envId=2024-04-02) -## 205. Isomorphic Strings +## Today's 03-04-24 [Problem Link](https://leetcode.com/problems/word-search/description/?envType=daily-question&envId=2024-04-03) +## 79. Word Search # Intuition -To check if two strings are isomorphic, we need to establish a one-to-one mapping between characters in one string to characters in the other string. This mapping must preserve the order of characters and ensure that no two characters map to the same character, while allowing a character to map to itself. +I should utiliz Depth-First Search (DFS) to systematically explore the board, aiming to find the given word by traversing adjacent cells. # Approach -**Initialization** : Initialized two hash maps (`sToTMap` and `tToSMap`) to store mappings from characters in string `s` to characters in string `t`, and vice versa. - -**Iteration** : Iterated through each character in the strings `s` and `t`. - -**Mapping Check** : - - For each character pair `(sChar, tChar)`, checked if `sChar` is already mapped to a character in `t` and if `tChar` is already mapped to a character in `s`. - - If a mapping existed and the mapped characters are not equal to each other, returned `false`. - - If a mapping does not exist, established the mapping by adding the characters to their respective maps. -**Completion** : If the loop completes without returning `false`, returned `true`, indicating that the strings are isomorphic. +**Main Method (exist) :** +- Iterated through each cell on the board. +- Initiated DFS exploration from each cell to search for the word. +- Returned true if the word is found, otherwise false. +**DFS Method (explore) :** +- Checked if the current cell is within bounds. +- Verified if the character at the current cell matches the word's character. +- Recursively explored adjacent cells to find the next character of the word. +- Marked visited cells to avoid revisiting and backtrack when necessary. +- If the entire word is found, returned true; otherwise, returned false. + --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(n)$ +- Time complexity : $ O(m \times n \times 4^l) $ -$n$ : length of the strings `s` and `t` -- Space complexity : $O(min(m, n))$ +$m$ : number of rows +$n$ : number of columns +$l$ : length of the word +- Space complexity : $O(1)$ -$m$ : size of the character set # Code ``` class Solution { - public boolean isIsomorphic(String s, String t) { - - // Initializing two hash maps to store mappings - Map sToTMap = new HashMap<>(); - Map tToSMap = new HashMap<>(); - - // Iterating through each character in the strings s and t - for (int i = 0; i < s.length(); i++) { - char sChar = s.charAt(i); - char tChar = t.charAt(i); - - // Checking if sChar is already mapped to a character in t - if (sToTMap.containsKey(sChar)) { - // If the mapped character is not equal to tChar, returning false - if (sToTMap.get(sChar) != tChar) { - return false; - } - } else { - // If sChar is not mapped, mapping it to tChar - sToTMap.put(sChar, tChar); - } - - // Checking if tChar is already mapped to a character in s - if (tToSMap.containsKey(tChar)) { - // If the mapped character is not equal to sChar, returning false - if (tToSMap.get(tChar) != sChar) { - return false; - } - } else { - // If tChar is not mapped, mapping it to sChar - tToSMap.put(tChar, sChar); - } + // Main method to check if the word exists on the board + public boolean exist(char[][] board, String word) { + for (int row = 0; row < board.length; ++row){ + for (int col = 0; col < board[0].length; ++col){ + if (explore(board, word, row, col, 0)){ + return true; } - - // If the loop completes without returning false, returning true - return true; + } + } + return false; + } + + // DFS method to explore the board and search for the word + private boolean explore(char[][] board, String word, int row, int col, int index) { + // Check if the current cell is out of bounds + if (row < 0 || row == board.length || col < 0 || col == board[0].length){ + return false; + } + + // Checking if the current cell matches the character of the word + if (board[row][col] != word.charAt(index) || board[row][col] == '*'){ + return false; } + + // Checking if the entire word has been found + if (index == word.length() - 1){ + return true; + } + + // Temporarily marking the current cell as visited + final char temp = board[row][col]; + board[row][col] = '*'; + + // Recursively exploring adjacent cells to find the next character of the word + final boolean isFound = explore(board, word, row + 1, col, index + 1) || + explore(board, word, row - 1, col, index + 1) || + explore(board, word, row, col + 1, index + 1) || + explore(board, word, row, col - 1, index + 1); + + // Backtrack by restoring the original value of the current cell + board[row][col] = temp; + + return isFound; + } } ``` \ No newline at end of file From 7eeae2ed4e6dd29f0885e0c969e34bca0d8f38cc Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 3 Apr 2024 22:43:10 +0530 Subject: [PATCH 275/300] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 45434d5..7eaf430 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ This is my attempt to make the coding experience easier for you guys so that you # Intuition -I should utiliz Depth-First Search (DFS) to systematically explore the board, aiming to find the given word by traversing adjacent cells. +I should utilize Depth-First Search (DFS) to systematically explore the board, aiming to find the given word by traversing adjacent cells. # Approach @@ -30,7 +30,7 @@ I should utiliz Depth-First Search (DFS) to systematically explore the board, ai Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $ O(m \times n \times 4^l) $ +- Time complexity : $O(m \times n \times 4^l)$ $m$ : number of rows $n$ : number of columns From 7b720d34c043d13d82f70ed55d3ce9d9a34846ae Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 3 Apr 2024 22:43:38 +0530 Subject: [PATCH 276/300] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 7eaf430..7fec614 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,9 @@ Keep Solving.:) - Time complexity : $O(m \times n \times 4^l)$ $m$ : number of rows + $n$ : number of columns + $l$ : length of the word - Space complexity : $O(1)$ From 78923ebf2e0376e6a8e3cf44e7fbc444f404b16a Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Wed, 3 Apr 2024 22:44:05 +0530 Subject: [PATCH 277/300] Create Daily 03-04-24.md --- 2024 April/Daily 03-04-24.md | 85 ++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 2024 April/Daily 03-04-24.md diff --git a/2024 April/Daily 03-04-24.md b/2024 April/Daily 03-04-24.md new file mode 100644 index 0000000..f18a9f6 --- /dev/null +++ b/2024 April/Daily 03-04-24.md @@ -0,0 +1,85 @@ +## Today's 03-04-24 [Problem Link](https://leetcode.com/problems/word-search/description/?envType=daily-question&envId=2024-04-03) +## 79. Word Search + +# Intuition + +I should utilize Depth-First Search (DFS) to systematically explore the board, aiming to find the given word by traversing adjacent cells. + +# Approach + + +**Main Method (exist) :** +- Iterated through each cell on the board. +- Initiated DFS exploration from each cell to search for the word. +- Returned true if the word is found, otherwise false. + +**DFS Method (explore) :** +- Checked if the current cell is within bounds. +- Verified if the character at the current cell matches the word's character. +- Recursively explored adjacent cells to find the next character of the word. +- Marked visited cells to avoid revisiting and backtrack when necessary. +- If the entire word is found, returned true; otherwise, returned false. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(m \times n \times 4^l)$ + +$m$ : number of rows + +$n$ : number of columns + +$l$ : length of the word +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + // Main method to check if the word exists on the board + public boolean exist(char[][] board, String word) { + for (int row = 0; row < board.length; ++row){ + for (int col = 0; col < board[0].length; ++col){ + if (explore(board, word, row, col, 0)){ + return true; + } + } + } + return false; + } + + // DFS method to explore the board and search for the word + private boolean explore(char[][] board, String word, int row, int col, int index) { + // Check if the current cell is out of bounds + if (row < 0 || row == board.length || col < 0 || col == board[0].length){ + return false; + } + + // Checking if the current cell matches the character of the word + if (board[row][col] != word.charAt(index) || board[row][col] == '*'){ + return false; + } + + // Checking if the entire word has been found + if (index == word.length() - 1){ + return true; + } + + // Temporarily marking the current cell as visited + final char temp = board[row][col]; + board[row][col] = '*'; + + // Recursively exploring adjacent cells to find the next character of the word + final boolean isFound = explore(board, word, row + 1, col, index + 1) || + explore(board, word, row - 1, col, index + 1) || + explore(board, word, row, col + 1, index + 1) || + explore(board, word, row, col - 1, index + 1); + + // Backtrack by restoring the original value of the current cell + board[row][col] = temp; + + return isFound; + } +} +``` \ No newline at end of file From ef7554b880dc6e6338b84dd488d5d1be4f2b0265 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 4 Apr 2024 15:15:26 +0530 Subject: [PATCH 278/300] Update README.md --- README.md | 101 ++++++++++++++++++++---------------------------------- 1 file changed, 37 insertions(+), 64 deletions(-) diff --git a/README.md b/README.md index 7fec614..9c1458b 100644 --- a/README.md +++ b/README.md @@ -1,91 +1,64 @@ + +#🎉 Special Day Greetings on the 4th! 🎉 + +## Hello everyone, + Today, the 4th, holds a special significance for me, and I want to take a moment to share my gratitude with all of you who visit this GitHub repository. Your presence here makes this community vibrant and inspiring. + +Thank you for being part of this journey. Here's to today and all the wonderful possibilities it brings! + # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. ## Always here to assist you guys. -## Today's 03-04-24 [Problem Link](https://leetcode.com/problems/word-search/description/?envType=daily-question&envId=2024-04-03) -## 79. Word Search +## Today's 04-04-24 [Problem Link](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/description/?envType=daily-question&envId=2024-04-04) +## 1614. Maximum Nesting Depth of the Parentheses # Intuition -I should utilize Depth-First Search (DFS) to systematically explore the board, aiming to find the given word by traversing adjacent cells. - +- I aim to find the maximum depth of nested parentheses in a given string. # Approach + - I initialized two variables, `jawab` and `khula`, to keep track of the maximum depth and current depth, respectively. + - Iterated through each character `c` in the string `s`. + - If `c` is an opening parenthesis '(', incremented `khula` and update `jawab` to the maximum of its current value and `khula`. + - If `c` is a closing parenthesis ')', decremented `khula`. + - Finally, returned `jawab` as the maximum depth of parentheses. -**Main Method (exist) :** -- Iterated through each cell on the board. -- Initiated DFS exploration from each cell to search for the word. -- Returned true if the word is found, otherwise false. - -**DFS Method (explore) :** -- Checked if the current cell is within bounds. -- Verified if the character at the current cell matches the word's character. -- Recursively explored adjacent cells to find the next character of the word. -- Marked visited cells to avoid revisiting and backtrack when necessary. -- If the entire word is found, returned true; otherwise, returned false. - --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(m \times n \times 4^l)$ +- Time complexity : $O(n)$ -$m$ : number of rows - -$n$ : number of columns - -$l$ : length of the word +$n$ : length of the given string - Space complexity : $O(1)$ # Code ``` class Solution { - // Main method to check if the word exists on the board - public boolean exist(char[][] board, String word) { - for (int row = 0; row < board.length; ++row){ - for (int col = 0; col < board[0].length; ++col){ - if (explore(board, word, row, col, 0)){ - return true; - } - } - } - return false; - } - - // DFS method to explore the board and search for the word - private boolean explore(char[][] board, String word, int row, int col, int index) { - // Check if the current cell is out of bounds - if (row < 0 || row == board.length || col < 0 || col == board[0].length){ - return false; - } - - // Checking if the current cell matches the character of the word - if (board[row][col] != word.charAt(index) || board[row][col] == '*'){ - return false; - } - - // Checking if the entire word has been found - if (index == word.length() - 1){ - return true; - } - - // Temporarily marking the current cell as visited - final char temp = board[row][col]; - board[row][col] = '*'; - - // Recursively exploring adjacent cells to find the next character of the word - final boolean isFound = explore(board, word, row + 1, col, index + 1) || - explore(board, word, row - 1, col, index + 1) || - explore(board, word, row, col + 1, index + 1) || - explore(board, word, row, col - 1, index + 1); + public int maxDepth(String s) { - // Backtrack by restoring the original value of the current cell - board[row][col] = temp; + // Initialize variables + int jawab = 0; // Store the maximum depth found so far + int khula = 0; // Keep track of the current depth - return isFound; - } + // Iterate through each character in the string + for (final char c : s.toCharArray()){ + // If the character is an opening parenthesis + if (c == '('){ + khula++; // Incrementing the current depth + jawab = Math.max(jawab, khula); // Updating maximum depth if necessary + } + // If the character is a closing parenthesis + else if (c == ')'){ + khula--; // Decrementing the current depth + } + } + // Returning the maximum depth found + return jawab; + } } ``` \ No newline at end of file From 2abe63316ddbf0109dc80d8609bc5c64da4af85d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 4 Apr 2024 15:16:10 +0530 Subject: [PATCH 279/300] Update README.md --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 9c1458b..6fee101 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ - #🎉 Special Day Greetings on the 4th! 🎉 -## Hello everyone, - Today, the 4th, holds a special significance for me, and I want to take a moment to share my gratitude with all of you who visit this GitHub repository. Your presence here makes this community vibrant and inspiring. +##### Today, the 4th, holds a special significance for me, and I want to take a moment to share my gratitude with all of you who visit this GitHub repository. Your presence here makes this community vibrant and inspiring. Thank you for being part of this journey. Here's to today and all the wonderful possibilities it brings! From f46850d743a2e8b097b6f238966d2623e0d5fafc Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 4 Apr 2024 15:16:51 +0530 Subject: [PATCH 280/300] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6fee101..31f231f 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ##### Today, the 4th, holds a special significance for me, and I want to take a moment to share my gratitude with all of you who visit this GitHub repository. Your presence here makes this community vibrant and inspiring. -Thank you for being part of this journey. Here's to today and all the wonderful possibilities it brings! +##### Thank you for being part of this journey. Here's to today and all the wonderful possibilities it brings ! # Leetcode Daily Challenge Solutions From 1e489ed4e82fa94b415e5d7c3d92d6e79ab6d62d Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 4 Apr 2024 15:17:43 +0530 Subject: [PATCH 281/300] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 31f231f..a46dede 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ #🎉 Special Day Greetings on the 4th! 🎉 +🎉 Special Day Greetings on the 4th! 🎉 ##### Today, the 4th, holds a special significance for me, and I want to take a moment to share my gratitude with all of you who visit this GitHub repository. Your presence here makes this community vibrant and inspiring. From df1b3d505ab93a12396809a792ba27a90b2a90d3 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 4 Apr 2024 15:18:10 +0530 Subject: [PATCH 282/300] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index a46dede..afaafb3 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,4 @@ -#🎉 Special Day Greetings on the 4th! 🎉 -🎉 Special Day Greetings on the 4th! 🎉 +🎉 # Special Day Greetings on the 4th ! 🎉 ##### Today, the 4th, holds a special significance for me, and I want to take a moment to share my gratitude with all of you who visit this GitHub repository. Your presence here makes this community vibrant and inspiring. From 67c9b93a82b01a313e609fc4d0fcdfaff3c04280 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <99122134+15-Ab@users.noreply.github.com> Date: Thu, 4 Apr 2024 15:19:41 +0530 Subject: [PATCH 283/300] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index afaafb3..7f44709 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -🎉 # Special Day Greetings on the 4th ! 🎉 +# 🎉 Special Day Greetings on the 4th ! 🎉 ##### Today, the 4th, holds a special significance for me, and I want to take a moment to share my gratitude with all of you who visit this GitHub repository. Your presence here makes this community vibrant and inspiring. @@ -59,4 +59,4 @@ class Solution { return jawab; } } -``` \ No newline at end of file +``` From db46171d64e97ac4354246d3f14a21b7abd154a6 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Thu, 4 Apr 2024 15:20:43 +0530 Subject: [PATCH 284/300] Create Daily 04-04-24.md --- 2024 April/Daily 04-04-24.md | 57 ++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 2024 April/Daily 04-04-24.md diff --git a/2024 April/Daily 04-04-24.md b/2024 April/Daily 04-04-24.md new file mode 100644 index 0000000..7ac9b2e --- /dev/null +++ b/2024 April/Daily 04-04-24.md @@ -0,0 +1,57 @@ +# 🎉 Special Day Greetings on the 4th ! 🎉 + +##### Today, the 4th, holds a special significance for me, and I want to take a moment to share my gratitude with all of you who visit this GitHub repository. Your presence here makes this community vibrant and inspiring. + +##### Thank you for being part of this journey. Here's to today and all the wonderful possibilities it brings ! + + +## Today's 04-04-24 [Problem Link](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/description/?envType=daily-question&envId=2024-04-04) +## 1614. Maximum Nesting Depth of the Parentheses + +# Intuition + +- I aim to find the maximum depth of nested parentheses in a given string. +# Approach + + - I initialized two variables, `jawab` and `khula`, to keep track of the maximum depth and current depth, respectively. + - Iterated through each character `c` in the string `s`. + - If `c` is an opening parenthesis '(', incremented `khula` and update `jawab` to the maximum of its current value and `khula`. + - If `c` is a closing parenthesis ')', decremented `khula`. + - Finally, returned `jawab` as the maximum depth of parentheses. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the given string +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + public int maxDepth(String s) { + + // Initialize variables + int jawab = 0; // Store the maximum depth found so far + int khula = 0; // Keep track of the current depth + + // Iterate through each character in the string + for (final char c : s.toCharArray()){ + // If the character is an opening parenthesis + if (c == '('){ + khula++; // Incrementing the current depth + jawab = Math.max(jawab, khula); // Updating maximum depth if necessary + } + // If the character is a closing parenthesis + else if (c == ')'){ + khula--; // Decrementing the current depth + } + } + // Returning the maximum depth found + return jawab; + } +} +``` From 7f264dc1b31f4e27ee95b17d3dcb76b3b72b4971 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 5 Apr 2024 22:42:06 +0530 Subject: [PATCH 285/300] Update README.md --- README.md | 85 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 51 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 7f44709..341581e 100644 --- a/README.md +++ b/README.md @@ -1,62 +1,79 @@ -# 🎉 Special Day Greetings on the 4th ! 🎉 - -##### Today, the 4th, holds a special significance for me, and I want to take a moment to share my gratitude with all of you who visit this GitHub repository. Your presence here makes this community vibrant and inspiring. - -##### Thank you for being part of this journey. Here's to today and all the wonderful possibilities it brings ! - # Leetcode Daily Challenge Solutions This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge. ## Always here to assist you guys. -## Today's 04-04-24 [Problem Link](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/description/?envType=daily-question&envId=2024-04-04) -## 1614. Maximum Nesting Depth of the Parentheses +## Today's 05-04-24 [Problem Link](https://leetcode.com/problems/make-the-string-great/description/?envType=daily-question&envId=2024-04-05) +## 1544. Make The String Great # Intuition -- I aim to find the maximum depth of nested parentheses in a given string. +This problem requires removing pairs of adjacent characters from the input string if they have the same letter but different cases. + +To solve the problem, I can use a stack (implemented as a linked list) to keep track of the characters that have not been removed. + # Approach - - I initialized two variables, `jawab` and `khula`, to keep track of the maximum depth and current depth, respectively. - - Iterated through each character `c` in the string `s`. - - If `c` is an opening parenthesis '(', incremented `khula` and update `jawab` to the maximum of its current value and `khula`. - - If `c` is a closing parenthesis ')', decremented `khula`. - - Finally, returned `jawab` as the maximum depth of parentheses. +- I iterated through each character in the input string. +- For each character : + - If the stack is not empty and the current character, when compared with the last character in the stack, forms a pair of characters with the same letter but different cases, I removed the last character from the stack. + - If the current character and the next character (if exists) form a pair of characters with the same letter but different cases, I skipped the next character. + - Otherwise, I added the current character to the stack. +- After processing all characters, I converted the characters remaining in the stack to a string, which represents the final result. +- Finally, I returned the final result string. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) + # Complexity - Time complexity : $O(n)$ -$n$ : length of the given string -- Space complexity : $O(1)$ +$n$ : length of the input string +- Space complexity : $O(n)$ # Code ``` class Solution { - public int maxDepth(String s) { - - // Initialize variables - int jawab = 0; // Store the maximum depth found so far - int khula = 0; // Keep track of the current depth - - // Iterate through each character in the string - for (final char c : s.toCharArray()){ - // If the character is an opening parenthesis - if (c == '('){ - khula++; // Incrementing the current depth - jawab = Math.max(jawab, khula); // Updating maximum depth if necessary - } - // If the character is a closing parenthesis - else if (c == ')'){ - khula--; // Decrementing the current depth + + public String makeGood(String s) { + + // Converting the input string to a character array for easier manipulation. + char[] chArr = s.toCharArray(); + + // Initializing an empty string 'jawab' to store the final result. + String jawab=""; + + // Initializing a linked list to store characters. + LinkedList linkedList = new LinkedList<>(); + + // Looping through each character in the input string. + for(int i = 0; i < chArr.length; i++){ + // If the linked list is not empty and the absolute difference between the last character in the linked list and the current character is equal to the difference between 'a' and 'A' (which represents the difference between lowercase and uppercase characters), + // Removing the last character from the linked list and continue to the next iteration. + if(!linkedList.isEmpty() && Math.abs(linkedList.getLast() - chArr[i]) == 'a' - 'A'){ + linkedList.removeLast(); + continue; } + + // If the current character and the next character (if exists) form a pair of characters with the same letter but different cases, + // Skipping the next character and continue to the next iteration. + if(i + 1 != chArr.length && Math.abs(chArr[i + 1] - chArr[i]) == 'a' - 'A') + i++; + else + // Otherwise, adding the current character to the linked list. + linkedList.add(chArr[i]); } - // Returning the maximum depth found + + // Converting the characters remaining in the linked list to a string and append them to the 'jawab' string. + while(!linkedList.isEmpty()){ + jawab+=(linkedList.removeFirst()); + } + + // Returning the final result string. return jawab; } } -``` +``` \ No newline at end of file From 0c7977d100bf793fd487cccc9f9b37ae33e80bfa Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Fri, 5 Apr 2024 22:43:13 +0530 Subject: [PATCH 286/300] Create Daily 05-04-24.md --- 2024 April/Daily 05-04-24.md | 73 ++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 2024 April/Daily 05-04-24.md diff --git a/2024 April/Daily 05-04-24.md b/2024 April/Daily 05-04-24.md new file mode 100644 index 0000000..62ddf1e --- /dev/null +++ b/2024 April/Daily 05-04-24.md @@ -0,0 +1,73 @@ +## Today's 05-04-24 [Problem Link](https://leetcode.com/problems/make-the-string-great/description/?envType=daily-question&envId=2024-04-05) +## 1544. Make The String Great + +# Intuition + +This problem requires removing pairs of adjacent characters from the input string if they have the same letter but different cases. + +To solve the problem, I can use a stack (implemented as a linked list) to keep track of the characters that have not been removed. + +# Approach + +- I iterated through each character in the input string. +- For each character : + - If the stack is not empty and the current character, when compared with the last character in the stack, forms a pair of characters with the same letter but different cases, I removed the last character from the stack. + - If the current character and the next character (if exists) form a pair of characters with the same letter but different cases, I skipped the next character. + - Otherwise, I added the current character to the stack. +- After processing all characters, I converted the characters remaining in the stack to a string, which represents the final result. +- Finally, I returned the final result string. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the input string +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + + public String makeGood(String s) { + + // Converting the input string to a character array for easier manipulation. + char[] chArr = s.toCharArray(); + + // Initializing an empty string 'jawab' to store the final result. + String jawab=""; + + // Initializing a linked list to store characters. + LinkedList linkedList = new LinkedList<>(); + + // Looping through each character in the input string. + for(int i = 0; i < chArr.length; i++){ + // If the linked list is not empty and the absolute difference between the last character in the linked list and the current character is equal to the difference between 'a' and 'A' (which represents the difference between lowercase and uppercase characters), + // Removing the last character from the linked list and continue to the next iteration. + if(!linkedList.isEmpty() && Math.abs(linkedList.getLast() - chArr[i]) == 'a' - 'A'){ + linkedList.removeLast(); + continue; + } + + // If the current character and the next character (if exists) form a pair of characters with the same letter but different cases, + // Skipping the next character and continue to the next iteration. + if(i + 1 != chArr.length && Math.abs(chArr[i + 1] - chArr[i]) == 'a' - 'A') + i++; + else + // Otherwise, adding the current character to the linked list. + linkedList.add(chArr[i]); + } + + // Converting the characters remaining in the linked list to a string and append them to the 'jawab' string. + while(!linkedList.isEmpty()){ + jawab+=(linkedList.removeFirst()); + } + + // Returning the final result string. + return jawab; + } +} +``` \ No newline at end of file From 4aeb9d38cdd2638fd72313787ae3388e46d8152b Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 6 Apr 2024 10:59:50 +0530 Subject: [PATCH 287/300] Update README.md --- README.md | 91 +++++++++++++++++++++++++------------------------------ 1 file changed, 42 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index 341581e..3d9444c 100644 --- a/README.md +++ b/README.md @@ -4,76 +4,69 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 05-04-24 [Problem Link](https://leetcode.com/problems/make-the-string-great/description/?envType=daily-question&envId=2024-04-05) -## 1544. Make The String Great +## Today's 06*04=24 [Problem Link](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/description/?envType=daily-question&envId=2024-04-06) +## 1249. Minimum Remove to Make Valid Parentheses # Intuition -This problem requires removing pairs of adjacent characters from the input string if they have the same letter but different cases. - -To solve the problem, I can use a stack (implemented as a linked list) to keep track of the characters that have not been removed. +To address this problem, I utilize a stack to manage the indices of unpaired '(' characters. I traverse the string, marking unpaired ')' characters as '#' and popping indices from the stack for each encountered ')', effectively pairing '(' and ')'. Any remaining unpaired '(' characters are marked as '#' after processing. Finally, I remove all '#' characters to obtain the valid string. # Approach -- I iterated through each character in the input string. -- For each character : - - If the stack is not empty and the current character, when compared with the last character in the stack, forms a pair of characters with the same letter but different cases, I removed the last character from the stack. - - If the current character and the next character (if exists) form a pair of characters with the same letter but different cases, I skipped the next character. - - Otherwise, I added the current character to the stack. -- After processing all characters, I converted the characters remaining in the stack to a string, which represents the final result. -- Finally, I returned the final result string. +**Initialized** an empty stack (`parenthesesStack`) to store indices of unpaired '(' characters. + +**Traversed** the input string character by character: + - If the current character is '(', push its index onto `parenthesesStack`. + - If the current character is ')': + - If `parenthesesStack` is empty, marked the ')' character as '#'. + - If `parenthesesStack` is not empty, popped the top index to pair '(' and ')'. + +**Marked** any remaining unpaired '(' characters as '#' by popping from `parenthesesStack`. + +**Removed** all '#' characters from the modified string. + +**Returned** the resulting string, which now contains the minimum removed parentheses to make it valid. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(s)$ -$n$ : length of the input string -- Space complexity : $O(n)$ +$s$ : length of the input string +- Space complexity : $O(s)$ # Code ``` class Solution { - - public String makeGood(String s) { - - // Converting the input string to a character array for easier manipulation. - char[] chArr = s.toCharArray(); - - // Initializing an empty string 'jawab' to store the final result. - String jawab=""; - - // Initializing a linked list to store characters. - LinkedList linkedList = new LinkedList<>(); - - // Looping through each character in the input string. - for(int i = 0; i < chArr.length; i++){ - // If the linked list is not empty and the absolute difference between the last character in the linked list and the current character is equal to the difference between 'a' and 'A' (which represents the difference between lowercase and uppercase characters), - // Removing the last character from the linked list and continue to the next iteration. - if(!linkedList.isEmpty() && Math.abs(linkedList.getLast() - chArr[i]) == 'a' - 'A'){ - linkedList.removeLast(); - continue; + public String minRemoveToMakeValid(String s) { + + Deque parenthesesStack = new ArrayDeque<>(); // Stores indices of unpaired '(' characters + StringBuilder modifiedString = new StringBuilder(s); + + for (int i = 0; i < s.length(); ++i) { + if (modifiedString.charAt(i) == '(') { + parenthesesStack.push(i); // Record the unpaired '(' index. + } + else if (modifiedString.charAt(i) == ')') { + if (parenthesesStack.isEmpty()) { + modifiedString.setCharAt(i, '#'); // Mark the unpaired ')' as '#'. + } + else { + parenthesesStack.pop(); // Find a pair! + } } - - // If the current character and the next character (if exists) form a pair of characters with the same letter but different cases, - // Skipping the next character and continue to the next iteration. - if(i + 1 != chArr.length && Math.abs(chArr[i + 1] - chArr[i]) == 'a' - 'A') - i++; - else - // Otherwise, adding the current character to the linked list. - linkedList.add(chArr[i]); } - - // Converting the characters remaining in the linked list to a string and append them to the 'jawab' string. - while(!linkedList.isEmpty()){ - jawab+=(linkedList.removeFirst()); + + // Marking the unpaired '(' as '#'. + while (!parenthesesStack.isEmpty()) { + modifiedString.setCharAt(parenthesesStack.pop(), '#'); } - - // Returning the final result string. - return jawab; + + return modifiedString.toString().replaceAll("#", ""); } } + ``` \ No newline at end of file From 6200c9b99ca20eea6b16f33e5c2b1eb5bed23738 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 6 Apr 2024 11:00:52 +0530 Subject: [PATCH 288/300] Create Daily 06-04-24.md --- 2024 April/Daily 06-04-24.md | 66 ++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 2024 April/Daily 06-04-24.md diff --git a/2024 April/Daily 06-04-24.md b/2024 April/Daily 06-04-24.md new file mode 100644 index 0000000..f57c804 --- /dev/null +++ b/2024 April/Daily 06-04-24.md @@ -0,0 +1,66 @@ +## Today's 06*04=24 [Problem Link](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/description/?envType=daily-question&envId=2024-04-06) +## 1249. Minimum Remove to Make Valid Parentheses + +# Intuition + +To address this problem, I utilize a stack to manage the indices of unpaired '(' characters. I traverse the string, marking unpaired ')' characters as '#' and popping indices from the stack for each encountered ')', effectively pairing '(' and ')'. Any remaining unpaired '(' characters are marked as '#' after processing. Finally, I remove all '#' characters to obtain the valid string. + +# Approach + +**Initialized** an empty stack (`parenthesesStack`) to store indices of unpaired '(' characters. + +**Traversed** the input string character by character: + - If the current character is '(', push its index onto `parenthesesStack`. + - If the current character is ')': + - If `parenthesesStack` is empty, marked the ')' character as '#'. + - If `parenthesesStack` is not empty, popped the top index to pair '(' and ')'. + +**Marked** any remaining unpaired '(' characters as '#' by popping from `parenthesesStack`. + +**Removed** all '#' characters from the modified string. + +**Returned** the resulting string, which now contains the minimum removed parentheses to make it valid. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(s)$ + +$s$ : length of the input string +- Space complexity : $O(s)$ + + +# Code +``` +class Solution { + public String minRemoveToMakeValid(String s) { + + Deque parenthesesStack = new ArrayDeque<>(); // Stores indices of unpaired '(' characters + StringBuilder modifiedString = new StringBuilder(s); + + for (int i = 0; i < s.length(); ++i) { + if (modifiedString.charAt(i) == '(') { + parenthesesStack.push(i); // Record the unpaired '(' index. + } + else if (modifiedString.charAt(i) == ')') { + if (parenthesesStack.isEmpty()) { + modifiedString.setCharAt(i, '#'); // Mark the unpaired ')' as '#'. + } + else { + parenthesesStack.pop(); // Find a pair! + } + } + } + + // Marking the unpaired '(' as '#'. + while (!parenthesesStack.isEmpty()) { + modifiedString.setCharAt(parenthesesStack.pop(), '#'); + } + + return modifiedString.toString().replaceAll("#", ""); + } +} + +``` \ No newline at end of file From 22ae6341e98359a0e6c2f50edc3d23d010fe5e17 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 7 Apr 2024 11:06:34 +0530 Subject: [PATCH 289/300] Update README.md --- README.md | 92 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 53 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 3d9444c..34289b2 100644 --- a/README.md +++ b/README.md @@ -4,69 +4,83 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 06*04=24 [Problem Link](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/description/?envType=daily-question&envId=2024-04-06) -## 1249. Minimum Remove to Make Valid Parentheses +## Today's 07-04-24 [Problem Link](https://leetcode.com/problems/valid-parenthesis-string/description/?envType=daily-question&envId=2024-04-07) +## 678. Valid Parenthesis String # Intuition -To address this problem, I utilize a stack to manage the indices of unpaired '(' characters. I traverse the string, marking unpaired ')' characters as '#' and popping indices from the stack for each encountered ')', effectively pairing '(' and ')'. Any remaining unpaired '(' characters are marked as '#' after processing. Finally, I remove all '#' characters to obtain the valid string. +My algorithm aims to determine whether a given string containing parentheses, '*' (wildcards), and other characters forms a valid combination of parentheses. In a valid combination, each open parenthesis '(' must have a corresponding closing parenthesis ')', and wildcards '*' can be either an open parenthesis, a closing parenthesis, or an empty string. # Approach -**Initialized** an empty stack (`parenthesesStack`) to store indices of unpaired '(' characters. -**Traversed** the input string character by character: - - If the current character is '(', push its index onto `parenthesesStack`. - - If the current character is ')': - - If `parenthesesStack` is empty, marked the ')' character as '#'. - - If `parenthesesStack` is not empty, popped the top index to pair '(' and ')'. +- I iterated through each character in the string and maintain two counts : + - `minOpen`: Represents the minimum count of open parentheses that must be closed. + - `maxOpen`: Represents the maximum count of open parentheses that could be closed. -**Marked** any remaining unpaired '(' characters as '#' by popping from `parenthesesStack`. +- I traversed the string character by character: + - If I encountered an open parenthesis '(', both `minOpen` and `maxOpen` are incremented. + - If I encountered a closing parenthesis ')', I decrement `minOpen` (ensuring it doesn't go below 0) and decrement `maxOpen`. + - If I encountered a wildcard '*', I decrement `minOpen` (ensuring it doesn't go below 0) and increment `maxOpen` because it can act as an open parenthesis, closing parenthesis, or an empty string. -**Removed** all '#' characters from the modified string. +- At any point during the iteration, if the count of open parentheses (`maxOpen`) became negative, it means I have encountered more closing parentheses than open ones, which makes the string invalid, so I return `false`. -**Returned** the resulting string, which now contains the minimum removed parentheses to make it valid. +- Finally, I checked if all open parentheses are closed by verifying if `minOpen` is back to 0. If it is, then the string is valid; otherwise, it's invalid. + +- My algorithm returned `true` if the string is valid and `false` otherwise. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(s)$ +- Time complexity : $O(n)$ -$s$ : length of the input string -- Space complexity : $O(s)$ +$n$ : length of the input string +- Space complexity : $O(1)$ # Code ``` class Solution { - public String minRemoveToMakeValid(String s) { - - Deque parenthesesStack = new ArrayDeque<>(); // Stores indices of unpaired '(' characters - StringBuilder modifiedString = new StringBuilder(s); - - for (int i = 0; i < s.length(); ++i) { - if (modifiedString.charAt(i) == '(') { - parenthesesStack.push(i); // Record the unpaired '(' index. - } - else if (modifiedString.charAt(i) == ')') { - if (parenthesesStack.isEmpty()) { - modifiedString.setCharAt(i, '#'); // Mark the unpaired ')' as '#'. - } - else { - parenthesesStack.pop(); // Find a pair! - } - } + public boolean checkValidString(String str) { + + // Initializing the minimum and maximum counts of open parentheses + int minOpen = 0; // minimum count of open parentheses + int maxOpen = 0; // maximum count of open parentheses + + // Iterating through each character in the string + for (char ch : str.toCharArray()) { + // Handling different cases based on the character + switch (ch) { + + case '(': + // Incrementing both minimum and maximum counts for open parentheses + minOpen++; + maxOpen++; + break; + case ')': + // Decreasing the minimum count, but ensure it doesn't go negative + minOpen = Math.max(0, --minOpen); + // Decreasing the maximum count for open parentheses + maxOpen--; + break; + case '*': + // Decreasing the minimum count, but ensure it doesn't go negative + minOpen = Math.max(0, --minOpen); + // Incrementing the maximum count for open parentheses + maxOpen++; + break; } - - // Marking the unpaired '(' as '#'. - while (!parenthesesStack.isEmpty()) { - modifiedString.setCharAt(parenthesesStack.pop(), '#'); + + // If the maximum count of open parentheses becomes negative, return false + if (maxOpen < 0){ + return false; } - - return modifiedString.toString().replaceAll("#", ""); } -} + // Checking if all open parentheses are closed + return minOpen == 0; + } +} ``` \ No newline at end of file From bc12abe32459a3b362c8d0191419c911bb683998 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 7 Apr 2024 11:07:47 +0530 Subject: [PATCH 290/300] Create Daily 07-04-24.md --- 2024 April/Daily 07-04-24.md | 80 ++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 2024 April/Daily 07-04-24.md diff --git a/2024 April/Daily 07-04-24.md b/2024 April/Daily 07-04-24.md new file mode 100644 index 0000000..7706b2d --- /dev/null +++ b/2024 April/Daily 07-04-24.md @@ -0,0 +1,80 @@ +## Today's 07-04-24 [Problem Link](https://leetcode.com/problems/valid-parenthesis-string/description/?envType=daily-question&envId=2024-04-07) +## 678. Valid Parenthesis String + +# Intuition + +My algorithm aims to determine whether a given string containing parentheses, '*' (wildcards), and other characters forms a valid combination of parentheses. In a valid combination, each open parenthesis '(' must have a corresponding closing parenthesis ')', and wildcards '*' can be either an open parenthesis, a closing parenthesis, or an empty string. + +# Approach + + +- I iterated through each character in the string and maintain two counts : + - `minOpen`: Represents the minimum count of open parentheses that must be closed. + - `maxOpen`: Represents the maximum count of open parentheses that could be closed. + +- I traversed the string character by character: + - If I encountered an open parenthesis '(', both `minOpen` and `maxOpen` are incremented. + - If I encountered a closing parenthesis ')', I decrement `minOpen` (ensuring it doesn't go below 0) and decrement `maxOpen`. + - If I encountered a wildcard '*', I decrement `minOpen` (ensuring it doesn't go below 0) and increment `maxOpen` because it can act as an open parenthesis, closing parenthesis, or an empty string. + +- At any point during the iteration, if the count of open parentheses (`maxOpen`) became negative, it means I have encountered more closing parentheses than open ones, which makes the string invalid, so I return `false`. + +- Finally, I checked if all open parentheses are closed by verifying if `minOpen` is back to 0. If it is, then the string is valid; otherwise, it's invalid. + +- My algorithm returned `true` if the string is valid and `false` otherwise. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(n)$ + +$n$ : length of the input string +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + public boolean checkValidString(String str) { + + // Initializing the minimum and maximum counts of open parentheses + int minOpen = 0; // minimum count of open parentheses + int maxOpen = 0; // maximum count of open parentheses + + // Iterating through each character in the string + for (char ch : str.toCharArray()) { + // Handling different cases based on the character + switch (ch) { + + case '(': + // Incrementing both minimum and maximum counts for open parentheses + minOpen++; + maxOpen++; + break; + case ')': + // Decreasing the minimum count, but ensure it doesn't go negative + minOpen = Math.max(0, --minOpen); + // Decreasing the maximum count for open parentheses + maxOpen--; + break; + case '*': + // Decreasing the minimum count, but ensure it doesn't go negative + minOpen = Math.max(0, --minOpen); + // Incrementing the maximum count for open parentheses + maxOpen++; + break; + } + + // If the maximum count of open parentheses becomes negative, return false + if (maxOpen < 0){ + return false; + } + } + + // Checking if all open parentheses are closed + return minOpen == 0; + } +} +``` \ No newline at end of file From 48550add1b510b55299ef15add5c00713d806542 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 8 Apr 2024 20:27:36 +0530 Subject: [PATCH 291/300] Update README.md --- README.md | 109 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 57 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 34289b2..6d70002 100644 --- a/README.md +++ b/README.md @@ -4,83 +4,88 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 07-04-24 [Problem Link](https://leetcode.com/problems/valid-parenthesis-string/description/?envType=daily-question&envId=2024-04-07) -## 678. Valid Parenthesis String +## Today's 08-04-24 [Problem Link](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/description/?envType=daily-question&envId=2024-04-08) +## 1700. Number of Students Unable to Eat Lunch # Intuition -My algorithm aims to determine whether a given string containing parentheses, '*' (wildcards), and other characters forms a valid combination of parentheses. In a valid combination, each open parenthesis '(' must have a corresponding closing parenthesis ')', and wildcards '*' can be either an open parenthesis, a closing parenthesis, or an empty string. +The task is to count the number of students who will be unable to get a sandwich. There are two types of sandwiches, circle, and square, represented by the integers 0 and 1 respectively. Students are also represented by integers, where 0 indicates a preference for circle sandwiches and 1 indicates a preference for square sandwiches. # Approach -- I iterated through each character in the string and maintain two counts : - - `minOpen`: Represents the minimum count of open parentheses that must be closed. - - `maxOpen`: Represents the maximum count of open parentheses that could be closed. +**Counting Students** : + - I iterated through the `students` array and count the number of students preferring each type of sandwich. + - Maintained separate counters for circle and square sandwiches (`circleStudentCount` and `squareStudentCount`). -- I traversed the string character by character: - - If I encountered an open parenthesis '(', both `minOpen` and `maxOpen` are incremented. - - If I encountered a closing parenthesis ')', I decrement `minOpen` (ensuring it doesn't go below 0) and decrement `maxOpen`. - - If I encountered a wildcard '*', I decrement `minOpen` (ensuring it doesn't go below 0) and increment `maxOpen` because it can act as an open parenthesis, closing parenthesis, or an empty string. +**Serving Sandwiches** : + - Iterated through the `sandwiches` array. + - For each sandwich : + - If it's a circle sandwich (`sandwich == 0`), check if there are remaining students preferring circle sandwiches (`circleStudentCount > 0`). + - If yes, serve the sandwich to a circle student by decrementing `circleStudentCount`. + - If no circle students left, return the count of remaining square students (`squareStudentCount`). + - If it's a square sandwich (`sandwich == 1`), check if there are remaining students preferring square sandwiches (`squareStudentCount > 0`). + - If yes, serve the sandwich to a square student by decrementing `squareStudentCount`. + - If no square students left, returned the count of remaining circle students (`circleStudentCount`). -- At any point during the iteration, if the count of open parentheses (`maxOpen`) became negative, it means I have encountered more closing parentheses than open ones, which makes the string invalid, so I return `false`. - -- Finally, I checked if all open parentheses are closed by verifying if `minOpen` is back to 0. If it is, then the string is valid; otherwise, it's invalid. - -- My algorithm returned `true` if the string is valid and `false` otherwise. +**Return** : + - If all sandwiches are served successfully, returned 0, indicating no students are left without sandwiches. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(n + m)$ -$n$ : length of the input string +$n$ : number of students +$m$ : number of sandwiches - Space complexity : $O(1)$ # Code ``` class Solution { - public boolean checkValidString(String str) { - - // Initializing the minimum and maximum counts of open parentheses - int minOpen = 0; // minimum count of open parentheses - int maxOpen = 0; // maximum count of open parentheses + public int countStudents(int[] students, int[] sandwiches) { + + // Count of students preferring circle sandwiches + int circleStudentCount = 0; + // Count of students preferring square sandwiches + int squareStudentCount = 0; - // Iterating through each character in the string - for (char ch : str.toCharArray()) { - // Handling different cases based on the character - switch (ch) { - - case '(': - // Incrementing both minimum and maximum counts for open parentheses - minOpen++; - maxOpen++; - break; - case ')': - // Decreasing the minimum count, but ensure it doesn't go negative - minOpen = Math.max(0, --minOpen); - // Decreasing the maximum count for open parentheses - maxOpen--; - break; - case '*': - // Decreasing the minimum count, but ensure it doesn't go negative - minOpen = Math.max(0, --minOpen); - // Incrementing the maximum count for open parentheses - maxOpen++; - break; + // Counting the number of students preferring each type of sandwich + for(int student : students) { + if(student == 0) { + circleStudentCount++; + } + else { + squareStudentCount++; + } } - - // If the maximum count of open parentheses becomes negative, return false - if (maxOpen < 0){ - return false; + + // Iterating through sandwiches and serving them to students + for(int sandwich : sandwiches) { + + // If the sandwich type is circle and there are no more students preferring circle sandwiches, return the count of students preferring square sandwiches + if(sandwich == 0 && circleStudentCount == 0) { + return squareStudentCount; + } + // If the sandwich type is square and there are no more students preferring square sandwiches, return the count of students preferring circle sandwiches + if(sandwich == 1 && squareStudentCount == 0) { + return circleStudentCount; + } + // If the sandwich type is circle, serve it to a circle student and decrease the count of circle students + if(sandwich == 0) { + circleStudentCount--; + } + // If the sandwich type is square, serve it to a square student and decrease the count of square students + else { + squareStudentCount--; + } } + // All sandwiches have been served without any issues + return 0; } - - // Checking if all open parentheses are closed - return minOpen == 0; - } } + ``` \ No newline at end of file From da9900f4061bc98ff9f43c42a8bc4e04815176d0 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Mon, 8 Apr 2024 20:28:01 +0530 Subject: [PATCH 292/300] Create Daily 08-04-24.md --- 2024 April/Daily 08-04-24.md | 85 ++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 2024 April/Daily 08-04-24.md diff --git a/2024 April/Daily 08-04-24.md b/2024 April/Daily 08-04-24.md new file mode 100644 index 0000000..7f583e9 --- /dev/null +++ b/2024 April/Daily 08-04-24.md @@ -0,0 +1,85 @@ +## Today's 08-04-24 [Problem Link](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/description/?envType=daily-question&envId=2024-04-08) +## 1700. Number of Students Unable to Eat Lunch + +# Intuition + +The task is to count the number of students who will be unable to get a sandwich. There are two types of sandwiches, circle, and square, represented by the integers 0 and 1 respectively. Students are also represented by integers, where 0 indicates a preference for circle sandwiches and 1 indicates a preference for square sandwiches. + +# Approach + + +**Counting Students** : + - I iterated through the `students` array and count the number of students preferring each type of sandwich. + - Maintained separate counters for circle and square sandwiches (`circleStudentCount` and `squareStudentCount`). + +**Serving Sandwiches** : + - Iterated through the `sandwiches` array. + - For each sandwich : + - If it's a circle sandwich (`sandwich == 0`), check if there are remaining students preferring circle sandwiches (`circleStudentCount > 0`). + - If yes, serve the sandwich to a circle student by decrementing `circleStudentCount`. + - If no circle students left, return the count of remaining square students (`squareStudentCount`). + - If it's a square sandwich (`sandwich == 1`), check if there are remaining students preferring square sandwiches (`squareStudentCount > 0`). + - If yes, serve the sandwich to a square student by decrementing `squareStudentCount`. + - If no square students left, returned the count of remaining circle students (`circleStudentCount`). + +**Return** : + - If all sandwiches are served successfully, returned 0, indicating no students are left without sandwiches. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(n + m)$ + +$n$ : number of students +$m$ : number of sandwiches +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + public int countStudents(int[] students, int[] sandwiches) { + + // Count of students preferring circle sandwiches + int circleStudentCount = 0; + // Count of students preferring square sandwiches + int squareStudentCount = 0; + + // Counting the number of students preferring each type of sandwich + for(int student : students) { + if(student == 0) { + circleStudentCount++; + } + else { + squareStudentCount++; + } + } + + // Iterating through sandwiches and serving them to students + for(int sandwich : sandwiches) { + + // If the sandwich type is circle and there are no more students preferring circle sandwiches, return the count of students preferring square sandwiches + if(sandwich == 0 && circleStudentCount == 0) { + return squareStudentCount; + } + // If the sandwich type is square and there are no more students preferring square sandwiches, return the count of students preferring circle sandwiches + if(sandwich == 1 && squareStudentCount == 0) { + return circleStudentCount; + } + // If the sandwich type is circle, serve it to a circle student and decrease the count of circle students + if(sandwich == 0) { + circleStudentCount--; + } + // If the sandwich type is square, serve it to a square student and decrease the count of square students + else { + squareStudentCount--; + } + } + // All sandwiches have been served without any issues + return 0; + } +} + +``` \ No newline at end of file From 979dfe590ebd63dd0c71ceb0296c0856ab66af44 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 9 Apr 2024 23:34:08 +0530 Subject: [PATCH 293/300] Update README.md --- README.md | 90 ++++++++++++++++++++----------------------------------- 1 file changed, 32 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 6d70002..82ee828 100644 --- a/README.md +++ b/README.md @@ -4,88 +4,62 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 08-04-24 [Problem Link](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/description/?envType=daily-question&envId=2024-04-08) -## 1700. Number of Students Unable to Eat Lunch +## Today's 09-04-24 [Problem Link](https://leetcode.com/problems/time-needed-to-buy-tickets/description/?envType=daily-question&envId=2024-04-09) +## 2073. Time Needed to Buy Tickets # Intuition -The task is to count the number of students who will be unable to get a sandwich. There are two types of sandwiches, circle, and square, represented by the integers 0 and 1 respectively. Students are also represented by integers, where 0 indicates a preference for circle sandwiches and 1 indicates a preference for square sandwiches. +Given a queue of ticket prices and a special position \( k \), the problem asks to calculate the total time required to buy tickets. If a person is at or before position \( k \), they buy tickets at the \( k \)-th price; otherwise, they buy at \( k \)-th price minus 1. # Approach - -**Counting Students** : - - I iterated through the `students` array and count the number of students preferring each type of sandwich. - - Maintained separate counters for circle and square sandwiches (`circleStudentCount` and `squareStudentCount`). - -**Serving Sandwiches** : - - Iterated through the `sandwiches` array. - - For each sandwich : - - If it's a circle sandwich (`sandwich == 0`), check if there are remaining students preferring circle sandwiches (`circleStudentCount > 0`). - - If yes, serve the sandwich to a circle student by decrementing `circleStudentCount`. - - If no circle students left, return the count of remaining square students (`squareStudentCount`). - - If it's a square sandwich (`sandwich == 1`), check if there are remaining students preferring square sandwiches (`squareStudentCount > 0`). - - If yes, serve the sandwich to a square student by decrementing `squareStudentCount`. - - If no square students left, returned the count of remaining circle students (`circleStudentCount`). - -**Return** : - - If all sandwiches are served successfully, returned 0, indicating no students are left without sandwiches. +- I initialized total time to 0. +- Iterated through the queue: + - For positions before or at \( k \), buy tickets at \( k \)-th price. + - For positions after \( k \), buy tickets at \( k \)-th price minus 1. +- Accumulated the time taken for each purchase. +- Returned the total time. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(n + m)$ +- Time complexity : $O(n)$ -$n$ : number of students -$m$ : number of sandwiches +$n$ : number of tickets - Space complexity : $O(1)$ # Code ``` class Solution { - public int countStudents(int[] students, int[] sandwiches) { - - // Count of students preferring circle sandwiches - int circleStudentCount = 0; - // Count of students preferring square sandwiches - int squareStudentCount = 0; - // Counting the number of students preferring each type of sandwich - for(int student : students) { - if(student == 0) { - circleStudentCount++; - } - else { - squareStudentCount++; + // Method to calculate the total time required to buy tickets + public int timeRequiredToBuy(int[] tickets, int k) { + // Variable to store the total time + int totalTime = 0; + + // Looping through each ticket price + for (int i = 0; i < tickets.length; i++) { + + // If the person is at or before the k-th position in the queue + if (i <= k) { + + // Adding the minimum of the ticket price at the current position and the price at the k-th position to the total time + totalTime += Math.min(tickets[i], tickets[k]); } - } - // Iterating through sandwiches and serving them to students - for(int sandwich : sandwiches) { - - // If the sandwich type is circle and there are no more students preferring circle sandwiches, return the count of students preferring square sandwiches - if(sandwich == 0 && circleStudentCount == 0) { - return squareStudentCount; - } - // If the sandwich type is square and there are no more students preferring square sandwiches, return the count of students preferring circle sandwiches - if(sandwich == 1 && squareStudentCount == 0) { - return circleStudentCount; - } - // If the sandwich type is circle, serve it to a circle student and decrease the count of circle students - if(sandwich == 0) { - circleStudentCount--; - } - // If the sandwich type is square, serve it to a square student and decrease the count of square students - else { - squareStudentCount--; + // If the person is after the k-th position in the queue + if (i > k) { + + // Adding the minimum of the ticket price at the current position and the price at the k-th position minus 1 to the total time + totalTime += Math.min(tickets[i], tickets[k] - 1); } } - // All sandwiches have been served without any issues - return 0; + + // Returning the total time required to buy tickets + return totalTime; } } - ``` \ No newline at end of file From 29e8fd37ed68388bf13b6cedfb9dd5f95512e440 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Tue, 9 Apr 2024 23:34:56 +0530 Subject: [PATCH 294/300] Create Daily 09-04-24.md --- 2024 April/Daily 09-04-24.md | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 2024 April/Daily 09-04-24.md diff --git a/2024 April/Daily 09-04-24.md b/2024 April/Daily 09-04-24.md new file mode 100644 index 0000000..93db623 --- /dev/null +++ b/2024 April/Daily 09-04-24.md @@ -0,0 +1,61 @@ +# Leetcode Daily Challenge Solutions + +## Today's 09-04-24 [Problem Link](https://leetcode.com/problems/time-needed-to-buy-tickets/description/?envType=daily-question&envId=2024-04-09) +## 2073. Time Needed to Buy Tickets + +# Intuition + +Given a queue of ticket prices and a special position \( k \), the problem asks to calculate the total time required to buy tickets. If a person is at or before position \( k \), they buy tickets at the \( k \)-th price; otherwise, they buy at \( k \)-th price minus 1. + +# Approach + +- I initialized total time to 0. +- Iterated through the queue: + - For positions before or at \( k \), buy tickets at \( k \)-th price. + - For positions after \( k \), buy tickets at \( k \)-th price minus 1. +- Accumulated the time taken for each purchase. +- Returned the total time. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(n)$ + +$n$ : number of tickets +- Space complexity : $O(1)$ + + +# Code +``` +class Solution { + + // Method to calculate the total time required to buy tickets + public int timeRequiredToBuy(int[] tickets, int k) { + // Variable to store the total time + int totalTime = 0; + + // Looping through each ticket price + for (int i = 0; i < tickets.length; i++) { + + // If the person is at or before the k-th position in the queue + if (i <= k) { + + // Adding the minimum of the ticket price at the current position and the price at the k-th position to the total time + totalTime += Math.min(tickets[i], tickets[k]); + } + + // If the person is after the k-th position in the queue + if (i > k) { + + // Adding the minimum of the ticket price at the current position and the price at the k-th position minus 1 to the total time + totalTime += Math.min(tickets[i], tickets[k] - 1); + } + } + + // Returning the total time required to buy tickets + return totalTime; + } +} +``` \ No newline at end of file From 922bf9bdf2ff2caaa798aad811b3ae8f2e4eca7b Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 13 Apr 2024 10:21:33 +0530 Subject: [PATCH 295/300] Update README.md --- README.md | 90 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 49 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 82ee828..f0653ea 100644 --- a/README.md +++ b/README.md @@ -4,62 +4,70 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 09-04-24 [Problem Link](https://leetcode.com/problems/time-needed-to-buy-tickets/description/?envType=daily-question&envId=2024-04-09) -## 2073. Time Needed to Buy Tickets +## Today's 13-04-24 [Problem Link](https://leetcode.com/problems/maximal-rectangle/description/?envType=daily-question&envId=2024-04-13) +## 85. Maximal Rectangle # Intuition -Given a queue of ticket prices and a special position \( k \), the problem asks to calculate the total time required to buy tickets. If a person is at or before position \( k \), they buy tickets at the \( k \)-th price; otherwise, they buy at \( k \)-th price minus 1. +The problem involves finding the maximal rectangle containing only 1s in a binary matrix. To solve this problem efficiently, I can utilize the concept of histograms. For each row in the matrix, I can treat it as the base of a histogram and calculate the height of bars in the histogram based on the consecutive 1s in that row. Then, I can apply the largest rectangle in histogram algorithm to find the maximal rectangle for each row. Finally, I return the maximum area among all rows as the result. # Approach -- I initialized total time to 0. -- Iterated through the queue: - - For positions before or at \( k \), buy tickets at \( k \)-th price. - - For positions after \( k \), buy tickets at \( k \)-th price minus 1. -- Accumulated the time taken for each purchase. -- Returned the total time. + +- I initialized a variable to store the maximal rectangle area. +- Iterate through each row in the matrix: + - Update the histogram of heights for each row. Treat 1s as bars and consecutive 1s as increasing heights in the histogram. + - Calculate the maximal rectangle area using the largest rectangle in histogram algorithm for the current histogram. + - Update the maximal rectangle area if the current area is greater. +- Return the maximal rectangle area as the result. + +##### Largest Rectangle in Histogram Algorithm : +- I nitialized a stack to store the indices of histogram bars. +- Iterated through each bar in the histogram: + - If the stack is empty or the current bar's height is greater than or equal to the height of the bar at the top of the stack, push the index of the current bar onto the stack. + - If the current bar's height is less than the height of the bar at the top of the stack, keep popping bars from the stack until the stack is empty or the height of the bar at the top of the stack is less than the current bar's height. For each popped bar, calculate its area using the popped height as the height of the rectangle and the difference between the current index and the index of the bar at the top of the stack as the width of the rectangle. Update the maximal rectangle area if the calculated area is greater. +- After iterating through all bars, if there are bars left in the stack, repeat step 2 for each remaining bar. +- Returned the maximal rectangle area calculated. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(n)$ +- Time complexity : $O(m*n)$ -$n$ : number of tickets -- Space complexity : $O(1)$ +$m$ : number of rows +$n$ : number of columns +- Space complexity : $O(n)$ # Code ``` -class Solution { - - // Method to calculate the total time required to buy tickets - public int timeRequiredToBuy(int[] tickets, int k) { - // Variable to store the total time - int totalTime = 0; - - // Looping through each ticket price - for (int i = 0; i < tickets.length; i++) { - - // If the person is at or before the k-th position in the queue - if (i <= k) { - - // Adding the minimum of the ticket price at the current position and the price at the k-th position to the total time - totalTime += Math.min(tickets[i], tickets[k]); - } - - // If the person is after the k-th position in the queue - if (i > k) { - - // Adding the minimum of the ticket price at the current position and the price at the k-th position minus 1 to the total time - totalTime += Math.min(tickets[i], tickets[k] - 1); - } - } - - // Returning the total time required to buy tickets - return totalTime; - } -} +class Solution: + def maximalRectangle(self, matrix: List[List[str]]) -> int: + if not matrix: + return 0 + + ans = 0 + hist = [0] * len(matrix[0]) + + def largestRectangleArea(heights: List[int]) -> int: + ans = 0 + stack = [] + + for i in range(len(heights) + 1): + while stack and (i == len(heights) or heights[stack[-1]] > heights[i]): + h = heights[stack.pop()] + w = i - stack[-1] - 1 if stack else i + ans = max(ans, h * w) + stack.append(i) + + return ans + + for row in matrix: + for i, num in enumerate(row): + hist[i] = 0 if num == '0' else hist[i] + 1 + ans = max(ans, largestRectangleArea(hist)) + + return ans ``` \ No newline at end of file From 7e9a961eb2e0580305762587407bca092a8cd4b0 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 13 Apr 2024 10:24:08 +0530 Subject: [PATCH 296/300] Update README.md --- README.md | 81 ++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 54 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index f0653ea..da16a91 100644 --- a/README.md +++ b/README.md @@ -43,31 +43,58 @@ $n$ : number of columns # Code ``` -class Solution: - def maximalRectangle(self, matrix: List[List[str]]) -> int: - if not matrix: - return 0 - - ans = 0 - hist = [0] * len(matrix[0]) - - def largestRectangleArea(heights: List[int]) -> int: - ans = 0 - stack = [] - - for i in range(len(heights) + 1): - while stack and (i == len(heights) or heights[stack[-1]] > heights[i]): - h = heights[stack.pop()] - w = i - stack[-1] - 1 if stack else i - ans = max(ans, h * w) - stack.append(i) - - return ans - - for row in matrix: - for i, num in enumerate(row): - hist[i] = 0 if num == '0' else hist[i] + 1 - ans = max(ans, largestRectangleArea(hist)) - - return ans +class Solution { + + // Method to find the maximal rectangle area in a given matrix + public int maximalRectangle(char[][] matrix) { + + // Check if the matrix is null or empty + if (matrix == null || matrix.length == 0) { + return 0; + } + + // Initialize the maximal rectangle area + int maxArea = 0; + // Initialize an array to store the histogram of heights + int[] heights = new int[matrix[0].length]; + + // Iterate through each row in the matrix + for (char[] row : matrix) { + // Update the histogram for each row + for (int i = 0; i < row.length; i++) { + heights[i] = row[i] == '0' ? 0 : heights[i] + 1; + } + // Update the maximal rectangle area + maxArea = Math.max(maxArea, calculateMaxArea(heights)); + } + + return maxArea; + } + + // Method to calculate the maximal rectangle area using histogram + private int calculateMaxArea(int[] heights) { + + // Initialize the maximal rectangle area + int maxArea = 0; + // Initialize a stack to store the indices of heights + Stack stack = new Stack<>(); + + // Iterate through each height and calculate the maximal rectangle area + for (int i = 0; i <= heights.length; i++) { + // Check if the stack is not empty and the current height is less than the height at the top of the stack + while (!stack.isEmpty() && (i == heights.length || heights[stack.peek()] > heights[i])) { + // Get the height at the top of the stack + int currentHeight = heights[stack.pop()]; + // Calculate the width of the rectangle + int width = stack.isEmpty() ? i : i - stack.peek() - 1; + // Update the maximal rectangle area + maxArea = Math.max(maxArea, currentHeight * width); + } + // Push the index of the current height onto the stack + stack.push(i); + } + + return maxArea; + } +} ``` \ No newline at end of file From 2662aaac06b2e7554c9cdc9cc5223e83bafa7d01 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 13 Apr 2024 10:24:36 +0530 Subject: [PATCH 297/300] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index da16a91..db1be18 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ Keep Solving.:) - Time complexity : $O(m*n)$ $m$ : number of rows + $n$ : number of columns - Space complexity : $O(n)$ From 1cd38a7cd865d76259ffb489e89f6485ffce9bc2 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sat, 13 Apr 2024 10:25:02 +0530 Subject: [PATCH 298/300] Create Daily 13-04-24.md --- 2024 April/Daily 13-04-24.md | 95 ++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 2024 April/Daily 13-04-24.md diff --git a/2024 April/Daily 13-04-24.md b/2024 April/Daily 13-04-24.md new file mode 100644 index 0000000..0415ecc --- /dev/null +++ b/2024 April/Daily 13-04-24.md @@ -0,0 +1,95 @@ +## Today's 13-04-24 [Problem Link](https://leetcode.com/problems/maximal-rectangle/description/?envType=daily-question&envId=2024-04-13) +## 85. Maximal Rectangle + +# Intuition + +The problem involves finding the maximal rectangle containing only 1s in a binary matrix. To solve this problem efficiently, I can utilize the concept of histograms. For each row in the matrix, I can treat it as the base of a histogram and calculate the height of bars in the histogram based on the consecutive 1s in that row. Then, I can apply the largest rectangle in histogram algorithm to find the maximal rectangle for each row. Finally, I return the maximum area among all rows as the result. + +# Approach + + +- I initialized a variable to store the maximal rectangle area. +- Iterate through each row in the matrix: + - Update the histogram of heights for each row. Treat 1s as bars and consecutive 1s as increasing heights in the histogram. + - Calculate the maximal rectangle area using the largest rectangle in histogram algorithm for the current histogram. + - Update the maximal rectangle area if the current area is greater. +- Return the maximal rectangle area as the result. + +##### Largest Rectangle in Histogram Algorithm : +- I nitialized a stack to store the indices of histogram bars. +- Iterated through each bar in the histogram: + - If the stack is empty or the current bar's height is greater than or equal to the height of the bar at the top of the stack, push the index of the current bar onto the stack. + - If the current bar's height is less than the height of the bar at the top of the stack, keep popping bars from the stack until the stack is empty or the height of the bar at the top of the stack is less than the current bar's height. For each popped bar, calculate its area using the popped height as the height of the rectangle and the difference between the current index and the index of the bar at the top of the stack as the width of the rectangle. Update the maximal rectangle area if the calculated area is greater. +- After iterating through all bars, if there are bars left in the stack, repeat step 2 for each remaining bar. +- Returned the maximal rectangle area calculated. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(m*n)$ + +$m$ : number of rows + +$n$ : number of columns +- Space complexity : $O(n)$ + + +# Code +``` +class Solution { + + // Method to find the maximal rectangle area in a given matrix + public int maximalRectangle(char[][] matrix) { + + // Check if the matrix is null or empty + if (matrix == null || matrix.length == 0) { + return 0; + } + + // Initialize the maximal rectangle area + int maxArea = 0; + // Initialize an array to store the histogram of heights + int[] heights = new int[matrix[0].length]; + + // Iterate through each row in the matrix + for (char[] row : matrix) { + // Update the histogram for each row + for (int i = 0; i < row.length; i++) { + heights[i] = row[i] == '0' ? 0 : heights[i] + 1; + } + // Update the maximal rectangle area + maxArea = Math.max(maxArea, calculateMaxArea(heights)); + } + + return maxArea; + } + + // Method to calculate the maximal rectangle area using histogram + private int calculateMaxArea(int[] heights) { + + // Initialize the maximal rectangle area + int maxArea = 0; + // Initialize a stack to store the indices of heights + Stack stack = new Stack<>(); + + // Iterate through each height and calculate the maximal rectangle area + for (int i = 0; i <= heights.length; i++) { + // Check if the stack is not empty and the current height is less than the height at the top of the stack + while (!stack.isEmpty() && (i == heights.length || heights[stack.peek()] > heights[i])) { + // Get the height at the top of the stack + int currentHeight = heights[stack.pop()]; + // Calculate the width of the rectangle + int width = stack.isEmpty() ? i : i - stack.peek() - 1; + // Update the maximal rectangle area + maxArea = Math.max(maxArea, currentHeight * width); + } + // Push the index of the current height onto the stack + stack.push(i); + } + + return maxArea; + } +} +``` \ No newline at end of file From 0ab480404ebde750b6912b82137f91f4385f7368 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 14 Apr 2024 10:46:31 +0530 Subject: [PATCH 299/300] Update README.md --- README.md | 104 ++++++++++++++++++------------------------------------ 1 file changed, 35 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index db1be18..a7c1fd8 100644 --- a/README.md +++ b/README.md @@ -4,98 +4,64 @@ This is my attempt to make the coding experience easier for you guys so that you ## Always here to assist you guys. -## Today's 13-04-24 [Problem Link](https://leetcode.com/problems/maximal-rectangle/description/?envType=daily-question&envId=2024-04-13) -## 85. Maximal Rectangle +## Today's 14-04-24 [Problem Link](https://leetcode.com/problems/sum-of-left-leaves/description/?envType=daily-question&envId=2024-04-14) +## 404. Sum of Left Leaves # Intuition -The problem involves finding the maximal rectangle containing only 1s in a binary matrix. To solve this problem efficiently, I can utilize the concept of histograms. For each row in the matrix, I can treat it as the base of a histogram and calculate the height of bars in the histogram based on the consecutive 1s in that row. Then, I can apply the largest rectangle in histogram algorithm to find the maximal rectangle for each row. Finally, I return the maximum area among all rows as the result. - +The goal is to find the sum of all left leaves in a binary tree. A left leaf is a leaf node that is the left child of its parent. # Approach -- I initialized a variable to store the maximal rectangle area. -- Iterate through each row in the matrix: - - Update the histogram of heights for each row. Treat 1s as bars and consecutive 1s as increasing heights in the histogram. - - Calculate the maximal rectangle area using the largest rectangle in histogram algorithm for the current histogram. - - Update the maximal rectangle area if the current area is greater. -- Return the maximal rectangle area as the result. - -##### Largest Rectangle in Histogram Algorithm : -- I nitialized a stack to store the indices of histogram bars. -- Iterated through each bar in the histogram: - - If the stack is empty or the current bar's height is greater than or equal to the height of the bar at the top of the stack, push the index of the current bar onto the stack. - - If the current bar's height is less than the height of the bar at the top of the stack, keep popping bars from the stack until the stack is empty or the height of the bar at the top of the stack is less than the current bar's height. For each popped bar, calculate its area using the popped height as the height of the rectangle and the difference between the current index and the index of the bar at the top of the stack as the width of the rectangle. Update the maximal rectangle area if the calculated area is greater. -- After iterating through all bars, if there are bars left in the stack, repeat step 2 for each remaining bar. -- Returned the maximal rectangle area calculated. +- I started with the root node. +- If the current node is null, returned 0. +- Check if the left child of the current node exists and if it is a leaf node (i.e., it has no left or right children). +- If the left child is a leaf node, add its value to the result and continue recursively with the right child. +- If the left child is not a leaf node, recursively call the function on both the left and right children. +- Returned the sum obtained from the left subtree and the right subtree. --- Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:) # Complexity -- Time complexity : $O(m*n)$ +- Time complexity : $O(n)$ -$m$ : number of rows - -$n$ : number of columns +$n$ : number of nodes in the binary tree - Space complexity : $O(n)$ # Code ``` -class Solution { - - // Method to find the maximal rectangle area in a given matrix - public int maximalRectangle(char[][] matrix) { +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ - // Check if the matrix is null or empty - if (matrix == null || matrix.length == 0) { +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) { return 0; } - - // Initialize the maximal rectangle area - int maxArea = 0; - // Initialize an array to store the histogram of heights - int[] heights = new int[matrix[0].length]; - - // Iterate through each row in the matrix - for (char[] row : matrix) { - // Update the histogram for each row - for (int i = 0; i < row.length; i++) { - heights[i] = row[i] == '0' ? 0 : heights[i] + 1; - } - // Update the maximal rectangle area - maxArea = Math.max(maxArea, calculateMaxArea(heights)); + + // Checking if the left node is a leaf node + if (root.left != null && root.left.left == null && root.left.right == null) { + return root.left.val + sumOfLeftLeaves(root.right); } - - return maxArea; - } - - // Method to calculate the maximal rectangle area using histogram - private int calculateMaxArea(int[] heights) { - // Initialize the maximal rectangle area - int maxArea = 0; - // Initialize a stack to store the indices of heights - Stack stack = new Stack<>(); - - // Iterate through each height and calculate the maximal rectangle area - for (int i = 0; i <= heights.length; i++) { - // Check if the stack is not empty and the current height is less than the height at the top of the stack - while (!stack.isEmpty() && (i == heights.length || heights[stack.peek()] > heights[i])) { - // Get the height at the top of the stack - int currentHeight = heights[stack.pop()]; - // Calculate the width of the rectangle - int width = stack.isEmpty() ? i : i - stack.peek() - 1; - // Update the maximal rectangle area - maxArea = Math.max(maxArea, currentHeight * width); - } - // Push the index of the current height onto the stack - stack.push(i); - } - - return maxArea; + // Exploring the tree further + return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right); } } ``` \ No newline at end of file From 9699e346fb6d18c9b36ccbc52c7fe157de22c219 Mon Sep 17 00:00:00 2001 From: 15-Ab Date: Sun, 14 Apr 2024 10:47:23 +0530 Subject: [PATCH 300/300] Create Daily 14-04-24.md --- 2024 April/Daily 14-04-24.md | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 2024 April/Daily 14-04-24.md diff --git a/2024 April/Daily 14-04-24.md b/2024 April/Daily 14-04-24.md new file mode 100644 index 0000000..e205f87 --- /dev/null +++ b/2024 April/Daily 14-04-24.md @@ -0,0 +1,63 @@ +# Leetcode Daily Challenge Solutions + +## Today's 14-04-24 [Problem Link](https://leetcode.com/problems/sum-of-left-leaves/description/?envType=daily-question&envId=2024-04-14) +## 404. Sum of Left Leaves + +# Intuition + +The goal is to find the sum of all left leaves in a binary tree. A left leaf is a leaf node that is the left child of its parent. +# Approach + + +- I started with the root node. +- If the current node is null, returned 0. +- Check if the left child of the current node exists and if it is a leaf node (i.e., it has no left or right children). +- If the left child is a leaf node, add its value to the result and continue recursively with the right child. +- If the left child is not a leaf node, recursively call the function on both the left and right children. +- Returned the sum obtained from the left subtree and the right subtree. + +--- +Have a look at the code , still have any confusion then please let me know in the comments +Keep Solving.:) + +# Complexity +- Time complexity : $O(n)$ + +$n$ : number of nodes in the binary tree +- Space complexity : $O(n)$ + + +# Code +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ + +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) { + return 0; + } + + // Checking if the left node is a leaf node + if (root.left != null && root.left.left == null && root.left.right == null) { + return root.left.val + sumOfLeftLeaves(root.right); + } + + // Exploring the tree further + return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right); + } +} +``` \ No newline at end of file