Rearrange Array Elements by Sign(Leetcode : 2149)
Rearrange Array Elements by Sign
Introduction
In this blog, we will discuss two approaches to solving the problem of rearranging an array such that positive and negative numbers appear alternately while maintaining their relative order.
Method 1: Using Separate Lists
This approach involves separating positive and negative numbers into two different lists and then merging them back into the original array.
Steps:
- Create two lists: one for positive numbers and one for negative numbers.
- Iterate through the given array and store positive numbers in one list and negative numbers in another.
- Reconstruct the array by alternating elements from both lists.
Code:
class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
positive = []
negative = []
for i in nums:
if i < 0:
negative.append(i)
else:
positive.append(i)
j = 0
k = 0
for i in range(len(nums)):
if i % 2 == 0:
nums[i] = positive[j]
j += 1
else:
nums[i] = negative[k]
k += 1
return nums
Time Complexity:
O(n) - We traverse the array twice, once to separate elements and once to reconstruct the array.
Method 2: Using Index Placement
This approach directly places elements at the correct positions using two pointers without needing additional lists.
Steps:
- Create an answer array of the same length as the input.
- Use two pointers: one starting at index 0 for positive numbers and another at index 1 for negative numbers.
- Iterate through the array and place each number at its corresponding position.
Code:
class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [0] * n
positive, negative = 0, 1
for i in range(n):
if nums[i] < 0:
ans[negative] = nums[i]
negative += 2
else:
ans[positive] = nums[i]
positive += 2
return ans
Time Complexity:
O(n) - We traverse the array once, making this approach more efficient in terms of space and time.
Conclusion
Both approaches efficiently solve the problem, but the second method is preferable due to its in-place nature and better space complexity.
LeetCode Solution
You can find my LeetCode solution here.
Comments
Post a Comment