diff --git a/dsa-solutions/gfg-solutions/Easy problems/square-root.md b/dsa-solutions/gfg-solutions/Easy problems/square-root.md index 640a3c101..9777b7f9e 100644 --- a/dsa-solutions/gfg-solutions/Easy problems/square-root.md +++ b/dsa-solutions/gfg-solutions/Easy problems/square-root.md @@ -1,11 +1,16 @@ --- id: square-root title: Square Root -sidebar_label: Square-Root +sidebar_label: 9 Square Root tags: - Math - Binary Search -description: "This document provides solutions to the problem of finding the Square Root of an integer." +- 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." --- ## Problem @@ -38,7 +43,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 @@ -185,4 +190,11 @@ 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)$ \ No newline at end of file +**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 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 af38b51f5..c89d28116 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,169 +1,227 @@ --- + id: copy-list-with-random-pointer -title: Copy List with Random Pointer -sidebar_label: 0138 Copy List with Random Pointer +title: Copy List With Random Pointer +level: medium +sidebar_label: Copy List With Random Pointer tags: + - Hash Table + - Linked List - Java - Python - C++ - - JavaScript - -description: "This is a solution to the Copy List with Random Pointer problem on LeetCode." +description: "This document provides solutions for the Copy List With Random Pointer problem on LeetCode." + --- ## Problem Description -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. +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. -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`. +Construct a deep copy of the list. ### 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: -## Solution for Copy List with Random Pointer +- 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. +--- -### Understand the Problem: +## Approach to Solve the Copy List with Random Pointer Problem -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. +To create a deep copy of a linked list with an additional random pointer, follow these steps: ### Approach -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. +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. + +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`. + +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. #### 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; + } - ```python + // 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; + } -class Node: - def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): - self.val = x - self.next = next - self.random = random + return copiedHead; + } +}; +``` -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 +### Java +```java class Node { - constructor(val, next = null, random = null) { + int val; + Node next; + Node random; + + public Node(int val) { this.val = val; - this.next = next; - this.random = random; + this.next = null; + this.random = null; } } -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; +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; } - 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; + + // 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; } - current = current.next; - copyCurrent = copyCurrent.next; - } - return newHead; -} + // 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; + } + return copiedHead; + } +} ``` - - - - -### Output +### Python +```python +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = x + self.next = next + self.random = random -![Screenshot from 2024-07-19 21-11-44](https://github.com/user-attachments/assets/2c2a7efb-711d-4f6e-aebd-8f540de015c3) +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 +``` ### Complexity -- **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. +- **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. -- **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). +### Summary +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 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/dsa-solutions/lc-solutions/0400-0499/0415-add-strings.md b/dsa-solutions/lc-solutions/0400-0499/0415-add-strings.md new file mode 100644 index 000000000..4c9eaddb4 --- /dev/null +++ b/dsa-solutions/lc-solutions/0400-0499/0415-add-strings.md @@ -0,0 +1,179 @@ +--- +id: add-strings +title: Add Strings +sidebar_label: 415-Add Strings +tags: + - String Manipulation + - Simulation + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Add Strings problem on LeetCode." +sidebar_position: 10 +--- + +## Problem Description + +Given two non-negative integers, `num1` and `num2`, represented as strings, return the sum of `num1` and `num2` as a string. + +You must solve the problem without using any built-in library for handling large integers (such as `BigInteger`). You must also not convert the inputs to integers directly. + +### Examples + +**Example 1:** + +``` +Input: num1 = "11", num2 = "123" +Output: "134" +``` + +**Example 2:** + +``` +Input: num1 = "456", num2 = "77" +Output: "533" +``` + +**Example 3:** + +``` +Input: num1 = "0", num2 = "0" +Output: "0" +``` + +### Constraints + +- `1 <= num1.length, num2.length <= 10^4` +- `num1` and `num2` consist of only digits. +- `num1` and `num2` don't have any leading zeros except for the zero itself. + +--- + +## Solution for Add Strings Problem + +To solve this problem, we simulate the addition of two numbers digit by digit from right to left, similar to how we perform addition manually. + +### Approach: Simulation of Digit-by-Digit Addition + +1. **Initialize Variables:** + - `i` and `j` to point to the last characters of `num1` and `num2`. + - `carry` to store the carry-over value during addition. + - `result` to store the result in reverse order. + +2. **Add Digits from Right to Left:** + - Loop until all digits from both numbers and the carry are processed. + - For each step, add the corresponding digits from `num1` and `num2` and the `carry`. + - Calculate the new `carry` and the digit to be added to the result. + - Append the result digit to the `result` list. + +3. **Handle Carry:** + - If there's any remaining carry after the loop, append it to the `result`. + +4. **Return Result:** + - Reverse the `result` list and join the digits to form the final string. + +#### Brute Force Approach + +1. Convert each string to an integer. +2. Add the two integers. +3. Convert the sum back to a string. + +This approach, while simple, is not allowed as per the problem constraints. + +#### Optimized Approach + +The optimized approach uses the manual digit-by-digit addition described above. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string addStrings(string num1, string num2) { + int i = num1.size() - 1, j = num2.size() - 1, carry = 0; + string result = ""; + + while (i >= 0 || j >= 0 || carry) { + int sum = carry; + if (i >= 0) sum += num1[i--] - '0'; + if (j >= 0) sum += num2[j--] - '0'; + carry = sum / 10; + result += (sum % 10) + '0'; + } + + reverse(result.begin(), result.end()); + return result; + } +}; +``` + + + + + +```java +class Solution { + public String addStrings(String num1, String num2) { + StringBuilder result = new StringBuilder(); + int carry = 0, i = num1.length() - 1, j = num2.length() - 1; + + while (i >= 0 || j >= 0 || carry != 0) { + int sum = carry; + if (i >= 0) sum += num1.charAt(i--) - '0'; + if (j >= 0) sum += num2.charAt(j--) - '0'; + result.append(sum % 10); + carry = sum / 10; + } + + return result.reverse().toString(); + } +} +``` + + + + + +```python +class Solution: + def addStrings(self, num1: str, num2: str) -> str: + i, j = len(num1) - 1, len(num2) - 1 + carry = 0 + result = [] + + while i >= 0 or j >= 0 or carry: + sum_val = carry + if i >= 0: + sum_val += ord(num1[i]) - ord('0') + i -= 1 + if j >= 0: + sum_val += ord(num2[j]) - ord('0') + j -= 1 + carry, digit = divmod(sum_val, 10) + result.append(str(digit)) + + return ''.join(result[::-1]) +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(max(n, m))$, where `n` and `m` are the lengths of `num1` and `num2`. +- **Space Complexity**: $O(max(n, m))$ for storing the result. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file 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 4eacd7aa6..fb5a1dfcc 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,188 +1,141 @@ --- -id: Sort-Array-By-Parity +id: sort-array-by-parity title: Sort Array By Parity -sidebar_label: Sort Array By Parity -tags: - - Arrays - - Sorting +sidebar_label: 0905 - Sort Array By Parity +tags: + - easy + - Arrays + - Algorithms --- ## Problem Description -| 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 - -Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. +Given an integer array `nums`, move all the even integers to the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. -### Example 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. +## Examples -### Example 2: +**Example 1:** -**Input:** `nums = [0]` -**Output:** `[0]` +``` +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. +``` -## Constraints +**Example 2:** -- `1 <= nums.length <= 5000` -- `0 <= nums[i] <= 5000` +``` +Input: nums = [0] +Output: [0] +``` -## Approach +## Constraints -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. +``` +1 <= nums.length <= 5000 +0 <= nums[i] <= 5000 +``` ## Solution ### Python ```python -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] +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] ``` -### Java +### C++ -```java -import java.util.*; +```cpp +#include +#include -public class EvenOddArray { - public static int[] sortArrayByParity(int[] nums) { - List even = new ArrayList<>(); - List odd = new ArrayList<>(); - +class Solution { +public: + std::vector sortArrayByParity(std::vector& nums) { + std::vector result; for (int num : nums) { if (num % 2 == 0) { - even.add(num); - } else { - odd.add(num); + 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); + for (int num : nums) { + if (num % 2 != 0) { + result.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 = sortArrayByParity(nums); - for (int num : result) { - std::cout << num << " "; - } - // Output: 2 4 3 1 + std::vector result = solution.sortArrayByParity(nums); // Output: [2, 4, 3, 1] + return 0; } ``` -### 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]; +### 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); + } + } + return result.stream().mapToInt(i -> i).toArray(); } - *returnSize = numsSize; - for (int i = 0; i < numsSize; ++i) { - nums[i] = result[i]; - } - free(result); -} -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]); + 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 + " "); + } } - // Output: 2 4 3 1 - return 0; } ``` ### JavaScript ```javascript -function sortArrayByParity(nums) { - let even = []; - let odd = []; - - for (let num of nums) { - if (num % 2 === 0) { - even.push(num); - } else { - odd.push(num); - } +var sortArrayByParity = function (nums) { + let result = []; + for (let num of nums) { + if (num % 2 === 0) { + result.push(num); } - - return [...even, ...odd]; -} + } + for (let num of nums) { + if (num % 2 !== 0) { + result.push(num); + } + } + return result; +}; -// Example usage -let nums = [3, 1, 2, 4]; -console.log(sortArrayByParity(nums)); // Output: [2, 4, 3, 1] +// Example usage: +console.log(sortArrayByParity([3, 1, 2, 4])); // 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