Skip to content

Latest commit

 

History

History
48 lines (32 loc) · 762 Bytes

File metadata and controls

48 lines (32 loc) · 762 Bytes

Rearrange Array Alternately

Problem Link

(Several variants: e.g., rearrange max/min alternately)


Pattern

  • Two Pointer
  • Sorting

Approach

For sorted array, use two pointers from ends and place elements alternately into new array, or use in-place encoding trick.


Time Complexity

O(n)

Space Complexity

O(n) or O(1) with encoding tricks


Java Solution (simple)

class Solution {
    public int[] rearrange(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        int[] res = new int[n];
        int l = 0, r = n - 1, idx = 0;
        while (l <= r) {
            if (idx < n) res[idx++] = nums[r--];
            if (idx < n) res[idx++] = nums[l++];
        }
        return res;
    }
}