From ec0c9911f3b79962fe65e595463841aee0af0da9 Mon Sep 17 00:00:00 2001 From: Shreya7tripathy Date: Thu, 24 Oct 2024 21:20:38 +0530 Subject: [PATCH 1/4] added arrays in java folder added arrays folder (containing easy ,medium ,hard questions) in java folder of the repo --- java/Arrays/1.Easy/Find missing number.md | 94 ++++++++++++ .../Remove Duplicates from Sorted Array.md | 88 +++++++++++ java/Arrays/2.Medium/Kadane's Algorithm.md | 103 +++++++++++++ .../2.Medium/Longest Subarray with sum K.md | 118 +++++++++++++++ .../Arrays/3.Hard/Maximum Product Subarray.md | 81 ++++++++++ java/Arrays/3.Hard/Reverse pairs.md | 141 ++++++++++++++++++ 6 files changed, 625 insertions(+) create mode 100644 java/Arrays/1.Easy/Find missing number.md create mode 100644 java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md create mode 100644 java/Arrays/2.Medium/Kadane's Algorithm.md create mode 100644 java/Arrays/2.Medium/Longest Subarray with sum K.md create mode 100644 java/Arrays/3.Hard/Maximum Product Subarray.md create mode 100644 java/Arrays/3.Hard/Reverse pairs.md diff --git a/java/Arrays/1.Easy/Find missing number.md b/java/Arrays/1.Easy/Find missing number.md new file mode 100644 index 000000000..26dd9d8ab --- /dev/null +++ b/java/Arrays/1.Easy/Find missing number.md @@ -0,0 +1,94 @@ +| id | title | sidebar_label | description | tags | +| --- | -------------------------------- | --------------------------- | ---------------------------------------------------------- | ----------------- | +| Find missing number | Find the Missing Number in Array | Find Missing Number in Array | Find the missing number in an array of size N containing numbers from 1 to N. | `Array`, `XOR`, `DSA` | + +--- + +## Problem Statement +You are given an array `a` of size `N-1` containing numbers from `1` to `N`. The array has one number missing. Find the missing number. + +[LeetCode Problem Link](https://leetcode.com/problems/missing-number/description/) + +--- + +## Examples + +**Example 1**: +Input: +`a = [1, 2, 4, 5]`, `N = 5` + +Output: +`3` + +Explanation: +Numbers between `1` to `N` are `[1, 2, 3, 4, 5]`. The missing number is `3`. + +--- + +**Example 2**: +Input: +`a = [2, 3, 4, 5]`, `N = 5` + +Output: +`1` + +Explanation: +Numbers between `1` to `N` are `[1, 2, 3, 4, 5]`. The missing number is `1`. + +--- + +## Intuition +This problem can be solved using the properties of XOR: +1. **Property 1**: XOR of two identical numbers is always 0 (`a ^ a = 0`). +2. **Property 2**: XOR of a number with 0 results in the number itself (`0 ^ a = a`). + +### Key Idea: +- XOR all the numbers from `1` to `N`, which results in `xor1 = 1 ^ 2 ^ ... ^ N`. +- XOR all the elements in the array `a[]`, which results in `xor2 = 1 ^ 2 ^ ... ^ N` (excluding the missing number). +- The result of `xor1 ^ xor2` will cancel out all the numbers except the missing one, as explained by the XOR properties. Hence, `missing number = xor1 ^ xor2`. + +--- + +## Approach +1. Initialize two variables `xor1` and `xor2` to 0. +2. XOR all the numbers from `1` to `N` and store the result in `xor1`. +3. XOR all the elements of the array and store the result in `xor2`. +4. XOR the values of `xor1` and `xor2`. The result will be the missing number. + +--- + +## Java Implementation + +```java +import java.util.*; + +public class tUf { + public static int missingNumber(int []a, int N) { + int xor1 = 0, xor2 = 0; + + for (int i = 0; i < N - 1; i++) { + xor2 = xor2 ^ a[i]; // XOR of array elements + xor1 = xor1 ^ (i + 1); //XOR up to [1...N-1] + } + xor1 = xor1 ^ N; //XOR up to [1...N] + + return (xor1 ^ xor2); // the missing number + } + + public static void main(String args[]) { + int N = 5; + int a[] = {1, 2, 4, 5}; + + int ans = missingNumber(a, N); + System.out.println("The missing number is: " + ans); + } +} +``` +--- +## Time Complexity +Time Complexity: O(N), where N is the number of elements in the array. We only need to iterate over the array once to calculate the XORs. +Space Complexity: O(1), as we are only using a constant amount of extra space. + +--- +## Conclusion +Using XOR properties, we can find the missing number in linear time without using any extra space, making it an optimal solution for this problem. \ No newline at end of file diff --git a/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md b/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md new file mode 100644 index 000000000..a9b93788c --- /dev/null +++ b/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md @@ -0,0 +1,88 @@ +| id | title | sidebar_label | description | tags | +| --- | ------------------------------------ | ----------------------------- | --------------------------------------------------------- | -------------- | +| Remove Duplicates from Sorted Array | Remove Duplicates in-place from Sorted Array | Remove Duplicates in-place | Given a sorted array, remove the duplicates in-place and return the new length. | `Array`, `In-place`, `DSA` | + +--- + +## Problem Statement +Given a sorted array `arr`, remove duplicates in-place such that each element appears only once and return the new length. The solution should modify the input array in-place and not use extra space. + +[LeetCode Problem Link](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/) + +--- +--- + +## Examples + +**Example 1**: +Input: +`arr = [1, 1, 2, 2, 2, 3, 3]` + +Output: +`arr = [1, 2, 3, _, _, _, _]` + +Explanation: +Total number of unique elements is 3, i.e., `[1, 2, 3]`. Therefore, return 3 after placing `[1, 2, 3]` at the beginning of the array. + +--- + +**Example 2**: +Input: +`arr = [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4]` + +Output: +`arr = [1, 2, 3, 4, _, _, _, _, _, _, _]` + +Explanation: +Total number of unique elements is 4, i.e., `[1, 2, 3, 4]`. Therefore, return 4 after placing `[1, 2, 3, 4]` at the beginning of the array. + +--- +## Approach +The problem can be solved using the two-pointer technique: +1. Maintain two pointers, `i` and `j`, where `i` tracks the position of unique elements and `j` iterates over the array. +2. If the element at index `j` is different from the element at index `i`, increment `i` and set `arr[i] = arr[j]`. +3. The new length of the array will be `i + 1`. + +### Steps: +- Initialize `i = 0` to track the first unique element. +- Traverse the array from `j = 1` to the end. +- If `arr[j]` is different from `arr[i]`, update `arr[i + 1]` with `arr[j]` and increment `i`. +- After the loop, the first `i + 1` elements of the array will be unique. + +--- + +## Java Implementation + +```java +import java.util.*; +public class Main { + public static void main(String[] args) { + int arr[] = {1,1,2,2,2,3,3}; + int k = removeDuplicates(arr); + System.out.println("The array after removing duplicate elements is "); + for (int i = 0; i < k; i++) { + System.out.print(arr[i] + " "); + } + } + + static int removeDuplicates(int[] arr) { + int i = 0; + for (int j = 1; j < arr.length; j++) { + if (arr[i] != arr[j]) { + i++; + arr[i] = arr[j]; + } + } + return i + 1; + } +} +``` + +--- +## Time Complexity +Time Complexity: O(n), where n is the length of the input array. We are using a single loop to traverse the array. +Space Complexity: O(1), since we are modifying the array in-place without using any extra space. + +--- +## Conclusion +This solution efficiently removes duplicates from a sorted array in-place using the two-pointer technique. It has a time complexity of O(n) and does not require extra space, making it optimal for large inputs. \ No newline at end of file diff --git a/java/Arrays/2.Medium/Kadane's Algorithm.md b/java/Arrays/2.Medium/Kadane's Algorithm.md new file mode 100644 index 000000000..fbb4d04e5 --- /dev/null +++ b/java/Arrays/2.Medium/Kadane's Algorithm.md @@ -0,0 +1,103 @@ +| id | title | sidebar_label | description | tags | +| --- | ------------------------------------- | ----------------------------------- | ------------------------------------------------------------------- | ----------------- | +| Kadane's Algorithm | Kadane's Algorithm: Maximum Subarray Sum | Maximum Subarray Sum | Find the maximum sum of a contiguous subarray in an integer array. | `Array`, `Dynamic Programming`, `Greedy`, `DSA` | + +--- + +## Problem Statement +Given an integer array `arr`, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. + +[Leetcode Problem Link](https://leetcode.com/problems/maximum-subarray/description/) + +--- + +## Examples + +**Example 1**: +Input: +`arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]` + +Output: +`6` + +Explanation: +The subarray `[4, -1, 2, 1]` has the largest sum = 6. + +--- + +**Example 2**: +Input: +`arr = [1]` + +Output: +`1` + +Explanation: +Array has only one element, which gives a positive sum of 1. + +--- + +## Intuition +The intuition behind **Kadane's Algorithm** is simple: a subarray with a negative sum will always reduce the sum of the total subarray, so it's better to discard such subarrays and reset the sum to 0 whenever the sum goes below 0. + +### Key Idea: +- Iterate through the array and add elements to a running sum. +- If the sum becomes negative at any point, reset it to zero since no subarray with a negative sum is worth considering. +- Track the maximum sum encountered during the iteration. + +--- + +## Approach: +1. Initialize two variables: `maxi` to store the maximum sum and `sum` to store the current subarray sum. +2. Iterate through the array: + - Add the current element to `sum`. + - If `sum` exceeds `maxi`, update `maxi`. + - If `sum` becomes negative, reset it to `0`. +3. Return `maxi` as the result. + +### Edge Case: +In some scenarios, the question may mention that the sum of an empty subarray should be considered. In that case, compare `maxi` with `0` before returning the result, and ensure you return the larger value. + +--- + +## Java Implementation : + +```java +import java.util.*; + +public class Main { + public static long maxSubarraySum(int[] arr, int n) { + long maxi = Long.MIN_VALUE; // maximum sum + long sum = 0; + + for (int i = 0; i < n; i++) { + sum += arr[i]; + if (sum > maxi) { + maxi = sum; + } + // If sum < 0: discard the sum calculated + if (sum < 0) { + sum = 0; + } + } + + return maxi; + } + + public static void main(String args[]) { + int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4}; + int n = arr.length; + long maxSum = maxSubarraySum(arr, n); + System.out.println("The maximum subarray sum is: " + maxSum); + } +} +``` + +--- +## Time Complexity +The time complexity of Kadane's Algorithm is O(n), where n is the number of elements in the array. This is because we make a single pass through the array to calculate the maximum subarray sum. +Space Complexity: O(1) as we are not using any extra space. + +--- +## Conclusion +Kadane's Algorithm efficiently finds the maximum subarray sum in linear time, making it a powerful technique for solving problems related to contiguous subarrays. The algorithm's simplicity and effectiveness make it a staple in competitive programming and interviews. \ No newline at end of file diff --git a/java/Arrays/2.Medium/Longest Subarray with sum K.md b/java/Arrays/2.Medium/Longest Subarray with sum K.md new file mode 100644 index 000000000..6426c8e5d --- /dev/null +++ b/java/Arrays/2.Medium/Longest Subarray with sum K.md @@ -0,0 +1,118 @@ +| id | title | sidebar_label | description | tags | +| --- | ------------------------------------- | ----------------------------------- | ------------------------------------------------------------------- | ----------------- | +| Longest Subarray with sum K | Find Longest Subarray with Sum k | Longest Subarray with Sum k | Find the length of the longest subarray whose sum equals to k. | `Array`, `Hashing`, `DSA` | + +--- + +## Problem Statement +Given an array `a[]` and an integer `k`, find the length of the longest subarray that sums to `k`. + +[LeetCode Problem Link](https://leetcode.com/problems/subarray-sum-equals-k/) +--- + +## Examples + +**Example 1**: +Input: +`N = 3, k = 5, array[] = {2, 3, 5}` + +Output: +`2` + +Explanation: +The longest subarray with sum `5` is `{2, 3}`. Its length is `2`. + +--- + +**Example 2**: +Input: +`N = 3, k = 1, array[] = {-1, 1, 1}` + +Output: +`3` + +Explanation: +The longest subarray with sum `1` is `{-1, 1, 1}`. Its length is `3`. + +--- + +## Intuition +To solve this problem optimally, we can use the concept of **prefix sum** combined with **hashing**. + +### Key Idea: +- Maintain a map to store the prefix sum and its corresponding index. +- As we iterate through the array, calculate the prefix sum up to each index. +- Check if the prefix sum equals `k`. If yes, update the maximum subarray length. +- Also, check if there is a prefix sum equal to `sum - k` (the remaining sum required to get `k` from the current subarray). If such a sum exists, calculate the length of the subarray and update the maximum length accordingly. +- Store the prefix sum and its earliest occurrence in the map to maximize the subarray length. + +--- + +## Approach +1. Declare a HashMap `preSumMap` to store prefix sums and their corresponding indices. +2. Initialize variables `sum = 0` (to store the running prefix sum) and `maxLen = 0` (to store the length of the longest subarray with sum `k`). +3. Iterate through the array. For each element: + - Add the current element to `sum` (prefix sum up to that index). + - If the sum is equal to `k`, update `maxLen` to `i + 1` (the length from the start). + - Check if `sum - k` exists in the map. If yes, update `maxLen` with the length of the subarray `i - preSumMap[sum - k]`. + - Add the current `sum` to the map if it doesn't already exist (to store the earliest occurrence of the prefix sum). +4. Return `maxLen`, which stores the length of the longest subarray with sum `k`. + +--- + +## Java Implementation + +```java +import java.util.*; + +public class tUf { + public static int getLongestSubarray(int[] a, int k) { + int n = a.length; // size of the array. + Map preSumMap = new HashMap<>(); + int sum = 0; + int maxLen = 0; + + for (int i = 0; i < n; i++) { + // calculate the prefix sum till index i: + sum += a[i]; + + // if the sum = k, update the maxLen: + if (sum == k) { + maxLen = Math.max(maxLen, i + 1); + } + + // calculate the sum of remaining part i.e. x-k: + int rem = sum - k; + + // calculate the length and update maxLen: + if (preSumMap.containsKey(rem)) { + int len = i - preSumMap.get(rem); + maxLen = Math.max(maxLen, len); + } + + // finally, update the map checking the conditions: + if (!preSumMap.containsKey(sum)) { + preSumMap.put(sum, i); + } + } + + return maxLen; + } + + public static void main(String[] args) { + int[] a = {-1, 1, 1}; + int k = 1; + int len = getLongestSubarray(a, k); + System.out.println("The length of the longest subarray is: " + len); + } +} +``` + +--- +## Time Complexity +Time Complexity: O(N), where N is the number of elements in the array. We process each element only once. +Space Complexity: O(N), as we are using a HashMap to store the prefix sums. + +--- +## Conclusion +Using a hash map to store prefix sums allows us to efficiently find the longest subarray with sum k in linear time. \ No newline at end of file diff --git a/java/Arrays/3.Hard/Maximum Product Subarray.md b/java/Arrays/3.Hard/Maximum Product Subarray.md new file mode 100644 index 000000000..a225b2bee --- /dev/null +++ b/java/Arrays/3.Hard/Maximum Product Subarray.md @@ -0,0 +1,81 @@ +| id | title | sidebar_label | description | tags | +| --- | ----------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------- | ----------------- | +| Maximum Product Subarray | Maximum Product Subarray in a Array | Maximum Product Subarray | Given an array containing both negative and positive integers, find the maximum product subarray. | `Dynamic Programming`, `Array` | + +--- + +## Problem Statement +Given an array that contains both negative and positive integers, find the maximum product subarray. + +**LeetCode Problem Link**: [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/description/) + +--- + +## Examples + +**Example 1**: +Input: +`Nums = [1, 2, 3, 4, 5, 0]` +Output: +`120` +**Explanation**: +In the given array, we can see `1 × 2 × 3 × 4 × 5` gives the maximum product value. + +--- + +**Example 2**: +Input: +`Nums = [1, 2, -3, 0, -4, -5]` +Output: +`20` +**Explanation**: +In the given array, we can see `(-4) × (-5)` gives the maximum product value. + +--- + +## Approach +The following approach is motivated by Kadane’s algorithm. The key insight is that we can obtain the maximum product from the product of two negative numbers as well. + +### Steps: +1. Initially, store the value at the 0th index in `prod1`, `prod2`, and `result`. +2. Traverse the array starting from the 1st index. +3. For each element: + - Update `prod1` to be the maximum of the current element, the product of the current element and `prod1`, and the product of the current element and `prod2`. + - Update `prod2` to be the minimum of the current element, the product of the current element and `prod1`, and the product of the current element and `prod2`. +4. Return the maximum of `result` and `prod1`. + +## Java Implementation + +```java +import java.util.*; + +public class Main { + static int maxProductSubArray(int arr[]) { + int prod1 = arr[0], prod2 = arr[0], result = arr[0]; + + for (int i = 1; i < arr.length; i++) { + int temp = Math.max(arr[i], Math.max(prod1 * arr[i], prod2 * arr[i])); + prod2 = Math.min(arr[i], Math.min(prod1 * arr[i], prod2 * arr[i])); + prod1 = temp; + + result = Math.max(result, prod1); + } + + return result; + } + + public static void main(String[] args) { + int nums[] = {1, 2, -3, 0, -4, -5}; + int answer = maxProductSubArray(nums); + System.out.print("The maximum product subarray is: " + answer); + } +} +``` + +--- +## Time Complexity +The time complexity of this algorithm is O(n), where n is the number of elements in the input array. We traverse the array once to calculate the maximum product.The space complexity is O(1) since we are using only a constant amount of space for variables. + +--- +## Conclusion +This approach efficiently finds the maximum product subarray by leveraging the properties of positive and negative integers. It maintains both the maximum and minimum products at each step, allowing it to handle negative values effectively. This solution is optimal in terms of both time and space complexity, making it suitable for large input sizes. \ No newline at end of file diff --git a/java/Arrays/3.Hard/Reverse pairs.md b/java/Arrays/3.Hard/Reverse pairs.md new file mode 100644 index 000000000..4b6bc564d --- /dev/null +++ b/java/Arrays/3.Hard/Reverse pairs.md @@ -0,0 +1,141 @@ +| id | title | sidebar_label | description | tags | +| --- | ---------------- | ------------------- | ----------------------------------------------------------------------------------------------- | ---------------------- | +| Reverse Pairs | Count Reverse Pairs | Count Reverse Pairs | Given an array, return the count of reverse pairs where i < j and arr[i] > 2 * arr[j]. | `Merge Sort`, `Array` | + +--- + +## Problem Statement +Given an array of numbers, return the count of reverse pairs. Reverse Pairs are those pairs where `i < j` and `arr[i] > 2 * arr[j]`. + +**LeetCode Problem Link**: [Reverse Pairs](https://leetcode.com/problems/reverse-pairs/description/) + +--- + +## Examples + +**Example 1**: +Input: +`N = 5, array[] = {1, 3, 2, 3, 1}` +Output: +`2` +**Explanation**: +The pairs are `(3, 1)` and `(3, 1)` as both satisfy the condition `arr[i] > 2 * arr[j]`. + +--- + +**Example 2**: +Input: +`N = 4, array[] = {3, 2, 1, 4}` +Output: +`1` +**Explanation**: +There is only 1 pair `(3, 1)` that satisfies the condition `arr[i] > 2 * arr[j]`. + +--- + +## Approach + +The problem can be solved using a modified **Merge Sort** approach, similar to the inversion count problem but with a change in the condition. The idea is to: +1. **Merge** the sorted halves. +2. **Count pairs** where `arr[i] > 2 * arr[j]` using two pointers during the merge step. +3. Merge sort ensures that both halves are sorted, making it efficient to count valid pairs. + +### Steps: +1. Implement a **modified merge sort** where: + - During the merge process, count valid pairs by iterating through the left and right halves. + - For each element in the left half, count how many elements in the right half satisfy the condition. +2. After counting the pairs, merge the two halves back into the original array. + +### Implementation + +```java +import java.util.*; + +public class CountReversePairs { + + // Merges two sorted halves and counts reverse pairs + private static void merge(int[] arr, int low, int mid, int high) { + ArrayList temp = new ArrayList<>(); + int left = low; + int right = mid + 1; + + // Merge two halves in sorted order + while (left <= mid && right <= high) { + if (arr[left] <= arr[right]) { + temp.add(arr[left]); + left++; + } else { + temp.add(arr[right]); + right++; + } + } + + // If there are remaining elements in the left half + while (left <= mid) { + temp.add(arr[left]); + left++; + } + + // If there are remaining elements in the right half + while (right <= high) { + temp.add(arr[right]); + right++; + } + + // Transfer all elements from temp back to arr + for (int i = low; i <= high; i++) { + arr[i] = temp.get(i - low); + } + } + + // Counts pairs where arr[i] > 2 * arr[j] in two sorted halves + public static int countPairs(int[] arr, int low, int mid, int high) { + int right = mid + 1; + int cnt = 0; + for (int i = low; i <= mid; i++) { + while (right <= high && arr[i] > 2 * arr[right]) right++; + cnt += (right - (mid + 1)); + } + return cnt; + } + + // Recursive merge sort with modification to count reverse pairs + public static int mergeSort(int[] arr, int low, int high) { + int cnt = 0; + if (low >= high) return cnt; + int mid = (low + high) / 2 ; + cnt += mergeSort(arr, low, mid); // left half + cnt += mergeSort(arr, mid + 1, high); // right half + cnt += countPairs(arr, low, mid, high); // Count reverse pairs + merge(arr, low, mid, high); // Merge sorted halves + return cnt; + } + + // Main function that triggers the merge sort + public static int reversePairs(int[] arr, int n) { + return mergeSort(arr, 0, n - 1); + } + + public static void main(String[] args) { + int[] array = {4, 1, 2, 3, 1}; + int n = 5; + int count = reversePairs(array, n); + System.out.println("The number of reverse pairs is: " + count); + } +} +``` + +--- +## Time Complexity +The time complexity is O(N log N), where N is the size of the array. + +Merge Sort: Recursively divides the array, which takes O(log N). +Counting pairs: For each split, the counting process takes O(N). +Thus, the total time complexity is O(N log N). + +Space Complexity +The space complexity is O(N) because of the temporary array used to store the merged elements. + +--- +## Conclusion +This problem is a modification of the inversion count problem, with the condition arr[i] > 2 * arr[j]. The approach uses merge sort to efficiently count such pairs in O(N log N) time. This is optimal for large arrays and ensures that the problem can be solved within reasonable time limits. \ No newline at end of file From bf2da69b0e6278a8def1c7df0987efff9c266072 Mon Sep 17 00:00:00 2001 From: Shreya7tripathy Date: Sun, 27 Oct 2024 19:06:11 +0530 Subject: [PATCH 2/4] updated files --- java/Arrays/1.Easy/Find missing number.md | 24 ++++++----- .../Remove Duplicates from Sorted Array.md | 30 ++++++++----- java/Arrays/2.Medium/Kadane's Algorithm.md | 35 ++++++++-------- .../2.Medium/Longest Subarray with sum K.md | 20 +++++---- .../Arrays/3.Hard/Maximum Product Subarray.md | 20 +++++---- java/Arrays/3.Hard/Reverse pairs.md | 42 +++++++++---------- 6 files changed, 95 insertions(+), 76 deletions(-) diff --git a/java/Arrays/1.Easy/Find missing number.md b/java/Arrays/1.Easy/Find missing number.md index 26dd9d8ab..4549fa13a 100644 --- a/java/Arrays/1.Easy/Find missing number.md +++ b/java/Arrays/1.Easy/Find missing number.md @@ -1,10 +1,13 @@ -| id | title | sidebar_label | description | tags | -| --- | -------------------------------- | --------------------------- | ---------------------------------------------------------- | ----------------- | -| Find missing number | Find the Missing Number in Array | Find Missing Number in Array | Find the missing number in an array of size N containing numbers from 1 to N. | `Array`, `XOR`, `DSA` | - +--- +id: +title: +sidebar_label: +sidebar_position: <1> +description: +tags: [, , ] --- -## Problem Statement +# Problem Statement You are given an array `a` of size `N-1` containing numbers from `1` to `N`. The array has one number missing. Find the missing number. [LeetCode Problem Link](https://leetcode.com/problems/missing-number/description/) @@ -62,15 +65,15 @@ This problem can be solved using the properties of XOR: ```java import java.util.*; -public class tUf { +public class FindMissingNumber { public static int missingNumber(int []a, int N) { int xor1 = 0, xor2 = 0; for (int i = 0; i < N - 1; i++) { xor2 = xor2 ^ a[i]; // XOR of array elements - xor1 = xor1 ^ (i + 1); //XOR up to [1...N-1] + xor1 = xor1 ^ (i + 1); // XOR up to [1...N-1] } - xor1 = xor1 ^ N; //XOR up to [1...N] + xor1 = xor1 ^ N; // XOR up to [1...N] return (xor1 ^ xor2); // the missing number } @@ -86,8 +89,9 @@ public class tUf { ``` --- ## Time Complexity -Time Complexity: O(N), where N is the number of elements in the array. We only need to iterate over the array once to calculate the XORs. -Space Complexity: O(1), as we are only using a constant amount of extra space. +**Time Complexity**: `O(N)`, where N is the number of elements in the array. We only need to iterate over the array once to calculate the XORs. + +**Space Complexity**: `O(1)`, as we are only using a constant amount of extra space. --- ## Conclusion diff --git a/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md b/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md index a9b93788c..d0cde4b99 100644 --- a/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md +++ b/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md @@ -1,15 +1,19 @@ -| id | title | sidebar_label | description | tags | -| --- | ------------------------------------ | ----------------------------- | --------------------------------------------------------- | -------------- | -| Remove Duplicates from Sorted Array | Remove Duplicates in-place from Sorted Array | Remove Duplicates in-place | Given a sorted array, remove the duplicates in-place and return the new length. | `Array`, `In-place`, `DSA` | - +--- +id: +title: +sidebar_label: +sidebar_position: <1> +description: +tags: [, , ] --- +# Remove Duplicates in-place from Sorted Array + ## Problem Statement Given a sorted array `arr`, remove duplicates in-place such that each element appears only once and return the new length. The solution should modify the input array in-place and not use extra space. [LeetCode Problem Link](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/) ---- --- ## Examples @@ -22,7 +26,7 @@ Output: `arr = [1, 2, 3, _, _, _, _]` Explanation: -Total number of unique elements is 3, i.e., `[1, 2, 3]`. Therefore, return 3 after placing `[1, 2, 3]` at the beginning of the array. +The unique elements are `[1, 2, 3]`, so the function returns `3` and places `[1, 2, 3]` at the start of the array. --- @@ -34,11 +38,13 @@ Output: `arr = [1, 2, 3, 4, _, _, _, _, _, _, _]` Explanation: -Total number of unique elements is 4, i.e., `[1, 2, 3, 4]`. Therefore, return 4 after placing `[1, 2, 3, 4]` at the beginning of the array. +The unique elements are `[1, 2, 3, 4]`, so the function returns `4` and places `[1, 2, 3, 4]` at the start of the array. --- + ## Approach The problem can be solved using the two-pointer technique: + 1. Maintain two pointers, `i` and `j`, where `i` tracks the position of unique elements and `j` iterates over the array. 2. If the element at index `j` is different from the element at index `i`, increment `i` and set `arr[i] = arr[j]`. 3. The new length of the array will be `i + 1`. @@ -55,9 +61,10 @@ The problem can be solved using the two-pointer technique: ```java import java.util.*; + public class Main { public static void main(String[] args) { - int arr[] = {1,1,2,2,2,3,3}; + int arr[] = {1, 1, 2, 2, 2, 3, 3}; int k = removeDuplicates(arr); System.out.println("The array after removing duplicate elements is "); for (int i = 0; i < k; i++) { @@ -80,9 +87,10 @@ public class Main { --- ## Time Complexity -Time Complexity: O(n), where n is the length of the input array. We are using a single loop to traverse the array. -Space Complexity: O(1), since we are modifying the array in-place without using any extra space. +**Time Complexity**: `O(n)`, where n is the length of the input array. We are using a single loop to traverse the array. + +**Space Complexity**: `O(1)`, since we are modifying the array in-place without using any extra space. --- ## Conclusion -This solution efficiently removes duplicates from a sorted array in-place using the two-pointer technique. It has a time complexity of O(n) and does not require extra space, making it optimal for large inputs. \ No newline at end of file +This solution efficiently removes duplicates from a sorted array in-place using the two-pointer technique. It has a time complexity of `O(n)` and does not require extra space, making it optimal for large inputs. \ No newline at end of file diff --git a/java/Arrays/2.Medium/Kadane's Algorithm.md b/java/Arrays/2.Medium/Kadane's Algorithm.md index fbb4d04e5..4ba7e7691 100644 --- a/java/Arrays/2.Medium/Kadane's Algorithm.md +++ b/java/Arrays/2.Medium/Kadane's Algorithm.md @@ -1,15 +1,18 @@ -| id | title | sidebar_label | description | tags | -| --- | ------------------------------------- | ----------------------------------- | ------------------------------------------------------------------- | ----------------- | -| Kadane's Algorithm | Kadane's Algorithm: Maximum Subarray Sum | Maximum Subarray Sum | Find the maximum sum of a contiguous subarray in an integer array. | `Array`, `Dynamic Programming`, `Greedy`, `DSA` | - --- +id: +title: +sidebar_label: +sidebar_position: <1> +description: +tags: [, , , ] +--- + +# Kadane's Algorithm: Maximum Subarray Sum ## Problem Statement Given an integer array `arr`, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. -[Leetcode Problem Link](https://leetcode.com/problems/maximum-subarray/description/) - ---- +[LeetCode Problem Link](https://leetcode.com/problems/maximum-subarray/description/) ## Examples @@ -40,14 +43,12 @@ Array has only one element, which gives a positive sum of 1. ## Intuition The intuition behind **Kadane's Algorithm** is simple: a subarray with a negative sum will always reduce the sum of the total subarray, so it's better to discard such subarrays and reset the sum to 0 whenever the sum goes below 0. -### Key Idea: +### Key Idea - Iterate through the array and add elements to a running sum. - If the sum becomes negative at any point, reset it to zero since no subarray with a negative sum is worth considering. - Track the maximum sum encountered during the iteration. ---- - -## Approach: +## Approach 1. Initialize two variables: `maxi` to store the maximum sum and `sum` to store the current subarray sum. 2. Iterate through the array: - Add the current element to `sum`. @@ -55,12 +56,10 @@ The intuition behind **Kadane's Algorithm** is simple: a subarray with a negativ - If `sum` becomes negative, reset it to `0`. 3. Return `maxi` as the result. -### Edge Case: +### Edge Case In some scenarios, the question may mention that the sum of an empty subarray should be considered. In that case, compare `maxi` with `0` before returning the result, and ensure you return the larger value. ---- - -## Java Implementation : +## Java Implementation ```java import java.util.*; @@ -91,12 +90,14 @@ public class Main { System.out.println("The maximum subarray sum is: " + maxSum); } } + ``` --- ## Time Complexity -The time complexity of Kadane's Algorithm is O(n), where n is the number of elements in the array. This is because we make a single pass through the array to calculate the maximum subarray sum. -Space Complexity: O(1) as we are not using any extra space. +The **Time complexity** of Kadane's Algorithm is `O(n)`, where n is the number of elements in the array. This is because we make a single pass through the array to calculate the maximum subarray sum. + +**Space Complexity**: `O(1)` as we are not using any extra space. --- ## Conclusion diff --git a/java/Arrays/2.Medium/Longest Subarray with sum K.md b/java/Arrays/2.Medium/Longest Subarray with sum K.md index 6426c8e5d..02b40d576 100644 --- a/java/Arrays/2.Medium/Longest Subarray with sum K.md +++ b/java/Arrays/2.Medium/Longest Subarray with sum K.md @@ -1,14 +1,16 @@ -| id | title | sidebar_label | description | tags | -| --- | ------------------------------------- | ----------------------------------- | ------------------------------------------------------------------- | ----------------- | -| Longest Subarray with sum K | Find Longest Subarray with Sum k | Longest Subarray with Sum k | Find the length of the longest subarray whose sum equals to k. | `Array`, `Hashing`, `DSA` | - +--- +id: +title: +sidebar_label: +sidebar_position: <1> +description: +tags: [, , ] --- -## Problem Statement +# Problem Statement Given an array `a[]` and an integer `k`, find the length of the longest subarray that sums to `k`. [LeetCode Problem Link](https://leetcode.com/problems/subarray-sum-equals-k/) ---- ## Examples @@ -106,12 +108,14 @@ public class tUf { System.out.println("The length of the longest subarray is: " + len); } } + ``` --- ## Time Complexity -Time Complexity: O(N), where N is the number of elements in the array. We process each element only once. -Space Complexity: O(N), as we are using a HashMap to store the prefix sums. +**Time Complexity**: `O(N)`, where N is the number of elements in the array. We process each element only once. + +**Space Complexity**: `O(N)`, as we are using a HashMap to store the prefix sums. --- ## Conclusion diff --git a/java/Arrays/3.Hard/Maximum Product Subarray.md b/java/Arrays/3.Hard/Maximum Product Subarray.md index a225b2bee..b3fc4e978 100644 --- a/java/Arrays/3.Hard/Maximum Product Subarray.md +++ b/java/Arrays/3.Hard/Maximum Product Subarray.md @@ -1,16 +1,17 @@ -| id | title | sidebar_label | description | tags | -| --- | ----------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------- | ----------------- | -| Maximum Product Subarray | Maximum Product Subarray in a Array | Maximum Product Subarray | Given an array containing both negative and positive integers, find the maximum product subarray. | `Dynamic Programming`, `Array` | - +--- +id: +title: +sidebar_label: +sidebar_position: <1> +description: +tags: [, ] --- -## Problem Statement +# Problem Statement Given an array that contains both negative and positive integers, find the maximum product subarray. **LeetCode Problem Link**: [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/description/) ---- - ## Examples **Example 1**: @@ -70,11 +71,14 @@ public class Main { System.out.print("The maximum product subarray is: " + answer); } } + ``` --- ## Time Complexity -The time complexity of this algorithm is O(n), where n is the number of elements in the input array. We traverse the array once to calculate the maximum product.The space complexity is O(1) since we are using only a constant amount of space for variables. +The **Time complexity** of this algorithm is `O(n)`, where n is the number of elements in the input array. We traverse the array once to calculate the maximum product. + +The **Space complexity** is `O(1)` since we are using only a constant amount of space for variables. --- ## Conclusion diff --git a/java/Arrays/3.Hard/Reverse pairs.md b/java/Arrays/3.Hard/Reverse pairs.md index 4b6bc564d..932fd070c 100644 --- a/java/Arrays/3.Hard/Reverse pairs.md +++ b/java/Arrays/3.Hard/Reverse pairs.md @@ -1,19 +1,20 @@ -| id | title | sidebar_label | description | tags | -| --- | ---------------- | ------------------- | ----------------------------------------------------------------------------------------------- | ---------------------- | -| Reverse Pairs | Count Reverse Pairs | Count Reverse Pairs | Given an array, return the count of reverse pairs where i < j and arr[i] > 2 * arr[j]. | `Merge Sort`, `Array` | - +--- +id: +title: +sidebar_label: +sidebar_position: <1> +description: 2 * arr[j].> +tags: [, ] --- -## Problem Statement +# Problem Statement Given an array of numbers, return the count of reverse pairs. Reverse Pairs are those pairs where `i < j` and `arr[i] > 2 * arr[j]`. **LeetCode Problem Link**: [Reverse Pairs](https://leetcode.com/problems/reverse-pairs/description/) ---- - ## Examples -**Example 1**: +### Example 1 Input: `N = 5, array[] = {1, 3, 2, 3, 1}` Output: @@ -21,9 +22,7 @@ Output: **Explanation**: The pairs are `(3, 1)` and `(3, 1)` as both satisfy the condition `arr[i] > 2 * arr[j]`. ---- - -**Example 2**: +### Example 2 Input: `N = 4, array[] = {3, 2, 1, 4}` Output: @@ -31,8 +30,6 @@ Output: **Explanation**: There is only 1 pair `(3, 1)` that satisfies the condition `arr[i] > 2 * arr[j]`. ---- - ## Approach The problem can be solved using a modified **Merge Sort** approach, similar to the inversion count problem but with a change in the condition. The idea is to: @@ -40,13 +37,13 @@ The problem can be solved using a modified **Merge Sort** approach, similar to t 2. **Count pairs** where `arr[i] > 2 * arr[j]` using two pointers during the merge step. 3. Merge sort ensures that both halves are sorted, making it efficient to count valid pairs. -### Steps: +### Steps 1. Implement a **modified merge sort** where: - During the merge process, count valid pairs by iterating through the left and right halves. - For each element in the left half, count how many elements in the right half satisfy the condition. 2. After counting the pairs, merge the two halves back into the original array. -### Implementation +## Java Implementation ```java import java.util.*; @@ -123,19 +120,20 @@ public class CountReversePairs { System.out.println("The number of reverse pairs is: " + count); } } + ``` --- ## Time Complexity -The time complexity is O(N log N), where N is the size of the array. +The **Time complexity** is O(N log N), where N is the size of the array. + +**Merge Sort**: Recursively divides the array, which takes O(log N). +**Counting pairs**: For each split, the counting process takes O(N). -Merge Sort: Recursively divides the array, which takes O(log N). -Counting pairs: For each split, the counting process takes O(N). -Thus, the total time complexity is O(N log N). +Thus, the total time complexity is `O(N log N)`. -Space Complexity -The space complexity is O(N) because of the temporary array used to store the merged elements. +**Space Complexity**: The space complexity is `O(N)` because of the temporary array used to store the merged elements. --- ## Conclusion -This problem is a modification of the inversion count problem, with the condition arr[i] > 2 * arr[j]. The approach uses merge sort to efficiently count such pairs in O(N log N) time. This is optimal for large arrays and ensures that the problem can be solved within reasonable time limits. \ No newline at end of file +This problem is a modification of the inversion count problem, with the condition `arr[i] > 2 * arr[j].` The approach uses merge sort to efficiently count such pairs in `O(N log N)` time. This is optimal for large arrays and ensures that the problem can be solved within reasonable time limits. \ No newline at end of file From 6bceb6ddad1bde6a4dc96e9336f31dd56cd7dfd1 Mon Sep 17 00:00:00 2001 From: Shreya7tripathy Date: Sun, 27 Oct 2024 21:46:26 +0530 Subject: [PATCH 3/4] updated files --- java/Arrays/1.Easy/Find missing number.md | 12 ++++++------ .../1.Easy/Remove Duplicates from Sorted Array.md | 12 ++++++------ java/Arrays/2.Medium/Kadane's Algorithm.md | 12 ++++++------ java/Arrays/2.Medium/Longest Subarray with sum K.md | 12 ++++++------ java/Arrays/3.Hard/Maximum Product Subarray.md | 12 ++++++------ java/Arrays/3.Hard/Reverse pairs.md | 12 ++++++------ 6 files changed, 36 insertions(+), 36 deletions(-) diff --git a/java/Arrays/1.Easy/Find missing number.md b/java/Arrays/1.Easy/Find missing number.md index 4549fa13a..fbf4c768b 100644 --- a/java/Arrays/1.Easy/Find missing number.md +++ b/java/Arrays/1.Easy/Find missing number.md @@ -1,10 +1,10 @@ --- -id: -title: -sidebar_label: -sidebar_position: <1> -description: -tags: [, , ] +id: find-missing-number +title: Find the Missing Number in Array +sidebar_label: Find Missing Number in Array +sidebar_position: 1 +description: Find the missing number in an array of size N containing numbers from 1 to N. +tags: [Array, XOR, DSA] --- # Problem Statement diff --git a/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md b/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md index d0cde4b99..aec67e5f4 100644 --- a/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md +++ b/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md @@ -1,10 +1,10 @@ --- -id: -title: -sidebar_label: -sidebar_position: <1> -description: -tags: [, , ] +id: remove-duplicates-sorted-array +title: Remove Duplicates in-place from Sorted Array +sidebar_label: Remove Duplicates in-place +sidebar_position: 1 +description: Given a sorted array, remove the duplicates in-place and return the new length. +tags: [Array, In-place, DSA] --- # Remove Duplicates in-place from Sorted Array diff --git a/java/Arrays/2.Medium/Kadane's Algorithm.md b/java/Arrays/2.Medium/Kadane's Algorithm.md index 4ba7e7691..68d24dca3 100644 --- a/java/Arrays/2.Medium/Kadane's Algorithm.md +++ b/java/Arrays/2.Medium/Kadane's Algorithm.md @@ -1,10 +1,10 @@ --- -id: -title: -sidebar_label: -sidebar_position: <1> -description: -tags: [, , , ] +id: kadanes-algorithm> +title: Kadane's Algorithm- Maximum Subarray Sum +sidebar_label: Maximum Subarray Sum +sidebar_position: 1 +description: Find the maximum sum of a contiguous subarray in an integer array. +tags: [Array, Dynamic Programming, Greedy, DSA] --- # Kadane's Algorithm: Maximum Subarray Sum diff --git a/java/Arrays/2.Medium/Longest Subarray with sum K.md b/java/Arrays/2.Medium/Longest Subarray with sum K.md index 02b40d576..8f66e0f22 100644 --- a/java/Arrays/2.Medium/Longest Subarray with sum K.md +++ b/java/Arrays/2.Medium/Longest Subarray with sum K.md @@ -1,10 +1,10 @@ --- -id: -title: -sidebar_label: -sidebar_position: <1> -description: -tags: [, , ] +id: longest-subarray-sum-k +title: Find Longest Subarray with Sum k +sidebar_label: Longest Subarray with Sum k +sidebar_position: 1 +description: Find the length of the longest subarray whose sum equals k. +tags: [Array, Hashing, DSA] --- # Problem Statement diff --git a/java/Arrays/3.Hard/Maximum Product Subarray.md b/java/Arrays/3.Hard/Maximum Product Subarray.md index b3fc4e978..92d596ccf 100644 --- a/java/Arrays/3.Hard/Maximum Product Subarray.md +++ b/java/Arrays/3.Hard/Maximum Product Subarray.md @@ -1,10 +1,10 @@ --- -id: -title: -sidebar_label: -sidebar_position: <1> -description: -tags: [, ] +id: maximum-product-subarray +title: Maximum Product Subarray in an Array +sidebar_label: Maximum Product Subarray +sidebar_position: 1 +description: Find the maximum product of a contiguous subarray within an array containing both negative and positive integers. +tags: [Dynamic Programming, Array] --- # Problem Statement diff --git a/java/Arrays/3.Hard/Reverse pairs.md b/java/Arrays/3.Hard/Reverse pairs.md index 932fd070c..fcdc336ae 100644 --- a/java/Arrays/3.Hard/Reverse pairs.md +++ b/java/Arrays/3.Hard/Reverse pairs.md @@ -1,10 +1,10 @@ --- -id: -title: -sidebar_label: -sidebar_position: <1> -description: 2 * arr[j].> -tags: [, ] +id: reverse-pairs +title: Count Reverse Pairs +sidebar_label: Count Reverse Pairs +sidebar_position: 1 +description: Count the number of reverse pairs in an array where i < j and arr[i] > 2 * arr[j]. +tags: [Merge Sort, Array] --- # Problem Statement From bceb7d567c6ce2a10e6218715b23c93ee716a54e Mon Sep 17 00:00:00 2001 From: Shreya7tripathy Date: Sat, 2 Nov 2024 21:16:56 +0530 Subject: [PATCH 4/4] updated description --- java/Arrays/3.Hard/Reverse pairs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/Arrays/3.Hard/Reverse pairs.md b/java/Arrays/3.Hard/Reverse pairs.md index fcdc336ae..828d5c762 100644 --- a/java/Arrays/3.Hard/Reverse pairs.md +++ b/java/Arrays/3.Hard/Reverse pairs.md @@ -3,7 +3,7 @@ id: reverse-pairs title: Count Reverse Pairs sidebar_label: Count Reverse Pairs sidebar_position: 1 -description: Count the number of reverse pairs in an array where i < j and arr[i] > 2 * arr[j]. +description: Count the number of reverse pairs in an array where i is less than j and the element at index i is greater than twice the element at index j. tags: [Merge Sort, Array] ---