From 4fa2599067837d5e5ad485578a2e60c442f0634e Mon Sep 17 00:00:00 2001 From: lovely mahour <141830010+lovelymahor@users.noreply.github.com> Date: Fri, 9 Aug 2024 16:37:14 +0530 Subject: [PATCH 1/2] Your commit message --- .../Easy problems/square-root.md | 20 +- .../0138-copy-list-with-random-pointer.md | 280 +++++++----------- .../0900-0999/0905-sort-array-by-parity.md | 229 ++++++++------ package-lock.json | 14 +- 4 files changed, 261 insertions(+), 282 deletions(-) diff --git a/dsa-solutions/gfg-solutions/Easy problems/square-root.md b/dsa-solutions/gfg-solutions/Easy problems/square-root.md index 9777b7f9e..640a3c101 100644 --- a/dsa-solutions/gfg-solutions/Easy problems/square-root.md +++ b/dsa-solutions/gfg-solutions/Easy problems/square-root.md @@ -1,16 +1,11 @@ --- id: square-root title: Square Root -sidebar_label: 9 Square Root +sidebar_label: Square-Root tags: - Math - Binary Search -- Python -- Java -- C++ -- JavaScript -- TypeScript -description: "This document provides solutions to the problem of finding the square root of a given integer using various programming languages." +description: "This document provides solutions to the problem of finding the Square Root of an integer." --- ## Problem @@ -43,7 +38,7 @@ You don't need to read input or print anything. The task is to complete the func **Expected Auxiliary Space:** $O(1)$ **Constraints** -- $1 ≤ x ≤ 10^7$ +- `1 ≤ x ≤ 10^7` ## Solution @@ -190,11 +185,4 @@ class Solution { The provided solutions efficiently find the floor value of the square root of a given integer `x` using binary search. This approach ensures a time complexity of $ O(log N) and an auxiliary space complexity of $O(1)$. The algorithms are designed to handle large values of `x` up to 10^7 efficiently without relying on built-in square root functions. **Time Complexity:** $O(log N)$ -**Auxiliary Space:** $O(1)$ - ---- - -## References - -- **GeeksforGeeks Problem:** [Square root](https://www.geeksforgeeks.org/problems/square-root/0) -- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/) \ No newline at end of file +**Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/lc-solutions/0100-0199/0138-copy-list-with-random-pointer.md b/dsa-solutions/lc-solutions/0100-0199/0138-copy-list-with-random-pointer.md index c89d28116..af38b51f5 100644 --- a/dsa-solutions/lc-solutions/0100-0199/0138-copy-list-with-random-pointer.md +++ b/dsa-solutions/lc-solutions/0100-0199/0138-copy-list-with-random-pointer.md @@ -1,227 +1,169 @@ --- - id: copy-list-with-random-pointer -title: Copy List With Random Pointer -level: medium -sidebar_label: Copy List With Random Pointer +title: Copy List with Random Pointer +sidebar_label: 0138 Copy List with Random Pointer tags: - - Hash Table - - Linked List - Java - Python - C++ -description: "This document provides solutions for the Copy List With Random Pointer problem on LeetCode." - + - JavaScript + +description: "This is a solution to the Copy List with Random Pointer problem on LeetCode." --- ## Problem Description -A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. +A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. + +Construct a deep copy of the list. The deep copy should consist of exactly `n` brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. -Construct a deep copy of the list. +For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. ### Examples **Example 1:** + +![e1](https://github.com/user-attachments/assets/af16a7ff-3439-4683-8f77-9fdbb3332bef) + ``` Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] ``` **Example 2:** + +![e2](https://github.com/user-attachments/assets/f805c77f-c6cd-4b92-9f9a-c17665bfa317) + ``` Input: head = [[1,1],[2,1]] Output: [[1,1],[2,1]] -``` -**Example 3:** ``` -Input: head = [[3,null],[3,0],[3,null]] -Output: [[3,null],[3,0],[3,null]] -``` - -### Constraints: - -- The number of nodes in the list is in the range [0, 1000]. -- `-10000 <= Node.val <= 10000` -- Node.random is null or is pointing to a node in the linked list. --- -## Approach to Solve the Copy List with Random Pointer Problem +## Solution for Copy List with Random Pointer -To create a deep copy of a linked list with an additional random pointer, follow these steps: -### Approach +### Understand the Problem: -1. **Create Clones Adjacent to Original Nodes:** - - Iterate through the original list and create a new node for each original node. Insert this new node right next to the original node. This way, each original node will have its clone right next to it. +Create a deep copy of a linked list where each node has a `next` and a `random` pointer. The new list should be identical in structure to the original, but with all new nodes. Ensure the `random` pointers in the new list accurately reflect the original's `random` pointer relationships. -2. **Assign Random Pointers to Cloned Nodes:** - - Iterate through the list again. For each original node, if it has a random pointer, set the random pointer of the clone node to point to the clone of the node that the original node’s random pointer is pointing to. This can be achieved because the clone of any node `A` is next to `A`. +### Approach -3. **Restore the Original List and Extract the Cloned List:** - - Iterate through the list once more to restore the original list by separating the original nodes from their clones. Extract the cloned list by linking the cloned nodes together. +1. **Interweaving Nodes**: Create and insert new nodes immediately after each original node, forming an interwoven list. +2. **Assigning Random Pointers**: Set the `random` pointers of the new nodes based on the `random` pointers of the original nodes. +3. **Separating Lists**: Restore the original list and extract the copied list by adjusting the `next` pointers of both original and new nodes. #### Code in Different Languages -### C++ -```cpp -class Node { -public: - int val; - Node* next; - Node* random; - - Node(int _val) { - val = _val; - next = NULL; - random = NULL; - } -}; - -class Solution { -public: - Node* copyRandomList(Node* head) { - if (!head) return nullptr; - - // Step 1: Create a new node for each original node and insert it next to the original node. - Node* curr = head; - while (curr) { - Node* newNode = new Node(curr->val); - newNode->next = curr->next; - curr->next = newNode; - curr = newNode->next; - } + + + + - // Step 2: Assign random pointers for the new nodes. - curr = head; - while (curr) { - if (curr->random) { - curr->next->random = curr->random->next; - } - curr = curr->next->next; - } + - // Step 3: Restore the original list and extract the copied list. - curr = head; - Node* copiedHead = head->next; - Node* copiedCurr = copiedHead; - while (curr) { - curr->next = curr->next->next; - if (copiedCurr->next) { - copiedCurr->next = copiedCurr->next->next; - } - curr = curr->next; - copiedCurr = copiedCurr->next; - } + ```python - return copiedHead; - } -}; -``` +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = x + self.next = next + self.random = random -### Java -```java +def copyRandomList(head: 'Node') -> 'Node': + if not head: + return None + + current = head + while current: + new_node = Node(current.val, current.next, None) + current.next = new_node + current = new_node.next + + current = head + while current: + if current.random: + current.next.random = current.random.next + current = current.next.next + + original = head + copy = head.next + copy_head = copy + + while original: + original.next = original.next.next + if copy.next: + copy.next = copy.next.next + original = original.next + copy = copy.next + + return copy_head + + ``` + + + + + + + ```JS class Node { - int val; - Node next; - Node random; - - public Node(int val) { + constructor(val, next = null, random = null) { this.val = val; - this.next = null; - this.random = null; + this.next = next; + this.random = random; } } -class Solution { - public Node copyRandomList(Node head) { - if (head == null) return null; - - // Step 1: Create a new node for each original node and insert it next to the original node. - Node curr = head; - while (curr != null) { - Node newNode = new Node(curr.val); - newNode.next = curr.next; - curr.next = newNode; - curr = newNode.next; - } - - // Step 2: Assign random pointers for the new nodes. - curr = head; - while (curr != null) { - if (curr.random != null) { - curr.next.random = curr.random.next; - } - curr = curr.next.next; +function copyRandomList(head) { + if (!head) return null; + + let current = head; + while (current) { + const newNode = new Node(current.val); + newNode.next = current.next; + current.next = newNode; + current = newNode.next; + } + + current = head; + while (current) { + if (current.random) { + current.next.random = current.random.next; } - - // Step 3: Restore the original list and extract the copied list. - curr = head; - Node copiedHead = head.next; - Node copiedCurr = copiedHead; - while (curr != null) { - curr.next = curr.next.next; - if (copiedCurr.next != null) { - copiedCurr.next = copiedCurr.next.next; - } - curr = curr.next; - copiedCurr = copiedCurr.next; + current = current.next.next; + } + current = head; + const newHead = head.next; + let copyCurrent = newHead; + + while (current) { + current.next = current.next.next; + if (copyCurrent.next) { + copyCurrent.next = copyCurrent.next.next; } - - return copiedHead; + current = current.next; + copyCurrent = copyCurrent.next; } + + return newHead; } + ``` + + + + -### Python -```python -class Node: - def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): - self.val = x - self.next = next - self.random = random +### Output -class Solution: - def copyRandomList(self, head: 'Node') -> 'Node': - if not head: - return None - - # Step 1: Create a new node for each original node and insert it next to the original node. - curr = head - while curr: - newNode = Node(curr.val) - newNode.next = curr.next - curr.next = newNode - curr = newNode.next - - # Step 2: Assign random pointers for the new nodes. - curr = head - while curr: - if curr.random: - curr.next.random = curr.random.next - curr = curr.next.next - - # Step 3: Restore the original list and extract the copied list. - curr = head - copiedHead = head.next - copiedCurr = copiedHead - while curr: - curr.next = curr.next.next - if copiedCurr.next: - copiedCurr.next = copiedCurr.next.next - curr = curr.next - copiedCurr = copiedCurr.next - - return copiedHead -``` +![Screenshot from 2024-07-19 21-11-44](https://github.com/user-attachments/assets/2c2a7efb-711d-4f6e-aebd-8f540de015c3) ### Complexity -- **Time Complexity:** $O(n)$ - Each of the three steps involves a single pass through the list. -- **Space Complexity:** $O(1)$ - The space complexity is constant as we are not using any additional data structures for storage. +- **Time Complexity:** O(n), where `n` is the number of nodes in the linked list. The algorithm iterates through the list three times: once for interweaving nodes, once for setting random pointers, and once for separating the lists. -### Summary +- **Space Complexity:** O(1), since the algorithm uses a constant amount of extra space beyond the input list itself (e.g., pointers for traversal and temporary variables). -This approach efficiently creates a deep copy of a linked list with random pointers by leveraging the existing structure of the list and ensuring that each node and its clone are linked adjacently. diff --git a/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md b/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md index fb5a1dfcc..4eacd7aa6 100644 --- a/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md +++ b/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md @@ -1,141 +1,188 @@ --- -id: sort-array-by-parity +id: Sort-Array-By-Parity title: Sort Array By Parity -sidebar_label: 0905 - Sort Array By Parity -tags: - - easy - - Arrays - - Algorithms +sidebar_label: Sort Array By Parity +tags: + - Arrays + - Sorting --- ## Problem Description -Given an integer array `nums`, move all the even integers to the beginning of the array followed by all the odd integers. +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/description/) | [Sort Array By Parity Solution on LeetCode](https://leetcode.com/problems/sort-array-by-parity/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | -Return any array that satisfies this condition. +## Problem Description -## Examples +Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. -**Example 1:** +Return any array that satisfies this condition. -``` -Input: nums = [3,1,2,4] -Output: [2,4,3,1] -Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. -``` +### Example 1: -**Example 2:** +**Input:** `nums = [3, 1, 2, 4]` +**Output:** `[2, 4, 3, 1]` +**Explanation:** The outputs `[4, 2, 3, 1]`, `[2, 4, 1, 3]`, and `[4, 2, 1, 3]` would also be accepted. -``` -Input: nums = [0] -Output: [0] -``` +### Example 2: + +**Input:** `nums = [0]` +**Output:** `[0]` ## Constraints -``` -1 <= nums.length <= 5000 -0 <= nums[i] <= 5000 -``` +- `1 <= nums.length <= 5000` +- `0 <= nums[i] <= 5000` + +## Approach + +1. **Identify even and odd integers**: Iterate through the array and separate the even and odd integers. +2. **Rearrange the array**: Place all even integers at the beginning of the array followed by the odd integers. ## Solution ### Python ```python -class Solution: - def sortArrayByParity(self, nums): - return [x for x in nums if x % 2 == 0] + [x for x in nums if x % 2 != 0] - -# Example usage: -solution = Solution() -print(solution.sortArrayByParity([3,1,2,4])) # Output: [2,4,3,1] +def sortArrayByParity(nums): + even = [x for x in nums if x % 2 == 0] + odd = [x for x in nums if x % 2 != 0] + return even + odd + +# Example usage +nums = [3, 1, 2, 4] +print(sortArrayByParity(nums)) # Output: [2, 4, 3, 1] ``` -### C++ +### Java -```cpp -#include -#include +```java +import java.util.*; -class Solution { -public: - std::vector sortArrayByParity(std::vector& nums) { - std::vector result; +public class EvenOddArray { + public static int[] sortArrayByParity(int[] nums) { + List even = new ArrayList<>(); + List odd = new ArrayList<>(); + for (int num : nums) { if (num % 2 == 0) { - result.push_back(num); + even.add(num); + } else { + odd.add(num); } } - for (int num : nums) { - if (num % 2 != 0) { - result.push_back(num); - } + + even.addAll(odd); + return even.stream().mapToInt(i -> i).toArray(); + } + + public static void main(String[] args) { + int[] nums = {3, 1, 2, 4}; + System.out.println(Arrays.toString(sortArrayByParity(nums))); // Output: [2, 4, 3, 1] + } +} +``` + +### C++ + +```cpp +#include +#include + +std::vector sortArrayByParity(std::vector& nums) { + std::vector even, odd; + for (int num : nums) { + if (num % 2 == 0) { + even.push_back(num); + } else { + odd.push_back(num); } - return result; } -}; + even.insert(even.end(), odd.begin(), odd.end()); + return even; +} -// Example usage: int main() { - Solution solution; std::vector nums = {3, 1, 2, 4}; - std::vector result = solution.sortArrayByParity(nums); // Output: [2, 4, 3, 1] - return 0; + std::vector result = sortArrayByParity(nums); + for (int num : result) { + std::cout << num << " "; + } + // Output: 2 4 3 1 } ``` -### Java - -```java -import java.util.ArrayList; -import java.util.List; - -class Solution { - public int[] sortArrayByParity(int[] nums) { - List result = new ArrayList<>(); - for (int num : nums) { - if (num % 2 == 0) { - result.add(num); - } - } - for (int num : nums) { - if (num % 2 != 0) { - result.add(num); - } +### C + +```c +#include +#include + +void sortArrayByParity(int* nums, int numsSize, int* returnSize) { + int* result = (int*)malloc(numsSize * sizeof(int)); + int evenIndex = 0, oddIndex = numsSize - 1; + + for (int i = 0; i < numsSize; ++i) { + if (nums[i] % 2 == 0) { + result[evenIndex++] = nums[i]; + } else { + result[oddIndex--] = nums[i]; } - return result.stream().mapToInt(i -> i).toArray(); } + *returnSize = numsSize; + for (int i = 0; i < numsSize; ++i) { + nums[i] = result[i]; + } + free(result); +} - public static void main(String[] args) { - Solution solution = new Solution(); - int[] nums = {3, 1, 2, 4}; - int[] result = solution.sortArrayByParity(nums); // Output: [2, 4, 3, 1] - for (int num : result) { - System.out.print(num + " "); - } +int main() { + int nums[] = {3, 1, 2, 4}; + int numsSize = sizeof(nums) / sizeof(nums[0]); + int returnSize; + sortArrayByParity(nums, numsSize, &returnSize); + + for (int i = 0; i < numsSize; ++i) { + printf("%d ", nums[i]); } + // Output: 2 4 3 1 + return 0; } ``` ### JavaScript ```javascript -var sortArrayByParity = function (nums) { - let result = []; - for (let num of nums) { - if (num % 2 === 0) { - result.push(num); - } - } - for (let num of nums) { - if (num % 2 !== 0) { - result.push(num); +function sortArrayByParity(nums) { + let even = []; + let odd = []; + + for (let num of nums) { + if (num % 2 === 0) { + even.push(num); + } else { + odd.push(num); + } } - } - return result; -}; + + return [...even, ...odd]; +} -// Example usage: -console.log(sortArrayByParity([3, 1, 2, 4])); // Output: [2, 4, 3, 1] +// Example usage +let nums = [3, 1, 2, 4]; +console.log(sortArrayByParity(nums)); // Output: [2, 4, 3, 1] ``` + +## Step-by-Step Algorithm + +1. Initialize two empty lists/arrays: one for even integers and one for odd integers. +2. Iterate through the given array: + - If the current integer is even, add it to the even list/array. + - If the current integer is odd, add it to the odd list/array. +3. Concatenate the even list/array with the odd list/array. +4. Return the concatenated list/array. + +## Conclusion + +This problem can be solved efficiently by iterating through the array once and separating the integers into even and odd lists/arrays. The time complexity is O(n), where n is the length of the array, making this approach optimal for the given constraints. \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index e6cf0d7ab..36b8ed9f2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9414,9 +9414,10 @@ } }, "node_modules/docusaurus2-dotenv/node_modules/terser-webpack-plugin": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.4.5.tgz", - "integrity": "sha512-04Rfe496lN8EYruwi6oPQkG0vo8C+HT49X687FZnpPF0qMAIHONI6HEXYPKDOE8e5HjXTyKfqRd/agHtH0kOtw==", + "version": "1.4.6", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.4.6.tgz", + "integrity": "sha512-2lBVf/VMVIddjSn3GqbT90GvIJ/eYXJkt8cTzU7NbjKqK8fwv18Ftr4PlbF46b/e88743iZFL5Dtr/rC4hjIeA==", + "license": "MIT", "peer": true, "dependencies": { "cacache": "^12.0.2", @@ -9753,9 +9754,10 @@ "integrity": "sha512-JWKDyqAdltuUcyxaECtYG6H4sqysXSLeoXuGUBfRNESMTkj+w+qdb0jya8Z/WI0jVd03WQtCGhS6FOFtlhD5FQ==" }, "node_modules/elliptic": { - "version": "6.5.5", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.5.tgz", - "integrity": "sha512-7EjbcmUm17NQFu4Pmgmq2olYMj8nwMnpcddByChSUjArp8F5DQWcIcpriwO4ZToLNAJig0yiyjswfyGNje/ixw==", + "version": "6.5.6", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.6.tgz", + "integrity": "sha512-mpzdtpeCLuS3BmE3pO3Cpp5bbjlOPY2Q0PgoF+Od1XZrHLYI28Xe3ossCmYCQt11FQKEYd9+PF8jymTvtWJSHQ==", + "license": "MIT", "peer": true, "dependencies": { "bn.js": "^4.11.9", From dc6bbcf7169f3fcda7f2a7e8479c83bca5c7da68 Mon Sep 17 00:00:00 2001 From: lovely mahour <141830010+lovelymahor@users.noreply.github.com> Date: Sat, 10 Aug 2024 17:35:13 +0530 Subject: [PATCH 2/2] Add Newsletter Subscription Section to Footer --- docusaurus.config.js | 18 + .../0200-0299/0240-search-a-2d-matrix-II.md | 354 ++---------------- src/css/custom.css | 26 ++ 3 files changed, 78 insertions(+), 320 deletions(-) diff --git a/docusaurus.config.js b/docusaurus.config.js index 3170eed21..238fb3572 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -397,6 +397,24 @@ const config = { }, ], }, + // Add a new section for the LinkedIn newsletter + { + title: "Newsletter", + items: [ + { + html: ` + + `, + }, + ], + }, + ], logo: { alt: "Powered by CodeHarborHub | Product Hunt", diff --git a/dsa-solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-II.md b/dsa-solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-II.md index e3b9a1324..85c5c6f1a 100644 --- a/dsa-solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-II.md +++ b/dsa-solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-II.md @@ -1,335 +1,49 @@ --- id: search-a-2d-matrix-ii -title: Search a 2D Matrix II Solution -sidebar_label: 0240 - Search a 2D Matrix II +title: Search A 2D Matrix ii +sidebar_label: 0240-Search A 2D Matrix ii tags: - - Search a 2D Matrix II - - Array - - Binary Search - - Divide and Conquer - - Matrix - - LeetCode - - JavaScript - - TypeScript -description: "This is a solution to the Search a 2D Matrix II problem on LeetCode." -sidebar_position: 240 + - DP + - Leet code +description: "Solution to leetocde 240" --- -In this tutorial, we will solve the Search a 2D Matrix II problem using efficient search techniques. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++. +## Approach +The approach involves starting from the top-right corner of the matrix and iteratively narrowing down the search based on comparisons with the target. -## Problem Description +1. Initialize `m` and `n` to the number of rows and columns in the matrix, respectively. Also, initialize `r` to 0 (the topmost row) and `c` to `n - 1` (the rightmost column). +2. Enter a while loop that continues as long as the current position is within the matrix (`r < m` and `c >= 0`). +3. Inside the loop, compare the element at the current position (`r, c`) with the target. + - If they are equal, it means the target is found, and the function returns `true`. + - If the element is greater than the target, update `c` to move to the left, narrowing down the search. + - If the element is less than the target, update `r` to move downwards, narrowing down the search. +4. The loop continues until the search range is exhausted or the target is found. +5. If the loop completes without finding the target, the function returns `false`. -Write an efficient algorithm that searches for a value in an `m x n` matrix. This matrix has the following properties: +## Time Complexity +The time complexity of this code is `O(m + n)`, where `m` is the number of rows and `n` is the number of columns in the matrix. In each iteration of the while loop, either `r` is incremented or `c` is decremented, leading to a total of at most `m + n` iterations. -- Integers in each row are sorted in ascending order from left to right. -- Integers in each column are sorted in ascending order from top to bottom. +## Space Complexity +The space complexity of this code is `O(1)` because it uses only a constant amount of extra space for variables (`m`, `n`, `r`, `c`). The space usage does not depend on the size of the input matrix. -### Examples +```cpp +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { -**Example 1:** + int m = matrix.size(), n = matrix[0].size(), r = 0, c = n - 1; -```plaintext -Input: matrix = [ - [1, 4, 7, 11, 15], - [2, 5, 8, 12, 19], - [3, 6, 9, 16, 22], - [10, 13, 14, 17, 24], - [18, 21, 23, 26, 30] -], target = 5 -Output: true -``` - -**Example 2:** - -```plaintext -Input: matrix = [ - [1, 4, 7, 11, 15], - [2, 5, 8, 12, 19], - [3, 6, 9, 16, 22], - [10, 13, 14, 17, 24], - [18, 21, 23, 26, 30] -], target = 20 -Output: false -``` - -### Constraints - -- `m == matrix.length` -- `n == matrix[i].length` -- $1 \leq n, m \leq 300$ -- $-10^9 \leq \text{matrix[i][j]} \leq 10^9$ -- All the integers in each row are sorted in ascending order. -- All the integers in each column are sorted in ascending order. -- $-10^9 \leq target \leq 10^9$ - ---- - -## Solution for Search a 2D Matrix II - -### Intuition and Approach - -To search for a value in this matrix efficiently, we can utilize the properties of the matrix. Since the matrix is sorted both row-wise and column-wise, we can start our search from the top-right corner of the matrix. From here, we have two options: -1. If the target is greater than the current value, move downwards. -2. If the target is less than the current value, move leftwards. - -This approach ensures that we eliminate one row or one column in each step, leading to an efficient search. - - - - -### Approach: Greedy Search + while (r < m && c >= 0){ -By leveraging the sorted properties of the matrix, we can search for the target value efficiently using a greedy approach. This involves starting from the top-right corner and adjusting our search direction based on the current value. + if (matrix[r][c] == target) + return true; + else if(matrix[r][c] > target) + c--; + else + r++; + } -#### Implementation - -```jsx live -function searchMatrix(matrix, target) { - if (!matrix || matrix.length === 0 || matrix[0].length === 0) return false; - let rows = matrix.length; - let cols = matrix[0].length; - let row = 0; - let col = cols - 1; - - while (row < rows && col >= 0) { - if (matrix[row][col] === target) { - return true; - } else if (matrix[row][col] > target) { - col--; - } else { - row++; - } - } - return false; + return false; + } } - -const matrix = [ - [1, 4, 7, 11, 15], - [2, 5, 8, 12, 19], - [3, 6, 9, 16, 22], - [10, 13, 14, 17, 24], - [18, 21, 23, 26, 30] -]; -const target = 5; -const result = searchMatrix(matrix, target); - -return ( -
-

- Input: matrix = [ - [1, 4, 7, 11, 15], - [2, 5, 8, 12, 19], - [3, 6, 9, 16, 22], - [10, 13, 14, 17, 24], - [18, 21, 23, 26, 30] - ], target = 5 -

-

- Output: {result ? "true" : "false"} -

-
-); ``` - -#### Codes in Different Languages - - - - - ```javascript - function searchMatrix(matrix, target) { - if (!matrix || matrix.length === 0 || matrix[0].length === 0) return false; - let rows = matrix.length; - let cols = matrix[0].length; - let row = 0; - let col = cols - 1; - - while (row < rows && col >= 0) { - if (matrix[row][col] === target) { - return true; - } else if (matrix[row][col] > target) { - col--; - } else { - row++; - } - } - return false; - } - ``` - - - - - ```typescript - function searchMatrix(matrix: number[][], target: number): boolean { - if (!matrix || matrix.length === 0 || matrix[0].length === 0) return false; - let rows = matrix.length; - let cols = matrix[0].length; - let row = 0; - let col = cols - 1; - - while (row < rows && col >= 0) { - if (matrix[row][col] === target) { - return true; - } else if (matrix[row][col] > target) { - col--; - } else { - row++; - } - } - return false; - } - ``` - - - - - ```python - def searchMatrix(matrix: List[List[int]], target: int) -> bool: - if not matrix or not matrix[0]: - return False - rows = len(matrix) - cols = len(matrix[0]) - row = 0 - col = cols - 1 - - while row < rows and col >= 0: - if matrix[row][col] == target: - return True - elif matrix[row][col] > target: - col -= 1 - else: - row += 1 - - return False - ``` - - - - - ```java - class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { - return false; - } - int rows = matrix.length; - int cols = matrix[0].length; - int row = 0; - int col = cols - 1; - - while (row < rows && col >= 0) { - if (matrix[row][col] == target) { - return true; - } else if (matrix[row][col] > target) { - col--; - } else { - row++; - } - } - return false; - } - } - ``` - - - - - ```cpp - class Solution { - public: - bool searchMatrix(vector>& matrix, int target) { - if (matrix.empty() || matrix[0].empty()) return false; - int rows = matrix.size(); - int cols = matrix[0].size(); - int row = 0; - int col = cols - 1; - - while (row < rows && col >= 0) { - if (matrix[row][col] == target) { - return true; - } else if (matrix[row][col] > target) { - col--; - } else { - row++; - } - } - return false; - } - }; - ``` - - - - -#### Complexity Analysis - -- **Time Complexity:** $O(m + n)$, where `m` is the number of rows and `n` is the number of columns. -- **Space Complexity:** $O(1)$, as we are not using any additional space. - -- The time complexity is linear in terms of the dimensions of the matrix. Each step eliminates either a row or a - - column, leading to a linear time complexity of $O(m + n)$. -- The space complexity is constant because we only use a few extra variables regardless of the matrix size. - -
-
- -:::tip Note -This solution leverages the matrix's properties to reduce the search space efficiently, making it suitable for large matrices. -::: - ---- - -## Video Explanation of Search a 2D Matrix II - - - - - - --- - - - - - - - - - - - - - - - - - - - - - diff --git a/src/css/custom.css b/src/css/custom.css index fc2716e1f..c36d07e10 100644 --- a/src/css/custom.css +++ b/src/css/custom.css @@ -160,6 +160,32 @@ mark { .footer_info--container { width: 380px; } +.newsletter-subscription { + text-align: center; + margin: 1rem 0; +} + +.newsletter-subscription h4 { + margin-bottom: 0.5rem; +} + +.newsletter-subscription p { + margin-bottom: 0.5rem; +} + +.newsletter-subscription a { + padding: 0.5rem 1rem; + border: none; + background-color: #007bff; + color: #fff; + border-radius: 4px; + text-decoration: none; + display: inline-block; +} + +.newsletter-subscription a:hover { + background-color: #0056b3; +} .footer_info--container img { width: 62px;