713999. Partition the Array

Hard

Partition the Array

Slug: partition-the-array--170647 Difficulty: Hard Id: 713999 Topic Tags: two-pointer-algorithm, Arrays, Binary Search, Data Structures, Algorithms

Summary

The problem involves partitioning a given array into two halves such that all elements in the first half are less than or equal to all elements in the second half. This requires a combination of binary search and two-pointer techniques.

Detailed Explanation

To solve this problem, we will use a two-pointer approach with an additional binary search for finding the partition point. Here's a step-by-step breakdown:

  1. Initialize two pointers left and right to the start and end of the array respectively.
  2. Perform a binary search in the array to find the middle element that separates the elements into two halves.
  3. Update the left pointer to the next element after the found partition point, ensuring all elements to its left are less than or equal to the elements in the right half.
  4. Continue this process until the right pointer reaches the end of the array.

Time complexity: O(log n) Space complexity: O(1)

Here's an ASCII art diagram illustrating the two-pointer approach:

  +---------------+
  |       left    |
  +---------------+
           ^
           |
  +---------------+
  |   middle     |
  +---------------+
           ^
           |
  +---------------+
  |      right    |
  +---------------+

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public int partitionArray(int[] arr) {
        int left = 0, right = arr.length - 1;
        while (left <= right) {
            int mid = findPartitionPoint(arr, left, right);
            if (mid == -1) break; // No partition found
            left = mid + 1;
            right = mid - 1;
        }
        return arr[left];
    }

    private int findPartitionPoint(int[] arr, int left, int right) {
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] > arr[right]) {
                left = mid + 1;
            } else if (arr[mid] < arr[left]) {
                right = mid - 1;
            } else {
                return mid; // Partition found
            }
        }
        return -1; // No partition found
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.