VMWare Inc Interview Question for Java Developers


Country: United States
Interview Type: Phone Interview




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

Keep a pointer next to the last even number found and traverse through the array. Keep swapping the elements whenever an even number is found.

public static void moveEvenToLeft(int[] array) {
		
		int i = 0;
		for (int j = 0; j < array.length; j++) {
			if (array[j] % 2 == 0) {
				swap(array, i, j);
				i++;
			}
		}
		
	}

- Chris June 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I like this. I wrote one where I explicitly keep track of the first odd index as well, but your solution is simpler. In the swap, you just have to make sure to avoid swapping the same element with itself.

- thushw June 05, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

i came up with this but your's is so much more elegant.

private static void rearrangeArray(Integer[] intarry) {

		// count the number of evens
		int count = 0;
		for (int i : intarry) {
			if (i % 2 == 0)
				count++;
		}
		int i = 0, j = intarry.length - 1;
		while (true) {
			if (i >= count) {
				break;
			}

			while (intarry[i] % 2 == 0) {
				i++;
			}
			while (intarry[j] % 2 != 0) {
				j--;
			}
			exchangeValues(intarry, i, j);
			i++;
			j--;
		}

	}

- getprith June 09, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

incorrect last swap, add if statement

- Anonymous April 21, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Chris: I am not sure but aren't you also swapping an element with itself, if this is implicitly assumed. You can perhaps add an if statement in the swap function

if( i != j).

- PJ August 13, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

public static void moveEvenToLeft(int[] array) {

int i = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] % 2 == 0 && i != j) {
swap(array, i, j);
i++;
}
}

}

- Anonymous September 28, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

public static void moveEvenToLeft(int[] array) {
		
		int i = 0;
		for (int j = 0; j < array.length; j++) {
			if (array[j] % 2 == 0 && i != j) {
				swap(array, i, j);
				i++;
			}
		}
		
	}

- Anonymous September 28, 2014 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 vote

This could be done in one scan.
We use 2 pointers evenRef and oddRef.
evenRef points to the first element of the array and oddRef to the last.
Now we increment and decrement the even and odd references respectively according to the element we encounter in the array and make appropriate swaps.
This process is repeated until both the references meet.

public static void reArrangeArray(int[] inputArray)
	{
		int n = inputArray.length;
		int evenRef=0,oddRef=n-1;
		
		while(evenRef<oddRef)
		{
			while(inputArray[evenRef]%2==0)
				evenRef++;
			while(inputArray[oddRef]%2!=0)
				oddRef--;
			swapAtIndices(inputArray,evenRef,oddRef);
			evenRef++;
			oddRef--;
		}
		
	}

	private static void swapAtIndices(int[] inputArray, int evenRef, int oddRef) {
		int temp=inputArray[evenRef];
		inputArray[evenRef]=inputArray[oddRef];
		inputArray[oddRef]=temp;		
	}

Please correct me if I'm wrong.

- teli.vaibhav June 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

What about [4,9] ?

- Avi August 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

while(j<k)
		{
			System.out.println("j"+j+"k"+k);
			if(arrayList.get(j)%2==0)
				j++;
			else if(arrayList.get(k)%2==1)
				k--;
			else
			{
				temp=arrayList.get(j);
				arrayList.set(j, arrayList.get(k));
				arrayList.set(k, temp);
			}
		}

- blueLagoon June 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

dutch national flag solution

- aka June 05, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Could you specify initial values for j, k please? Otherwise, it is not clear how you would avoid boundary conditions on the array.

- thushw June 05, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

int end = array.Count - 1;
            for (int i = 0; i < end; i++)
            {
                if(array[i]%2 == 0) continue;//even

                for (int j = end; j > i; j--)
                {
                    if (array[j] % 2 != 0) continue; //odd at right side
                    else
                    {
                        //swap 
                        int temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                        end = j --;
                        break;
                    }
                }
            }

- droidlooms June 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Working java code:

public static void seperate_evens_odds(int array[]){
                int i=0;
                int j=array.length-1;

                while (true){
                        if(array[i] % 2 == 0) ++i;
                        if(array[j] % 2 == 1) --j;
                        if(i >= j) break;
                        if(array[i] % 2 == 1 && array[j] % 2 == 0)
                        {
                                int tmp = array[i];
                                array[i] = array[j];
                                array[j] = tmp;
                        }
                }
        }

- Anonymous June 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

quick sort with added tweak.Pivot can be either even or odd always untill end of array.

- aka June 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int even(int n)
{
if(n==1) return 0;
else if(n%2==0) return 1;
else return 0;
}
int odd(int n)
{
if(n==1) return 1;
else if (n%2==0) return 0;
else return 1;
}
void separate_the_array(int a[],int i,int j)
{
int n=j;
while(1)
{
while(i<j && even(a[i]))
i++;
while(i<j && odd(a[j]))
j--;
if(i>=j) break;
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
for(i=0;i<=n;i++)
printf("%d ",a[i]);
}
void main()
{
int a[]={4,5,10,3,2,11,14,7,6};
int n=sizeof(a)/4;
separate_the_array(a,0,n-1);
}

- Anonymous June 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.ad.test.string;

public class EvenOdd {

	/**
	 * @param args
	 */
	int test[]={4,6,2,5,7,1,2,3,4,5,6,7,8,9,7,6,5,4,3,2,34,5,56,6};
	void setEvenOdd(){
		int temp=0;
		for(int i=0;i<test.length;i++){
			//			even
			if(test[i]%2!=0){
				for(int j=i+1;j<test.length;j++){
					if(test[j]%2==0){
						test[j]=test[i]+test[j];
						test[i]=test[j]-test[i];
						test[j]=test[j]-test[i];
						break;
					}
				}
			}
		}
		for(int i=0;i<test.length;i++){
			System.out.print(" "+test[i]);
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		new EvenOdd().setEvenOdd();
	}

}

- AD June 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

For moving the elements that is the even to the left and odd to the right we could take the following approach:
a.Consider two references such that one reference points to the start of the array and another points to the last of the array. Increment the first reference and decrement the second reference until first is equal to second.
b.Now if the both references point to even element then increment the first reference as the second reference now points to the even element and whenever we find that the first points to the odd then we swap both the elements.
c.If last points to even and first points to odd then first swap and then decrement the second and increment the first pointer
d.If first points to even and second points to odd then decrement the second reference as it is already that is the odd element is already in the right side of the array.
e.If both the elements are odd then also decrement the second reference as the odd element should be to the right and for the first one pointing to the odd whenever an even element is found that condition is handled in the c. condition. Below is the code:

void swap(int arr[],int i,int j)
{
    int temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
}
void placeElements(int arr[],int n)
{
    int i=0,j=n-1;
    while(i<j)
    {
        if(arr[j]%2==0&&arr[i]%2==0)
        {
            i++;

        }
        else if(arr[j]%2==0&&arr[i]%2!=0)
        {
            swap(arr,i,j);
            j--;
            i++;
        }
        else if(arr[j]%2!=0&&arr[i]%2==0)
        {
            j--;
        }
        else
        {
            j--;
        }
    }

}
void printArray(int arr[],int n)
{
    int i;
    for(i=0;i<n;i++)
        printf("%d ",arr[i]);
}
int main()
{
    int arr[]={3,3,3,5};
    int n=sizeof(arr)/sizeof(arr[0]);
    placeElements(arr,n);
    printArray(arr,n);
}

- vgeek June 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

for(int i=0, j= N-1;i<N && j>=0;)
while(j>i)
{
while(a[i] & 1) i++;
while(!(a[j] & 1))j--;
swap(&a[i++],&a[j--]);
}

- tohana June 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void doIt(int[] arr) {
	for (int left = 0, right = arr.length - 1; left < right;) {
		if ((arr[left] & 1) != 0) {
			int temp = arr[left];
			arr[left] = arr[right];
			arr[right--] = temp;
		} else {
			++left;
		}
	}
}

- Anonymous June 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How is it working here you are checking for whether the element is not odd that is even and then exchanging with the element at the right whereas even elements should be at the left and not the right.

- vgeek June 06, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@vibhutiwari321, how could you say the code checks for odd instead of even?

- Anonymous June 06, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void dis(int *a, int len);

void even_odd(int *a, int len)
{
        int i=0;

        int e,o;

        int i_e=0;
        int i_o=len-1;

        for(i=0; i<len; i++)
        {
                //printf("i = %d , i_e = %d , i_o = %d\n", i, i_e, i_o);


                if(i > i_o)
                        break;

                if(a[i] % 2 == 0)
                {
                        a[i_e++] = a[i];
                }
                else
                {
                        int t;

                        t=a[i];

                        a[i] = a[i_o];

                        a[i_o] = t;

                        i_o--;
                        i--;

                        //dis(a,len);

                }
        }

        dis(a,len);
        //dis(a,i_e);

}

void dis(int *a, int len)
{
        int i;
        for(i=0; i<len; i++)
        {
                printf("%d ", a[i]);
        }
        printf("\n");
}

- naveen balam June 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
int main()
{
	int *a,n,i,j,temp;
	int evenCount=0;
	printf("enter the number of elements u want in the array");
	scanf("%d",&n);
	a=(int *)malloc(sizeof(int)*n);
	printf("\n\nenter the %d elements u want in the array",n);
	for(i=0;i<n;i++){
		scanf("%d",&a[i]);
	}
	
	for(i=0;i<n;i++){
		if(a[i]%2==0)
			evenCount++;
	}
	
	
	for(i=0;i<evenCount;i++){
		if(a[i]%2!=0){
			for(j=n-1;j>=evenCount;j--){
				if(a[j]%2==0){
					temp=a[i];
					a[i]=a[j];
					a[j]=temp;
				}	
			}	
		}
				
	}

	printf("\n\nthe final array is ");
	for(i=0;i<n;i++){
		printf("%d ",a[i]);
	}
return 0;
}

- Surya Pratap June 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// Given +ve numbers in an array.
        // Put the even #s to the left of the array and the odd to the right side of the array . Don't use extra array.
        public static void Question1()
        {
            // assumption, left and right sides of the array are un-orderd.
            int[] input = new int[] { 1, 2, 3, 4, 6, 2, 1, 5, 6, 7, 8, 2, 2, 2, 2 };
            int start = 0;
            int end = input.Length - 1;

            Console.WriteLine(string.Join(",", input));

            while (start < end)
            {
                if (input[start] % 2 == 0) // start is even - skip it
                {
                    start++;
                    continue;
                }
                if (input[end] % 2 != 0) // end is odd - skip it
                {
                    end--;
                    continue;
                }
                int temp = input[start];
                input[start] = input[end];
                input[end] = temp;
                start++;
                end--;
            }

            Console.WriteLine(string.Join(",", input));
        }

- Salvatore June 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

u can use the simple concept of partitioning.take two pointer one start from front one from end then start moving 1st ponter from left till u wont get the odd no do same for other pointer and check for even.if 1st pointer doesnot overpass the second pointer then then swap other wise u reach to the solution.

- go4gold June 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args)
   {
       int arr[]=new int[20];
       Scanner scn=new Scanner(System.in);
       System.out.println("enter elements in array");
       for(int i=0;i<20;i++)
       {
           arr[i]=scn.nextInt();
       }
       for(int i=0;i<20;i++)
       {
           if(arr[i]%2==0)
           {
               break;
           }
           else
           {
           for(int j=i+1;j<20;j++)
           {
            if(arr[j]%2==0)
            {
                int tmp=arr[i];
                arr[i]=arr[j];
                arr[j]=tmp;
                break;
            }
           }
           }
       }
       for(int i=0;i<20;i++)
       {
           System.out.print(arr[i]+",");
       }
   }

- sumant September 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class SwipeEvenOdd {
private int a[] = {2,3,2,3,2,3};

public void reArrange(){
int i = 0, j = a.length-1;
while(i<=j){
if(a[i] % 2 == 0 && a[j] % 2 !=0){
i++;
j--;
}else{
exchange(i,j);
i++;
j--;
}
}
}

private void exchange(int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

public void display(){
for(int i=0;i<a.length-1;i++){
System.out.println(a[i]);
}
}

public static void main(String[] args) {
SwipeEvenOdd obj = new SwipeEvenOdd();
System.out.println("Before reArrange");
obj.display();
System.out.println("After reArrange");
obj.reArrange();
obj.display();
}

}

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

def OddEven(vec, start, end):
    if start == end:
        return vec
    else:
        if vec[start]%2 == 0:
            start += 1
        else:
            if vec[end]%2 == 0:
                vec[start], vec[end] = vec[end], vec[start]
                start += 1
                end -= 1
            else:
                end = end-1
        return OddEven(vec, start, end)

import numpy as np
vec = np.random.randint(1, 10, 10)
print vec

print OddEven(vec,0, len(vec)-1)

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

def OddEven(vec, start, end):
    if start == end:
        return vec
    else:
        if vec[start]%2 == 0:
            start += 1
        else:
            if vec[end]%2 == 0:
                vec[start], vec[end] = vec[end], vec[start]
                start += 1
                end -= 1
            else:
                end = end-1
        return OddEven(vec, start, end)

import numpy as np
vec = np.random.randint(1, 10, 10)
print vec

print OddEven(vec,0, len(vec)-1)

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

Partition the given array into all even numbers followed by odd numbers.

void even_odd_partition(int A[], int i, int j) {
	while (i < j) {
		if (A[i] % 2 != 0) {
			while (i < j && A[j] % 2 != 0)
				--j;
			if (i < j)
				swap(A, i, j);
		} else if (A[i] % 2 == 0) {
			while (i < j && A[j] % 2 == 0)
				++i;
			if (i < j)
				swap(A, i, j);
		}
	}
}

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

```def Bubble(a):
    # Bubbles the even number to the right end of the array
    # Time : O(N^2)
    # Space : O(1)
    for i in range(0,len(a)):
        for j in range(0,len(a)-i-1):
            if a[j] % 2 == 0:
                a[j],a[len(a)-j-1] = a[len(a)-j-1],a[j] 
    return a 

Bubble([2,4,6,8,10,1,3,5,7,9])```
# [9, 7, 5, 3, 1, 10, 8, 6, 4, 2]

- Vamshi G January 05, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

int j =0;
	for (int i=0;i<array.length;i++) {
		if(array[i]%2==0){
			int temp = array[i];
			array[i]=array[j];
			array[j]=temp;
			j++;
		}
	}

- William June 06, 2013 | Flag Reply


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