Given an array of positive and negative integers, re-arrange it so that you have positive integers on one end and negative integers on other

sort array with negative numbers followed by positive numbers
given an array a 1 n of n numbers both positive and negative
alternate positive and negative numbers in array java
separate positive and negative numbers in array java
rearrange positive and negative numbers leetcode
sort an array without changing position of negative numbers in c++
how to sort negative and positive numbers in python
alternate positive and negative elements leetcode

I recently came across a Microsoft Interview Question for Software Engineer.

Given an array of positive and negative integers, re-arrange it so that you have positive integers on one end and negative integers on other, but retain their order of appearance in the original array.

For example, given [1, 7, -5, 9, -12, 15] The answer would be: [-5, -12, 1, 7, 9, 15]

This should be done in O(n).

We could easily do it in O(n), but I am not able to think how we can maintain the order of elements as in original array. If we forget about O(n) complexity, could someone tell me how we can preserve the order of elements without taking into consideration the space and time complexity.

EDIT: In actual question we are required to have O(1) space complexity also.

To achieve this result in constant space (but quadratic time), you can use the two-queue approach by placing one queue at each end of the array (similar to the Dutch National Flag algorithm). Read items left-to-right : adding an item to the left queue means leaving it alone, adding an item to the right queue means shifting all elements not in a queue to the left by one and placing the added item at the end. Then, to concatenate the queues, simply reverse the order of elements in the second queue.

This performs an O(n) operation (shifting elements left) up to O(n) times, which yields an O(n²) running time.

By using a method similar to merge sort, you can achieve a lower O(n log n) complexity: slice the array in two halves, recursively sort them in the form [N P] [N P] then swap the first P with the second N in O(n) time (it gets a bit tricky when they don't have exactly the same size, but it's still linear).

I have absolutely no idea of how to get this down to O(n) time.

EDIT: actually, your linked list insight is right. If the data is provided as a doubly linked list, you can implement the two-queue strategy in O(n) time, O(1) space:

sort(list):
  negative = empty
  positive = empty
  while (list != empty)
     first = pop(list)
     if (first > 0) 
         append(positive,first)
     else
         append(negative,first)
  return concatenate(negative,positive)

With a linked list implementation that keeps pointers to the first and last elements, then pop, append and concatenate are all O(1) operations, so the total complexity is O(n). As for space, none of the operations allocate any memory (append merely uses the memory released by pop), so it's O(1) overall.

Rearrange positive and negative numbers in O(n) time and O(1 , Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of If there are more positive numbers they appear at the end of the array. If there elements of given array. It puts See your article appearing on the GeeksforGeeks main page and help other Geeks. Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like hash table, arrays, etc. The order of appearance should be maintained.

Here is a constriant version of O(n) time O(1) space solution, it assume maxValue*(maxValue+1) is less than Integer.MAX_VALUE, where maxValue is the result of maxmum value minus minmum value in the array. It utilize the original array as the temporary array to store the result.

public static void specialSort(int[] A){
    int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
    for(int i=0; i<A.length; i++){
        if(A[i] > max)
            max = A[i];
        if(A[i] < min)
            min = A[i];
    }
    //Change all values to Positive
    for(int i=0; i<A.length; i++)
        A[i]-= min;

    int newMax = max-min+1;

    //Save original negative values into new positions
    int currNegativeIndex = 0;
    for(int i=0; i<A.length; i++)
        if(A[i]%newMax < (-min))
            A[currNegativeIndex++] += (A[i]%newMax)*newMax;
    //Save original positive values into new positions
    int currPositiveIndex = currNegativeIndex;
    for(int i=0; i<A.length; i++)
        if(A[i]%newMax > (-min))
            A[currPositiveIndex++] += (A[i]%newMax)*newMax;
    //Recover to original value 
    for(int i=0; i<A.length; i++){
        A[i] = A[i]/newMax + min; 
    }
}

Given an array of positive and negative integers, rearrange it so that , Given an array of positive and negative integers, re-arrange it so that you have positive integers on one end and negative integers on other, but� Given an array of positive and negative integers, re-arrange it so that you have postives on one end and negatives on the other, BUT retain the original order of appearance. For eg. 1, 7, -5, 9, -12, 15 => -5, -12, 1, 7, 9, 15

Given an array of positive and negative integers, re-arrange it so that , To achieve this result in constant space (but quadratic time), you can use the two- queue approach by placing one queue at each end of the array (similar to the� Output: Modified array with positive numbers and negative numbers are on each side of the array. Approach: Method 1. One naive approach is to have another array of same size and navigate the input array and one scan place all the negative numbers to the new array and in second scan place all the positive numbers to new array.

Rearrange an array such that it contains positive and negative , Given an array of integers, rearrange the array such that it contains positive and negative numbers at alternate positions. If array contains more positive or negative elements, they should be moved to end of the array. We can solve this problem in linear time by using partitioning logic of quicksort. Segregate positive and negative numbers in Array. Collect all the positive numbers and negative numbers together.

Edit (5/29/2015): I overlooked the requirement for maintaining order of appearance, so the answer below does not satisfy all of the requirements of the question. However, I leave the original response up for general interest.


This is a special version of a very important subroutine of quicksort known as "partition." Definition: an array A having N numeric entries is partitioned about value K at index p if A[i] < K for 0 <= i < p and A[j] >= K for p <= j < N, unless all the entries are less than K (meaning p = N) or not less than K (meaning p = 0). For the problem in question, we will partition the array around K = 0.

You can partition an unsorted array about any value K in O(n) time, accessing each entry in the array just once, using O(1) additional memory. Informally, you step through the array from both ends, moving values that are on the wrong side. Perform a swap when one misplaced value is found on each side of the array, then continuing stepping inward. Now the C++ code:

// Assume array A[] has size N
int K = 0; // For particular example partitioning positive and negative numbers
int i = 0, j = N-1; // position markers, start at first and last entries
while(1) { // Break condition inside loop
    while(i < N && A[i] < K) i++; // Increase i until A[i] >= K
    while(j >= 0 && A[j] >= K) j--; // Decrease j until A[j] < K
    if(i < j) 
        swap(A[i],A[j]);
    else
        break;
}
// A[] is now partitioned, A[0]...A[j] < K, unless i==0 (meaning all entries >= K).

Note that if all elements are equal to K (zero in this case), i is never incremented and j = 0 at the end. The problem statement assumes this will never happen. Partition is very fast and efficient, and this efficiency is the reason why quicksort is the most popular sorting routine for large arrays. The swap function can be std::swap in C++ or you can easily write your own:

void swap(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

Or just for fun, numbers can be swapped in place with no temporary memory, though be mindful of overflow:

// This code swaps a and b with no extra space.  Watch out for overflow!
a -= b;
b += a;
a = b - a;

There are many variations to partition for special cases, such as a three way partition for [elements < K] [elements == K] [elements > K]. The quicksort algorithm calls partition recursively, and the partition value K is usually the first entry in the current sub-array or computed from a few entries (such as median of three). See textbooks: Algorithms by Sedgewick and Wayne (4th ed., p. 288) or The Art of Computer Programming Vol. 3 by Knuth (2nd ed., p. 113).

Rearrange positive and negative numbers in array alternatively, In the given random array with both positive and negative integers, rearrange the array so that positive and negative are placed alternatively If there are more positive or more negative they appear at the end of the array. //Rearrange function void Rearrange(int array[], int n) { int i = -1; //swap positive elements to the start� An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array.

Java exercises: Arrange the elements of a given array of integers , Java array exercises and solution: Write a Java program to arrange the elements of integers where all positive integers appear before all the negative integers. Java Array: Exercise-49 with Solution arra_nums[j-1] = temp; j--; } } System. out.println("New array : "+Arrays. Group code to let others join. Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers) Segregating negative and positive maintaining order and O(1) space; Find ratio of zeroes, positive numbers and negative numbers in the Array; C program to count Positive and Negative numbers in an Array

Give you an array which has n, After that,the negative integers should in the front,and the positive integers Observation: given an array A, say [1, -2, , 4], with n elements, we can get 1. We recursively 'sort' two smaller arrays of size n/2 (here 'sort' is defined in the question) The conventional partition algorithm isn't stable, so you'll end up ruining the� Given array is 3 2 0 1 Modified array is 1 0 3 2. Complexity Analysis: Time Complexity: O(n), Only one traversal of the array is needed. So time complexity is O(n). Auxiliary Space: O(1), No extra space is required. The problem with the above solution is, it may cause an overflow. Here is a better solution:

Rearrange Positive and Negative Numbers of Array On Each Side in , Rearrange Positive and Negative Numbers of an Array so that one side you have positive numbers and other side with negative Integers without changing their� Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. And if the given numbers are {1, 34, 3, 98, 9, 76, 45, 4}, then the arrangement 998764543431 gives the largest value.

Comments
  • Guys i think instead of arrays can we use linked list data structure to achieve O(n) and O(1).
  • @Yochai: Why do you say that it is impossible to sort that way in O(n) time and O(1) space using an array ?
  • You have 2 sets of information. 1 is the order they are in, and 2 is positive\negative . So if you want to sort it, you either need more than O(n) computation time, or a database that can represent the 2 datasets.
  • @Yochai: why is this an nlogn problem?
  • Please add lower bound proofs as answers so I can downvote the incorrect ones ;-) (Since there is an algorithm with O(n), any claims of a lower bound of n log n are wrong.)
  • What is list? It looks like you're building a new list with the required properties, but you're supposed to change the original array. If you're doing this, it's not O(1) space.
  • IVIad : changed the wording for clarification. I mean to say that if the original data is represented as a linked list, then that is possible. It would be interesting to know if the mention of arrays in the question is present in the original interview question or merely an artifact of being reworded by yogi15490.
  • Well, I hope it's an array :). It's way too easy if you're given a linked list. I think we should assume an array until the OP clarifies. Besides, I think the words "rearrange it" makes it unlikely the OP added arrays himself.
  • Your merge sort implementation uses log(n) space for the stack.
  • could you please elaborate your answer? It seems nice, but I cannot understand the logic.
  • especially this part: int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; why you choose MAX as min, and MIN as max?
  • Can you please explain the logic especially where you are doing "Save original values to the new positions"