From b6acb73119152e38bc4945144dd2c9aafb4eba39 Mon Sep 17 00:00:00 2001 From: ImmidiSivani <147423543+ImmidiSivani@users.noreply.github.com> Date: Thu, 18 Jul 2024 22:47:16 +0530 Subject: [PATCH 1/3] Update 0493-reverse-pairs.md --- .../0400-0499/0493-reverse-pairs.md | 380 ++++++++++++------ 1 file changed, 266 insertions(+), 114 deletions(-) diff --git a/dsa-solutions/lc-solutions/0400-0499/0493-reverse-pairs.md b/dsa-solutions/lc-solutions/0400-0499/0493-reverse-pairs.md index ab99d358c..33f1c7b9a 100644 --- a/dsa-solutions/lc-solutions/0400-0499/0493-reverse-pairs.md +++ b/dsa-solutions/lc-solutions/0400-0499/0493-reverse-pairs.md @@ -1,172 +1,324 @@ --- id: reverse-pairs title: Reverse Pairs -sidebar_label: 0493 - Reverse Pairs +sidebar_label: 493-Reverse-Pairs tags: - - Leetcode + - Array + - Binary Search + - Divide and conquer + - Binary Indexed Tree + - Segment Tree - Merge Sort + - Ordered Set +description: The problem is to reverse the pairs. +sidebar_position: 2667 --- -## Problem Statement +## Problem Statement -Given an integer array `nums`, return the number of reverse pairs in the array. - -A reverse pair is defined as a pair `(i, j)` where: - -- $0 <= i < j < nums.length and$ -- $nums[i] > 2 * nums[j].$ +### Problem Description -## Examples +Given an integer array `nums`, return the number of reverse pairs in the array. -### Example 1 +A reverse pair is a pair `(i, j)` where: -- Input: `nums = [1,3,2,3,1]` -- Output: `2` -- Explanation: The reverse pairs are: - - `(1, 4)` -> `nums[1] = 3`, `nums[4] = 1`, `3 > 2 * 1` - - `(3, 4)` -> `nums[3] = 3`, `nums[4] = 1`, `3 > 2 * 1` +`0 <= i < j < nums.length` and +`nums[i] > 2 * nums[j]`. -### Example 2 +### Examples -- Input: `nums = [2,4,3,5,1]` -- Output: `3` -- Explanation: The reverse pairs are: - - `(1, 4)` -> `nums[1] = 4`, `nums[4] = 1`, `4 > 2 * 1` - - `(2, 4)` -> `nums[2] = 3`, `nums[4] = 1`, `3 > 2 * 1` - - `(3, 4)` -> `nums[3] = 5`, `nums[4] = 1`, `5 > 2 * 1` +**Example 1:** -## Constraints +``` +Input: nums = [1,3,2,3,1] +Output: 2 +Explanation: The reverse pairs are: +(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1 +(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1 +``` -- $1 <= nums.length <= 5 * 104$ -- $-231 <= nums[i] <= 231 - 1$ +**Example 2:** -## Algorithm +``` +Input: nums = [2,4,3,5,1] +Output: 3 +Explanation: The reverse pairs are: +(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1 +(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1 +(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1 +``` -To solve this problem efficiently, we can use a modified merge sort algorithm, which not only sorts the array but also counts the number of reverse pairs during the merging process. The idea is to leverage the divide-and-conquer approach to count pairs in `O(n log n)` time complexity. +### Constraints -### Steps: +- `1 <= nums.length <= 5 * 10^4` -1. **Divide**: Split the array into two halves. -2. **Count**: Count the reverse pairs in each half recursively. -3. **Merge and Count**: While merging the two halves, count the reverse pairs where one element is from the left half and the other is from the right half. +## Solution of Given Problem -## Code +### Intuition and Approach -### Python +The intuition behind this solution is to use a modified Merge Sort algorithm to count the number of reverse pairs in the array. -```python -class Solution: - def reversePairs(self, nums: List[int]) -> int: - def merge_sort(nums, l, r): - if l >= r: - return 0 - mid = (l + r) // 2 - count = merge_sort(nums, l, mid) + merge_sort(nums, mid + 1, r) +### Approaches - j = mid + 1 - for i in range(l, mid + 1): - while j <= r and nums[i] > 2 * nums[j]: - j += 1 - count += j - (mid + 1) +- Divide the array into smaller subarrays until each subarray has only one element. +- Merge the subarrays back together, counting the number of reverse pairs between each pair of subarrays. +- The merge step is done in a way that ensures the count of reverse pairs is accurate. - nums[l:r + 1] = sorted(nums[l:r + 1]) - return count - return merge_sort(nums, 0, len(nums) - 1) -``` +#### Codes in Different Languages -### C++ + + + + ```javascript + function mergeSortedArrays(nums, left, mid, right, temp) { + let i = left, j = mid + 1, k = 0; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) temp[k++] = nums[i++]; + else temp[k++] = nums[j++]; + } + while (i <= mid) temp[k++] = nums[i++]; + while (j <= right) temp[k++] = nums[j++]; +} -```cpp -#include -using namespace std; +function merge(nums, left, mid, right) { + let count = 0; + let j = mid + 1; + for (let i = left; i <= mid; i++) { + while (j <= right && nums[i] > 2 * nums[j]) j++; + count += j - mid - 1; + } + let temp = new Array(right - left + 1); + mergeSortedArrays(nums, left, mid, right, temp); + for (let i = left; i <= right; i++) nums[i] = temp[i - left]; + return count; +} +function mergeSort(nums, left, right) { + if (left >= right) return 0; + let mid = left + (right - left) / 2; + let count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right); + count += merge(nums, left, mid, right); + return count; +} class Solution { -public: - int reversePairs(vector& nums) { - return reversePairsSub(nums, 0, nums.size() - 1); - } - -private: - int reversePairsSub(vector& nums, int l, int r) { - if (l >= r) return 0; - - int m = l + ((r - l) >> 1); - int res = reversePairsSub(nums, l, m) + reversePairsSub(nums, m + 1, r); + reversePairs(nums) { + return mergeSort(nums, 0, nums.length - 1); + } +} - int i = l, j = m + 1, k = 0, p = m + 1; - vector merge(r - l + 1); - while (i <= m) { - while (p <= r && nums[i] > 2L * nums[p]) p++; - res += p - (m + 1); + ``` - while (j <= r && nums[i] >= nums[j]) merge[k++] = nums[j++]; - merge[k++] = nums[i++]; - } + + + + ```typescript + function mergeSortedArrays(nums: number[], left: number, mid: number, right: number, temp: number[]) { + let i = left, j = mid + 1, k = 0; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) temp[k++] = nums[i++]; + else temp[k++] = nums[j++]; + } + while (i <= mid) temp[k++] = nums[i++]; + while (j <= right) temp[k++] = nums[j++]; +} - while (j <= r) merge[k++] = nums[j++]; +function merge(nums: number[], left: number, mid: number, right: number) { + let count = 0; + let j = mid + 1; + for (let i = left; i <= mid; i++) { + while (j <= right && nums[i] > 2 * nums[j]) j++; + count += j - mid - 1; + } + let temp = new Array(right - left + 1); + mergeSortedArrays(nums, left, mid, right, temp); + for (let i = left; i <= right; i++) nums[i] = temp[i - left]; + return count; +} +function mergeSort(nums: number[], left: number, right: number) { + if (left >= right) return 0; + let mid = left + (right - left) / 2; + let count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right); + count += merge(nums, left, mid, right); + return count; +} - copy(merge.begin(), merge.end(), nums.begin() + l); +class Solution { + reversePairs(nums: number[]) { + return mergeSort(nums, 0, nums.length - 1); + } +} - return res; - } -}; -``` + ``` + + + + + ```python + def merge_sorted_arrays(nums, left, mid, right, temp): + i, j, k = left, mid + 1, 0 + while i <= mid and j <= right: + if nums[i] <= nums[j]: + temp[k] = nums[i] + i += 1 + else: + temp[k] = nums[j] + j += 1 + k += 1 + while i <= mid: + temp[k] = nums[i] + i += 1 + k += 1 + while j <= right: + temp[k] = nums[j] + j += 1 + k += 1 + +def merge(nums, left, mid, right): + count = 0 + j = mid + 1 + for i in range(left, mid + 1): + while j <= right and nums[i] > 2 * nums[j]: + j += 1 + count += j - mid - 1 + temp = [0] * (right - left + 1) + merge_sorted_arrays(nums, left, mid, right, temp) + for i in range(left, right + 1): + nums[i] = temp[i - left] + return count + +def merge_sort(nums, left, right): + if left >= right: + return 0 + mid = left + (right - left) // 2 + count = merge_sort(nums, left, mid) + merge_sort(nums, mid + 1, right) + count += merge(nums, left, mid, right) + return count -### Java +class Solution: + def reversePairs(self, nums): + return merge_sort(nums, 0, len(nums) - 1) -```java -import java.util.Arrays; + ``` -class Solution { + + + + ```java + public class Solution { public int reversePairs(int[] nums) { return mergeSort(nums, 0, nums.length - 1); } - private int mergeSort(int[] nums, int left, int right) { - if (left >= right) return 0; - + public int mergeSort(int[] nums, int left, int right) { + if (left >= right) { + return 0; + } int mid = left + (right - left) / 2; int count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right); - + count += merge(nums, left, mid, right); + return count; + } + public int merge(int[] nums, int left, int mid, int right) { + int count = 0; int j = mid + 1; for (int i = left; i <= mid; i++) { - while (j <= right && nums[i] > 2L * nums[j]) j++; - count += j - (mid + 1); + while (j <= right && nums[i] > 2 * nums[j]) { + j++; + } + count += j - mid - 1; + } + int[] temp = new int[right - left + 1]; + mergeSortedArrays(nums, left, mid, right, temp); + for (int i = left; i <= right; i++) { + nums[i] = temp[i - left]; } - - Arrays.sort(nums, left, right + 1); return count; } -} -``` -### JavaScript + public void + mergeSortedArrays(int[] nums, int left, int mid, int right, int[] temp) { + int i = left, j = mid + 1, k = 0; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) { + temp[k++] = nums[i++]; + } else { + temp[k++] = nums[j++]; + } + } + while (i <= mid) { + temp[k++] = nums[i++]; + } + while (j <= right) { + temp[k++] = nums[j++]; + } + } +} -```javascript -var reversePairs = function (nums) { - function mergeSort(nums, left, right) { + ``` + + + + ```cpp + void mergeSortedArrays(vector& nums, int left, int mid, int right, vector& temp) { + int i = left, j = mid + 1, k = 0; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) temp[k++] = nums[i++]; + else temp[k++] = nums[j++]; + } + while (i <= mid) temp[k++] = nums[i++]; + while (j <= right) temp[k++] = nums[j++]; +} +int merge(vector& nums, int left, int mid, int right) { + int count = 0; + int j = mid + 1; + for (int i = left; i <= mid; i++) { + while (j <= right && nums[i] > 2 * nums[j]) j++; + count += j - mid - 1; + } + vector temp(right - left + 1); + mergeSortedArrays(nums, left, mid, right, temp); + for (int i = left; i <= right; i++) nums[i] = temp[i - left]; + return count; +} +int mergeSort(vector& nums, int left, int right) { if (left >= right) return 0; + int mid = left + (right - left) / 2; + int count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right); + count += merge(nums, left, mid, right); + return count; +} - let mid = left + Math.floor((right - left) / 2); - let count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right); - let j = mid + 1; - for (let i = left; i <= mid; i++) { - while (j <= right && nums[i] > 2 * nums[j]) j++; - count += j - (mid + 1); - } +class Solution { +public: + int reversePairs(vector& nums) { + return mergeSort(nums, 0, nums.size() - 1); - nums.splice( - left, - right - left + 1, - ...nums.slice(left, right + 1).sort((a, b) => a - b) - ); - return count; - } - return mergeSort(nums, 0, nums.length - 1); + } }; -``` + ``` + + + +### Complexity Analysis + +- **Time Complexity**: $$O(n*log(n))$$, where n is the length of the input array. This is because the solution uses a modified Merge Sort algorithm, which has a time complexity of O(n log n). + + +- **Space Complexity**: $$O(n)$$, where n is the length of the input array. This is because the solution uses a temporary array to store the merged sorted arrays. + + + +--- + +

Authors:

+ +
+{['Ishitamukherjee2004'].map(username => ( + +))} +
\ No newline at end of file From 2c666e09e704798cf95a3440a40868540095b1b9 Mon Sep 17 00:00:00 2001 From: ImmidiSivani <147423543+ImmidiSivani@users.noreply.github.com> Date: Thu, 18 Jul 2024 22:53:16 +0530 Subject: [PATCH 2/3] solution added for 3163 --- .../3000-3099/3163-string-compression-III.md | 241 ++++++++++++++++++ 1 file changed, 241 insertions(+) create mode 100644 dsa-solutions/lc-solutions/3000-3099/3163-string-compression-III.md diff --git a/dsa-solutions/lc-solutions/3000-3099/3163-string-compression-III.md b/dsa-solutions/lc-solutions/3000-3099/3163-string-compression-III.md new file mode 100644 index 000000000..4525848dd --- /dev/null +++ b/dsa-solutions/lc-solutions/3000-3099/3163-string-compression-III.md @@ -0,0 +1,241 @@ +--- +id: string-compression +title: String Compression Solution +sidebar_label: String Compression +tags: + - String Compression + - Brute Force + - Optimized + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the String Compression problem on LeetCode." +sidebar_position: 2 +--- + +In this tutorial, we will solve the String Compression problem using two different approaches: brute force and optimized. We will provide the implementation of the solution in C++, Java, and Python. + +## Problem Description + +Given a string `word`, compress it using the following algorithm: + +Begin with an empty string `comp`. While `word` is not empty, use the following operation: +Remove a maximum length prefix of `word` made of a single character `c` repeating at most 9 times. +Append the length of the prefix followed by `c` to `comp`. + +Return the string `comp`. + +### Examples + +**Example 1:** + +``` +Input: word = "abcde" +Output: "1a1b1c1d1e" +``` + +**Example 2:** + +``` +Input: word = "aaaaaaaaaaaaaabb" +Output: "9a5a2b" +``` + +### Constraints + +- `1 <= word.length <= 2 * 105` +- `word` consists only of lowercase English letters. + +--- + +## Solution for String Compression Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized approach. The brute force approach directly iterates through the string and constructs the result, while the optimized approach efficiently handles consecutive characters. + + + + +### Approach 1: Brute Force (Naive) + +The brute force approach iterates through each character of the string, counts consecutive characters up to 9, and appends the count followed by the character to the result string. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string compressString(string word) { + string comp; + int i = 0; + while (i < word.length()) { + char c = word[i]; + int count = 0; + while (i < word.length() && word[i] == c && count < 9) { + count++; + i++; + } + comp += to_string(count) + c; + } + return comp; + } +}; +``` + + + + + +```java +class Solution { + public String compressString(String word) { + StringBuilder comp = new StringBuilder(); + int i = 0; + while (i < word.length()) { + char c = word.charAt(i); + int count = 0; + while (i < word.length() && word.charAt(i) == c && count < 9) { + count++; + i++; + } + comp.append(count).append(c); + } + return comp.toString(); + } +} +``` + + + + + +```python +class Solution: + def compressString(self, word: str) -> str: + comp = [] + i = 0 + while i < len(word): + c = word[i] + count = 0 + while i < len(word) and word[i] == c and count < 9: + count += 1 + i += 1 + comp.append(f"{count}{c}") + return ''.join(comp) +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- Space Complexity: $O(n)$ +- Where `n` is the length of `word`. +- The time complexity is $O(n)$ because we iterate through the string once. +- The space complexity is $O(n)$ because we store the result in a new string. + + + + +### Approach 2: Optimized Approach + +The optimized approach is similar to the brute force but handles the prefix length more efficiently, ensuring it counts up to 9 characters in each iteration. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string compressString(string word) { + string comp; + int i = 0; + while (i < word.length()) { + char c = word[i]; + int count = 1; + while (i + count < word.length() && word[i + count] == c && count < 9) { + count++; + } + comp += to_string(count) + c; + i += count; + } + return comp; + } +}; +``` + + + + + +```java +class Solution { + public String compressString(String word) { + StringBuilder comp = new StringBuilder(); + int i = 0; + while (i < word.length()) { + char c = word.charAt(i); + int count = 1; + while (i + count < word.length() && word.charAt(i + count) == c && count < 9) { + count++; + } + comp.append(count).append(c); + i += count; + } + return comp.toString(); + } +} +``` + + + + + +```python +class Solution: + def compressString(self, word: str) -> str: + comp = [] + i = 0 + while i < len(word): + c = word[i] + count = 1 + while i + count < len(word) and word[i + count] == c and count < 9: + count += 1 + comp.append(f"{count}{c}") + i += count + return ''.join(comp) +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- Space Complexity: $O(n)$ +- Where `n` is the length of `word`. +- The time complexity is $O(n)$ because we iterate through the string once. +- The space complexity is $O(n)$ because we store the result in a new string. + + + + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
From 8c6c703e2e1544993d4287938f58ce7c584e28b0 Mon Sep 17 00:00:00 2001 From: Ajay Dhangar <99037494+Ajay-Dhangar@users.noreply.github.com> Date: Fri, 19 Jul 2024 22:11:09 +0530 Subject: [PATCH 3/3] Update 0493-reverse-pairs.md --- dsa-solutions/lc-solutions/0400-0499/0493-reverse-pairs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dsa-solutions/lc-solutions/0400-0499/0493-reverse-pairs.md b/dsa-solutions/lc-solutions/0400-0499/0493-reverse-pairs.md index 539422453..ec1d771d6 100644 --- a/dsa-solutions/lc-solutions/0400-0499/0493-reverse-pairs.md +++ b/dsa-solutions/lc-solutions/0400-0499/0493-reverse-pairs.md @@ -320,4 +320,4 @@ public:
{['Ishitamukherjee2004'].map(username => ( -))} \ No newline at end of file +))}