Rearrange Array Elements by Sign in O(N) Time

Day 15 of my 100-Day LeetCode Challenge: Streamlining Data Streams! 🌊 Today I tackled LeetCode #2149: Rearrange Array Elements by Sign. The problem asks you to take an array of positive and negative numbers and interleave them perfectly (positive, negative, positive...) while strictly maintaining their original relative order. The Engineering Solution: The Two-Pointer Placement Technique. While you could split the data into two separate lists and merge them, that requires multiple passes. To do this efficiently, I used a single-pass approach: • Initialize an exact-size result array. • Use two separate index trackers: 'positive' starting at 0, and 'negative' starting at 1. • Iterate through the raw data once. If a number is positive, place it at positive and jump the pointer forward by 2. If negative, place it at negative and jump by 2. The Complexity Win: ⏱️ Time: O(N) - The raw data is evaluated in exactly one pass. 💾 Space: O(N) - We allocate exactly what is needed for the restructured output. Often, engineers get hyper-focused on trying to achieve O(1) space. But trying to solve this specific problem in-place while preserving relative order requires heavy element shifting, resulting in a massive O(N^2) time penalty. Understanding when to trade space for speed is the core of system design! #100DaysOfCode #Java #LeetCode #DataStructures #Algorithms #SeniorEngineer #BackendDevelopment #SoftwareEngineering

  • text

To view or add a comment, sign in

Explore content categories