Skip to content

Commit 2469d90

Browse files
Leetcode 2149
1 parent cf02057 commit 2469d90

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Leetcode/Leetcode_2149.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# LeetCode 2149. Rearrange Array Elements by Sign
2+
#
3+
# Problem Statement:
4+
# Given an array nums of even length consisting of an equal number of positive
5+
# and negative integers, rearrange the elements such that:
6+
#
7+
# 1. Every consecutive pair of integers has opposite signs.
8+
# 2. For all integers with the same sign, their relative order is preserved.
9+
# 3. The rearranged array begins with a positive integer.
10+
#
11+
# Return the modified array.
12+
#
13+
# Example:
14+
# Input: nums = [3,1,-2,-5,2,-4]
15+
# Output: [3,-2,1,-5,2,-4]
16+
#
17+
# Approach:
18+
# - Create a result array of the same size as nums.
19+
# - Use two pointers:
20+
# pos = 0 -> stores the next available even index for positive numbers.
21+
# neg = 1 -> stores the next available odd index for negative numbers.
22+
# - Traverse the input array once:
23+
# * If the current number is positive, place it at index 'pos'
24+
# and move pos by 2.
25+
# * If the current number is negative, place it at index 'neg'
26+
# and move neg by 2.
27+
# - This preserves the relative ordering of positive and negative numbers
28+
# while ensuring alternating signs.
29+
#
30+
# Time Complexity: O(n)
31+
# - Each element is visited exactly once.
32+
#
33+
# Space Complexity: O(n)
34+
# - An additional array of size n is used to store the result.
35+
36+
from typing import List
37+
38+
class Solution:
39+
def rearrangeArray(self, nums: List[int]) -> List[int]:
40+
n = len(nums)
41+
42+
# Even indices for positive numbers
43+
pos = 0
44+
45+
# Odd indices for negative numbers
46+
neg = 1
47+
48+
# Result array
49+
temp = [0] * n
50+
51+
for i in range(n):
52+
if nums[i] > 0:
53+
temp[pos] = nums[i]
54+
pos += 2
55+
else:
56+
temp[neg] = nums[i]
57+
neg += 2
58+
59+
return temp

0 commit comments

Comments
 (0)