Amazon Interview Question for SDE1s


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
1
of 1 vote

Isn't it the memory/complexity tradeoff problem? Can't see how can it be done meeting the requirements.

- joe kidd July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I agree. It seems impossible to do both. I believe the interviewee must have misunderstood the interviewer. I am curious as to how to prove that this is an impossible task, though.

- utopia July 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

I believe this question is not possible. The interviewee must have gotten confused with the interview question.

I believe the interviewer must have asked "How do we do this problem?" The problem is certainly doable. We can divide the initial array into a positive array and a negative array, and then weave the arrays. This would work in linear time, but also has linear space requirement.

Then, as a follow up question, I imagine the interviewer must have asked "So, what is the time complexity of this problem?"
Interviewee: "It is O(N)."
Interviewer: "Good. Now, what if we find we need to constrain the space to O(1) since we are dealing with humongo data sets like we tend to do at Amazon. How would you change the algorithm?"
Interviewee: "Here is a different algorithm where we maintain several pointers into the array, a temporary value for shifts, and do some shifting within the array. The space requirement is now O(1)."

The thing is, to get the space requirement down to O(1), we have blown up the time requirement to O(N^2), I believe.

My intuition will go as follows.

Create an array A of length N with N=a power of 2. For clarity use this example A =
[1, 2, 3, ... 512, -1, -2, -3, ... -512].

To maintain ordering, I believe we need to do a series of shifts.

Like, we will shift value -1 from index 512 to index 1 (so, 511 shifts).
We will shift value -2 from index 513 to index 3 (so, 510 shifts).
...
Shift value -511 from index 1023 to 1022 (1 shift).
Value -512 starts in index 1024 and remains there (0 shifts).

This would involve a sum
sum(i) from i=1 to 511
= (511+1) + (510+2) + (509+3) ... = ~512*(512/2) = N*N/2 = O(N^2)

Of course, that is the time complexity for the shifting-based algorithm. There may be a better solution. I will think about it more later today, but anyone interested in collaborating here please do consider that example array I gave.

Another idea to consider proceeding with is doing multiple loops through the array. e.g. you can do a loop through to count the number of positive integers and negative integers, and then do a processing loop after that. The problem is maintaining order of positives and negatives within the resultant array seems like it must involve shifting.

I could also imagine an idea like this, though...
[1,2,3,4,-1,-2,-3,-4]
count 4 pos values, 4 neg values in loop 1
loop to find first neg value at index 4, calculate its end position (which is index 1), then stick it in position 1, and lift up value 2,
[1,-1,3,4,null,-2,-3,-4]
tmpval=2
tmpidx=1
and calculate 2's rightful end position, which would be index 2
[1,-1,2,4,null,-2,-3,-4]
tmpval=3
tmpidx=2
now we need to place value 3 back into the array
[1,-1,2,4,3,-2,-3,-4]
tmpval=-1
tmpidx=4

So, at this point, we have done a few switches of variables, and now shifting (like my previous algorithm). I think this method has a chance of working. I may have made some mistakes since I am underslept today, but I believe this general approach will work. Props to anyone who makes this one work.

--Tom

- Tom July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

I am glad I am not the only one who shares this point of view :)

- joe kidd July 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 vote

Algorithm :
- Divide array into two parts : -ve and +ve numbers assuming 0 as a modified version of quicksort .
- Now we have all the positive numbers at the end of the array and all the negative numbers at the start of the array
- have 2 pointers , one pointing to the first number in the array which is a negative number and the other one to be pointing to the first positive number in the array.
- Swap the two elements. Increment positive counter by 1 and negative counter by 2. repeat
- If there are more positive numbers or more negative numbers than they will appear at the end of the array.

Java code:

void rearrange(int arr[]) 
	int len = arr.length;
	int i = -1;
	
	for(int j =0;j<len;j++) 
	{
		if(arr[j] < 0)
		{
			i++;
			int temp = arr[i];
			arr[i] = arr[j];
			arr[j] = temp;
		}
	}

	int pos = i+1;
	int neg = 0;
	
	while (pos < n && neg < pos && arr[neg] < 0)
    	{
        	int temp = arr[neg];
		arr[neg] = arr[pos];
		arr[pos] = temp;
        	pos++;
        	neg += 2;
    	}

Taken from : http://www.geeksforgeeks.org/rearrange-positive-and-negative-numbers-publish/

- smdmustaffa July 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Thanks for answering.
but this does not maintain the relative order...let me know how that can be handled.

- peechus July 29, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

for stability Instead of using using quick sort style partition scan the array from the end and move the -Ve numbers to the next available position ahead of whatever that had been scanned so far.

- Harish July 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

After thinking a bit more about this problem, I think the only way this can be done in-place (no extra memory) and with linear time is to consider the comparison operation as the function to evaluate. If it's comparisons what we care about, the code below is an O( n ) solution. Now, this makes O (n^2) memory swaps to maintain the constant space constraint.

inline bool RightSign(int x, bool pos)
{
    return pos ? x >= 0 : x < 0;
}

void Alternate(int* a, size_t n)
{
    assert(n > 0);
    size_t wrong = 0;
    size_t candidate = 0;
    bool pos = false;
    while (wrong < n)
    {
        while (RightSign(a[wrong], pos))
        {
            pos = !pos;
            ++wrong;
        }
        candidate = candidate <= wrong ? wrong + 1 : candidate;
        while (candidate < n && !RightSign(a[candidate], pos))
        {
            ++candidate;
        }
        if (candidate >= n) return;
        for (size_t i = candidate; i > wrong; --i)
        {
            assert(i < n);
            std::swap(a[i], a[i - 1]);
        }
        wrong += 2;
    }
}

- Max July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How do you make O(n^2) swaps in O(n) time?
This algorithm is correct, but it is an O(n^2) algorithm.

- djmclaugh July 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

You analyze complexity by considering a 'fundamental operation' to be counted or analyzed. If you're only considering comparisons this is O(n) because this makes at most 2n comparisons. As I said in my previous post, if considering only comparisons, this algorithm is linear, since the number of comparisons depends linearly on the imput. Swaps is different, to swap two elements you don't care about comparing them, and given that the input is an array, performing an insertion in any point you'll need to do O ( n ) swaps and you'll have at most n/2 inserts that yields O ( n^2 ) swaps. If instead of getting an array, this was a list, the insertion would be constant time, but still the number of comparisons stay O( n ). That makes sense?

- Max July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

It seems to me that there are some questions that need to be asked:

1. When you say "the order should be same as previous array", what do you mean? By switching positive and negative numbers you are, in essence, changing the order of the array.

1a. Do you mean: If there are multiple positives or negatives in a row, they should maintain their order?

2. What is the expected result if the array has only 1 negative number? e.g., [1, 2, 3, 4, 5, 6, 7, -8, 9]?

2a. Is the expected result from 2 the same if the array has only 1 positive number?

3. My initial thought was that this was a contrived question to get you to in-place sort pairs of numbers ensuring that they are in positive, negative,... order.

My solution works for most cases except the ones I listed above. My solution, though it fits the question, is ambiguous and depends on what the interviewer is looking for.

- Chris July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

If You carefully observer then we will get following pattern :
Count the -ve and +ve.. Which one is lesser that has to be in the middle for i-1, i, i+1 ...

I am taking only one case : -ve are lesser than +ve... but this sol will easily work for other case also.

1) If left(i-1) is negative and mid (i) is also negative : shift the mid val to right to nextOpposite flag. If nothing is found then break. then swap left and mid.

2) if left (i-1) is negative and mid is positive : swap the i-1 and i;
3) If both are positive : shift i the next possible opposite flag.

i+=2;


Code will look like this way (There needs some modification for second case but it will work I assume):

public static void sol2(int[] arr)
{
int i = 1;

while (i < arr.length)
{
int left = arr[i - 1];
int mid = arr[i];

if (left < 0 && mid < 0)
{
boolean found = shiftMiddleToNextOppositeFlag(arr, i);
if (!found)
break;
swap(arr, i, i - 1);
}
else if (left < 0)
swap(arr, i, i - 1);
else if (left > 0 && mid > 0)
{
boolean found = shiftMiddleToNextOppositeFlag(arr, i);
if (!found)
break;
}
i += 2;
}
}

private static boolean shiftMiddleToNextOppositeFlag(int[] arr, int i)
{
int temp = arr[i], idx = -1;
boolean isMidPositive = temp > 0;
for (int j = i+1; j < arr.length; j++)
{
boolean isCurrPositive = arr[j] > 0;
if (isMidPositive ^ isCurrPositive)
{
idx = j;
break;
}

}
if (idx == -1)
return false;

int high = arr[idx];

shiftRight(arr, i, idx);

arr[i] = high;

return true;
}

private static void shiftRight(int[] arr, int low, int high)
{
for (int i = high; i > low; i--)
{
arr[i] = arr[i - 1];
}
}


private static void swap(int[] arr, int i1, int i2)
{
int temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}


public static void main(String args[])
{
int[] arr = {-2, 3, 4, 5, -1, -6, 7, 9, 1};

sol2(arr);

for (int i : arr)
System.out.print(i + " ");


}

- Anonymous July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

how abt this??? first scan entire array , and get total count of positives and negatives. now in that array , lets take 2 pointers , one starts at start and other at the start + count of positives. now seperate positives and negatives in following manner. keep on incrementing first index , till u get negative value. once u get , swap with that the value of second index and increment second index.
now we have both posittives and negatives seperated.
now again take 2 pointers and swap alternative numbers .
total time ocmplexity is similar to o(n) , space is o(1)

- gopi.komanduri July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

It's a good approach but it's not stable. The relative order of both negative and positive numbers gets messed up with this solution. I thought about this too.

- Max July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Could you please tell me whether the below code is ok?

public static void main(String[] args) {
Integer[] a = new Integer[]{-2, 3, 4, 5, -1, -6, 7, 9, 1};
alternate(a);
int n= positive.size()>negative.size()?positive.size():negative.size();
System.out.println(positive.size());
System.out.println(negative.size());
for(int i=0;i<n;i++){
if(i<=positive.size()){
System.out.print(positive.get(i)+",");
}
if(i<negative.size()){
System.out.print(negative.get(i)+",");
}
}
}
private static List negative = new ArrayList();
private static List positive = new ArrayList();

public static void alternate(Integer[] a) {
for(int val : a){
if(val>0){
positive.add(val);
}else{
negative.add(val);
}
}

}

- Kiran July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hmm , how abt like this??
1.scan entire array , take the max positive value , max negative values , count of negative , total count.
2.Now the challange is to maintain order. so for every number , lets say x is the positive number , max positive is mp , max negative is mn.
scan array .. , take two pointers , , positiveP , negativeP.
now for each value in the array , change the value as value follows ..
if(number is positive , use positiveP) else , use negativeP ....
value as value + (positiveP or negativeP)*(mp+1 or mn+1)
mp if we use positiveP , mn if we uuse negativeP .
increment whichever is used (is positiveP is used , incr positiveP else ince negativeP)
so now each value is modified as value + its finalposition*(maxValue+1)..
then arrange array as mentioned in my above proposal.
now in final array,
take two pointers , val , pos .
for each array element , if taht is positive , % taht with maxP if negative % taht with maxN , to get position , and divide with maxP or maxN to get val ...
and arrange accordingly.
time complexity is o(n)
space is (1)

- gopi.komanduri July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

How about this?
public static void main(String[] args) {
Integer[] a = new Integer[]{-2, 3, 4, 5, -1, -6, 7, 9, 1};
aArray = new Integer[a.length*2];
alternate(a);
for(int i=0;i<aArray.length;i++){
if(aArray[i]!=null)
System.out.print(aArray[i]+",");
}
}
private static Integer[] aArray;
public static void alternate(Integer[] a) {
int positiveIndex = 0;
int negativeIndex = 1;
for(int i=0;i<a.length;i++){
if(a[i]>0){
aArray[positiveIndex] = a[i];
positiveIndex = positiveIndex+2;
}else{
aArray[negativeIndex] = a[i];
negativeIndex = negativeIndex+2;
}
}
}

- Kiran July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@ Kiran : space complexity shoould be 1. but in the solution provide by you , you are using o(n) space.

- gopi.komanduri July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Gopi : If possible, can you please share your code.

- Kiran July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

sure , will share

- gopi.komanduri July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Thanks alot Gopi.

- Kiran July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void swap(int* array, int i, int j)
{
    int tmp = array[i];
	array[i] = array[j];
	array[j] = tmp;
}

int next(int* array, int n, int x, bool isPositive)
{
	for (int i = x+1; i < n; i++)
	{
		if (isPositive && array[i] >= 0) return i;
		else if (!isPositive && array[i] < 0) return i;
	}
	
	return n;
}

void alternatePositiveAndNegative(int* array, int n)
{
    //invariant -> all elements before nexP are ordered or negatives
	int nextP = next(array, n, -1, true);
    swap(array, 0, nextP);
    
    //invariant -> all elements before nexN are ordered or positives
    int nextN = -1;
	
    //invariant -> all elements before i are ordered
	for (int i = 1; i < n; i++)
	{
        if (i%2==0) {
    		nextP = next(array, n, max(i-1, nextP), true);
    		if (nextP < n) swap(array, i, nextP);
        }else {
		    nextN = next(array, n, max(i-1, nextN), false);
        	if (nextN < n) swap(array, i, nextN);
		}
	}

}

- Anonymous July 31, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Worst case : O(n^2)

public class AlternatePosNeg {

	public static void main(String[] args) {
		int []arr = {-1,-2,3,5,-3,-4,6,12,-41,13};
		int len = arr.length;
		int nextNeg = -1, nextPos = -1;
		boolean nextPostive = true;
		for(int pivot=0;pivot<len;pivot++){
			System.out.print(" "+arr[pivot]);
		}
		System.out.println("");
		for(int pivot=0;pivot<len-1;pivot++){
			if(nextPostive){ //need to fill with +ve
				if (arr[pivot] < 0)	{			
					nextPos = pivot+1;
					while(nextPos < len && arr[nextPos++] < 0);
					int temp = arr[--nextPos];
					while(temp > 0 && nextPos > 0 && nextPos > pivot){
						arr[nextPos] = arr[nextPos-1];
						nextPos--;
					}
					if(temp > 0)
						arr[pivot] = temp;
				}
				nextPostive = !nextPostive;
			}else{//need to fill with -ve
				if (arr[pivot] > 0)
				{
					nextNeg = pivot+1;
					while(nextNeg < len && arr[nextNeg++] > 0);
					int temp = arr[--nextPos];
					while(temp < 0 && nextPos > 0 && nextPos > pivot){
						arr[nextPos] = arr[nextPos-1];
						nextPos--;
					}
					if(temp < 0)
						arr[pivot] = temp;
				}
				nextPostive = !nextPostive;
			}
		}
		for(int pivot=0;pivot<len;pivot++){
			System.out.print(" "+arr[pivot]);
		}
	}

}

- Anonymous July 31, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

average case O(n), but worst case O(n^2)

public class AlternatePosNeg {

	public static void main(String[] args) {
		int []arr = {-1,-2,3,5,-3,-4,6,12,-41,13};
		int len = arr.length;
		int nextNeg = -1, nextPos = -1;
		boolean nextPostive = true;
		for(int pivot=0;pivot<len;pivot++){
			System.out.print(" "+arr[pivot]);
		}
		System.out.println("");
		for(int pivot=0;pivot<len-1;pivot++){
			if(nextPostive){ //need to fill with +ve
				if (arr[pivot] < 0)	{			
					nextPos = pivot+1;
					while(nextPos < len && arr[nextPos++] < 0);
					int temp = arr[--nextPos];
					while(temp > 0 && nextPos > 0 && nextPos > pivot){
						arr[nextPos] = arr[nextPos-1];
						nextPos--;
					}
					if(temp > 0)
						arr[pivot] = temp;
				}
				nextPostive = !nextPostive;
			}else{//need to fill with -ve
				if (arr[pivot] > 0)
				{
					nextNeg = pivot+1;
					while(nextNeg < len && arr[nextNeg++] > 0);
					int temp = arr[--nextPos];
					while(temp < 0 && nextPos > 0 && nextPos > pivot){
						arr[nextPos] = arr[nextPos-1];
						nextPos--;
					}
					if(temp < 0)
						arr[pivot] = temp;
				}
				nextPostive = !nextPostive;
			}
		}
		for(int pivot=0;pivot<len;pivot++){
			System.out.print(" "+arr[pivot]);
		}
	}

}

- Learning July 31, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is the C# Code with time complexity O(n-2).

public static void SetArray(int[] A)
        {
            int p = -1;
            for (int i = 1; i < A.Length-1; i++)
            {
                if (isnegative(A[i-1]) == isnegative(A[i]) && isnegative(A[i]) != isnegative(A[i+1]))
                {
                    int temp = A[i];
                    A[i] = A[i + 1];
                    A[i + 1] = temp;
                    p = i;
                }
                else if (isnegative(A[i]) == isnegative(A[i+1]) && isnegative(A[i+1]) != isnegative(A[i-1]))
                {
                    if (i - 1 != p)
                    {
                        int temp = A[i];
                        A[i] = A[i - 1];
                        A[i - 1] = temp;
                    }
                    p = i;
                }
                else if ( isnegative(A[i-1]) == isnegative(A[i]) && isnegative(A[i]) == isnegative(A[i+1]))
                {
                    break;
                }
                else
                {
                    p = ++i;
                }
            }
        }

        public static bool isnegative(int number)
        {
            return number < 0 ? true : false;
        }

- Dirish Kumar August 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// into empty duplicate array, copy positives in order from duplicate's start and negatives in reverse order from duplicate's end
// copy from duplicate array back to original array alternating as long as you can
// if positives are left, copy them back in order
// if negatives are left, copy them back in reverse order

import java.util.Arrays;

public class Alternate {
	
	public static int[] array = new int[] {-2, 3, 4, 5, -1, -6, 7, 9, 1};

	public static void main(String[] args) {
		System.out.println(Arrays.toString(array));
		
		int[] posNeg = new int[array.length];
		int pos = 0;
		int neg = array.length - 1;

		// put pos at start in order, neg at end in reverse order
		for (int x = 0; x < array.length; x++)
			if (array[x] >= 0)
				posNeg[pos++] = array[x];
			else
				posNeg[neg--] = array[x];

		pos = 0;
		neg = array.length - 1;
		int x = 0;

		// copy back to original array alternating 
		while (posNeg[pos] >= 0 && posNeg[neg] < 0 && x < array.length - 1) {
			array[x++] = posNeg[pos++];
			array[x++] = posNeg[neg--];			
		}
		
		// when done alternating, copy back the rest
		if (x < array.length) {
			if (posNeg[pos] >= 0) 
				while (x < array.length)
					array[x++] = posNeg[pos++];
			else
				while (x < array.length)
					array[x++] = posNeg[neg--];
		}
		System.out.println(Arrays.toString(array));
	}
}

- Steve August 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void Alternate(int[] numbers)
        {
            int p1 = 0;
            int p2 = 0;
            while (p2 < numbers.Length && p1 < numbers.Length -2)
            {
                if (IsPostive(numbers[p1]) != IsPostive(numbers[p1 + 1]))
                {
                    p1++;
                }
                else
                {
                    if(p2 < p1)
                    {
                        p2 = p1 + 2;
                    }
                    if (IsPostive(numbers[p2]) != IsPostive(numbers[p1]))
                    {
                        int temp = numbers[p2];
                        for (int i = p2; i > p1; i--)
                        {
                            numbers[i] = numbers[i-1];
                        }
                        numbers[p1 + 1] = temp;
                    }
                    p2++;
                }
            }
        }

        static bool IsPostive(int num)
        {
            return num > 0;
        }

- Bo August 08, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>

int get_next_neg(int a[], int n, int p){
  for(int i=p+1; i<n; i++){
    if(a[i]<0)
      return i;
  }
  return n;
}

int get_next_pos(int a[], int n, int p){
  for(int i=p+1; i<n; i++){
    if(a[i]>0)
      return i;
  }
  return n;
}

int swap(int a[], int p, int next){
  int t = a[p]; 
  a[p]=next;
  return t;
}

void alternate(int a[], int n){
  int p_neg, p_pos;         //Positions of the last found positive and negative elements respectively
  int next_pos, next_neg;   //Next positive and negative elements
  
  p_neg = p_pos = -1;
  p_neg = get_next_neg(a,n,p_neg);
  p_pos = get_next_pos(a,n,p_pos);
  if(p_neg<n)
    next_neg = a[p_neg];
  if(p_pos<n)
    next_pos = a[p_pos];

  for(int i=0; i<n; i++){
    if( (i&1)==0 && p_neg<n ){
      p_neg = get_next_neg(a,n,p_neg);
      if(p_neg==i)
	next_neg = swap(a,p_neg,next_neg);
      else{
	a[i] = next_neg;
	if(p_neg<n)
	  next_neg = a[p_neg];
      }	
    }
    else if( p_pos < n ){
      p_pos = get_next_pos(a,n,p_pos);
      if(p_pos==i)
	next_pos = swap(a,p_pos,next_pos);
      else{
	a[i] = next_pos;
	if(p_pos<n)
	  next_pos = a[p_pos];
      }
    }
  }
}

int main(int argc, char**argv){
  int n;
  std::cout << "Enter n::";
  std::cin >> n;
  
  std::cout << "Enter the elements::\n" ;
  int a[n];
  for(int i=0; i<n; i++){
    std::cin >> a[i];
  }

  alternate(a,n);
  
  for(int i=0; i<n; i++){
    std::cout << a[i] << " ";
  }
}

- abhiyanta.mahesh August 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int[] positiveNegativeAlt(int[] a) {
		int k = 0, i = 1;

		while (k < a.length) {
			// array should start with positive value;
			
			if ((a[k] < 0) && (k % 2 == 0)) {
				while (a[i] < 0 && i < a.length-1) {
					i++;
				}
				if (a[i] < 0)
					break;
				int temp = a[i];
				a[i] = a[k];
				a[k] = temp;
			} else if ((a[k] > 0) && (k % 2 == 1)) {
				while (a[i] > 0 && i < a.length-1) {
					i++;
				}
				if (a[i] > 0)
					break;
				int temp = a[i];
				a[i] = a[k];
				a[k] = temp;
			}

			k++;
			if (k < a.length)
				i = k + 1;
			else {
				break;
			}

		}

		for (int j = 0; j < a.length; j++) {
			System.out.print("\t" + a[j]);
		}
		return a;

	}

- Anonymous September 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int[] positiveNegativeAlt(int[] a) {
		int k = 0, i = 1;

		while (k < a.length) {
			// array should start with positive value;
			if ((a[k] < 0) && (k % 2 == 0)) {
				while (a[i] < 0 && i < a.length-1) {
					i++;
				}
				if (a[i] < 0)
					break;
				int temp = a[i];
				a[i] = a[k];
				a[k] = temp;
			} else if ((a[k] > 0) && (k % 2 == 1)) {
				while (a[i] > 0 && i < a.length-1) {
					i++;
				}
				if (a[i] > 0)
					break;
				int temp = a[i];
				a[i] = a[k];
				a[k] = temp;
			}

			k++;
			if (k < a.length)
				i = k + 1;
			else {
				break;
			}

		}

		for (int j = 0; j < a.length; j++) {
			System.out.print("\t" + a[j]);
		}
		return a;

	}

- Anonymous September 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(1)-space but not sure O(N) time-complexity solution:

void sortNumbers(vector<long> &data)
{
	size_t j;
	long tmp;
	for (size_t i = 0; i < data.size(); i++) {
		if (data[i] < 0 && data[i + 1] < 0) {// Look for positive number
			for (j = i + 1; j < data.size() && data[j] < 0; j++);
			if (j == data.size())
				break;
			// Shift i+1 to j-1
			tmp = data[j];
			for (size_t k = j; k > i; k--)
				data[k] = data[k - 1];
			data[i + 1] = tmp;
		}  else if (data[i] > 0 && data[i + 1] > 0) {// Look for positive number
			for (j = i + 1; j < data.size() && data[j] > 0; j++);
			if (j == data.size())
				break;
			// Shift i+1 to j-1
			tmp = data[j];
			for (size_t k = j; k > i; k--)
				data[k] = data[k - 1];
			data[i + 1] = tmp;
		}
	}
}

- Teh Kok How September 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Sign
{
	Boolean sign;

	Boolean getsign(int num)
	{
		if (num > 0)
		{
			sign = true;
		}
		else
		{
			sign = false;
		}
		return sign;
	}
}

public class OrderOfNumbers
{
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		int[] arr1 =
		{ 1, -1, 2, -2, -3, -4 };
		// int[] arr1 = {-2,2,3,-4,-5,-6};
		Sign obj = new Sign();
		Boolean signofnumber = obj.getsign(arr1[0]);
		int i = 1;
		int j = 1;
		int temp1 = i;
		int temp2 = i;
		int temp = 0;
		while (temp1 < arr1.length)
		{
			if (signofnumber != obj.getsign(arr1[temp2]))
			{
				temp1++;
				temp2 = temp1;
				signofnumber = !(signofnumber);
			}
			else
			{
				while (obj.getsign(arr1[temp2]) == ((signofnumber)))
				{
					temp2 = temp2 + 1;
					if (temp2 == arr1.length)
					{
						break;
					}
				}
				if (temp2 == arr1.length)
				{
					break;
				}
				temp = arr1[temp1];
				arr1[temp1] = arr1[temp2];
				arr1[temp2] = temp;
				temp1++;
				temp2 = temp1;
				signofnumber = !(signofnumber);
			}
		}
		for (i = 0; i < arr1.length; i++)
		{
			System.out.println(arr1[i]);
		}
	}
}

- Gaurav September 15, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

#!/usr/bin/env python

import sys

def comparator(val, positive):
    return True if val > 0 and positive else False

def alternate(vals, positive):
    if not vals:
        return
    skipped = []
    for i in range(len(vals)):
        if comparator(vals[i], positive):
            return [vals[i]] + alternate(skipped + vals[i+1:], not comparator)
        else:
            skipped.append(vals[i])
    return vals

if __name__ == '__main__':
    vals = [int(val.strip()) for val in sys.argv[1].split(',') if val.strip()]
    print ','.join([str(val) for val in alternate(vals, True)])

Test:

./negposalternate.py -2,3,4,5,-1,-6,7,9,1
3,-2,4,5,-1,-6,7,9,1

- Dan July 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Oops - that's not the right answer. I guess I can't delete this.

- Dan July 29, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is what I meant.

./negposalternate.py -2,3,4,5,-1,-6,7,9,1
3,-2,4,-1,5,-6,7,9,1

#!/usr/bin/env python

import sys

def comparator(val, positive):
    return val >= 0 if positive else val < 0

def alternate(vals, positive):
    if not vals:
        return
    skipped = []
    for i in range(len(vals)):
        if comparator(vals[i], positive):
            return [vals[i]] + alternate(skipped + vals[i+1:], not positive)
        else:
            skipped.append(vals[i])
    return vals

if __name__ == '__main__':
    vals = [int(val.strip()) for val in sys.argv[1].split(',') if val.strip()]
    print ','.join([str(val) for val in alternate(vals, True)])

- Dan July 29, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Could you please explain the algo.

- peechus July 29, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This does two things when scanning the input. It has an alternating comparator -- testing for positive (I chose to include 0) or negative. At the beginning, the comparator is testing for positive. It is reversed each time.

The algorithm is recursive. First it skips the leading elements that don't match the current comparator. When it find one that matches, it takes the matching element as the first element of the result, and recurse on the skipped elements and any remaining elements, reversing the comparator.

Here are the recursive calls (vals, printed on each call) as it is processed:

./negposalternate.py -2,3,4,5,-1,-6,7,9,1
[-2, 3, 4, 5, -1, -6, 7, 9, 1]
[-2, 4, 5, -1, -6, 7, 9, 1]
[4, 5, -1, -6, 7, 9, 1]
[5, -1, -6, 7, 9, 1]
[5, -6, 7, 9, 1]
[-6, 7, 9, 1]
[7, 9, 1]
[9, 1]
3,-2,4,-1,5,-6,7,9,1

- Dan July 29, 2014 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

This could be opimized in "C" of course. I like to sketch out the algorithm first in Python, then deal with the memory management in "C" as a port. I'm fairly convinced it could be O(n) with (1) space allocated, using the recursive approach.

- Dan July 29, 2014 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Insertion Sort uses O(1) auxiliary space, so we can use that as a base and do some modifications to suit for this problem.

int counter = 0
for (int j = 1; j < list.length; j ++) {
     if (counter%2 == 0 and list[j] > 0 and list[j-1] < 0) {
        value = list[j-1]
        list[j-1] = list[j]
        list[j] = value
    } else if (counter%2 == 1 and list[j] < 0 and list[j-1] > 0) {
        value = list[j-1]
        list[j-1] = list[j]
        list[j] = value
    }
    counter ++
}

-2,3,4,5,-1,-6,7,9,1
j = 1 -> counter = 0 even, 3 > 0 and -2 < 0, swap => 3,-2,4,5,-1,-6,7,9,1
j = 2 -> counter = 1 odd, 4 > 0 and -2 < 0, do nothing
j = 3 -> counter = 2 even, 5 > 0 and 4 > 0, do nothing
j = 4 -> counter = 3, odd, -1 < 0 and 5 > 0, swap => 3,-2,4,-1,5,-6,7,9,1
j = 5 -> counter = 4, even, -6 < 0 and 5 > 0, do nothing
j = 6 -> counter = 5, odd, 7 > 0 and -6 < 0, do nothing
j = 7 -> counter = 6, even, 9 > 0 and 7 > 0, do nothing
j = 8 -> counter = 7, odd, 1 > 0 and 9 > 0, do nothing
final result => 3, -2, 4, -1, 5, -6, 7, 9, 1

- Angel July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Insertion sort is O(N^2), right? Why is your code just a single for loop?

That code definitely will not work. Run it on an array
[1,2,3,4,-1,-2,-3,-4]

The result is:
[1,2,3,-1,4,-2,-3,-4]
--> wrong answer

- Anonymous July 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
-2
of 2 vote

but your code more extra space

- Anonymous July 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Which one, mine? I'm quite sure I could do it in "C" using constant space, using the same O(n) recursive approach. I'll try to get around to it. Easier to prototype in Python and then port.

- Dan July 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Your code looks ok but your complexity analysis is off. When you splice lists in python and you're representing the list as an array internally you're performing an O ( n ) operation so analyzing your code it will be O ( n ) total. Now, if Python internally represents the array as a list, then you'll have your O ( n ) time solution but you'll be using additional O ( n ) space. Porting it to C will be tricky since you won't be able to hold both constraints (linear time and constant memory).

- Max July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
-2
of 2 vote

a = [1,2,45,45,6,878,7,96,87,8,-909,-7,-5,-5,-4,-4,6,-7,-5,-3,-3,6,7,-1, -1];
pi = 0;
ni = 0;
y = 0;
x = 0;

while (y < len(a)-1):
    for x in range(y,len(a)-1):
        if (a[x]>0) and (a[x+1])<0:
            x=x+2;
        else: 
            break;

    while (x >0) and (a[x]<0): x = x-1;
    pi = x;
    while (x < len(a)) and (a[x]>0): x = x+1;
    ni = x;
     
    print x, pi, ni
    if pi%2 == 0 :
        a = a[:pi+1] + [a[ni]] + a[pi+1:ni] + a[ni+1:];
    else :
        a = a[:pi] + [a[ni]] + a[pi:ni] + a[ni+1:];

    if(y == pi+2):
        break
    else:
        y = pi+2;

print a

- nosh July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

a = [1,2,45,45,6,878,7,96,87,8,-909,-7,-5,-5,-4,-4,6,-7,-5,-3,-3,6,7,-1, -1];
pi = 0;
ni = 0;
y = 0;
x = 0;

while (y < len(a)-1):
    for x in range(y,len(a)-1):
        if (a[x]>0) and (a[x+1])<0:
            x=x+2;
        else: 
            break;

    while (x >0) and (a[x]<0): x = x-1;
    pi = x;
    while (x < len(a)) and (a[x]>0): x = x+1;
    ni = x;
     
    print x, pi, ni
    if pi%2 == 0 :
        a = a[:pi+1] + [a[ni]] + a[pi+1:ni] + a[ni+1:];
    else :
        a = a[:pi] + [a[ni]] + a[pi:ni] + a[ni+1:];

    if(y == pi+2):
        break
    else:
        y = pi+2;

print a

- nosh July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This seems to work and with no extra space .. Can you explain the solution .

- Jason July 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
-2
of 2 vote

public static void main(String args[]){
int[] sat = {-2,3,4,5,-1,-6,7,9,1};


for(int i=0;i<sat.length-2;i=i+2){
int temp=0;
if(sat[i]<0 && sat[i+1]>0 && sat[i+2]>0){
temp = sat[i];
sat[i] = sat[i+1];
sat[i+1] = temp;

}else if(sat[i]>0 && sat[i+1]>0 && sat[i+2]<0){
temp = sat[i+1];
sat[i+1] = sat[i+2];
sat[i+2] = temp;
}
}

for(int j=0;j<sat.length;j++){
System.out.print(sat[j] + " ");
}

}

- Sathishwaran Selvaraj July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

List<int> Alternate(List<int> input)
{
	int posPtr=0,negPtr=0;
	Pair<int,int> tempIndexValuePair;	
	for(int index=0;index < input.Length; input++)
	{
		if(index%2==0)
		{
			// If even index then find positive integer
			while(posPtr < input.Length)
			{ 
				if(tempIndexValuePair.Key == posPtr  && tempIndexValuePair.Value > 0)
				{
					int tempValue = input[index];
					input[Index] = tempIndexValuePair.Value;
					tempIndexValuePair = new Pair<int,int>(index, tempValue);
					break;
				}
				elseif(input[index] > 0)
				{
					tempIndexValuePair = new Pair<int,int>(index,input[index]);
					input[index] = input[posPtr];
					break;
				}
				posPtr++;
			 }
			if(posPtr > input.Length) break;

			
		}
		else
		{
			//find next negative integer
			Similar to above
		}
	}
	
	// Copy over the remaining array if there is excess of positive or negative  
}

- Adi July 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This does not work. Sorry cannt delete.

- Adi July 30, 2014 | Flag


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More