703042. Reorganize The Array

Easy

Reorganize The Array

Summary

The problem requires you to reorganize an array such that all elements less than a given target value appear before all elements greater than or equal to the target value. This is a classic array manipulation problem that involves sorting and rearranging the elements in a specific order.

Detailed Explanation

To solve this problem, we can use a two-pointer approach. Initialize two pointers, one at the beginning of the array (let's call it low) and one at the end of the array (let's call it high). We'll also maintain a variable target to store the target value.

Here are the steps:

  1. Start by initializing low to 0 and high to the length of the array minus 1.
  2. Compare the values at indices low and high. If the value at index low is less than the target, increment low and move all elements less than the target to the beginning of the array.
  3. If the value at index high is greater than or equal to the target, decrement high and move all elements greater than or equal to the target to the end of the array.
  4. Continue iterating until low meets high.
  5. Return the reorganized array.

Here's a step-by-step breakdown:

View on GeeksforGeeks
public static int[] reorganizeArray(int[] arr, int target) {
    int low = 0;
    int high = arr.length - 1;

    while (low <= high) {
        if (arr[low] < target && arr[high] >= target) {
            break;
        }
        if (arr[low] < target) {
            low++;
        } else if (arr[high] >= target) {
            high--;
        } else {
            int temp = arr[low];
            arr[low] = arr[high];
            arr[high] = temp;
            low++;
            high--;
        }
    }

    return arr;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.