logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›arrays›faqs medium

Rearrange Array Elements by Sign

# Question

Given a 0-indexed integer array nums of even length with an equal number of positive and negative integers, rearrange the array such that:

  1. Every consecutive pair of integers have opposite signs.
  2. For all integers with the same sign, their relative order is preserved.
  3. The rearranged array begins with a positive integer.

Return the modified array.

# Solution

# Pattern

Two Pointers with Pre-allocated Array Allocate a result array and use two separate pointers (starting at index 0 and 1) to track the next insertion position for positive and negative streams, jumping by 2.

# How to Identify

  • Problem involves interleaving or alternating elements based on a condition (sign, parity).
  • There is a strict requirement to preserve relative order (stability).
  • An O(N)O(N)O(N) time constraint strongly hints that in-place swapping won't work, as in-place stable partitioning is highly complex and slower than O(N)O(N)O(N).

# Description

Step-by-step explanation:

  1. Create a new array result of the same length as the input array.
  2. Initialize two pointers: posIndex = 0 (even indices for positives) and negIndex = 1 (odd indices for negatives).
  3. Iterate through every element num in the original array nums sequentially (left to right).
  4. If num is positive, place it at result[posIndex] and increment posIndex by 2 to point to the next available even index.
  5. If num is negative, place it at result[negIndex] and increment negIndex by 2 to point to the next available odd index.
  6. Because we read the original array left-to-right and place elements immediately, the relative order of both positive and negative elements is mathematically guaranteed to be preserved.

# The Intuition

Think of this as directing two streams of traffic (positive cars and negative cars) into a single parking lot with assigned spots. All even spots are reserved for positive cars, and all odd spots are reserved for negative cars. Because we process the incoming traffic sequentially, the first positive car gets the first positive spot, the second gets the second, etc. We never have to shift cars around once they are parked, ensuring perfect relative ordering in exactly one pass.

# Complexity

LabelWorstAverage
Time ComplexityO(N)O(N)O(N)O(N)O(N)O(N)
Space ComplexityO(N)O(N)O(N)O(N)O(N)O(N)

# Time Complexity

We iterate through the array of size NNN exactly once. Index lookups and assignments are O(1)O(1)O(1). Therefore, the time complexity is strictly O(N)O(N)O(N).

# Space Complexity

We must allocate a new array of size NNN to store the output. No additional auxiliary data structures (like queues or stacks) are needed, yielding O(N)O(N)O(N) space.

# Code

class Solution {
    public int[] rearrangeArray(int[] nums) {
        int[] result = new int[nums.length];
        
        // Positives go to even indices, negatives go to odd indices
        int posIndex = 0;
        int negIndex = 1;
        
        for (int num : nums) {
            if (num > 0) {
                result[posIndex] = num;
                posIndex += 2;
            } else {
                result[negIndex] = num;
                negIndex += 2;
            }
        }
        
        return result;
    }
}

# Caveats

  • Strict Memory Constraints: If the environment has severe memory constraints (e.g., embedded systems) where O(N)O(N)O(N) extra space is impossible, this approach fails. You must fallback to an in-place algorithm and sacrifice time complexity.
  • Unequal Counts: This algorithm assumes the count of positive and negative numbers is perfectly balanced. If unequal, you will hit an ArrayIndexOutOfBoundsException.

# Concepts to Think About

  • Stable vs Unstable Partitioning: If the problem didn't require preserving the relative order (stability), you could solve this in O(N)O(N)O(N) time and O(1)O(1)O(1) space using a variation of the Dutch National Flag algorithm (swapping elements in place).

  • In-place Stable Partitioning limitation: Achieving O(1)O(1)O(1) space and preserving relative order in O(N)O(N)O(N) time is a famous unsolved problem in computer science. Knowing this theoretical limit prevents you from wasting time trying to invent an impossible solution during an interview.

  • Data Locality: Pre-allocating an array and writing to it sequentially is extremely cache-friendly, making this approach blazing fast at the CPU level despite the memory allocation overhead.

  • Stability: This approach is "stable" because we process nums from left to right. Why is it impossible to do this in O(1) space and O(n) time while remaining stable? (Look up "Stable In-Place Partitioning").

  • Unequal Counts: How would your logic change if the number of positive and negative integers were not equal? You would likely need to fill the remaining slots with whatever numbers are left over at the end of the array.

  • Follow-up - In-place (Unstable): If the interviewer says "I don't care about the original order, just alternate the signs in O(1) space," how would you use a two-pointer approach to swap elements in-place?

  • Data Streams: If nums was a stream of data (too large to fit in an array), could you still produce an alternating output? (Hint: You would need two Queues to buffer the "wrong-signed" numbers until their slot comes up).

# Logical Follow-up

Question: What if the array has an unequal number of positive and negative integers? The rules remain the same, but once you run out of pairs, simply append the remaining elements at the end, preserving their relative order. Solution: We use two passes (or Fallback Lists). First, use two separate Lists (or dynamic arrays) to collect all positive and negative numbers separately. Then, iterate and overwrite the original array: as long as both lists have elements, interleave them. Once one list is exhausted, just sequentially write the remaining elements from the other list. This takes O(N)O(N)O(N) time and O(N)O(N)O(N) space.

Question: Can you solve the original problem in O(1)O(1)O(1) space? (Follow-up often asked to test your understanding of algorithmic tradeoffs). Solution: Yes, but we must sacrifice the O(N)O(N)O(N) time complexity. We can use the Array Rotation technique. We iterate through the array to find the first out-of-place element (e.g., a negative number at an even index). Then we find the next positive number ahead of it. We right-rotate the subarray between these two indices to bring the positive number into the correct position while shifting the negative numbers down. Because array rotation takes O(K)O(K)O(K) time (where KKK is the distance shifted), the overall worst-case time complexity degrades to O(N2)O(N^2)O(N2).

PreviousSpiral Matrix TraversalNextRotate Image
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up