question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
find-minimum-in-rotated-sorted-array
Short and Clear | C++
short-and-clear-c-by-sunny_38-2sfk
\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int l = 0,r = nums.size()-1;\n while(l<=r){\n int mid = (l+r)/2;\n
sunny_38
NORMAL
2021-08-31T11:33:19.352440+00:00
2021-08-31T11:33:19.352494+00:00
185
false
```\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int l = 0,r = nums.size()-1;\n while(l<=r){\n int mid = (l+r)/2;\n if((mid-1<0 or nums[mid-1]>nums[mid]) and (mid+1==nums.size() or nums[mid]<nums[mid+1]))\n return nums[mid];\n if(nums[mid]>nums.back())\n l = mid + 1;\n else\n r = mid - 1;\n }\n return 0;\n }\n};\n```
6
0
[]
1
find-minimum-in-rotated-sorted-array
[JavaScript] Using Binary Search (easy to understand)
javascript-using-binary-search-easy-to-u-0xb6
Before we go forward, this is what we know:\n- The array is rotated, and it could be rotated in a way it does not look rotated at all (smallest value on left, l
drewbie
NORMAL
2020-12-17T00:24:30.488960+00:00
2020-12-17T00:24:30.489031+00:00
1,389
false
Before we go forward, this is what we know:\n- The array is rotated, and it could be rotated in a way it does not look rotated at all (smallest value on left, largest value on right)\n- If the array is shifted, there will be ONE occurance where\n\n`a[mid - 1] > a[mid]`\n\nYou see this in `[4,5,1,2,3]`. There\'s only one time where the mid - 1 value is greater than mid value. That\'s a key to finding the solution.\n\nI wrote all of the if/else if statements with these tests. It\'s all you need! \n\n[1,2,3,4,5]\n[5,1,2,3,4]\n[4,5,1,2,3]\n[3,4,5,1,2]\n[2,3,4,5,1]\n\nThis helps us with edge cases like "what if the array is regularly sorted" or "what if the values is all the way on the right? The `[5,1,2,3,4]` needs a special case just for itself (a[mid] < a[left] && a[mid] < a[right]).\n\n**Space Complexity**: O(1)\n**Time Complexity** : O(log n)\n\n```\nconst findMin = (a) => {\n\tif (!a || a.length === 0) return null;\n\n\tlet left = 0,\n\t\tright = a.length - 1;\n\n\twhile (left < right) {\n\t\tlet mid = (left + (right - left) / 2) | 0; // This helps avoid overflows with large data sets\n\t\t\n\t\t// The one instance I mentioned above\n\t\tif (mid > 0 && a[mid - 1] > a[mid]) return a[mid];\n\t\telse if (a[mid] >= a[left] && a[mid] < a[right]) right = mid - 1;\n\t\telse if (a[mid] >= a[left] && a[mid] > a[right]) left = mid + 1;\n\t\telse if (a[mid] < a[left] && a[mid] < a[right]) right = mid - 1;\n\t}\n\n\treturn a[left];\n};\n```
6
0
['Binary Search', 'JavaScript']
0
find-minimum-in-rotated-sorted-array
Come and see! Binary search but logic is different, natural and intuitive
come-and-see-binary-search-but-logic-is-ykujp
My Comment\nI see lots of posts solving this problem using binary search, but I cannot agree with their logic of binary search... Their logic is comparing the n
416486188
NORMAL
2020-05-10T07:53:29.523460+00:00
2020-05-15T05:04:05.633441+00:00
606
false
**My Comment**\nI see lots of posts solving this problem using binary search, but I **cannot agree with** their logic of binary search... Their logic is comparing the `num[mid]` with `nums[left/start]`, I would say **it is vague, and hard to understand...**\nI use binary search as well, but I always compare with `nums[n - 1]` which is easier. Please take a look at my logic and explanations\n\n---\n**Algorithm**\nBinary Search as you know\n\n---\n**Explanation**\nSince the original array is sorted in ascending order, `nums[0] < nums[n - 1]`\nIt would be like below:\n```\n\t\t /\t\n\t /\n\t /\n /\n\t /\n /\n /\n```\nAfter rotated, think about how it would be like?\n```\n\t\t /\t\n\t /\n<--\t /\n /\n------------------\n\t/\n /\n /\n\nIt becomes like below:\n \n\t/\t\n /\n /\n /\n------------------\n\t\t/\n\t /\n\t / \n\n```\n\nWe can notice that from the pivot, **all the elements in the left hand side `>` all the elements in the right hand side**. And the largest number in the right hand side is `nums[n - 1]`\n\nWhen comes to binary search, 2 cases:\n1. If the `nums[mid]` is in the left hand side, look at the graph below, then it must be **greater than** the largest number in the right hand side, i.e. `nums[n - 1]`. That is **\'nums[mid] > nums[n - 1]\'**. Then we know the minimum number must in the right side of `mid`. So move `left` to `mid + 1`\n\t```\n\t | /\t\n\t |/\n\t |\n\t /|\n\t / |\n\t------------------\n\t\t\t/\n\t\t /\n\t\t / \n\t```\n2. If the `nums[mid]` is in the right hand side, look at the graph below, then it must be **no greater than** the largest number in the right hand side, i.e. `nums[n - 1]`. That is **\'nums[mid] <= nums[n - 1]\'**. Then we know the minimum number must in the left side of `mid`. So move `right` to `mid`. (Why `mid` not `mid - 1`? Because `num[mid]` can be the minimum number which is the result, we cannot rule out the `mid`)\n\t```\n\t\t/\t\n\t /\n\t /\n\t /\n\t------------------\n\t\t | /\n\t\t |/\n\t\t |\n\t\t /| \n\t```\n\nSo the difference with other solutions is: **we always compares the `nums[mid]` with `nums[n - 1]`.** Unlike other solutions comparing `nums[mid]` with `nums[left]` or `nums[right]`, the logic is vague, right???\n\n---\n**Final Code**\n```java\nclass Solution {\n public int findMin(int[] nums) {\n // corner case\n if(nums == null || nums.length == 0) return -1;\n if(nums.length == 1) return nums[0];\n \n // if the array is not rotated\n int n = nums.length;\n if(nums[0] < nums[n - 1]) return nums[0];\n \n // get to business: find min if array is rotated\n int left = 0;\n int right = n - 1;\n while(left < right - 1){\n int mid = left + (right - left)/2;\n if(nums[mid] <= nums[n - 1]){\n right = mid;\n }else{\n left = mid + 1;\n }\n }\n \n return Math.min(nums[left], nums[right]);\n }\n}\n```\n\n---\n**Complexity Analysis**\nTC(Time Complexity): O(logn), since we are using binary search\nSC(Space Complexity): O(1)\n
6
0
['Binary Search', 'Java']
1
find-minimum-in-rotated-sorted-array
Simple Java Solution
simple-java-solution-by-diaa-ed89
public int findMin(int[] nums) {\n \n \tint start = 0, end = nums.length - 1, mid;\n \twhile (start < end) {\n \t\tmid = (start +
diaa
NORMAL
2015-09-16T16:33:40+00:00
2015-09-16T16:33:40+00:00
1,459
false
public int findMin(int[] nums) {\n \n \tint start = 0, end = nums.length - 1, mid;\n \twhile (start < end) {\n \t\tmid = (start + end) / 2;\n \t\tif (nums[mid] > nums[end])\n \t\t\tstart = mid + 1;\n \t\telse\n \t\t\tend = mid;\n \t}\n \treturn nums[start];\n }
6
0
[]
1
find-minimum-in-rotated-sorted-array
Python solution with detailed explanation
python-solution-with-detailed-explanatio-p9zj
Solution\n\nFind Minimum in Rotated Sorted Array https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/\n\nKey insight is that if an array is rotat
gabbu
NORMAL
2017-01-20T14:14:45.404000+00:00
2017-01-20T14:14:45.404000+00:00
648
false
**Solution**\n\n**Find Minimum in Rotated Sorted Array** https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/\n\nKey insight is that if an array is rotated, then between the two sub-arrays around the mid point, the lowest element lies in the array which is out of order. Now there are three possibilities which are shown in the figures below. We observe that lowest element is the first element when all elements are sorted. Otherwise it is in the segment about the mid element which is unsorted.\nhttps://goo.gl/photos/3CJrFiV72te92xC88\nhttps://postimg.org/image/asbbeo2c9/.\n\n**What is a single condition that can discriminate between the three cases? **\n* if nums[mid] > nums[high] then minimum number is in right half, otherwise it is in left half (first two)\n* if minimum number must be in the right half, then we must do low = mid+1. Doing low = mid will result in infinite loop. Case: [2,1]\n```\nclass Solution(object):\n def findMin(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n low,high = 0, len(nums)-1\n while low < high:\n mid = low + (high-low)//2\n if nums[mid] > nums[high]:\n low = mid + 1 # Note that mid+1 is important.\n else:\n high = mid\n return nums[low]\n```\n\n**What if we used nums[low] < nums[mid] as the discriminating condition?**\n* Note that this only helps distinguish 2 and 3 (from figure) and we need a special condition for case 1 when rotation is zero.\n* Note that we dont do low = mid+1. Case [2,1]\n* The stopping condition is again an array of length 2.\n```\nclass Solution(object):\n def findMin(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n low,high = 0, len(nums)-1\n if nums[low] <= nums[high]:\n return nums[low]\n while low < high:\n mid = low + (high-low)//2\n if nums[low] < nums[mid]:\n low = mid\n else:\n high = mid\n return nums[low+1]\n```\n\n**Another Approach**\nWe apply binary search and out stopping condition is an out of order array of length 2. The smallest element is then nums[high]. Do not forget to test for boundary condition that array is in order already.\n```\nclass Solution(object):\n def findMin(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n low,high = 0, len(nums)-1\n if nums[low] <= nums[high]:\n return nums[low]\n while high-low != 1:\n mid = low + (high-low)//2\n if nums[low] < nums[mid]:\n low = mid\n else:\n high = mid\n return nums[high]\n```
6
0
[]
0
find-minimum-in-rotated-sorted-array
EASY TO MEDIUM SOLUTION || 153. Find Minimum in Rotated Sorted Array
easy-to-medium-solution-153-find-minimum-3hq6
null
shivambit
NORMAL
2024-12-12T07:42:32.409760+00:00
2024-12-12T07:42:32.409760+00:00
344
false
# Intuition\n\nThe task is to find the minimum element in a rotated sorted array, which may contain duplicates. The key points to consider are:\n1. **Rotated Sorted Array**: The array is originally sorted but has been rotated at some pivot, meaning that the smallest element is somewhere in the array.\n2. **Handling Duplicates**: Duplicates can complicate the search, as they may obscure the boundaries of sorted portions.\n\n# Approach\n\nThe approach leverages binary search to efficiently locate the minimum element. Here\u2019s a detailed step-by-step breakdown:\n1. **Initialization**: Start with two pointers, low and high, initialized to the first and last indices of the array, respectively.\n2. **Binary Search Loop**: Continue searching while low is less than high:\n - Calculate mid as low + (high - low) / 2.\n - **Check for Sorted Portion**: If nums[low] < nums[high], it indicates that the portion from low to high is sorted, and thus the minimum element must be at low. Return nums[low].\n - **Handle Duplicates**: If nums[low], nums[mid], and nums[high] are equal, increment low and decrement high. This reduces the search space when duplicates are present.\n - **Determine Sorted Half**:\n - If the left half (nums[low] to nums[mid]) is sorted (i.e., nums[low] <= nums[mid]), then the minimum must be in the right half. Set low = mid + 1.\n - If the right half (nums[mid] to nums[high]) is sorted, then the minimum must be in the left half or could be at mid. Set high = mid.\n3. **Return Minimum**: When the loop ends, low will point to the minimum element. Return nums[low]\n\n# Complexity\n- **Time complexity**: The average case time complexity is O(logN) due to binary search. However, in cases with many duplicates, it can degrade to O(N) in the worst case when all elements are duplicates.\n\n- **Space complexity**: The space complexity is O(1) since we are using a constant amount of extra space for variables.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int n = nums.size();\n if (n == 1) return nums[0];\n\n int low = 0, high = n - 1;\n\n while (low < high) {\n int mid = low + (high - low) / 2;\n\n // If we find a sorted part\n if (nums[low] < nums[high]) {\n return nums[low]; // The smallest element is at \'low\'\n }\n\n // Handle duplicates\n if (nums[low] == nums[mid] && nums[mid] == nums[high]) {\n low++; \n high--; // Shrink the search space\n } \n else if (nums[low] <= nums[mid]) {\n // Left side is sorted, so move to the right\n low = mid + 1;\n } \n else {\n // Right side must be sorted, so move to the left\n high = mid; // Note: We keep mid here because it could be the minimum\n }\n }\n\n return nums[low]; // At the end of loop, low should point to the minimum\n }\n};\n\n```
5
0
['Array', 'Binary Search', 'C++']
0
find-minimum-in-rotated-sorted-array
C++ || Binary Search || 0 ms || Beats 100%
c-binary-search-0-ms-beats-100-by-meurud-p3y9
\n# Code\n\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int low = 0;\n int high = nums.size() - 1;\n int ans = INT_MA
meurudesu
NORMAL
2024-02-02T15:19:32.707081+00:00
2024-02-02T15:43:03.565424+00:00
1,319
false
\n# Code\n```\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int low = 0;\n int high = nums.size() - 1;\n int ans = INT_MAX;\n while(low <= high) {\n int mid = (low + high) / 2;\n if(nums[low] <= nums[mid]) {\n ans = min(ans, nums[low]);\n low = mid + 1;\n } else {\n ans = min(ans, nums[mid]);\n high = mid - 1;\n }\n }\n return ans;\n }\n};\n```
5
0
['C++']
1
find-minimum-in-rotated-sorted-array
Easy Beats 100% || CPP || 0 ms
easy-beats-100-cpp-0-ms-by-rudrakshtomar-ddbs
Intuition\nTricky one. Do refer Hint before seeing solution. Try dry running for small vectors, eventually you will be able to build logic.\n# Approach\nWe know
rudrakshtomar
NORMAL
2024-01-30T09:46:52.031359+00:00
2024-01-30T09:49:40.676811+00:00
294
false
# Intuition\nTricky one. Do refer Hint before seeing solution. Try dry running for small vectors, eventually you will be able to build logic.\n# Approach\nWe know if(nums[0]>nums[nums.size()-1]) , we got rotated array. if there are 3 elements a,b,c in ascending fashion, we know a<b<c.\nBut Now we will get a point where either a>b or b>c. Then return smallest, thats our answer.\nI compared mid with nums[0] and nums[n] to figure out which side smallest would lie. Try dry running with yourself.\n\n# Complexity\n- Time complexity:\nO(logN)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n if(nums.size()==1) return nums[0];\n\n if(nums[0]<nums[nums.size()-1]) return nums[0];\n\n int a=0;\n int b=nums.size()-1;\n\n while(a<b){\n int mid=(a+b)/2;\n\n if(b-a==1){\n if(nums[b]<nums[a]) return nums[b]; \n }\n\n if(nums[mid-1]>nums[mid]) return nums[mid];\n\n else if(nums[mid]>nums[mid+1]) return nums[mid+1];\n\n if(nums[mid]>nums[0]) a=mid+1;\n\n else \n b=mid-1;\n\n }\n return 0;\n }\n};\n```\nPlease Upvote if u liked my explanation.\n![upvote.jpeg](https://assets.leetcode.com/users/images/6d938979-1223-4f6d-833f-2e10aa564133_1706607940.7488573.jpeg)\n\n\n
5
0
['C++']
0
find-minimum-in-rotated-sorted-array
c++ solution || binary search (log n)
c-solution-binary-search-log-n-by-harshi-fviu
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
harshil_sutariya
NORMAL
2023-04-28T17:37:09.510853+00:00
2023-04-28T17:37:09.510896+00:00
1,589
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(log n)\n\n- Space complexity:\nO(1)\n![IMG_9181.jpg](https://assets.leetcode.com/users/images/11ba6d96-e074-4947-b06a-308c2a1e6c2e_1682703362.935578.jpeg)\n\n\n# Code\n```\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int i=0;\n int j=nums.size()-1;\n while(i<j){\n int mid = (i+j)/2;\n if(nums[mid] > nums[j]) i = mid+1;\n else j=mid;\n }\n return nums[i];\n }\n};\n```
5
0
['Binary Search', 'C++']
1
find-minimum-in-rotated-sorted-array
Simple Java Solution || beats 100% || Please upvote if you find it helpful. <3
simple-java-solution-beats-100-please-up-c3w5
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach \n- Binary search \n\n Describe your approach to solving the problem. \n\n
prashantbhardwaj190
NORMAL
2023-04-24T16:54:56.081526+00:00
2023-06-05T14:32:39.924960+00:00
1,718
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach \n- Binary search \n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: log(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: o(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int findMin(int[] nums) {\n int start = 0;\n int end = nums.length - 1;\n while (start < end) {\n int mid = start + (end - start) / 2;\n if (nums[mid] < nums[end]) {\n end = mid;\n } else {\n start = mid + 1;\n }\n }\n return nums[start];\n//Do upvote please\n }\n}\n```
5
0
['Binary Search', 'Java']
3
find-minimum-in-rotated-sorted-array
Find Minimum in Rotated Sorted Array | Brute Force | Optimized ( O(log N) ) | C++ | Python
find-minimum-in-rotated-sorted-array-bru-34nr
Intuition\n\nThis seems like an easy problem if we want to brute force it. But given it is a rotated "sorted" array, we can think about optimizing the solution.
draco_rocks
NORMAL
2023-02-11T10:15:39.337939+00:00
2023-02-12T21:21:29.127133+00:00
946
false
# Intuition\n\nThis seems like an easy problem if we want to brute force it. But given it is a rotated "sorted" array, we can think about optimizing the solution. Algorithms with ```log N``` approach comes to mind and Binary search seems like a good candidate given the nature of the problem wherein we have to incrementally prune some sample space to get closer to our result.\n\nThe array in question looks something like below.\n\n![SmartSelect_20230211_152712_Samsung Notes.jpg](https://assets.leetcode.com/users/images/20894a32-4a98-4c03-bdd7-41b3830fdd5a_1676109667.668417.jpeg)\n\n\n\nIt is clear that we can apply some form of pruning on the array space to narrow down the result. Then it becomes a classic binary search problem with minor changes in logic for boundary and mid pointers.\n\n----------------\n\n# Approach 1 - Brute Force (Accepted)\n\nThe simplest approach that comes to mind after reading the problem is brute forcing through the array space and returning the minimum element among all candidates.\n\n## Complexity\n- Time complexity:\n```O(n)``` as we are traversing all the elements to arrive at the result.\n\n- Space complexity:\n```O(1)``` as we are not using any extra container / array etc. to store intermediate results to arrive at the solution.\n\n## Code\n```cpp []\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int min_ele = INT_MAX; // Assign min as INT_MAX\n for(int i = 0; i < nums.size(); ++i) {\n if(nums[i] < min_ele) {\n min_ele = nums[i]; // Check if cur element less than min and update\n }\n }\n return min_ele;\n }\n};\n```\n```python []\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n # Keeping it simple, no fancy lamda\'s here for now\n min = 1e9\n for num in nums:\n if num < min:\n min = num\n\n return min\n```\n\n--------------\n\n# Approach 2 - Optimized ( Binary Search )\n\nAs mentioned above, we are given in the problem statement that the array is a rotated form of its sorted version, so binary search comes to mind. We can prune the search space according to the condition in hand and proceed further. Compare the mid element with the last element and if its larger, prune the left side as minimum will lie on right side. Similarly, follow this for left side conversions.\n\n\n## Code\n```cpp []\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n // Assign l and r as array boundaries for initial search space\n int l = 0,r = nums.size() - 1;\n // Binary search loop\n while(l < r) {\n int m = (l + r) / 2; // Or use l + (r - l) / 2 for overflows\n if(nums[m] > nums[r]) l = m + 1; // Prune the left space as min lie in right\n else r = m; // Prune the right space, m can be min also\n }\n return nums[l]; // Return the min i.e. l index\n }\n};\n```\n```python []\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n # Keeping it simple, no fancy lamda\'s here for now\n # Assign l and r as array boundaries for initial search space\n l, r = 0, len(nums) - 1\n\n # Binary search loop\n while l < r:\n\n m = (l + r) // 2 # Or use l + (r - l) / 2 for overflows\n if nums[m] > nums[r]: l = m + 1 # Prune the left space as min lie in right\n else: r = m # Prune the right space, m can be min also\n \n return nums[l] # Return the min i.e. l index\n```\n\n## Algorithm\n\nWe will look at the algorithm using an example array ```[4, 5, 6, 7, 0, 1, 2]```.\n\n1. *Iteration 1*: ```m = (l + r) / 2``` which gives ```m = 3```. Now clearly ```nums[m] > nums[r]```, hence we can prune the left portion as minimum can\'t lie in this range. So, ```l = m + 1``` and ```r``` will remain unchanged.\n\n![SmartSelect_20230211_152407_Samsung Notes.jpg](https://assets.leetcode.com/users/images/303fba0d-0dea-4d94-ae19-968cf08d7c16_1676109720.698023.jpeg)\n\n\n\n2. *Iteration 2*: ```m = (l + r) / 2``` which gives ```m = 5```. Now, code will go into the else condition as ```nums[m] < nums[r]```. This means result should lie in left portion ( It can be mid as well ). Hence, ```r = m``` and ```l``` remains unchanged.\n\n![SmartSelect_20230211_152355_Samsung Notes.jpg](https://assets.leetcode.com/users/images/c1283262-ea27-4516-995e-dabfea92aaad_1676109733.7054012.jpeg)\n\n\n\n\n3. *Iteration 3*: ```m = (l + r) / 2``` which gives ```m = 4```. Now, code will go into the else condition as ```nums[m] < nums[r]```. This means result should lie in left portion ( It can be mid as well ). Hence, ```r = m = 4``` and ```l = 4``` as well (unchanged).\n\n![SmartSelect_20230211_152334_Samsung Notes.jpg](https://assets.leetcode.com/users/images/5ef33a0e-5d5b-4d64-8690-56b71501fb65_1676109749.5078168.jpeg)\n\n\n4. Iteration 4: Here, ```l(4)``` not less than ```r(4)```, hence the loop will break and we will return ```nums[l]``` i.e. 0 as our result.\n\n\nWe can quickly look at some corner case as well ( e.g. ```[5, 4]```. This will return after setting ```l``` to index ```1``` as ```arr[m] > arr[r]```). You can dry run on some other cases to have a better understanding / visualisation.\n\n\n\n\n## Complexity\n- Time complexity:\n```O(log N)``` similar to Binary Search algorithm\n\n- Space complexity:\n```O(1)``` similar to Binary Search as we are not using any extra space.\n
5
0
['Python', 'C++']
0
find-minimum-in-rotated-sorted-array
Easy to Understand ||O(log(n)) time O(1) space
easy-to-understand-ologn-time-o1-space-b-vrcj
Intuition\nWe want to search for the minimum of the array.And it\'s pretty obvious the minimum of the array would lie as the first element of the non rotated or
venkateshjaiswal_793
NORMAL
2023-01-24T16:52:06.696471+00:00
2023-01-24T16:52:06.696510+00:00
1,748
false
# Intuition\nWe want to search for the minimum of the array.And it\'s pretty obvious the minimum of the array would lie as the first element of the non rotated or non shifted part of the array.So we try to reach to the non shifted part of the array.\n\nEx:- Consider the array (4,5,1,2,3)\nHere (4,5) represents the rotated part of array and (1,2,3) represents the non rotated part of the array.\n\n# Approach\n1)Keep two pointers low and high.Whenever mid element is higher than low element it means that we are still in the rotated part of the array.So we Shift your low 1 place ahead of the mid element.\n\n2)Else if that is not the case,it means we are already in the non rotated part of the array but in the farther right side,so we shift the high 1 place behind the mid.We do this to reach that part of the non rotated array which has lesser value elements.\n\n3)Each time during the search we take a mini variable which stores the minimum between mid element,low element and mini in mini.\n\n# Complexity\n- Time complexity:\nO(log(n))\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int findMin(vector<int>& arr) {\n int n=arr.size();\n int l=0;\n int h=n-1;\n int mini=INT_MAX;\n while(l<=h){\n int mid=l+(h-l)/2;\n mini=min(mini,arr[mid]);\n mini=min(mini,arr[l]);\n if(arr[mid]>=arr[l]){\n l=mid+1;\n }\n else{\n h=mid-1;\n }\n }\n return mini;\n }\n};\n```
5
0
['Binary Search', 'C++']
0
find-minimum-in-rotated-sorted-array
JAVA Binary search with little twist
java-binary-search-with-little-twist-by-z6k4p
Intuition\nBy O(logn) we know it is only possible via binary search.\n\n# Approach\nIt is quite similar to - https://leetcode.com/problems/search-in-rotated-sor
kushguptacse
NORMAL
2022-12-20T10:45:43.030936+00:00
2022-12-20T10:50:31.038381+00:00
655
false
# Intuition\nBy $$O(logn)$$ we know it is only possible via binary search.\n\n# Approach\nIt is quite similar to - https://leetcode.com/problems/search-in-rotated-sorted-array/solutions/1566310/simple-java-solution-with-explaination-0-ms-binary-search-logn/?envType=study-plan&id=algorithm-ii&orderBy=most_votes\n\nIn binary search check-> if right boundary element is greater than mid. in such case mid could be the answeer or elements to the left of mid could be the answer. but we are sure right elements will be greater. hence do \nr=m\nelse do l=m+1\n\n\n\n# Complexity\n- Time complexity:\n $$O(logn)$$ \n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\n public int findMin(int[] nums) {\n\t\tint l = 0;\n\t\tint r = nums.length - 1;\n\t\tint m;\n\t\twhile (l < r) {\n\t\t\tm = (l + r) / 2;\n\t\t\tif (nums[m] < nums[r]) {\n\t\t\t\tr=m;\n\t\t\t} else {\n\t\t\t\tl=m+1;\n\t\t\t}\n\t\t}\n\t\treturn nums[l];\n\t}\n}\n```
5
0
['Binary Search', 'Java']
0
find-minimum-in-rotated-sorted-array
👾C#,Java,Python3,JavaScript Solution
cjavapython3javascript-solution-by-daisy-qpy2
\u2B50https://zyrastory.com/en/coding-en/leetcode-en/leetcode-153-find-minimum-in-rotated-sorted-array-solution-and-explanation-en/\u2B50\n\nIf you got any prob
Daisy001
NORMAL
2022-10-19T07:03:11.846741+00:00
2022-10-19T07:03:11.846777+00:00
1,133
false
**\u2B50[https://zyrastory.com/en/coding-en/leetcode-en/leetcode-153-find-minimum-in-rotated-sorted-array-solution-and-explanation-en/](https://zyrastory.com/en/coding-en/leetcode-en/leetcode-153-find-minimum-in-rotated-sorted-array-solution-and-explanation-en/)\u2B50**\n\nIf you got any problem about the explanation or you need other programming language solution, please feel free to let me know (leave comment or messenger me).\n\n**Example : C# Solution(\u2B06To see other languages \u2B06)**\n```\npublic class Solution {\n public int FindMin(int[] nums) {\n int li = 0; //low index\n int hi = nums.Length-1; //high index\n \n while(hi>li)\n {\n int midi = li+(hi-li)/2;\n \n if (nums[midi] < nums[hi]) \n {\n hi = midi;\n } \n else \n {\n li = midi+1;\n }\n }\n \n return nums[li];\n }\n}\n```\nTime Complexity : O(log n)\n\n\nIf you got any problem about the explanation or you need other programming language solution, please feel free to let me know. Thanks!\n\nYou can find out other LeetCode problems solution\u2B07\n**\u2B50[Zyrastory - Food & Code Research Center](https://zyrastory.com/en/category/coding-en/leetcode-en/)\u2B50**
5
0
['Java', 'Python3', 'JavaScript']
1
find-minimum-in-rotated-sorted-array
✅✅100% Faster || 0ms || Optimal approach
100-faster-0ms-optimal-approach-by-arpit-d4wg
\n\n\n\n\nclass Solution {\npublic:\n int findMin(vector<int>& arr) {\n int n = arr.size();\n int mini = INT_MAX;\n int low = 0, high =
Arpit507
NORMAL
2022-10-11T23:49:53.183155+00:00
2022-10-11T23:50:35.459272+00:00
780
false
![image](https://assets.leetcode.com/users/images/b0ff0d83-2079-47f2-a568-3dd71a271a4f_1665532212.5354164.png)\n![image](https://assets.leetcode.com/users/images/777aed88-e46f-467b-8350-5c8ca8882cc1_1665532229.7139807.gif)\n\n\n```\nclass Solution {\npublic:\n int findMin(vector<int>& arr) {\n int n = arr.size();\n int mini = INT_MAX;\n int low = 0, high = n-1;\n while(low <= high){\n long int mid = low + (high-low)/2;\n if(arr[mid] >= arr[low]){\n mini = min(mini, arr[low]);\n low = mid+1;\n }\n else{\n mini = min(mini, arr[mid]);\n high = mid-1;\n }\n }\n return mini;\n }\n};\n/* If you like it please upvote */\n```\n\nIf you like it please upvote
5
0
['C', 'Binary Tree']
0
find-minimum-in-rotated-sorted-array
✅PYTHON || Explained Steps || Clean Code 🔥||✔️ Best Method
python-explained-steps-clean-code-best-m-bd41
Hello!\n\nTo solve this problem we have to do binary search, but we compare current element with the second one and then with the last one.\n\n1. If our current
LulitosKoditos
NORMAL
2022-09-19T16:15:45.591782+00:00
2022-09-19T16:15:45.591826+00:00
431
false
Hello!\n\nTo solve this problem we have to do **binary search**, but we compare current element with the **second one** and then with the **last one**.\n\n1. If our current element is greater than the next one, then it means that next element is our **result** (because it means it is rotation point)\n2. If our current element is greater than the last element, then it means that we have to move **start** index (because on the left we won\'t find the target).\n3. If those statements are not true, then we change **end** index.\n\nFor example: [4, 5, 1, 2, 3], target = 5\nOur mid point is value **1**. It is not greater than **2**, so it is not the target. It is not greater than the last value, so we know, that we won\'t find the target on the right, so we decrease **end** index.\n\nNow we consider subarray [4, 5] etc.\n\nCode:\n```\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n if len(nums) == 1:\n return nums[0]\n \n start = 0\n end = len(nums)-1\n \n while start <= end:\n mid = (start + end) // 2\n \n if nums[mid] > nums[mid+1]:\n return nums[mid+1]\n elif nums[mid] > nums[-1]:\n start = mid + 1\n else:\n end = mid - 1\n \n return nums[0]\n```\n\nPlease upvote if it was helpful :))
5
0
['Python']
0
find-minimum-in-rotated-sorted-array
beats 100% || c++ solution ||
beats-100-c-solution-by-_uday14-p5hx
thanks to love babbar\n\n\n\n\tint findMin(vector& nums) {\n int s = 0;\n int e = nums.size()-1;\n while(s < e)\n {\n int
_uday14
NORMAL
2022-08-26T21:23:48.591176+00:00
2022-08-28T15:26:17.711830+00:00
255
false
**thanks to love babbar**\n\n\n\n\tint findMin(vector<int>& nums) {\n int s = 0;\n int e = nums.size()-1;\n while(s < e)\n {\n int m = s + (e-s)/2;\n if(nums[m] > nums[e])\n {\n s = m +1;\n }\n else{\n e = m;\n }\n }\n return nums[s];\n }\n\n\n**hope u find it helpfull : - ) dont forgot to upvote**\n
5
0
[]
0
find-minimum-in-rotated-sorted-array
C++ | multiple solutions | diffrent approaches
c-multiple-solutions-diffrent-approaches-y9ae
Codes are available in comments
theyashvishnoi
NORMAL
2022-07-30T13:30:35.803809+00:00
2022-07-30T15:17:06.260709+00:00
389
false
**Codes are available in comments**
5
0
['C', 'Binary Tree']
2
find-minimum-in-rotated-sorted-array
Using Binary Search, Simple & Easy to Understand, [C++]
using-binary-search-simple-easy-to-under-sbzp
Implementation\n\nTime Complexity: O(LogN)\nSpace Complexity: O(1)\n\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int left = 0, rig
akashsahuji
NORMAL
2022-03-27T17:07:34.318543+00:00
2022-03-27T17:07:34.318577+00:00
228
false
Implementation\n\n**Time Complexity: O(LogN)\nSpace Complexity: O(1)**\n```\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int left = 0, right = nums.size()-1, minVal = INT_MAX;\n \n while(left <= right){\n int mid = left + (right - left)/2;\n \n if(nums[left] <= nums[mid]){\n minVal = min(minVal, nums[left]);\n left = mid+1;\n }\n else{\n minVal = min(minVal, nums[mid]);\n right = mid-1;\n }\n }\n \n return minVal;\n }\n};\n```\nIf you find any issue in understanding the solution then comment below, will try to help you.\nIf you found my solution useful.\nSo **please do upvote and encourage me** to document all leetcode problems\uD83D\uDE03\nHappy Coding :)
5
0
['Binary Search', 'C']
1
find-minimum-in-rotated-sorted-array
Faster Than 100% users C++ time O(logn) space O(1)
faster-than-100-users-c-time-ologn-space-8rn4
I have just have used simple binary search with a little bit of modification as I have checked last element with the mid one so that I can swap change left righ
diwanshubansal
NORMAL
2021-11-21T12:30:36.931254+00:00
2021-11-21T12:30:36.931285+00:00
132
false
I have just have used simple binary search with a little bit of modification as I have checked last element with the mid one so that I can swap change left right accordingly. \n\t \n\t \n\t int findMin(vector<int>& nums) {\n int left=0,right=nums.size()-1;\n while(left<right)\n {\n int mid = (left+right)/2;\n if(nums[mid]<nums[mid+1])\n {\n if(nums[mid]>nums[right])\n {\n left=mid+1;\n }\n else\n right=mid;\n }\n else\n left=mid+1;\n }\n return nums[left];\n }
5
0
[]
0
find-minimum-in-rotated-sorted-array
Easy C++ binary search solution
easy-c-binary-search-solution-by-tejas70-pogd
\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int n = nums.size();\n int left = 0, right = n-1;\n if(nums[right] > nu
tejas702
NORMAL
2021-08-31T10:50:29.719922+00:00
2021-08-31T10:50:29.719957+00:00
224
false
```\nclass Solution {\npublic:\n int findMin(vector<int>& nums) {\n int n = nums.size();\n int left = 0, right = n-1;\n if(nums[right] > nums[left]) return nums[left];\n while(left < right){\n int mid = left + (right-left)/2;\n if(nums[mid] < nums[right]) right=mid;\n else left = mid+1;\n }\n return nums[left];\n }\n};\n```\n**Time complexity:** O(logN) where N is the size of array.\n**Space complexity:** O(1)\n**Questions/ Discussions are welcome.**
5
1
['Binary Search', 'C']
2
find-minimum-in-rotated-sorted-array
Easiest Solution with Binary Search
easiest-solution-with-binary-search-by-c-5mtp
\n public int findMin(int[] nums) {\n \n\t\t //taking start and end as first and last index \n\t\tint start =0,next,prev;\n int end = nums.length -1;\n\t
cracko
NORMAL
2021-06-29T06:35:46.865563+00:00
2021-06-29T06:35:46.865607+00:00
75
false
\n public int findMin(int[] nums) {\n \n\t\t //taking start and end as first and last index \n\t\tint start =0,next,prev;\n int end = nums.length -1;\n\t \n //finding the length of nums array\n\t int n =nums.length;\n\t\t\n //This is where result stored\n\t\tint res =-1;\n \n\t while(start<=end)\n {\n //If the array is sorted then we just need to return the first index element that is minimum element\n\t\t if(nums[start]<=nums[end])\n {\n res = nums[start];\n break;\n }\n\t\t\t\n\t\t\n int mid = (start +end)/2;\n \n\t\t\t//next and prev is for storing next index and previous index if suppose we are at i so it will be (i+1) and (i-1) \n\t\t\t\n next = (mid+1)%n;\n prev = (mid-1+n)%n;\n \n\t\t //If our mid element is less than both prev and next element then the mid element is minimum element\n\t\t \n if((nums[mid]<=nums[prev])&&(nums[mid]<=nums[next]))\n {\n res = nums[mid];\n break;\n }\n \n\t\t //If the first half array is already sorted then we will get minimum element in next half array\n if(nums[start]<=nums[mid])\n start =mid+1;\n \n else if(nums[mid]<=nums[end])\n end =mid-1;\n \n }\n return res;\n }\n\t//**Please upvote me **
5
1
[]
0
find-minimum-in-rotated-sorted-array
Divide & Conquer | Explanation + Visual | [Python]
divide-conquer-explanation-visual-python-3300
TLDR(expalanation + visual below code snippet) This problem can be solved by using divide and conquer strategy. We repeatedly divide the problem into subproblem
gtshepard
NORMAL
2021-01-18T01:58:02.151852+00:00
2021-01-18T21:02:20.881265+00:00
282
false
***TLDR(expalanation + visual below code snippet)*** This problem can be solved by using divide and conquer strategy. We repeatedly divide the problem into subproblems on the basis of whether or not ```arr[low] <= arr[high]``` (whether or not array is sorted) until subporblems become small. Then we solve them directly. we begin combining solutions to subproblems by taking the minimum of the left and right subproblem solutions.\n\n```python\ndef findMin(self, nums: List[int]) -> int:\n return self.find_min(nums, 0, len(nums) - 1)\n\t\ndef find_min(self, nums, lo, hi):\n\tif lo >= hi: return nums[lo]\n\tif nums[lo] <= nums[hi]: return nums[lo]\n\tmid = (lo + hi)//2\n\n\tleft = self.find_min(nums, lo, mid)\n\tright = self.find_min(nums, mid + 1, hi)\n\treturn min(left, right);\n\n```\n* * * \n### Divide & Conquer Strategy \n* * * \n\nDivide & Conquer is a strategy for a solving a problem. \n\nWe take a large problem and ***divide*** it into subproblems until the subproblems become ***small*** (we define the meaning of small). Once we have small subproblemsm we can solve them directly because the answer is trivial. Once we start getting solutions to small subproblems we can start to ***combine*** or ***conquer*** these solutions, to get solutions to larger subproblems eventually solving the our intial large problem. \n\nThis figure denotes a general way to approach ***Divide & Conquer*** \n![image](https://assets.leetcode.com/users/images/d24f02b7-1a45-4899-a908-e5fe584bf29a_1610922746.512331.png)\n\n* * * \n### Why Divide & Conquer ?\n* * * \n\nIn this problem we are given a ***sorted*** array of ***unqiue*** elements that has been rotated and we are asked to find the ***minimum element****. \n\nin general when given a ***sorted array*** and asked to find an element. ***binary search*** is applicable. Binary search is an algorithm that uses the ***divide and conquer*** strategy. \n\nTechnically this array is not perfectly sorted and becuase the array has been rotated. However the relative ordering of the elements is still preserved after rotation.\n\nThus it still may be possible to modify the original binary search algorithm and/or use a ***divide an conquer strategy***.\n\n* * * \n### Applying Divide & Conquer Strategy\n* * * \nwe need to find the minimum in a sorted array that has been rotated zero or more times. \n\nRecall, we say a problem is large when it cannot be solved directly, and the problem is small when it can be solved directly.\n\nWhen the array is sorted, the problem is small because we can solve the problem directly by taking the first element of the array. \n\n![image](https://assets.leetcode.com/users/images/e4ca6343-2e17-4cb6-b3ed-9612a6a7a935_1610931992.3232388.png)\n* * * \nif the array is not completely sorted (in our case rotated 1 or more times) we cannot solve the problem directly, thus the problem is large. \n\n* * * \n***The question now becomes how do we solve large problems?***\n* * * \n\nObserve a rotated array , notice the relative order of the elements is still preserved leaving sections of the array still sorted. \n\n* * * \n![image](https://assets.leetcode.com/users/images/19285d72-c4f1-491f-8b00-00be7a513840_1610932157.6701047.png)\n\nThe goal is in the example above is to find sorted arrays so we can solve the problem directly. This entire block is not sorted, but if we cut the array in half we are left with 2 sorted pieces.we can solve each peice directly. \n\nin other words if he problem is large (array not sorted) we can divide the problem into subproblems (smaller arrays) until we get small problems (sorted arrrays) and then solve them directly. \n\n![image](https://assets.leetcode.com/users/images/b6d57473-54b0-4d99-b01f-25553a255063_1610932628.1464949.png)\n\nwe know the ***right*** array is sorted because ```arr[4] < arr[6]```so we could solve for the minimum directly \n\nhowever notice the ***left*** array is also sorted because ```arr[0] < arr[3]``` so can also solve directly and we get a minimum of ```4```\n\nour original problem can only have one solution. How do we ensure we choose the correct value? we take the minimum ```min(4, 0) = 0```. in otherwords we combine or conquer subproblems by taking the minimum of solutions to our subproblems. \n\n* * * \nat each stage we decide if the problem is ***large (not a sorted array)*** if it is ***large***, we break the problem into smaller subproblems (cut the array in half by a midpoint) otherwise the problem is ***small (sorted array***) so we solve the problem ***directly (take first value block of sorted elements)*** when we have found the solution for both the left and right havles of a subproblem we ***combine or conquer*** the solutions ***by taking the minimum of both solutions***.\n\nThis approach becomes clear on a larger example. \n\n![image](https://assets.leetcode.com/users/images/de35a51d-4cd5-49c4-8909-d34f1b23dd37_1610921714.4782262.png)\n\n```python\ndef findMin(self, nums: List[int]) -> int:\n return self.find_min(nums, 0, len(nums) - 1)\n\t\ndef find_min(self, nums, lo, hi):\n\tif lo >= hi: return nums[lo]\n\tif nums[lo] <= nums[hi]: return nums[lo]\n\tmid = (lo + hi)//2\n\n\tleft = self.find_min(nums, lo, mid)\n\tright = self.find_min(nums, mid + 1, hi)\n\treturn min(left, right)\n```\n\ncode courtesy of [junhaowanggg](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/582964/4-Solutions-Including-Divide-and-Conquer-Binary-Search-(%2B-Follow-Up))\n\n
5
0
['Divide and Conquer', 'Binary Tree']
1
find-minimum-in-rotated-sorted-array
runtime beats 94.57 %, memory usage beats 94.67 %[best][easy][c++]
runtime-beats-9457-memory-usage-beats-94-fhu6
\n class Solution {\n public:\n int findMin(vector& nums) {\n int start=0,end=nums.size()-1;\n while(start<end){\n
rajat_gupta_
NORMAL
2020-08-16T16:00:15.746249+00:00
2020-08-16T16:06:52.598157+00:00
224
false
\n class Solution {\n public:\n int findMin(vector<int>& nums) {\n int start=0,end=nums.size()-1;\n while(start<end){\n int mid=(start+end)/2;\n if(nums[mid]<nums[end])\n end=mid;\n else\n start=mid+1;\n }\n return nums[end];\n }\n };\n\t \n**Feel free to ask any question in the comment section.\nIf you like this solution, do UPVOTE.\nHappy Coding :)**\n\t
5
0
['C', 'Binary Tree', 'C++']
0
find-minimum-in-rotated-sorted-array
Intuitive Javascript Solution
intuitive-javascript-solution-by-dawchih-fd8t
\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findMin = function(nums) {\n let left = 0;\n let right = nums.length - 1;\n // the goal
dawchihliou
NORMAL
2020-04-06T19:41:34.829844+00:00
2020-04-06T19:41:34.829899+00:00
1,165
false
```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findMin = function(nums) {\n let left = 0;\n let right = nums.length - 1;\n // the goal is to use `left` to point at the minimn number \n while (left < right) {\n const mid = Math.floor((left + right) / 2);\n if (nums[mid] > nums[right]) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n\n return nums[left];\n};\n```
5
0
['Binary Search', 'JavaScript']
2
find-minimum-in-rotated-sorted-array
Python Binary Search ( Compare to 154)
python-binary-search-compare-to-154-by-g-2jr5
The problem 154 is harder than 153. \n\nAt first , we need to solve 153 ( no duplicate exists in the array )\n\n153.Find Minimum in Rotated Sorted Array:\n\nThe
gyh75520
NORMAL
2019-09-03T08:48:10.345169+00:00
2019-09-03T08:48:10.345207+00:00
634
false
The problem 154 is harder than 153. \n\nAt first , we need to solve 153 ( no duplicate exists in the array )\n\n153.Find Minimum in Rotated Sorted Array:\n\nThese problems give no clear target , we can use ```nums[r]``` as judgement condition \nIt is very easy to find\uFF1A\n>if nums[mid] > nums[r]: # [3,4,5,1,2]\n>l = mid+1 # min exist on the right side of the middle value\n\n>if nums[mid] < nums[r]: # [1,2,3,4,5] ,[4,5,1,2,3]\n>r = mid # min exist on the left side of the middle value ( inclue middle value)\n\n>if nums[mid] == nums[r]: # Invalid\n\nCombining these conditions\uFF1A\n```python\n# 153. Find Minimum in Rotated Sorted Array\ndef findMin(self, nums: List[int]) -> int:\n l, r = 0, len(nums)-1\n while l < r:\n mid = (l+r)//2\n if nums[mid] > nums[r]:\n l = mid+1\n else:\n r = mid\n return nums[l]\n```\n\n---------------------------------------\n\n154.Find Minimum in Rotated Sorted Array II:\n\nSame idea with 153\n\nIt is very easy to find\uFF1A\n>if nums[mid] > nums[r]: # [3,4,5,1,2]\n>l = mid+1 # min exists on the right side of the middle value\n\n>if nums[mid] < nums[r]: # [1,2,3,4,5] ,[4,5,1,2,3]\n>r = mid # min exists on the left side of the middle value ( inclue middle value)\n\nHere are the different parts\uFF1A\n\n```python\nif nums[mid] == nums[r]: # valid\n\tif nums[mid] == nums[l]: # [10, 5, 10, 10, 10] or [10, 10, 10, 5, 10] \n\t\tl = l+1 # or r = r-1 # min could be on either side\uFF0Cwe just narrow the interval\n\telif nums[l] < nums[mid]: # [1, 5, 10, 10, 10] \n\t\tr = mid-1\n\telse:# [20, 5, 10, 10, 10] or [20, 10, 10, 10, 10]\n\t\tr = mid\n```\n\nCombining these conditions\uFF1A\n```python\n\t# 154. Find Minimum in Rotated Sorted Array II\n def findMin(self, nums: List[int]) -> int:\n l, r = 0, len(nums)-1\n while l < r:\n mid = (l+r)//2\n\t\t\t# condition for 154\n if nums[mid] == nums[r]:\n if nums[mid] == nums[l]:\n l = l+1 # or r = r-1\n elif nums[l] < nums[mid] : \n\t r = mid-1\n else:\n r = mid\n\t\t\t# same as 153\n elif nums[mid] > nums[r]:\n l = mid+1\n else:\n r = mid\n return nums[l]\n```\n\nWe can combine the judgment conditions in the loop, and choose a larger interval when we combine\n\n```python\n\t# 154. Find Minimum in Rotated Sorted Array II\n def findMin(self, nums: List[int]) -> int:\n l, r = 0, len(nums)-1\n while l < r:\n mid = (l+r)//2\n if nums[mid] == nums[r]:\n if nums[mid] == nums[l]:\n l = l+1 # or r = r-1\n else:\n r = mid\n elif nums[mid] > nums[r]:\n l = mid+1\n else:\n r = mid\n return nums[l]\n```
5
0
['Binary Search', 'Python3']
0
sort-array-by-parity-ii
Java two pointer one pass inplace
java-two-pointer-one-pass-inplace-by-wan-72a6
\n\nclass Solution {\n public int[] sortArrayByParityII(int[] A) {\n int i = 0, j = 1, n = A.length;\n while (i < n && j < n) {\n wh
wangzi6147
NORMAL
2018-10-14T03:40:56.858970+00:00
2018-10-26T18:01:19.582043+00:00
17,920
false
```\n\nclass Solution {\n public int[] sortArrayByParityII(int[] A) {\n int i = 0, j = 1, n = A.length;\n while (i < n && j < n) {\n while (i < n && A[i] % 2 == 0) {\n i += 2;\n }\n while (j < n && A[j] % 2 == 1) {\n j += 2;\n }\n if (i < n && j < n) {\n swap(A, i, j);\n }\n }\n return A;\n }\n private void swap(int[] A, int i, int j) {\n int temp = A[i];\n A[i] = A[j];\n A[j] = temp;\n }\n}\n\n```
208
3
[]
33
sort-array-by-parity-ii
Python one-pass, O(1) memory, simple code, beats 90%
python-one-pass-o1-memory-simple-code-be-8b2x
\nclass Solution:\n def sortArrayByParityII(self, a):\n i = 0 # pointer for even misplaced\n j = 1 # pointer for odd misplaced\n sz = le
peregrin
NORMAL
2018-12-16T15:32:56.364571+00:00
2018-12-16T15:32:56.364615+00:00
9,306
false
```\nclass Solution:\n def sortArrayByParityII(self, a):\n i = 0 # pointer for even misplaced\n j = 1 # pointer for odd misplaced\n sz = len(a)\n \n # invariant: for every misplaced odd there is misplaced even\n # since there is just enough space for odds and evens\n\n while i < sz and j < sz:\n if a[i] % 2 == 0:\n i += 2\n elif a[j] % 2 == 1:\n j += 2\n else:\n # a[i] % 2 == 1 AND a[j] % 2 == 0\n a[i],a[j] = a[j],a[i]\n i += 2\n j += 2\n\n return a\n```
175
2
[]
19
sort-array-by-parity-ii
C++ 5 lines, two pointers + 2-liner bonus
c-5-lines-two-pointers-2-liner-bonus-by-b06t6
Use two pointers to search for missplaced odd and even elements, and swap them.\n\nvector<int> sortArrayByParityII(vector<int>& A) {\n for (int i = 0, j = 1;
votrubac
NORMAL
2018-10-14T03:39:51.147321+00:00
2019-11-05T18:07:08.647681+00:00
9,576
false
Use two pointers to search for missplaced odd and even elements, and swap them.\n```\nvector<int> sortArrayByParityII(vector<int>& A) {\n for (int i = 0, j = 1; i < A.size(); i += 2, j += 2) {\n while (i < A.size() && A[i] % 2 == 0) i += 2;\n while (j < A.size() && A[j] % 2 == 1) j += 2;\n if (i < A.size()) swap(A[i], A[j]);\n }\n return A;\n}\n```\nNow, some fun for for my minimalistic functional friends. It\'s techically a two-liner, though I split ```swap``` into 3 lines for readability :) It actually may even look a bit cleaner, as you do not have to do "plus 2".\n```\nvector<int> sortArrayByParityII(vector<int>& A) {\n for (int i = 0, j = 0; i < A.size() && j < A.size(); ) swap(\n *find_if(begin(A) + i, end(A), [&] (int v) { return (i++ % 2 == 0 && v % 2 != 0) || i == A.size(); }),\n *find_if(begin(A) + j, end(A), [&] (int v) { return (j++ % 2 != 0 && v % 2 == 0) || j == A.size(); }));\n return A;\n}\n```
94
5
[]
18
sort-array-by-parity-ii
C++ O(n) time O(1) space solution with intuition for building the solution
c-on-time-o1-space-solution-with-intuiti-3pk6
Basic Idea of Question\nWe are given an array in which half of the numbers are odd, and the other half are even. So the length of the array is always even, and
sajals5031
NORMAL
2021-06-05T10:13:50.114788+00:00
2021-06-05T10:13:50.114821+00:00
3,227
false
## Basic Idea of Question\nWe are given an array in which half of the numbers are odd, and the other half are even. So the length of the array is always even, and the first index is even (0), while the last index is odd (n-1). We have to arrange the numbers in the array such that at every even index, there is an even number, while at every odd index, there is an odd number.\n\nThe most naive solution to this question is to just traverse the array, and upon finding an out-of-place element, find its replacement in the array by traversing the subarray after it. This algorithm will cost us **O(n<sup>2</sup>)** in time and **O(1)** in space, but it isn\'t enough. It just seems too naive of a solution.\n<br>\n\n## Approach 1: Separate even and odd numbers\nThe next approach that might come to mind is to just iterate over the array and separate the numbers into two groups, even and odd.\nThen we build the array again from the start by choosing an even number for each even index and an odd number for each odd index.\nThis is a good solution, and it does fit in with the least runtime possible for such an algorithm, which is **O(n)** since we have to at least check every element, so that they are all at their place, but it also requires extra space of O(n) for storing the even and odd numbers.\n\nThe code for the approach is as follows:\n```\nvector<int> sortByParityII(vector<int>& nums) {\n\tint n = nums.size();\n\tvector<int> evens, odds;\n\tevens.reserve(n/2);\n\todds.reserve(n/2);\n\tfor(int i = 0; i<n; i++) {\n\t\tif(nums[i] % 2 == 0) {\n\t\t\tevens.push_back(nums[i]);\n\t\telse {\n\t\t\todds.push_back(nums[i]);\n\t}\n\t//filling even spaces\n\tfor(int i = 0; i<n; i+=2) {\n\t\tnums[i] = evens[i/2];\n\t}\n\t//filling odd spaces\n\tfor(int i = 1; i<n; i+=2) {\n\t\tnums[i] = odds[i/2];\n\t}\n\treturn nums;\n}\n```\nIf you are confused by the lines ```evens.reserve(n/2)``` and ```odds.reserve(n/2)```, they are just ensuring beforehand that our vectors have adequate capacities, so that all push back operations are completed in O(1).\n\n**Time: O(n)** as we just iterate the array two times.\n**Space: O(n)**, the extra space required for the two arrays.\n<br>\n\n## Approach 2: Swap outliers\nWe can think of this question in another way as well. Since the number of even and odd numbers in the array is equal, if there is one outlier (even number at odd index or vice versa), there must be another outlier somewhere, since if there isn\'t, then this place has no rightful element which can fill it.\nIf we find and swap such pairs, we wouldn\'t have to care about finding the odd or even numbers and separating them. In fact, we can even do it in one iteration only, using two pointers.\n\nComing back to the question statement, as n is even,, so index 0 is even and the index (n-1) is odd. So starting at index 0 for the even pointer, and n-1 for the odd pointer would be just fine.\nWe follow the below algorithm until one of the pointers reaches the other end of the array (here i represents the even pointer, and j represents the odd pointer):\n\n1. Keep incrementing i by 2 until either it reaches the other end, or an outlier (odd number at even index).\n2. Keep decrementing j by 2 until either it reaches the other end, or an outlier (even number at odd index).\n3. Swap nums[i] and nums[j]\n\nYou might be thinking, what happens if i stops at an outlier and j reaches the other end, or vice versa?\nWell, the fact that n is even, and there being equal number of even and odd numbers prevents that situation from happening (as explained above). If there will be a pair, it will be a valid pair, otherwise both of them will reach the ends.\n\nThe code for this approach is as follows:\n```\nvector<int> sortByParityII(vector<int>& nums) {\n\tint n = nums.size();\n\tint i = 0, j = n-1;\n\twhile(i<n) {\n\t\twhile(i<n && nums[i]%2==0) i+=2;\n\t\tif(i==n) break;\n\t\twhile(j>=0 && nums[j]%2==1) j-=2;\n\t\t//swap the outliers\n\t\tswap(nums[i], nums[j]);\n\t}\n\treturn nums;\n}\n```\n\n**Time: O(n)** as we traverse the array once.\n**Space: O(1)** as we only use two pointers, and no other space.\n\n<br>\n\n**Don\'t forget to upvote** if you liked this post and learned something from it, and feel free to ask any doubts, or suggest any corrections/improvements in the comments.\n\n\n
56
1
['Two Pointers', 'C']
3
sort-array-by-parity-ii
[C++] Two pointers solution
c-two-pointers-solution-by-pankajgupta20-6ixp
\tclass Solution {\n\tpublic:\n\t\tvector sortArrayByParityII(vector& nums) {\n\t\t\tint n = nums.size();\n\t\t\tint i = 0, j = 1;\n\t\t\twhile(i < n && j < n){
pankajgupta20
NORMAL
2021-09-28T07:30:07.919140+00:00
2021-09-28T07:30:07.919174+00:00
3,206
false
\tclass Solution {\n\tpublic:\n\t\tvector<int> sortArrayByParityII(vector<int>& nums) {\n\t\t\tint n = nums.size();\n\t\t\tint i = 0, j = 1;\n\t\t\twhile(i < n && j < n){\n\t\t\t\tif(nums[i] % 2 == 0){\n\t\t\t\t\ti += 2;\n\t\t\t\t}\n\t\t\t\telse if(nums[j] % 2 == 1){\n\t\t\t\t\tj += 2;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tswap(nums[i], nums[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nums;\n\t\t}\n\t};
50
2
['Two Pointers', 'C', 'C++']
0
sort-array-by-parity-ii
[Python] O(1) space solution, explained
python-o1-space-solution-explained-by-db-bnn6
O(n) space complexity soluiton is straightforward. It is more interseting to investigate O(1) solution. The idea is to use two pointers approach, where we start
dbabichev
NORMAL
2021-09-28T07:42:22.594828+00:00
2021-09-28T07:59:35.552630+00:00
1,893
false
`O(n)` space complexity soluiton is straightforward. It is more interseting to investigate `O(1)` solution. The idea is to use two pointers approach, where we start with index `0` for even numbers and with index `1` for odd numbers. We traverse our numbers, where we can have the following options:\n\n1. if `nums[i] % 2 == 0`, then number is already on place, so we look at the next place for `i`.\n2. if `nums[j] % 2 == 1`, then number is already on place, so we look ate the next place for `j`.\n3. In the opposite case we need to sweich elements.\n\n\n#### Complexity\nTime complexity is `O(n)`, space complexity is `O(1)`.\n\n#### Code\n```python\nclass Solution:\n def sortArrayByParityII(self, nums):\n i, j, n = 0, 1, len(nums)\n while j < n and i < n:\n if nums[i] % 2 == 0:\n i += 2\n elif nums[j] % 2 == 1:\n j += 2\n else:\n nums[i], nums[j] = nums[j], nums[i]\n return nums\n```
44
1
['Two Pointers']
3
sort-array-by-parity-ii
[Java] Two pointers inplace O(n) time simple & straightforward
java-two-pointers-inplace-on-time-simple-dpf6
\npublic int[] sortArrayByParityII(int[] A) {\n int e = 0;\n int o = 1;\n \n while(e < A.length && o < A.length) {\n if(A
user2406z
NORMAL
2018-10-14T23:02:43.873830+00:00
2018-10-20T05:21:00.496008+00:00
3,731
false
```\npublic int[] sortArrayByParityII(int[] A) {\n int e = 0;\n int o = 1;\n \n while(e < A.length && o < A.length) {\n if(A[e]%2 != 0) {\n swap(A, e, o);\n o += 2;\n } else {\n e += 2;\n }\n }\n\n return A;\n }\n```
39
3
[]
11
sort-array-by-parity-ii
Linear pass using 2 pointers in C++.
linear-pass-using-2-pointers-in-c-by-tts-nzzq
We need to maintain a following invariant: A[i] is an even number at even position and A[j] is an odd number at odd position. As soon as this invariant is viola
ttsugrii
NORMAL
2018-11-15T07:22:39.617277+00:00
2018-11-15T07:22:39.617326+00:00
1,813
false
We need to maintain a following invariant: `A[i]` is an even number at even position and `A[j]` is an odd number at odd position. As soon as this invariant is violated, it\'s possible to swap numbers to restore it.\n\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& A) {\n for (int i = 0, j = 1; j < A.size() && i < A.size();) {\n if (A[i] % 2 == 0) {\n i += 2;\n } else if (A[j] % 2 == 1) {\n j += 2;\n } else {\n swap(A[i], A[j]);\n }\n }\n return A;\n }\n};\n```
30
0
[]
5
sort-array-by-parity-ii
(Python O(n) T & O(1) S) easy to understand with explanation.
python-on-t-o1-s-easy-to-understand-with-no1f
The idea: \nGetting odd numbers on odd indices, after which, even numbers would also stand right positions;\ni as even index starts from 0 (2, 4, 6...), j as od
stoneiii
NORMAL
2019-06-25T02:53:27.976198+00:00
2019-06-25T03:01:58.887728+00:00
1,823
false
The idea: \nGetting odd numbers on odd indices, after which, even numbers would also stand right positions;\n**i** as even index starts from 0 (2, 4, 6...), **j** as odd index starts from 1 (3, 5, 7...)\n\nA half of A is odd, so the length of A - **L** so 2|L, also means **L - 1** is odd;\n\nJudging every number on odd indices if it is odd, if it is, it stands at a right position, then j = j + 2 (jumping to next odd index), and \'i\' keep the same. \nOtherwise, exchanging the values between index j and i, then index \'i\' has a right value and can point to next even position i = i + 2, but we don\'t know the original value on i is odd, so j keep unchanged.\n\nAfter processing all odd indices, we get the result we want.\n```\nclass Solution(object):\n def sortArrayByParityII(self, A):\n i, j, L = 0, 1, len(A) # i - even index, j - odd index, L - length of A\n while j < L: # (L - 1) is odd, j can reach the last element, so this condition is enough\n if A[j] % 2 == 0: # judge if the value on odd indices is odd\n A[j], A[i] = A[i], A[j] # if it is even, exchange the values between index j and i\n i += 2 # even indices get a right value, then i pointer jump to next even index\n else:\n j += 2 # if it is odd, odd indices get a right value, then j pointer jump to next odd index\n return A\n```
28
0
['Python']
3
sort-array-by-parity-ii
[javascript] O(n)
javascript-on-by-haleyysz-gbgl
\n/**\n * @param {number[]} A\n * @return {number[]}\n */\nvar sortArrayByParityII = function(A) {\n let result = new Array(A.length);\n \n for(let i =
haleyysz
NORMAL
2019-02-10T22:15:45.271506+00:00
2019-02-10T22:15:45.271574+00:00
1,828
false
```\n/**\n * @param {number[]} A\n * @return {number[]}\n */\nvar sortArrayByParityII = function(A) {\n let result = new Array(A.length);\n \n for(let i = 0, even = 0, odd = 1; i < A.length; i ++) {\n if(A[i] % 2 === 0) {\n result[even] = A[i];\n even += 2;\n } else {\n result[odd] = A[i];\n odd += 2;\n }\n }\n return result;\n};\n```
23
0
['JavaScript']
2
sort-array-by-parity-ii
Python easy 2-liner
python-easy-2-liner-by-cenkay-p9mf
\nclass Solution:\n def sortArrayByParityII(self, A):\n even, odd = [a for a in A if not a % 2], [a for a in A if a % 2]\n return [even.pop() i
cenkay
NORMAL
2018-10-14T07:32:40.141117+00:00
2018-10-22T01:42:35.894099+00:00
3,458
false
```\nclass Solution:\n def sortArrayByParityII(self, A):\n even, odd = [a for a in A if not a % 2], [a for a in A if a % 2]\n return [even.pop() if not i % 2 else odd.pop() for i in range(len(A))]\n```
19
4
[]
6
sort-array-by-parity-ii
✅✅C++ two pointer Best Solution. Detailed Explanation with comments
c-two-pointer-best-solution-detailed-exp-wkrx
Intuition\n Describe your first thoughts on how to solve this problem. \nIt is given that the number of odd and even elements is the same. Now, if even elements
MdKhizr98
NORMAL
2024-01-31T05:54:38.925233+00:00
2024-11-24T05:47:31.323683+00:00
1,306
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is given that the number of odd and even elements is the same. Now, if even elements are in even positions, then automatically odd elements will be in odd positions.\n This provides the insight that if k even elements are in odd positions, then there must be k odd elements in even positions.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitially, I set i=0 and j=1.\nNOTE:- "i" will keep track of even places, and "j" will keep track of odd places.\n\nSo, if even elements are in even positions and odd elements are in odd positions, then no action is required.\n\nHowever, if this is not the case, then Swapping will occur when either of the two conditions is met:-\n\n 1. The element nums[i] is in an odd position, and it is waiting for nums[j] to be found at an even position.\n \n2. The element nums[j] is in an even position, and it is waiting for nums[i] to be found at an odd position.\n\n \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int n = nums.size();\n int i=0; //i will keep track of even place\n int j = 1; //j will keep track of odd place\n while(i<n && j<n){\n if(nums[i]%2==0) i+=2; //No need to change(i.e already in even place)\n else if(nums[j]%2==1) j+=2;//No need to change(i.e already in odd place)\n else swap(nums[i],nums[j]); \n /* Swapping will occur when either of the two conditions is met:-\n 1. The element nums[i] will be in an odd position, and it will wait until \n nums[j] is found at an even position.\n\n 2. The element nums[j] will be in an even position, and it will wait until \n nums[i] is found at an odd position.\n */\n }\n return nums;\n }\n};\n```\n![Screenshot 2024-02-19 172132.png](https://assets.leetcode.com/users/images/a3f758c0-1c71-4b67-854c-4bb2fbb3a0ca_1708343567.1240585.png)
17
0
['C++']
5
sort-array-by-parity-ii
Java 2ms (99.76% faster)
java-2ms-9976-faster-by-kbenriquez-0mj4
Get first even entry at the wrong index\n2. Get first odd entry at the wrong index\n3. swap\n4. repeat\n\npublic int[] sortArrayByParityII(int[] A) {\n i
kbenriquez
NORMAL
2019-04-28T22:34:35.640937+00:00
2019-04-28T22:34:35.641005+00:00
2,124
false
1. Get first even entry at the wrong index\n2. Get first odd entry at the wrong index\n3. swap\n4. repeat\n```\npublic int[] sortArrayByParityII(int[] A) {\n int even = 0, odd = 1;\n while(true){\n while(even < A.length && A[even] % 2 == 0) /*(1)*/\n even += 2;\n while(odd < A.length && A[odd] % 2 != 0) /*(2)*/\n odd += 2;\n if(odd >= A.length || even >= A.length) return A;\n\t\t\t\n\t\t\t/*(3)*/\n int temp = A[even];\n A[even] = A[odd];\n A[odd] = temp;\n }\n }\n```
17
1
['Java']
4
sort-array-by-parity-ii
Python3|| Easy solution.
python3-easy-solution-by-kalyan_2003-xfqp
Code\n\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n even = []\n odd = []\n lst=[]\n for i in
Kalyan_2003
NORMAL
2023-03-03T17:50:34.208298+00:00
2023-03-03T17:50:34.208339+00:00
1,783
false
# Code\n```\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n even = []\n odd = []\n lst=[]\n for i in range(len(nums)):\n if nums[i]%2 == 0:\n even.append(nums[i])\n else:\n odd.append(nums[i])\n for i in range(len(even)):\n lst.append(even[i])\n lst.append(odd[i])\n return lst\n```\n![image.png](https://assets.leetcode.com/users/images/d1d1fa02-4b7b-4404-b577-ebef47fd1b2f_1677865820.3052886.png)\n
14
0
['Array', 'Python3']
0
sort-array-by-parity-ii
3 lines JavaScript solution.
3-lines-javascript-solution-by-edgar__li-1fwq
\n let evenArray = A.filter(x => x % 2 === 0);\n let oddArray = A.filter(x => x % 2 === 1);\n return A.map((x, index) => index % 2 === 0 ? evenArray.pop() :
edgar__li
NORMAL
2019-01-03T12:44:33.139480+00:00
2019-01-03T12:44:33.139541+00:00
635
false
```\n let evenArray = A.filter(x => x % 2 === 0);\n let oddArray = A.filter(x => x % 2 === 1);\n return A.map((x, index) => index % 2 === 0 ? evenArray.pop() : oddArray.pop());\n```
13
1
[]
2
sort-array-by-parity-ii
[Python] Two Pointers - O(1) Space - Clean & Concise
python-two-pointers-o1-space-clean-conci-ukt1
Idea\n- Let iEven point to the first number which has an even index but the value is odd.\n- Let iOdd point to the first number which has an odd index but the v
hiepit
NORMAL
2021-09-28T10:20:17.348455+00:00
2021-09-28T10:24:49.448686+00:00
440
false
**Idea**\n- Let `iEven` point to the first number which has an even index but the value is odd.\n- Let `iOdd` point to the first number which has an odd index but the value is even.\n- We need to swap `nums[iEven]` and `nums[iOdd]` together since they are mismatch.\n```python\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n n = len(nums)\n iEven = 0\n iOdd = 1\n while True:\n while iEven < n and nums[iEven] % 2 == 0:\n iEven += 2\n while iOdd < n and nums[iOdd] % 2 == 1:\n iOdd += 2\n if iEven >= n or iOdd >= n:\n break\n\n nums[iEven], nums[iOdd] = nums[iOdd], nums[iEven]\n iEven += 2\n iOdd += 2\n return nums\n```\nComplexity:\n- Time: `O(N)`, where `N <= 2*10^4` is length of `nums` array.\n- Space: `O(1)`
12
0
[]
2
sort-array-by-parity-ii
Python Beginner Solution
python-beginner-solution-by-rstoltzm-rc3n
Tried to make a simple solution. \n1. Loop through initial list, check for odd/even, and append to an odd_list or even list\n2. Combine the lists with slicing t
rstoltzm
NORMAL
2018-10-16T23:59:38.734805+00:00
2018-10-17T03:23:52.773476+00:00
1,102
false
Tried to make a simple solution. \n1. Loop through initial list, check for odd/even, and append to an odd_list or even list\n2. Combine the lists with slicing to alternate odd/even lists\n\n```class Solution:\n def sortArrayByParityII(self, A):\n """\n :type A: List[int]\n :rtype: List[int]\n """\n odd_list = []\n even_list = []\n \n for i in A:\n if i % 2 == 1:\n odd_list.append(i)\n else:\n even_list.append(i)\n\n result = [None]*(len(odd_list)+len(even_list))\n result[::2] = even_list\n result[1::2] = odd_list\n return result
11
3
[]
5
sort-array-by-parity-ii
100% t.c. short solution. easy to undesrtand
100-tc-short-solution-easy-to-undesrtand-xhe6
\nPLEASE UPVOTE IF YOU LIKE.\n\n int[] ans = new int[nums.length];\n int even = -2, odd = -1;\n\n for (int i: nums){\n if (i %
Hurshidbek
NORMAL
2022-08-15T21:48:30.295623+00:00
2022-08-20T11:44:31.750878+00:00
892
false
```\nPLEASE UPVOTE IF YOU LIKE.\n```\n int[] ans = new int[nums.length];\n int even = -2, odd = -1;\n\n for (int i: nums){\n if (i % 2 == 0) ans[even+=2] = i;\n else ans[odd+=2] = i;\n }\n\n return ans;
10
0
['Java']
1
sort-array-by-parity-ii
📌📌 Simple to understand || For Beginners || 91% faster 🐍
simple-to-understand-for-beginners-91-fa-l4m4
IDEA:\n Separate all even and odd numbers Once.\n Then now replace original arr with alternate even and odd numbers.\n Here flag denotes you are at even index.\
abhi9Rai
NORMAL
2021-09-28T07:31:05.407184+00:00
2021-09-28T07:38:38.096691+00:00
1,087
false
## IDEA:\n* Separate all even and odd numbers Once.\n* Then now replace original arr with alternate even and odd numbers.\n* Here flag denotes you are at even index.\n\n**For Biginners:**\n\'\'\'\n\n\tclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n \n odd,even = [],[]\n for n in nums:\n if n%2: odd.append(n)\n else: even.append(n)\n \n o,e = 0,0\n for i in range(len(nums)):\n if i%2==0:\n nums[i]=even[e]\n e+=1\n else:\n nums[i]=odd[o]\n o+=1\n \n return nums\n\n**Most Efficient:**\n\'\'\'\n\t\n\tclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n \n e = 0 #even_index\n o = 1 #odd_index\n \n while e<len(nums) and o<len(nums):\n if nums[e]%2==0:\n e+=2\n else:\n if nums[o]%2!=0:\n o+=2\n else:\n nums[e],nums[o] = nums[o],nums[e]\n e+=2\n o+=2\n \n return num\n\n### Thanks and Upvote If you got any help !!\uD83E\uDD1E
10
0
['Python', 'Python3']
0
sort-array-by-parity-ii
Swift: Sort Array By Parity II (+ Test Cases)
swift-sort-array-by-parity-ii-test-cases-nspe
swift\nclass Solution {\n func sortArrayByParityII(_ nums: [Int]) -> [Int] {\n var map = [Int](repeating: 0, count: nums.count)\n var i = 0, j
AsahiOcean
NORMAL
2021-05-27T21:51:16.336431+00:00
2021-05-27T21:51:16.336470+00:00
327
false
```swift\nclass Solution {\n func sortArrayByParityII(_ nums: [Int]) -> [Int] {\n var map = [Int](repeating: 0, count: nums.count)\n var i = 0, j = 1\n nums.forEach({\n if $0 % 2 == 0 {\n map[i] = $0\n i += 2\n } else {\n map[j] = $0\n j += 2\n }\n })\n return map\n }\n}\n```\n\n```swift\nimport XCTest\n\n// Executed 2 tests, with 0 failures (0 unexpected) in 0.005 (0.007) seconds\n\nclass Tests: XCTestCase {\n private let s = Solution()\n func test1() {\n XCTAssertEqual(s.sortArrayByParityII([4,2,5,7]), [4,5,2,7])\n }\n func test2() {\n XCTAssertEqual(s.sortArrayByParityII([2,3]), [2,3])\n }\n}\n\nTests.defaultTestSuite.run()\n```
10
0
['Swift']
1
sort-array-by-parity-ii
[Python3] 2-pointer
python3-2-pointer-by-ye15-tmlc
Even & odd indices \n1) maintain two indices "even" and "odd" which start at 0 and 1 spectively;\n2) loop through elements in array;\n3) if element is of odd pa
ye15
NORMAL
2019-10-14T03:09:06.269602+00:00
2021-09-28T14:56:31.608812+00:00
721
false
Even & odd indices \n1) maintain two indices "even" and "odd" which start at 0 and 1 spectively;\n2) loop through elements in array;\n3) if element is of odd parity, copy it to position of "odd" index and increase odd by two; if element is of even parity, copy it to positon of "even" index and increase even by two.\n```\nclass Solution:\n def sortArrayByParityII(self, A: List[int]) -> List[int]:\n ans = [None] * len(A)\n index = [0, 1] #even & odd indices\n for x in A:\n ans[index[x%2]] = x\n index[x%2] += 2\n return ans \n```\n\nAn alternative implementation which updates A in place is as below. \n```\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n ii, i = 0, 1\n while ii < len(nums) and i < len(nums): \n if not nums[ii] & 1: ii += 2\n elif nums[i] & 1: i += 2\n else: \n nums[ii], nums[i] = nums[i], nums[ii]\n ii += 2\n i += 2\n return nums\n```
10
1
['Python3']
1
sort-array-by-parity-ii
[Java] simple code - swap odd and even indices elements.
java-simple-code-swap-odd-and-even-indic-xhkl
Use i and j to denote even and odd indices, respectively.\nLoop through input array,\n1. locate next wrongly placed item with odd index j;\n2. if current even-i
rock
NORMAL
2018-10-14T03:01:57.077075+00:00
2018-10-14T14:02:07.678038+00:00
2,817
false
Use i and j to denote even and odd indices, respectively.\nLoop through input array,\n1. locate next wrongly placed item with odd index j;\n2. if current even-index item, A[i], is wrongly placed, swap it with A[j]; otherwise, forward to the next even index;\n\nTime: O(n), space: O(1).\n\n```\n public int[] sortArrayByParityII(int[] A) {\n for (int i = 0, j = 1; i < A.length; i += 2) {\n while (j < A.length && A[j] % 2 == 1) { j += 2; } //find next odd-index item A[j] with even value.\n if (A[i] % 2 == 1) { // if odd-index item A[i] is odd, swap it with A[j].\n int t = A[i];\n A[i] = A[j];\n A[j] = t;\n j += 2;\n }\n }\n return A;\n }\n```
10
1
[]
2
sort-array-by-parity-ii
SMARTEST Solution with JAVA(beats 99% / 90%) 1.way
smartest-solution-with-javabeats-99-90-1-3zm4
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
amin_aziz
NORMAL
2023-04-21T12:03:20.335149+00:00
2023-04-21T12:03:20.335183+00:00
1,415
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int odd = 1;\n int even = 0;\n int[] ret = new int[nums.length];\n for(int a: nums){\n if(a%2==0){\n ret[even] = a;\n even += 2;\n }else{\n ret[odd] = a;\n odd+=2;\n }\n }\n return ret;\n }\n}\n```
8
0
['Java']
1
sort-array-by-parity-ii
C++[Easy to understand & simple logic]
ceasy-to-understand-simple-logic-by-roy_-vz6k
IntuitionApproachComplexity Time complexity: O[n] Space complexity: O[n] Code
roy_priyanka
NORMAL
2023-04-15T18:57:18.851430+00:00
2025-03-12T06:28:02.752713+00:00
1,759
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: - O[n] <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: - O[n] <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ``` class Solution { public: vector<int> sortArrayByParityII(vector<int>& nums) { vector<int> ans(nums.size()); int e=0,o=1; for(int i=0;i<nums.size();i++) { if(nums[i]%2==0) { ans[e]=nums[i]; e+=2; } else if(nums[i]%2!=0) { ans[o]=nums[i]; o+=2; } } return ans; } };
8
0
['C++']
4
sort-array-by-parity-ii
[JavaScript] One loop solution
javascript-one-loop-solution-by-alazebny-gnfb
\nconst sortArrayByParityII = arr => {\n let res = []\n let evenIndex = 0\n let oddIndex = 1\n for (let i = 0; i < arr.length; i++) {\n if (a
alazebnyi
NORMAL
2019-10-05T12:49:42.840034+00:00
2019-10-05T12:49:42.840119+00:00
740
false
```\nconst sortArrayByParityII = arr => {\n let res = []\n let evenIndex = 0\n let oddIndex = 1\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] % 2 === 0) {\n res[evenIndex] = arr[i]\n evenIndex = evenIndex + 2\n } else {\n res[oddIndex] = arr[i]\n oddIndex = oddIndex + 2\n }\n }\n return res\n}\n```
8
0
['JavaScript']
0
sort-array-by-parity-ii
python two pointers one pass
python-two-pointers-one-pass-by-printf_l-94tn
one pointer is used to remember the odd position, the other is to remember the even position\n\nclass Solution:\n def sortArrayByParityII(self, A):\n
printf_ll_
NORMAL
2019-01-24T03:11:44.136621+00:00
2019-01-24T03:11:44.136663+00:00
653
false
one pointer is used to remember the odd position, the other is to remember the even position\n```\nclass Solution:\n def sortArrayByParityII(self, A):\n """\n :type A: List[int]\n :rtype: List[int]\n """\n odd = 1\n even = 0\n result = [0]*len(A)\n for num in A:\n if num%2==0:\n result[even] = num\n even += 2\n else:\n result[odd] = num\n odd += 2\n return result\n```
8
0
[]
0
sort-array-by-parity-ii
Sort Array by Parity II (Java)
sort-array-by-parity-ii-java-by-harshita-gzgu
Intuition\nThe intuition behind this approach is to use two pointers, one for even indices and another for odd indices, to place even and odd numbers at their r
HarshitaSharma_Tech_1176
NORMAL
2024-01-10T16:31:05.464207+00:00
2024-01-10T16:31:05.464245+00:00
1,036
false
# Intuition\n**The intuition behind this approach is to use two pointers, one for even indices and another for odd indices, to place even and odd numbers at their respective positions in the result array. The goal is to satisfy the condition that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.**\n\n# Approach\n*Initialize evenIndex to 0 and oddIndex to 1.\nIterate through the array, and for each element:\nIf it is even, place it at the evenIndex position and increment evenIndex by 2.\nIf it is odd, place it at the oddIndex position and increment oddIndex by 2.\nReturn the modified array result.*\n\n# Complexity\n### - Time complexity: O(n)\n\n### - Space complexity: O(n)\n\n# Code\n```\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int len = nums.length;\n int[] result = new int[len];\n\n int evenIndex = 0;\n int oddIndex = 1;\n\n for (int num : nums) {\n if (num % 2 == 0) {\n result[evenIndex] = num;\n evenIndex += 2;\n } else {\n result[oddIndex] = num;\n oddIndex += 2;\n }\n }\n return result;\n }\n}\n```
7
0
['Array', 'Math', 'Two Pointers', 'Sorting', 'Java']
0
sort-array-by-parity-ii
[C++] Three O(n) Solutions
c-three-on-solutions-by-hadi15-iev2
Solution #1: Two-pass solution using two-pointer technique [O(n) Time & O(1) Space]\n\nvector<int> sortArrayByParityII(vector<int>& nums) {\n\tfor (int i = 0, c
Hadi15
NORMAL
2022-01-03T23:58:01.003600+00:00
2022-01-03T23:58:01.003666+00:00
421
false
**Solution #1:** Two-pass solution using two-pointer technique [O(n) Time & O(1) Space]\n```\nvector<int> sortArrayByParityII(vector<int>& nums) {\n\tfor (int i = 0, c = 0; i < nums.size(); i++) {\n\t\tif (nums[i] % 2 != 0) c++;\n\t\telse if (c > 0) swap(nums[i], nums[i - c]);\n\t}\n\tfor (int i = 1; i < nums.size() / 2; i += 2) swap(nums[i], nums[nums.size() - i - 1]);\n\treturn nums;\n}\n```\n\n**Solution #2:** One-pass solution using two-pointer technique [O(n) Time & O(1) Space]\n```\nvector<int> sortArrayByParityII(vector<int>& nums) {\n\tint i = 0, j = nums.size() - 1;\n\twhile (i < nums.size() && j >= 0) {\n\t\tif (nums[i] % 2 == 0) i += 2;\n\t\telse if (nums[j] % 2 != 0) j -= 2;\n\t\telse swap(nums[i], nums[j]);\n\t}\n\treturn nums;\n}\n```\n\n**Solution #3:** One-pass solution [O(n) Time & O(n) Space] \n```\nvector<int> sortArrayByParityII(vector<int>& nums) {\n\tvector<int> result(nums.size());\n\tfor (int i = 0, j = 0, k = 1; i < nums.size(); i++) {\n\t\tif (nums[i] % 2 == 0) {\n\t\t\tresult[j] = nums[i];\n\t\t\tj += 2;\n\t\t}\n\t\telse {\n\t\t\tresult[k] = nums[i];\n\t\t\tk += 2;\n\t\t}\n\t}\n\treturn result;\n}\n```\n**Note:** Not an in-place solution.
7
0
['C']
1
sort-array-by-parity-ii
Very easy two pointer solution in java for Beginners
very-easy-two-pointer-solution-in-java-f-ovq0
\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int even = 0 ;\n int odd = 1 ;\n \n while(even < nums.leng
AyushItachi
NORMAL
2021-10-02T11:39:13.860237+00:00
2021-10-02T11:39:13.860284+00:00
477
false
```\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int even = 0 ;\n int odd = 1 ;\n \n while(even < nums.length && odd < nums.length){\n \n if(nums[even]%2 != 0){\n swap(nums , even , odd);\n odd += 2 ;\n } else{\n even += 2 ;\n }\n }\n \n return nums ;\n }\n \n public void swap(int[] arr , int e1 , int e2){\n int temp = arr[e1];\n arr[e1] = arr[e2];\n arr[e2] = temp ;\n }\n}\n```
7
0
['Two Pointers', 'Java']
0
sort-array-by-parity-ii
JavaScript beats 100%
javascript-beats-100-by-fedecarrizo-tv8c
```\n var ans = new Array(A.length);\n var odd = 1, even = 0;\n \n for (var i = 0; i < A.length ; i++){\n if (A[i] % 2 === 0){\n a
fedecarrizo
NORMAL
2018-10-22T21:02:47.664727+00:00
2018-10-22T21:02:47.664769+00:00
691
false
```\n var ans = new Array(A.length);\n var odd = 1, even = 0;\n \n for (var i = 0; i < A.length ; i++){\n if (A[i] % 2 === 0){\n ans[even] = A[i];\n even += 2;\n }else{\n ans[odd] = A[i];\n odd += 2;\n }\n }\n\n return ans;
7
0
[]
2
sort-array-by-parity-ii
Python3 O(n) || O(1)
python3-on-o1-by-arshergon-psx8
\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n even, odd = 0, 1\n \n while even < len(nums) and odd
arshergon
NORMAL
2022-06-19T08:16:43.380968+00:00
2022-06-19T08:16:43.381020+00:00
936
false
```\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n even, odd = 0, 1\n \n while even < len(nums) and odd < len(nums):\n while even < len(nums) and nums[even] % 2 == 0:\n even += 2\n while odd < len(nums) and nums[odd] % 2 != 0:\n odd += 2\n \n if even < len(nums) and odd < len(nums):\n nums[even], nums[odd] = nums[odd], nums[even]\n \n even += 2\n odd += 2\n \n return nums\n```
6
0
['Two Pointers', 'Python', 'Python3']
0
sort-array-by-parity-ii
One Pass - Two Pointer Solution
one-pass-two-pointer-solution-by-uzzwal-07cq
Consider two pointers, one oddIx, pointing to odd position and the other evenIx, pointing to even position.\nBegining with oddIx at 1 and evenIx at 0, we will i
uzzwal
NORMAL
2021-10-02T18:11:15.297660+00:00
2021-10-02T18:11:35.962780+00:00
848
false
Consider two pointers, one **oddIx**, pointing to odd position and the other **evenIx**, pointing to even position.\nBegining with **oddIx at 1** and **evenIx at 0**, we will increment these **until one exceeds the length** of the array.\nIf we have odd number at even position or even number at odd position, we will like to change this, so we will **swap** only **when both**, oddIx and evenIx, **holds number of opposite category(even/odd)**.\nElse, we would simply skip the position for oddIx and evenIx if they hold number belonging to their category.\n\n\n```\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int oddIx = 1, evenIx = 0;\n while(oddIx < nums.length && evenIx < nums.length){\n if (nums[oddIx] % 2 < nums[evenIx] % 2){\n int temp = nums[oddIx];\n nums[oddIx] = nums[evenIx];\n nums[evenIx] = temp;\n }\n if (nums[oddIx] % 2 == 1)\n oddIx = oddIx + 2;\n if (nums[evenIx] % 2 == 0)\n evenIx = evenIx + 2;\n }\n return nums;\n }\n}\n```
6
0
['Two Pointers', 'Java']
1
sort-array-by-parity-ii
C++ (Simpler than Top Voted Answer)
c-simpler-than-top-voted-answer-by-mazha-jo3d
\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int n = nums.size();\n int i = 0, j = n-1;\n //i st
mazhar_mik
NORMAL
2021-09-21T08:51:09.392608+00:00
2021-09-21T08:51:09.392653+00:00
156
false
```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int n = nums.size();\n int i = 0, j = n-1;\n //i stands for even\n //j stands for odd\n while(i < n && j >= 0) {\n if (nums[i]%2 == 0) i += 2;\n else if(nums[j] %2 == 1) j -= 2;\n else swap(nums[i], nums[j]);\n }\n return nums;\n }\n};\n```
6
0
[]
0
sort-array-by-parity-ii
JAVA| faster than 99%
java-faster-than-99-by-sardineany-idat
\tclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int oddindex = 1;\n int evenindex = 0;\n int res[] = new int[nums.le
sardineany
NORMAL
2021-04-13T06:39:08.564696+00:00
2021-04-13T06:39:08.564730+00:00
640
false
\tclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int oddindex = 1;\n int evenindex = 0;\n int res[] = new int[nums.length];\n for (int i = 0; i < nums.length; i++) {\n if (nums[i]%2==0) {\n res[evenindex]=nums[i];\n evenindex+=2;\n }\n else\n {\n res[oddindex]=nums[i];\n oddindex+=2;\n }\n }\n return res;\n }\n}
6
0
['Java']
0
sort-array-by-parity-ii
Good to go 💯🚀
good-to-go-by-dixon_n-6sjz
26. Remove Duplicates from Sorted Array\n27. Remove Element\n80. Remove Duplicates from Sorted Array II\n283. Move Zeroes\n2460. Apply Operations to an Array\n9
Dixon_N
NORMAL
2024-09-19T21:42:31.975934+00:00
2024-09-19T21:47:40.910538+00:00
480
false
[26. Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/solutions/5505499/my-accepted-java-solution/)\n[27. Remove Element](https://leetcode.com/problems/remove-element/solutions/5505493/good-to-go/)\n[80. Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/solutions/5505483/my-accepted-java-solution-with-similar-problems/)\n[283. Move Zeroes](https://leetcode.com/problems/move-zeroes/solutions/5810033/good-to-go-okay-so-here-is-the-template/)\n[2460. Apply Operations to an Array](https://leetcode.com/problems/apply-operations-to-an-array/solutions/5810074/good-to-go-must-read-easy-template/)\n[905. Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/solutions/5810076/fastest-solution-out-there-bits-on-fire/)\n[2418. Sort the People](https://leetcode.com/problems/sort-the-people/solutions/5810092/goo-to-go-all-possible-solution/)\n\n# Code\n```java []\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int i = 0, j = 1, n = nums.length;\n\n while (i < n && j < n) {\n // Find the next even index with an odd number\n while (i < n && (nums[i] & 1) == 0) {\n i += 2;\n }\n // Find the next odd index with an even number\n while (j < n && (nums[j] & 1) == 1) {\n j += 2;\n }\n // If both indices are valid, swap the elements\n if (i < n && j < n) {\n swap(i, j,nums);\n }\n }\n return nums;\n }\n\n void swap(int i, int j, int[] nums) {\n if (nums[i] != nums[j]) { // Only perform swap if the indices are different to avoid zeroing out the same number\n nums[i] = nums[i] ^ nums[j]; // Step 1: nums[i] holds the XOR of nums[i] and nums[j]\n nums[j] = nums[i] ^ nums[j]; // Step 2: nums[j] now holds the original value of nums[i]\n nums[i] = nums[i] ^ nums[j]; // Step 3: nums[i] now holds the original value of nums[j]\n }\n }\n}\n\n```
5
0
['Java']
4
sort-array-by-parity-ii
Easy to Understand Java Code || Beats 100%
easy-to-understand-java-code-beats-100-b-vurl
Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n# Code\n\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int i =
Saurabh_Mishra06
NORMAL
2024-02-15T04:50:45.459815+00:00
2024-02-15T04:50:45.459839+00:00
832
false
# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int i = 0, j = 1, n = nums.length;\n while (i < n && j < n) {\n while (i < n && nums[i] % 2 == 0) {\n i += 2;\n }\n while (j < n && nums[j] % 2 == 1) {\n j += 2;\n }\n if (i < n && j < n) {\n swap(nums, i, j);\n }\n }\n return nums;\n }\n private void swap(int[] nums, int i, int j) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n}\n```
5
0
['Java']
1
sort-array-by-parity-ii
Solution
solution-by-deleted_user-ydp9
C++ []\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int n=nums.size();\n int i=0;\n int j=1;\n
deleted_user
NORMAL
2023-05-13T12:10:06.784641+00:00
2023-05-13T13:33:41.868929+00:00
855
false
```C++ []\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int n=nums.size();\n int i=0;\n int j=1;\n while(i<n && j<n){\n if(nums[i]%2==0)\n i=i+2;\n else if(nums[j]%2==1)\n j=j+2;\n else\n swap(nums[i],nums[j]);\n }\n return nums;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n\n j=1\n\n for i in range(0,len(nums),2):\n if nums[i]%2:\n while nums[j]%2:\n j+=2\n nums[i],nums[j]=nums[j],nums[i]\n\n return nums\n```\n\n```Java []\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int[] freq = new int[1001];\n for (int n : nums){\n freq[n]++;\n }\n for (int k = 0; k < 2; k++) {\n int cur = k;\n for (int i = k; i < nums.length; i += 2) {\n while (freq[cur] == 0) cur += 2;\n freq[cur]--;\n nums[i] = cur;\n }\n }\n return nums;\n }\n}\n```\n
5
0
['C++', 'Java', 'Python3']
0
sort-array-by-parity-ii
SImple C++ two pointers solution
simple-c-two-pointers-solution-by-sachde-5eyy
Simple two pointers solution\n```\nclass Solution {\npublic:\n vector sortArrayByParityII(vector& A) {\n int n = A.size();\n for(int i = 0, j = 1
sachdeva282
NORMAL
2021-02-04T09:40:45.762423+00:00
2021-02-04T09:40:45.762455+00:00
398
false
Simple two pointers solution\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& A) {\n int n = A.size();\n for(int i = 0, j = 1; j < A.size() && i < A.size();){\n if(A[i]%2==0 )\n i+=2;\n else if(A[j]%2==1)\n j+=2;\n else(swap(A[i],A[j]));\n \n }\n return A;\n }\n};
5
0
['C']
0
sort-array-by-parity-ii
simple and easy understanding c++ code
simple-and-easy-understanding-c-code-by-hcyj8
\ncpp []\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int n=nums.size();\n vector<int>arr(n);\n i
sampathkumar718
NORMAL
2024-10-11T13:24:52.737100+00:00
2024-10-11T13:24:52.737131+00:00
342
false
\n```cpp []\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int n=nums.size();\n vector<int>arr(n);\n int a=0,b=1;\n for(int i=0;i<n;i++){\n if(nums[i]%2==0){\n arr[a]=nums[i];\n a+=2;\n }\n else{\n arr[b]=nums[i];\n b+=2;\n }\n }\n return arr;\n \n }\n};\n```
4
0
['C++']
0
sort-array-by-parity-ii
C++ | Easy Solution
c-easy-solution-by-venispatel-2lht
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
VenisPatel
NORMAL
2023-07-07T18:44:52.972532+00:00
2023-07-07T18:44:52.972560+00:00
378
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int even = 0 , odd=1;\n\t\t\t\tint n = nums.size() ;\n\t\t\t\twhile(even < n && odd < n){\n\t\t\t\t\tif(nums[even]%2==0){\n\t\t\t\t\t\teven += 2;\n\t\t\t\t\t}\n\t\t\t\t\tif(nums[odd]%2 == 1){\n\t\t\t\t\t\todd+=2;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tswap(nums[even],nums[odd]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nums;\n }\n};\n```
4
0
['C++']
1
sort-array-by-parity-ii
🔥🔥Beats 99%||OPTIMIZATION||Two solution||O(2N)->O(N)
beats-99optimizationtwo-solutiono2n-on-b-j8j1
Intuition One\n Describe your first thoughts on how to solve this problem. \n1. since half of array contains even and odd numbers, and we have to place even at
Bhaskar_Agrawal
NORMAL
2023-01-31T07:05:49.534007+00:00
2023-01-31T07:05:49.534034+00:00
736
false
# Intuition One\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. since half of array contains even and odd numbers, and we have to place even at even elements indexes and odd elements at odd indexes so to avoid complexity we declare another vector for even and odd for easy way.\n# Approach Number One\n<!-- Describe your approach to solving the problem. -->\n1. declare even and odd vector. if nums[i] is even array, pushback it in even and if it is odd then in odd array\n2. now, in loop, check whether i is even or odd, accordingly set even elements at even indexes and odd elements at odd indexes respectively.\n3. I have taken k and m so that i can excess even and odd array elements\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(2N)-> O(N)\n\n# Code One\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n vector<int> even;\n vector<int> odd;\n\n //seperating even and odd elements\n for(int i=0; i < nums.size(); i++)\n {\n if(nums[i] & 1)\n odd.push_back(nums[i]);\n else \n even.push_back(nums[i]);\n }\n int k=0, m=0;\n inserting even element at even index and odd at odd index.\n for(int i=0; i < nums.size(); i++)\n {\n if(i&1)//odd\n nums[i]= odd[m++];\n else//even\n nums[i]= even[k++];\n }\n return nums;\n }\n};\n```\n# Intuition Two\nWe can solve this without declaring extra arrays, that is, even and odd. We will check directly nums[i] is even or odd and directly place it at its respective index in ans vector.\n\n# Approach Number Two(OPTIMIZED)\n1. iterate throughout the array, check nums[i] is even or odd. \n2. if nums[i] is even set it to even index and if it is odd set it to odd index.\n\n# Time Complexity -> O(N)\n# Space Complexity ->O(1)\nCode block\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n vector<int> ans;\n int k=1, m=0;\n for(int i=0; i < nums.size(); i++)\n {\n if(nums[i] & 1) //odd\n {\n ans[k]= nums[i];\n k=k+2;\n }\n else//even\n {\n ans[m]=nums[i];\n m=m+2;\n }\n }\n return ans;\n }\n};\n// hope you like it. Upvote it please. If you find any problem, do let me know in the comment section.\n
4
1
['C++']
2
sort-array-by-parity-ii
js
js-by-bakigul-0f79
\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar sortArrayByParityII = function(nums) {\nlet res = [];\nnums = nums.sort()\n\n\nlet odd = [];\n
bakigul
NORMAL
2022-10-29T13:48:54.552875+00:00
2022-10-29T13:48:54.552916+00:00
620
false
```\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar sortArrayByParityII = function(nums) {\nlet res = [];\nnums = nums.sort()\n\n\nlet odd = [];\nlet even = [];\nfor (let i = 0; i < nums.length; i++) {\n if(nums[i] % 2 === 0) odd.push(nums[i]);\n else {\n even.push(nums[i])\n } \n}\nfor (let i = 0; i < nums.length; i++) {\n if(i % 2 === 0)\n res.push(odd.pop())\n else res.push(even.pop())\n}\nreturn res\n};\n```\n
4
0
['JavaScript']
1
sort-array-by-parity-ii
C++ || Easy ||Even & odd Vector || ✅
c-easy-even-odd-vector-by-tridibdalui04-lfvi
Simple Solution using Even & Odd Vector \n\n\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& a) {\n vector<int>even;\n
tridibdalui04
NORMAL
2022-10-19T13:42:07.676322+00:00
2022-10-19T13:42:07.676363+00:00
915
false
### Simple Solution using Even & Odd Vector \n\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& a) {\n vector<int>even;\n vector<int>odd;\n vector<int>ans;\n for(int i=0;i<a.size();i++)\n {\n if(a[i]%2==0)\n even.push_back(a[i]);\n else\n odd.push_back(a[i]);\n }\n int n=even.size();\n for(int i=0;i<n;i++)\n {\n ans.push_back(even[i]);\n ans.push_back(odd[i]);\n }\n return ans;\n }\n};\n```
4
0
['C']
0
sort-array-by-parity-ii
✔ 2 Solutions || Using Extra Space and Without Extra Space || C++
2-solutions-using-extra-space-and-withou-ejpa
Using Extra Space : O(N) #\n\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n \n vector<int> odd, even;\n
BharatUpadhyay
NORMAL
2022-09-26T20:41:00.313548+00:00
2022-09-26T20:41:00.313587+00:00
937
false
# **Using Extra Space : O(N)** #\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n \n vector<int> odd, even;\n for(int i = 0 ; i < nums.size(); i++)\n {\n if((nums[i]&1) == 1)\n odd.push_back(nums[i]);\n else\n even.push_back(nums[i]);\n }\n int e = 0, o = 0;\n for(int i = 0 ; i < nums.size(); i++)\n {\n if((i & 1) == 0){\n nums[i] = even[e];\n e++;\n }\n else\n {\n nums[i] = odd[o];\n o++;\n }\n }\n return nums;\n }\n};\n```\n# **Without Using Extra Space : O(1)** #\n```\nclass Solution{\npublic:\n vector<int> sortArrayByParityII(vector<int> &nums)\n {\n int i = 0, j = 1, n = nums.size();\n while (i < n && j < n)\n {\n if (nums[i] % 2 == 0)\n i += 2;\n else if (nums[j] % 2 != 0)\n j += 2;\n else\n {\n swap(nums[i], nums[j]);\n i += 2;\n j += 2;\n }\n }\n return nums;\n }\n\t```
4
0
['C']
0
sort-array-by-parity-ii
Python | Two Pointers | O(n) Time |Explanation.
python-two-pointers-on-time-explanation-rg7sl
Success\nDetails \nRuntime: 228 ms, faster than 73.41% of Python3 online submissions for Sort Array By Parity II.\nMemory Usage: 16.1 MB, less than 91.62% of Py
vkadu68
NORMAL
2022-05-20T15:21:36.666289+00:00
2022-05-20T15:21:36.666328+00:00
323
false
<b>Success</b>\nDetails \nRuntime: 228 ms, faster than <b>73.41% </b>of Python3 online submissions for Sort Array By Parity II.\nMemory Usage: 16.1 MB, less than <b>91.62%</b> of Python3 online submissions for Sort Array By Parity II.\n\n\n1. Itterating i pointer over the array starting from zero and skipping one element so i will be always even.\n2. Check if the current element is odd or even\n3. If even we dont have to do anything\n4. if odd chek j pointer which was initillized at 1.\n5. Itterating j pointer over the array starting from one and skipping one element so i will be always odd.\n6. if jth element is even we have to swap jth element with ith.\n\n```\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n j=1\n for i in range(0,len(nums),2):\n if nums[i]%2!=0:\n while nums[j]%2!=0:\n j=j+2\n nums[i],nums[j]=nums[j],nums[i]\n return nums\n \n```
4
0
['Two Pointers', 'Python']
0
sort-array-by-parity-ii
C++ easy to understand step by step solution
c-easy-to-understand-step-by-step-soluti-xu86
\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n \n vector<int> result(nums.size());\n int even=0,od
Richach10
NORMAL
2022-02-16T02:56:31.201020+00:00
2022-02-16T02:56:31.201067+00:00
427
false
```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n \n vector<int> result(nums.size());\n int even=0,odd=1;\n for(int i=0;i<nums.size();i++)\n {\n if(nums[i]%2==0)\n {\n result[even]=nums[i];\n even+=2;\n }\n else if(nums[i]%2!=0)\n \n {\n result[odd]=nums[i];\n odd+=2;\n }\n \n }\n return result;\n }\n};\n```
4
0
['C', 'C++']
0
sort-array-by-parity-ii
Two Pointer Solution | Python 3 | beats 90%
two-pointer-solution-python-3-beats-90-b-bx0q
\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n \n e = 0 #even_index\n o = 1 #odd_index\n \n
aishvary
NORMAL
2021-07-11T08:41:55.204993+00:00
2021-07-11T08:41:55.205025+00:00
462
false
```\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n \n e = 0 #even_index\n o = 1 #odd_index\n \n while e<len(nums) and o<len(nums):\n if nums[e]%2==0:\n e+=2\n else:\n if nums[o]%2!=0:\n o+=2\n else:\n nums[e],nums[o] = nums[o],nums[e]\n e+=2\n o+=2\n \n return nums\n\n```
4
0
['Two Pointers', 'Python', 'Python3']
0
sort-array-by-parity-ii
C++ in place solution for 90% faster solution
c-in-place-solution-for-90-faster-soluti-69i7
\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n \n for(int i =0 , j =1 ; j < nums.size() && i <nums.size(
sourav_17
NORMAL
2021-05-15T16:00:53.836759+00:00
2021-05-15T16:00:53.836804+00:00
374
false
```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n \n for(int i =0 , j =1 ; j < nums.size() && i <nums.size();)\n {\n if(nums[i] %2 ==0)\n i+=2;\n else if(nums[j] % 2 ==1)\n j+=2;\n else\n swap(nums[i],nums[j]);\n }\n return nums;\n \n \n }\n};\n```
4
0
['C', 'C++']
2
sort-array-by-parity-ii
[Javascript] InPlace and using space 90% faster
javascript-inplace-and-using-space-90-fa-tb5s
Please upvote if you find this solution useful\n\nIn place\n\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar sortArrayByParityII = function(num
shubhamsoni8769
NORMAL
2021-05-13T11:21:15.779167+00:00
2021-09-28T09:39:10.986370+00:00
220
false
**Please upvote if you find this solution useful**\n\n**In place**\n```\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar sortArrayByParityII = function(nums) {\n let even = 0;\n let odd = nums.length - 1;\n while(even < nums.length && odd >= 0){\n \n if(nums[even] % 2==0 && nums[odd] % 2 !== 0){\n even = even + 2;\n odd = odd - 2\n }else if(nums[even] % 2 !== 0 && nums[odd] % 2 == 0){\n [ nums[even] , nums[odd] ] = [ nums[odd] , nums[even] ]\n }else if(nums[even] % 2 ==0 ){\n even = even+2;\n }else{\n odd = odd - 2;\n }\n }\n return nums\n};\n```\n\n\n**Using space**\n```\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar sortArrayByParityII = function(nums) {\n var arr = new Array(nums.length);\n var even =0;\n var odd = 1;\n for(let i=0; i<nums.length; i++){\n if(nums[i] % 2 === 0){\n arr[even] = nums[i];\n even +=2;\n }else{\n arr[odd] = nums[i]\n odd +=2\n }\n }\n return arr\n \n};\n```
4
0
['Two Pointers', 'JavaScript']
1
sort-array-by-parity-ii
c++(12ms 98%) two pointers, in place
c12ms-98-two-pointers-in-place-by-zx007p-8z4p
Runtime: 12 ms, faster than 98.13% of C++ online submissions for Sort Array By Parity II.\nMemory Usage: 21.5 MB, less than 29.09% of C++ online submissions for
zx007pi
NORMAL
2021-05-08T14:04:12.882336+00:00
2021-05-08T14:04:12.882369+00:00
308
false
Runtime: 12 ms, faster than 98.13% of C++ online submissions for Sort Array By Parity II.\nMemory Usage: 21.5 MB, less than 29.09% of C++ online submissions for Sort Array By Parity II.\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& A) {\n int i = 0, ni = A.size(), j = 1, nj = A.size() + 1;\n \n while(true){\n while(i != ni && A[i]%2 == 0) i+=2;\n while(j != nj && A[j]%2 == 1) j+=2;\n if(i == ni) break;\n swap(A[i],A[j]);\n }\n return A;\n }\n};\n```
4
0
['C', 'C++']
0
sort-array-by-parity-ii
Python3 easy to understand solution
python3-easy-to-understand-solution-by-a-s7w5
class Solution:\n def sortArrayByParityII(self, A: List[int]) -> List[int]:\n\t\n op=[0]*len(A)\n e=0\n o=1\n for i in A:\n
ashu_y
NORMAL
2020-11-01T15:34:04.163416+00:00
2020-11-01T15:34:04.163452+00:00
293
false
class Solution:\n def sortArrayByParityII(self, A: List[int]) -> List[int]:\n\t\n op=[0]*len(A)\n e=0\n o=1\n for i in A:\n if i%2==0:\n op[e]=i\n e+=2\n else:\n op[o]=i\n o+=2\n return op\n
4
0
['Python', 'Python3']
0
sort-array-by-parity-ii
C O(n) solution
c-on-solution-by-debbiealter-6bx8
\nint* sortArrayByParityII(int* A, int ASize, int* returnSize)\n{\n int *res = malloc(sizeof(int) * ASize);\n *returnSize = ASize;\n int *odd, *even, i
debbiealter
NORMAL
2020-07-30T20:35:15.245461+00:00
2020-07-30T21:28:17.311174+00:00
177
false
```\nint* sortArrayByParityII(int* A, int ASize, int* returnSize)\n{\n int *res = malloc(sizeof(int) * ASize);\n *returnSize = ASize;\n int *odd, *even, i = 0;\n \n odd = res + 1;\n even = res;\n \n while(i < ASize)\n {\n if(A[i] % 2)\n {\n *odd = A[i];\n odd +=2;\n i++;\n \n }\n else\n {\n *even = A[i];\n even += 2;\n i++;\n }\n }\n return res;\n}\n```
4
0
[]
1
sort-array-by-parity-ii
Java | faster than 99.63%
java-faster-than-9963-by-monsterspyy-zsgv
\nclass Solution {\n \n void swap(int[] A, int i, int j){\n int tmp = A[i];\n A[i] = A[j];\n A[j] = tmp;\n }\n \n public
monsterspyy
NORMAL
2020-03-31T16:01:42.148427+00:00
2020-06-30T19:31:06.502446+00:00
372
false
```\nclass Solution {\n \n void swap(int[] A, int i, int j){\n int tmp = A[i];\n A[i] = A[j];\n A[j] = tmp;\n }\n \n public int[] sortArrayByParityII(int[] A) {\n int odd_p = 1;\n int n = A.length;\n \n for(int i=0;i<n;i+=2){\n if(A[i]%2 == 1){\n while(A[odd_p]%2 == 1)\n odd_p += 2;\n swap(A, i, odd_p);\n }\n }\n \n return A;\n }\n}\n```
4
0
['Java']
1
sort-array-by-parity-ii
Solution in Python 3 (beats 100%) (two-pointer) ( Space: O(1) )
solution-in-python-3-beats-100-two-point-baj5
```\nclass Solution:\n def sortArrayByParityII(self, A: List[int]) -> List[int]:\n \tj = 1\n \tfor i in range(0,len(A),2):\n \t\tif A[i] % 2 == 0: c
junaidmansuri
NORMAL
2019-08-02T05:19:10.701553+00:00
2019-08-02T17:10:07.774799+00:00
172
false
```\nclass Solution:\n def sortArrayByParityII(self, A: List[int]) -> List[int]:\n \tj = 1\n \tfor i in range(0,len(A),2):\n \t\tif A[i] % 2 == 0: continue\n \t\twhile A[j] % 2 != 0: j += 2\n \t\tA[i], A[j] = A[j], A[i]\n \treturn A\n\t\t\n\t\t\n- Junaid Mansuri
4
0
['Two Pointers']
0
sort-array-by-parity-ii
Java two pointers one pass, beats 99%
java-two-pointers-one-pass-beats-99-by-g-ph5u
\n`public int[] sortArrayByParityII(int[] A) {\n int[] res = new int[A.length];\n int i = 0, k = 1;\n for (int j = 0; j < A.length; j++) {\
guptapreksha0
NORMAL
2019-04-01T22:44:04.984569+00:00
2019-04-01T22:44:04.984634+00:00
212
false
```\n`public int[] sortArrayByParityII(int[] A) {\n int[] res = new int[A.length];\n int i = 0, k = 1;\n for (int j = 0; j < A.length; j++) {\n if (A[j] % 2 == 0) {\n res[i] = A[j];\n i+=2;\n } \n else {\n res[k] = A[j];\n k+=2;\n }\n }\n return res;\n }\n```
4
0
[]
1
sort-array-by-parity-ii
C++ . this problem is so easy that I code it fluently with no change
c-this-problem-is-so-easy-that-i-code-it-tkju
\n\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& A) {\n \n for(int i=0,j=1;j<A.size();){\n if(A[i]%2 ==
ignorantcoding
NORMAL
2018-12-22T15:45:26.357228+00:00
2018-12-22T15:45:26.357276+00:00
269
false
```\n\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& A) {\n \n for(int i=0,j=1;j<A.size();){\n if(A[i]%2 == 1 && A[j]%2 == 0){\n swap(A[i],A[j]);\n i=i+2;\n j=j+2;\n }else if(A[i]%2 == 0 && A[j]%2 == 0){\n i=i+2;\n }else if(A[i]%2 == 1 && A[j]%2 == 1){\n j=j+2;\n }else{\n i=i+2;\n j=j+2;\n }\n }\n return A;\n }\n};\n\n```
4
0
[]
0
sort-array-by-parity-ii
javascript
javascript-by-yinchuhui88-6i7a
``` var sortArrayByParityII = function(A) { let oddIndex = 1; let evenIndex = 0; let result = new Array(A.length); for(let i = 0; i < A.length; i++) {
yinchuhui88
NORMAL
2018-10-18T01:54:41.610539+00:00
2018-10-18T01:54:41.610608+00:00
369
false
``` var sortArrayByParityII = function(A) { let oddIndex = 1; let evenIndex = 0; let result = new Array(A.length); for(let i = 0; i < A.length; i++) { if(A[i] % 2 == 0) { result[evenIndex] = A[i]; evenIndex += 2; } else { result[oddIndex] = A[i]; oddIndex += 2; } } return result; }; ```
4
0
[]
2
sort-array-by-parity-ii
EASY SOLUTION IN JAVA BEATING 99.94% IN 2ms
easy-solution-in-java-beating-9994-in-2m-kscp
IntuitionWe are given an array nums where half of the integers are even and the other half are odd. Our goal is to rearrange the array such that: - Even integer
arshi_bansal
NORMAL
2025-02-03T06:16:30.210048+00:00
2025-02-03T06:16:30.210048+00:00
452
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> We are given an array nums where half of the integers are even and the other half are odd. Our goal is to rearrange the array such that: - Even integers are placed at even indices (i.e., indices 0, 2, 4, …). - Odd integers are placed at odd indices (i.e., indices 1, 3, 5, …). # Approach <!-- Describe your approach to solving the problem. --> 1. **Two Pointer Technique:** - **We use two indices:** evenIndex to track the next available even index (starting from 0) and oddIndex to track the next available odd index (starting from 1). - **Iterate through the array:** - For each number in nums, check if it is even or odd. - If the number is even, place it at the current evenIndex and then increment evenIndex by 2 to move to the next available even position. - If the number is odd, place it at the current oddIndex and then increment oddIndex by 2 to move to the next available odd position. 2. **Fill the Result Array:** - During the iteration, we populate the result array with the appropriate numbers in their respective indices. 3. **Final Output:** - After processing all numbers, the result array will contain the even numbers at even indices and odd numbers at odd indices, as required. # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> ![image.png](https://assets.leetcode.com/users/images/70fa4bf9-fadb-4c6c-bb20-3cd93d6d8906_1738563381.3005545.png) # Code ```java [] class Solution { public int[] sortArrayByParityII(int[] nums) { int n = nums.length; int[] result = new int[n]; int evenIndex = 0; int oddIndex = 1; for (int num : nums) { if (num % 2 == 0) { result[evenIndex] = num; evenIndex += 2; } else { result[oddIndex] = num; oddIndex += 2; } } return result; } } ```
3
0
['Array', 'Two Pointers', 'Sorting', 'Java']
0
sort-array-by-parity-ii
Easy Solution in c++ || Beats 88% of c++ users
easy-solution-in-c-beats-88-of-c-users-b-uu2r
Intuition\nGiven an array of integers where half of the integers are even and half are odd, we need to rearrange the array so that every even-indexed position c
mdrashid7520
NORMAL
2024-06-07T08:22:31.500438+00:00
2024-06-07T08:22:31.500469+00:00
226
false
# Intuition\nGiven an array of integers where half of the integers are even and half are odd, we need to rearrange the array so that every even-indexed position contains an even number and every odd-indexed position contains an odd number.\n\n# Approach\n1. **Separate Odd and Even Numbers:** Traverse the array and separate the numbers into two different vectors, one for odd numbers and one for even numbers.\n2. **Reconstruct the Array:** Using the two vectors, place the even numbers at the even indices and the odd numbers at the odd indices of the original array.\n\n# Complexity\n- Time complexity:\n**O(N)**\n\n- Space complexity:\n**O(N)**\n![3815c804-b225-4c1f-b62b-c2af5cfc1a0e_1679045089.4677224.jpeg](https://assets.leetcode.com/users/images/f9019711-6399-4c71-8f01-408380dfbb3c_1717748538.8602538.jpeg)\n\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n\n vector<int> odd, even;\n\n for(int i = 0; i<nums.size(); i++)\n {\n if(nums[i]%2 != 0)\n odd.push_back(nums[i]);\n else\n even.push_back(nums[i]);\n }\n for(int i = 0; i<nums.size()/2; i++)\n {\n nums[2*i] = even[i];\n nums[2*i + 1] = odd[i];\n }\n return nums;\n \n }\n};\n```
3
0
['C++']
1
sort-array-by-parity-ii
SMARTEST Solution with JAVA(beats 99% / 50%) 2.way
smartest-solution-with-javabeats-99-50-2-f6e9
\n\n# Code\n\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int even = 0;\n int odd = 1;\n\n while(true){\n
amin_aziz
NORMAL
2023-04-21T12:07:57.890370+00:00
2023-04-21T12:07:57.890407+00:00
677
false
\n\n# Code\n```\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int even = 0;\n int odd = 1;\n\n while(true){\n while(even<nums.length && nums[even]%2 == 0){\n even += 2;\n }\n while(odd<nums.length && nums[odd]%2 == 1){\n odd += 2;\n }\n if(odd >= nums.length || even >= nums.length) break;\n\n int temp = nums[odd];\n nums[odd] = nums[even];\n nums[even] = temp;\n }\n return nums;\n }\n}\n```
3
0
['Java']
2
sort-array-by-parity-ii
Most easy way, Efficient approach, Beats 95%
most-easy-way-efficient-approach-beats-9-24sv
Intuition\nAs soon as i saw the problem it was clear that we have to swap any unwanted element with respect to its index. i.e even element in odd index and odd
Adit_14
NORMAL
2023-03-16T15:19:45.162452+00:00
2023-03-16T15:19:45.162488+00:00
495
false
# Intuition\nAs soon as i saw the problem it was clear that we have to swap any unwanted element with respect to its index. i.e even element in odd index and odd element in even index.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTwo pointers approach. Here we will take two pointers i and j, i is to find any odd element in even index, so i will start from 0 (i=0), j is to find even any element in odd index. When these both condition are true just swap i and j.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int n=nums.size();\n int i=0,j=1;\n while(i<n && j<n)\n {\n while(i<n && nums[i]%2==0)\n i+=2;\n while(j<n && nums[j]%2!=0)\n j+=2;\n if(i<n)\n swap(nums[i],nums[j]);\n i+=2;j+=2;\n }\n return nums;\n }\n};\n```
3
0
['C++']
0
sort-array-by-parity-ii
Python3 - Simple Solution - Beats 99%
python3-simple-solution-beats-99-by-astr-ynbu
\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n\n answer=[]\n\n # We split nums into even entries and odd en
Astros
NORMAL
2022-12-26T09:16:53.254019+00:00
2022-12-26T09:16:53.254062+00:00
815
false
```\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n\n answer=[]\n\n # We split nums into even entries and odd entries\n even = [n for n in nums if n%2 == 0]\n odd = [n for n in nums if n%2 == 1]\n\n # We fill answer with even and odd entries \n for a, b in zip(even, odd):\n answer.append(a)\n answer.append(b)\n \n return answer\n```
3
0
['Python3']
0
sort-array-by-parity-ii
Cpp || Two pointer || In-Place 🔥🔥🔥
cpp-two-pointer-in-place-by-mighty_horse-s1uf
\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n \n int odd = 1; // pointer at odd index\n int even
vikramsingh027
NORMAL
2022-11-16T15:42:05.653797+00:00
2022-11-16T15:42:05.653833+00:00
334
false
```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n \n int odd = 1; // pointer at odd index\n int even = 0; //pointer at even index \n \n while(even<nums.size()){\n if(nums[even] % 2 == 0){ // if even place has even value \n even += 2; // increment even pointer\n }\n else{ // else even place has odd value\n swap(nums[even], nums[odd]); // swap values such that odd pointer will surely have odd value\n odd += 2; // increment odd pointer\n }\n }\n return nums; // return your in-place solution \n }\n};\n```
3
0
[]
1
sort-array-by-parity-ii
85ms Java Solution but Easy to Understand
85ms-java-solution-but-easy-to-understan-0vs6
\nclass Solution {\n public int[] sortArrayByParityII(int[] A) {\n \n List<Integer> even = new ArrayList<>();\n List<Integer> odd = new
Janhvi__28
NORMAL
2022-10-14T18:13:37.680299+00:00
2022-10-14T18:13:37.680338+00:00
856
false
```\nclass Solution {\n public int[] sortArrayByParityII(int[] A) {\n \n List<Integer> even = new ArrayList<>();\n List<Integer> odd = new ArrayList<>();\n \n for (int n : A) {\n if (n % 2 == 0)\n even.add(n);\n else \n odd.add(n);\n }\n int[] result = new int[A.length];\n for (int i = 0; i < A.length; i++) {\n if (i % 2 == 0) {\n result[i] = even.remove(0);\n } else {\n result[i] = odd.remove(0);\n }\n }\n return result;\n }\n}\n```
3
0
[]
1
sort-array-by-parity-ii
Java Easiest Solution || 2 Approaches Faster Than 80%Online Submission || Easy Understanding
java-easiest-solution-2-approaches-faste-ecxb
\n//Approch :- 1 Runtime 9Ms Faster Than 33.3%\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int even = 0,odd = 1;\n int
Hemang_Jiwnani
NORMAL
2022-10-14T11:02:56.018784+00:00
2022-10-14T11:02:56.018809+00:00
553
false
```\n//Approch :- 1 Runtime 9Ms Faster Than 33.3%\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int even = 0,odd = 1;\n int[] arr = new int[nums.length];\n for(int i: nums){\n if(i%2 == 0){\n arr[even] = i;\n even+=2;\n }\n else{\n arr[odd] = i;\n odd+=2;\n }\n }\n return arr;\n }\n}\n\n\n//Approch :- 2 Runtime 4Ms Faster Than 77.63%\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int even=0,odd=1;\n int[] arr = new int[nums.length];\n while(even<nums.length && odd<nums.length){\n while(even<nums.length && nums[even]%2 == 0){\n even+=2;\n }\n while(odd<nums.length && nums[odd]%2 == 1){\n odd+=2;\n }\n if(even<nums.length && odd<nums.length){\n int temp = nums[even];\n nums[even] = nums[odd];\n nums[odd] = temp;\n }\n }\n return nums;\n }\n}\n```
3
0
['Java']
1
sort-array-by-parity-ii
JAVA | Two solutions | Extra space and In-place
java-two-solutions-extra-space-and-in-pl-c1en
Please Upvote !!! (\u25E0\u203F\u25E0)\n##### 1. Using extra-space (stack):\n\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n Sta
sourin_bruh
NORMAL
2022-10-03T12:37:47.479988+00:00
2022-10-03T12:37:47.480039+00:00
220
false
### ***Please Upvote !!!*** **(\u25E0\u203F\u25E0)**\n##### 1. Using extra-space (stack):\n```\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n Stack<Integer> evens = new Stack<>();\n Stack<Integer> odds = new Stack<>();\n\n for (int n : nums) {\n if (n % 2 == 0) evens.add(n);\n else odds.add(n);\n }\n\n for (int i = 0; i < nums.length; i++) {\n if (i % 2 == 0) nums[i] = evens.pop();\n else nums[i] = odds.pop();\n }\n\n return nums;\n }\n}\n\n// TC: O(n), SC: O(n)\n```\n##### 2. In-place: \n```\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int i = 0, j = 1;\n int n = nums.length;\n\n while (i < n && j < n) {\n while (i < n && nums[i] % 2 == 0) i += 2;\n while (j < n && nums[j] % 2 == 1) j += 2;\n\n if (i < n && j < n) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n }\n\n return nums;\n }\n}\n\n// TC: O(N), SC: O(1)\n```
3
0
['Two Pointers', 'Stack', 'Java']
0
sort-array-by-parity-ii
[JAVA] O(1) space | O(n) time | 90% faster | Easy Explained
java-o1-space-on-time-90-faster-easy-exp-a79j
A brief about logical approach:\n We have two poiters,\n\t i at index 0 (for even indices)\n\t j at index 1 (for odd indices)\n Now we check whether i has an ev
namanpokhriyal
NORMAL
2022-08-09T18:10:32.824172+00:00
2022-08-09T18:10:32.824196+00:00
518
false
A brief about logical approach:\n* We have two poiters,\n\t* `i` at index 0 (for even indices)\n\t* `j` at index 1 (for odd indices)\n* Now we check whether `i` has an `even` number,\n\t* if `nums[i]` is even : `i+=2` (move to next even index)\n\t* if `nums[i]` is odd: we check whether `j` has an `odd` number,\n\t\t* if `nums[j]` is odd : `j+=2` (move to next odd index)\n\t\t* if `nums[j]` is even: swap `nums[i]` and `nums[j]`\n\nThats it!\n\nIf you found it helpful upvote. And if you have any doubts or suggestions, comment them down. \u270C\n\n\n```\nclass Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int i=0,j=1;\n\t\t\n while(i<nums.length && j<nums.length){\n if(nums[i]%2==0) i+=2;\n else{\n if(nums[j]%2!=0) j+=2;\n else{\n int temp = nums[i];\n nums[i]=nums[j];\n nums[j] = temp;\n }\n }\n }\n return nums;\n }\n}\n```
3
0
['Java']
1
sort-array-by-parity-ii
100%faster code for the problem
100faster-code-for-the-problem-by-ayush_-efjf
class Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int result[]=new int[nums.length];\n int j=0,k=1;\n \n for(in
ayush_gupta-123
NORMAL
2022-07-29T08:46:32.438056+00:00
2022-07-29T08:46:32.438097+00:00
180
false
class Solution {\n public int[] sortArrayByParityII(int[] nums) {\n int result[]=new int[nums.length];\n int j=0,k=1;\n \n for(int i=0;i<nums.length;i++)\n {\n if(nums[i]%2==0)\n {\n result[j]=nums[i];\n j+=2;\n }\n else{\n \n result[k]=nums[i];\n k+=2;\n }\n }\n return(result);\n \n }\n}
3
0
['Java']
0
sort-array-by-parity-ii
c++ easy two pointer solution , clean code
c-easy-two-pointer-solution-clean-code-b-qte5
```\nclass Solution {\npublic:\n vector sortArrayByParityII(vector& nums) \n {\n vectorans;\n vectoreven;\n vectorodd;\n for(int
sailakshmi1
NORMAL
2022-06-03T15:01:31.667869+00:00
2022-06-03T15:01:31.668060+00:00
202
false
```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) \n {\n vector<int>ans;\n vector<int>even;\n vector<int>odd;\n for(int i=0;i<nums.size();i++){\n if(nums[i]%2==0){\n even.push_back(nums[i]);\n }\n if(nums[i]%2==1){\n odd.push_back(nums[i]);\n }\n }\n int j=0;\n int k=0;\n for(int i=0;i<nums.size();i++){\n if(i%2==0){\n ans.push_back(even[j]);\n j++;\n }\n else{\n ans.push_back(odd[k]);\n k++;\n }\n }\n return ans;\n \n }\n};\n \n \n
3
0
['Two Pointers', 'C']
0
sort-array-by-parity-ii
C++ Solution || Simply Explained || Constant Space || Fast Algorithm
c-solution-simply-explained-constant-spa-a7m7
\nclass Solution {\n public:\n void reArrange(int arr[], int n) {\n //I have tried writing a simple while-loop method to swap wrongly placed odd and
9_semi_colons
NORMAL
2022-05-26T06:38:36.624354+00:00
2022-05-26T06:43:52.076616+00:00
185
false
```\nclass Solution {\n public:\n void reArrange(int arr[], int n) {\n //I have tried writing a simple while-loop method to swap wrongly placed odd and wrongly placed even elements.\n \n int x = 0;\n int y = 0;\n \n while(x<n && y<n){\n \n //wrongly placed odd\n if(x%2==0 and arr[x]%2==1){\n x++;\n }\n //rightly placed even\n else if(x%2==0 and arr[x]%2==0){\n x++;\n }\n //rightly placed odd\n else if(x%2==1 and arr[x]%2==1){\n x++;\n }\n \n //wrongly placed even\n if(y%2==1 and arr[y]%2==0){\n y++;\n }\n //rightly placed even\n else if(y%2==0 and arr[y]%2==0){\n y++;\n }\n //rightly placed odd\n else if(y%2==1 and arr[y]%2==1){\n y++;\n }\n \n //swap wrongly placed even and wrongly placed odd\n if(x%2==1 and arr[x]%2==0 and y%2==0 and arr[y]%2==1){\n swap(arr[x],arr[y]);\n x++;\n y++;\n }\n }\n }\n};\n```\nDo upvote and comment. Thanks.
3
0
['Two Pointers', 'C']
3
sort-array-by-parity-ii
JS easiest
js-easiest-by-andrezzz-y7si
\nvar sortArrayByParityII = function(nums) {\n \n let res = new Array(nums.length) ;\n let e = 0, o = 1;\n \n for(i = 0; i < nums.length; i++){\n
andrezzz
NORMAL
2022-05-20T20:52:11.705438+00:00
2022-05-20T20:52:11.705462+00:00
294
false
```\nvar sortArrayByParityII = function(nums) {\n \n let res = new Array(nums.length) ;\n let e = 0, o = 1;\n \n for(i = 0; i < nums.length; i++){\n if(nums[i] % 2 === 0){\n res[e] = nums[i];\n e += 2\n }\n else{\n res[o] = nums[i];\n o += 2\n }\n } \n return res;\n};\n```
3
0
['JavaScript']
1
sort-array-by-parity-ii
C++ Solution:Two pointer,Using bitwise operator
c-solutiontwo-pointerusing-bitwise-opera-k0d9
If the Solution helps you,please do consider upvoting it.\n\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) \n {\n fo
arceus_1702
NORMAL
2021-11-01T05:20:14.800790+00:00
2021-11-01T05:20:14.800838+00:00
232
false
**If the Solution helps you,please do consider upvoting it.**\n```\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) \n {\n for(int i=0,j=1;i<nums.size() and j<nums.size();)\n {\n if(!(nums[i]&1))\n i+=2;\n else if(nums[j]&1)\n j+=2;\n else\n swap(nums[i],nums[j]);\n }\n return nums;\n }\n};\n```
3
0
['Two Pointers', 'C', 'C++']
0
sort-array-by-parity-ii
C++ Solution
c-solution-by-saurabhvikastekam-ffb4
\nclass Solution \n{\n public:\n\tvector<int> sortArrayByParityII(vector<int>& nums) \n {\n\t\tint n = nums.size();\n\t\tint i = 0, j = 1;\n\t\twhile(i <
SaurabhVikasTekam
NORMAL
2021-09-29T17:22:29.091722+00:00
2021-09-29T17:22:29.091769+00:00
112
false
```\nclass Solution \n{\n public:\n\tvector<int> sortArrayByParityII(vector<int>& nums) \n {\n\t\tint n = nums.size();\n\t\tint i = 0, j = 1;\n\t\twhile(i < n && j < n)\n {\n\t\t\tif(nums[i] % 2 == 0)\n {\n\t\t\t\ti += 2;\n\t\t\t}\n\t\t\telse if(nums[j] % 2 == 1)\n {\n\t\t\t\tj += 2;\n\t\t\t}\n\t\t\telse\n {\n\t\t\t\tswap(nums[i], nums[j]);\n\t\t\t}\n\t\t}\n\t\treturn nums;\n\t}\n};\n```
3
0
['C', 'C++']
0
sort-array-by-parity-ii
Inplace solution using two pointers - Java
inplace-solution-using-two-pointers-java-ynmd
It is given that the array will have same count of even and odd numbers which means that the length of the array will always be even. \nIf we maintain two point
anirudh03sharma
NORMAL
2021-09-28T16:05:44.155559+00:00
2021-09-28T16:07:56.496896+00:00
168
false
It is given that the array will have same count of even and odd numbers which means that the length of the array will always be even. \nIf we maintain two pointers `left` and `right` at opposite ends of the array, i.e.,\n\n```java\nleft = 0\nright = n - 1\n```\n\nThen we can safely say that `left` will be at even index and `right` will be at odd index. We will use this property and always make sure that the element at `left` will always be even and element at `right` will always be odd. We will move both pointers two steps ahead and behind respectively. It will result in the following three cases -\n\n1. If both the elements are violating the constraint, we will swap them and move both pointers\n2. If only a single element is violating the constraint, we will move that pointer only.\n3. If both the elements are not violating the constraint, we will just move both the pointers.\n\n```java\npublic class Problem28_SortArrayByParityII {\n\n public int[] sortArrayByParityII(int[] nums) {\n // Special case\n if (nums == null || nums.length == 0) {\n return nums;\n }\n // Length of the array\n int n = nums.length;\n // Left and right pointers\n int left = 0;\n int right = n - 1;\n // Loop until the condition is met\n while (left < n && right >= 0) {\n // If both the numbers at wrong positions, we will swap them\n if (nums[left] % 2 == 1 && nums[right] % 2 == 0) {\n int temp = nums[left];\n nums[left] = nums[right];\n nums[right] = temp;\n left += 2;\n right -= 2;\n }\n // If the left number is at wrong position but right\n // number is at correct position, we will move right\n // pointer two steps before\n else if (nums[left] % 2 == 1 && nums[right] % 2 == 1) {\n right -= 2;\n }\n // If the right number is at wrong position but left\n // number is at correct position, we will move left\n // pointer two steps after\n else if (nums[left] % 2 == 0 && nums[right] % 2 == 0) {\n left += 2;\n }\n // If both the numbers are at correct position, we just move\n // both the pointers\n else {\n left += 2;\n right -= 2;\n }\n }\n return nums;\n }\n}\n```
3
0
['Two Pointers']
1