Leetcode 2149: Rearrange Array Elements by Sign

grid47
grid47
Exploring patterns and algorithms
Apr 6, 2024 5 min read

You are given an integer array ’nums’ of even length consisting of an equal number of positive and negative integers. Rearrange the array such that every consecutive pair of integers has opposite signs, the order of integers with the same sign is preserved, and the array begins with a positive integer.
Problem
Approach
Steps
Complexity
Input: The input consists of a 0-indexed integer array 'nums' of even length.
Example: nums = [6, 3, -1, -5, 2, -4]
Constraints:
• 2 <= nums.length <= 2 * 10^5
• nums.length is even
• 1 <= |nums[i]| <= 10^5
• nums consists of an equal number of positive and negative integers.
Output: Return the rearranged array where consecutive elements have opposite signs and the order of same-signed integers is preserved.
Example: Output: [6, -1, 3, -5, 2, -4]
Constraints:
• The array must start with a positive integer and alternate between positive and negative integers.
Goal: We need to rearrange the elements such that positive and negative integers alternate, and the order of elements with the same sign remains intact.
Steps:
• Iterate over the 'nums' array and segregate the positive and negative integers.
• Place positive integers at even indices and negative integers at odd indices.
• Return the rearranged array.
Goal: The input array length is guaranteed to be even, with an equal number of positive and negative integers.
Steps:
• 2 <= nums.length <= 2 * 10^5
• nums.length is even
• 1 <= |nums[i]| <= 10^5
• nums consists of equal numbers of positive and negative integers.
Assumptions:
• The array is guaranteed to contain an equal number of positive and negative integers.
Input: Example 1: nums = [6, 3, -1, -5, 2, -4]
Explanation: The positive integers are [6, 3, 2] and the negative integers are [-1, -5, -4]. The only valid rearrangement is [6, -1, 3, -5, 2, -4] which alternates signs while preserving the order of positive and negative integers.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus