diff --git a/dsa-problems/gfg-problems/basic/problems.md b/dsa-problems/gfg-problems/basic/problems.md index 461cd1078..3482553ed 100644 --- a/dsa-problems/gfg-problems/basic/problems.md +++ b/dsa-problems/gfg-problems/basic/problems.md @@ -8,7 +8,6 @@ keywords: - gfg problems problems --- - export const problems = [ { "problemName": "1. Inorder Traversal", diff --git a/dsa-solutions/gfg-solutions/Easy problems/square-root.md b/dsa-solutions/gfg-solutions/Easy problems/square-root.md index f0c2eb177..cbe2cf0d3 100644 --- a/dsa-solutions/gfg-solutions/Easy problems/square-root.md +++ b/dsa-solutions/gfg-solutions/Easy problems/square-root.md @@ -3,8 +3,8 @@ id: square-root title: Square Root sidebar_label: Square-Root tags: - - Math - - Binary Search +- Math +- Binary Search description: "This document provides solutions to the problem of finding the Square Root of an integer." --- @@ -38,7 +38,6 @@ 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` ## Solution @@ -129,27 +128,25 @@ public: ```javascript class Solution { - floorSqrt(x) { - if (x === 0 || x === 1) { - return x; - } - let start = 1, - end = x, - ans = 0; - while (start <= end) { - let mid = Math.floor((start + end) / 2); - if (mid * mid === x) { - return mid; - } - if (mid * mid < x) { - start = mid + 1; - ans = mid; - } else { - end = mid - 1; - } + floorSqrt(x) { + if (x === 0 || x === 1) { + return x; + } + let start = 1, end = x, ans = 0; + while (start <= end) { + let mid = Math.floor((start + end) / 2); + if (mid * mid === x) { + return mid; + } + if (mid * mid < x) { + start = mid + 1; + ans = mid; + } else { + end = mid - 1; + } + } + return ans; } - return ans; - } } ``` @@ -158,27 +155,25 @@ class Solution { ```typescript class Solution { - floorSqrt(x: number): number { - if (x === 0 || x === 1) { - return x; - } - let start = 1, - end = x, - ans = 0; - while (start <= end) { - let mid = Math.floor((start + end) / 2); - if (mid * mid === x) { - return mid; - } - if (mid * mid < x) { - start = mid + 1; - ans = mid; - } else { - end = mid - 1; - } + floorSqrt(x: number): number { + if (x === 0 || x === 1) { + return x; + } + let start = 1, end = x, ans = 0; + while (start <= end) { + let mid = Math.floor((start + end) / 2); + if (mid * mid === x) { + return mid; + } + if (mid * mid < x) { + start = mid + 1; + ans = mid; + } else { + end = mid - 1; + } + } + return ans; } - return ans; - } } ``` @@ -190,4 +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)$ +**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/0200-0299/0240-search-a-2d-matrix-ii.md b/dsa-solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-ii.md index bdd389ce2..e3b9a1324 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 @@ -69,7 +69,6 @@ Output: false ### 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. @@ -77,7 +76,7 @@ This approach ensures that we eliminate one row or one column in each step, lead - + ### Approach: Greedy Search 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. @@ -109,7 +108,7 @@ const matrix = [ [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], - [18, 21, 23, 26, 30], + [18, 21, 23, 26, 30] ]; const target = 5; const result = searchMatrix(matrix, target); @@ -117,8 +116,13 @@ 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 + 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"} @@ -178,7 +182,7 @@ return ( ``` - + ```python def searchMatrix(matrix: List[List[int]], target: int) -> bool: @@ -255,7 +259,7 @@ return ( }; ``` - + #### Complexity Analysis @@ -265,8 +269,7 @@ return ( - 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)$. - + 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. @@ -284,8 +287,8 @@ This solution leverages the matrix's properties to reduce the search space effic ---- - + --- + @@ -303,7 +306,7 @@ This solution leverages the matrix's properties to reduce the search space effic params="autoplay=1&autohide=1&showinfo=0&rel=0" title="Search a 2D Matrix II Problem Explanation | Search a 2D Matrix II Solution" poster="maxresdefault" - webp + webp /> @@ -312,7 +315,7 @@ This solution leverages the matrix's properties to reduce the search space effic params="autoplay=1&autohide=1&showinfo=0&rel=0" title="Search a 2D Matrix II Problem Explanation | Search a 2D Matrix II Solution" poster="maxresdefault" - webp + webp /> @@ -325,7 +328,7 @@ This solution leverages the matrix's properties to reduce the search space effic params="autoplay=1&autohide=1&showinfo=0&rel=0" title="Search a 2D Matrix II Problem Explanation | Search a 2D Matrix II Solution" poster="maxresdefault" - webp + webp /> 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 4278ec3fb..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 @@ -2,15 +2,15 @@ id: Sort-Array-By-Parity title: Sort Array By Parity sidebar_label: Sort Array By Parity -tags: - - Arrays - - Sorting +tags: + - Arrays + - Sorting --- ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :-------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | :--------------------------------------------------- | +| 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/) | ## Problem Description @@ -21,13 +21,13 @@ Return any array that satisfies this condition. ### Example 1: -**Input:** `nums = [3, 1, 2, 4]` -**Output:** `[2, 4, 3, 1]` +**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 2: -**Input:** `nums = [0]` +**Input:** `nums = [0]` **Output:** `[0]` ## Constraints @@ -64,7 +64,7 @@ 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) { even.add(num); @@ -72,11 +72,11 @@ public class EvenOddArray { odd.add(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] @@ -122,7 +122,7 @@ int main() { 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]; @@ -142,7 +142,7 @@ int main() { int numsSize = sizeof(nums) / sizeof(nums[0]); int returnSize; sortArrayByParity(nums, numsSize, &returnSize); - + for (int i = 0; i < numsSize; ++i) { printf("%d ", nums[i]); } @@ -155,23 +155,23 @@ int main() { ```javascript function sortArrayByParity(nums) { - let even = []; - let odd = []; - - for (let num of nums) { - if (num % 2 === 0) { - even.push(num); - } else { - odd.push(num); + let even = []; + let odd = []; + + for (let num of nums) { + if (num % 2 === 0) { + even.push(num); + } else { + odd.push(num); + } } - } - - return [...even, ...odd]; + + return [...even, ...odd]; } // Example usage let nums = [3, 1, 2, 4]; -console.log(sortArrayByParity(nums)); // Output: [2, 4, 3, 1] +console.log(sortArrayByParity(nums)); // Output: [2, 4, 3, 1] ``` ## Step-by-Step Algorithm @@ -185,4 +185,4 @@ console.log(sortArrayByParity(nums)); // Output: [2, 4, 3, 1] ## 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. +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/dsa-solutions/lc-solutions/0900-0999/0906-super-palindromes.md b/dsa-solutions/lc-solutions/0900-0999/0906-super-palindromes.md index bdc410957..b4c6801dc 100644 --- a/dsa-solutions/lc-solutions/0900-0999/0906-super-palindromes.md +++ b/dsa-solutions/lc-solutions/0900-0999/0906-super-palindromes.md @@ -2,15 +2,15 @@ id: super-palindromes title: Super Palindromes sidebar_label: Super Palindromes -tags: - - Palindrome - - Math +tags: + - Palindrome + - Math --- ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :-------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------- | :--------------------------------------------------- | +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | | [Super Palindromes](https://leetcode.com/problems/super-palindromes/description/) | [Super Palindromes Solution on LeetCode](https://leetcode.com/problems/super-palindromes/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | ## Problem Description @@ -62,7 +62,7 @@ def super_palindromes(left, right): left, right = int(left), int(right) count = 0 limit = int(math.sqrt(right)) + 1 - + for i in range(1, limit): s = str(i) pal = s + s[::-1] @@ -71,14 +71,14 @@ def super_palindromes(left, right): break if num >= left and is_palindrome(str(num)): count += 1 - + pal = s + s[-2::-1] num = int(pal) ** 2 if num > right: break if num >= left and is_palindrome(str(num)): count += 1 - + return count ``` @@ -178,7 +178,7 @@ int superPalindromes(char* left, char* right) { for (long long i = 1; i < limit; i++) { sprintf(s, "%lld", i); int len = strlen(s); - + // Palindrome of even length snprintf(pal, 40, "%s%s", s, strrev(strdup(s))); long long num1 = atoll(pal) * atoll(pal); @@ -200,29 +200,28 @@ int superPalindromes(char* left, char* right) { ```javascript function isPalindrome(s) { - return s === s.split("").reverse().join(""); + return s === s.split('').reverse().join(''); } function superPalindromes(left, right) { - let l = BigInt(left), - r = BigInt(right); - let count = 0; - let limit = BigInt(Math.sqrt(Number(r))) + BigInt(1); - - for (let i = BigInt(1); i < limit; i++) { - let s = i.toString(); - let pal1 = s + s.split("").reverse().join(""); - let num1 = BigInt(pal1) ** BigInt(2); - if (num1 > r) break; - if (num1 >= l && isPalindrome(num1.toString())) count++; - - let pal2 = s + s.slice(0, -1).split("").reverse().join(""); - let num2 = BigInt(pal2) ** BigInt(2); - if (num2 > r) break; - if (num2 >= l && isPalindrome(num2.toString())) count++; - } - - return count; + let l = BigInt(left), r = BigInt(right); + let count = 0; + let limit = BigInt(Math.sqrt(Number(r))) + BigInt(1); + + for (let i = BigInt(1); i < limit; i++) { + let s = i.toString(); + let pal1 = s + s.split('').reverse().join(''); + let num1 = BigInt(pal1) ** BigInt(2); + if (num1 > r) break; + if (num1 >= l && isPalindrome(num1.toString())) count++; + + let pal2 = s + s.slice(0, -1).split('').reverse().join(''); + let num2 = BigInt(pal2) ** BigInt(2); + if (num2 > r) break; + if (num2 >= l && isPalindrome(num2.toString())) count++; + } + + return count; } ``` @@ -231,13 +230,12 @@ function superPalindromes(left, right) { 1. **Generate Palindromes:** - Iterate through possible values of `i` from 1 to the square root of the right boundary. - Construct palindromes by concatenating `s` with its reverse and with its reverse minus the last character. + 2. **Square Palindromes:** - - Compute the square of each palindrome. - Check if the squared value is within the range `[left, right]`. 3. **Check for Super-Palindromes:** - - Verify if the squared palindrome is also a palindrome. 4. **Count and Return:**