#2149
Rearrange Array Elements by Sign
MediumArrayTwo PointersSimulationTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses two pointers to efficiently rearrange the elements in a single pass. This method is faster and uses less space than the brute-force approach.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two pointers, one for the positive integers and one for the negative integers.
- 2Step 2: Create an empty result array of the same length as nums.
- 3Step 3: Use a loop to fill the result array by alternating between the positive and negative integers, starting with the positive integer.
solution.py11 lines
1def rearrangeArray(nums):
2 result = [0] * len(nums)
3 pos_index, neg_index = 0, 1
4 for num in nums:
5 if num > 0:
6 result[pos_index] = num
7 pos_index += 2
8 else:
9 result[neg_index] = num
10 neg_index += 2
11 return resultℹ
Complexity note: The time complexity is O(n) because we traverse the array only once. The space complexity is O(n) due to the result array that we create to store the rearranged elements.
- 1The array has an equal number of positive and negative integers, allowing for a straightforward alternating arrangement.
- 2Maintaining the order of elements is crucial, which is why we separate them before merging.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.