LeetCode 2161: Partition Array According to Given Pivot Solution

Master LeetCode problem 2161 (Partition Array According to Given Pivot), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2161. Partition Array According to Given Pivot

Problem Explanation

Explanation

To solve this problem, we can use a two-pointer approach where we maintain two pointers left and right. The left pointer starts from the beginning of the array and moves right until it finds an element greater than or equal to the pivot. The right pointer starts from the end of the array and moves left until it finds an element less than or equal to the pivot. When both pointers stop, we swap the elements at their respective positions. We repeat this process until the left pointer crosses the right pointer.

Solution Code

class Solution {
    public int[] partitionArray(int[] nums, int pivot) {
        int left = 0, right = nums.length - 1;
        
        while (left <= right) {
            while (left <= right && nums[left] < pivot) {
                left++;
            }
            
            while (left <= right && nums[right] > pivot) {
                right--;
            }
            
            if (left <= right) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            }
        }
        
        return nums;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2161 (Partition Array According to Given Pivot)?

This page provides optimized solutions for LeetCode problem 2161 (Partition Array According to Given Pivot) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2161 (Partition Array According to Given Pivot)?

The time complexity for LeetCode 2161 (Partition Array According to Given Pivot) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2161 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2161 in Java, C++, or Python.

Back to LeetCode Solutions