Move All Negative Numbers To Beginning

You are given an array 'ARR' consisting of 'N' integers. You need to rearrange the array elements such that all negative numbers appear before all positive numbers.

Follow Up:
Can you solve this in O(1) auxiliary space?

Note:

The order of elements in the resulting array is not important.

Example:

Let the array be [1, 2, -3, 4, -4, -5]. On rearranging the array such that all negative numbers appear before all positive numbers we get the resulting array [-3, -5, -4, 2, 4, 1].
Input format:
The very first line of input contains an integer ‘T’ denoting the number of test cases. 

The first line of every test case contains an integer ‘N’ denoting the number of elements present in the array.

The second line of every test case contains ‘N’ space-separated integers denoting the elements present in the array.
Output format:
For each test case, “Yes” is printed if the resulting array is correct otherwise “No”.

Output for each test case is printed on a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just return the resulting array. 
Constraints:
1 <= T <= 10
1 <= N <= 5 * 10^4
-10^5 <= ARR[i] <= 10^5

Where  ‘T’ represents the number of test cases and ‘N’ represents the number of elements present in the array.

Time Limit: 1 sec
CodingNinjas
author
2y
Using Sorting

Approach: A brute force approach could be to just sort the given array in ascending order. This will result in all negative numbers to appear at the beginning and positive number at the e...read more

CodingNinjas
author
2y
Partitioning The Array Into Two Parts

Approach: A better approach could be to use the concept similar to the partitioning algorithm of quicksort. The idea is to start from the leftmost element in the ...read more

CodingNinjas
author
2y
Using Two Pointers

Approach: A simple approach could be to use the concept of a two-pointer. In this approach keep two pointers ‘LEFT’ and ‘RIGHT’ which initially point to the first and the last elemen...read more

Add answer anonymously...
Samsung Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter