Walmart Labs Interview Question for Software Engineer / Developers


Country: United States
Interview Type: Phone Interview




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

Repost with formatting

static void Main(string[] args)
        {
            // first sort A (left out here)
            //int[] A = new int[] { -2, 0, 4, 5, 6 };
            int[] A = new int[] { -3, -2, 0, 2, 4 };

            for (int i = 0; i < A.Length; i++)
            {
                int j = i+1; //start where i is
                int k = A.Length - 1; // start at the end of array

                while (k >= j)
                {
                    if (A[i] + A[k] + A[j] == 0)
                    {
                        Console.WriteLine("{0}, {1}, {2}", A[i], A[j], A[k]);
                        return;
                    }

                    // no match. 
                    // if sum is too big, decrement k
                    // if sum is too small, increment j
                    if (A[i] + A[j] + A[k] > 0) k--;
                    else j++;                   
                }
            }

            Console.WriteLine("not found");

        }

- Gohawks March 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

You are assuming that the array is sorted. Isnt it?

- Alpha0 February 23, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I tried the above code and it failed for case - { -3, -2, 0, 1, 4 }; - Got o/p - -2,1,1 which is incorrect.
I just changed the while(k>j) rather than k>=j and it gave correct o/p as "not found"

- bimmr February 12, 2016 | Flag
Comment hidden because of low score. Click to expand.
3
of 5 vote

This should be an extended form to find sum of two equal to some specified value.
1> Sort the array in ascend order.
2> Beginning from the end of the list, pick each number, as P1
3> from the rest of the numbers in the array try to find P2+P3 = -P1, which has O(n) complexity.
4> If find one in 3>, terminate the search.

Worst case complexity: O(n*n).

- chenlc626 March 15, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

See the solution from @Gohawks to see how to solve P2+P3=n on a sorted list in O(n) time. You start with P2 as the min and P3 as the max, and then each iteration you either increment P2 or decrement P3, depending on whether P2+P3 is too small or too big, respectively. The magic here is that once P2+P3 >= n, you can stop finding pairs for P3, since all the remaining P candidates will be greater than P2 by virtue of the list being sorted. This is what prevents the inner loop of this algorithm from being N-squared.

- showell30@yahoo.com March 16, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

List<int> array = new List<int>() { -7, -3, 2, 10, 3, 4, 6, 7 };

        public void FindNumbers()
        {
            array.Sort();
            for (int i = array.Count - 1; i >= 0; i--)
            {
                int number = array[i];
                int signNumber = Math.Sign(number);
                int j = 0;
                while (Math.Sign(array[j]) * -1 == signNumber && j < array.Count)
                {
                    int k = j + 1;
                    while (Math.Sign(array[k]) * -1 == signNumber && k < array.Count)
                    {
                        if (Math.Abs(array[j] + array[k]) == number)
                        {
                            Console.WriteLine("Found " + array[j] + " " + array[k] + " " + number);
                            Console.Read();
                            return;
                        }
                        k++;
                    }
                    j++;
                }
            }
            Console.Write("Not found");
            Console.Read();
            return;
        }

Further, the number of iterations can be reduced by having few checks:
1. If the large number is positive, the other 2 must be negative and the vice versa is also true

- aneudupi March 15, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

Please explain what you mean by "best" algorithm.

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

I don't know of any obvious way to do this faster than N squared time. To do it in N squared time, first create a reverse mapping of numbers to the index(es) of the array containing that number. Then do an N-squared pass on pairs of numbers, take their sum, then look in the reverse mapping to find the index of the additive inverse of the pair's sum.

You can prune the outer edges of the list by finding the most negative number and most positive number (in linear time), and then during your N-squared pass exclude numbers on the other side of the zero that have double the magnitude. For example, if your largest positive number is 6, then you can immediately reject -13 as being part of the solution, since you'd need at least one number > 6.5 to get back to zero.

- showell30@yahoo.com March 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

One has to rule out all positive and all negative numbers. Then, sort the array O(log n). Now, pick the highest number P1. Then, scroll down the array finding a value with magnitude less than -P1; call it P2. Now, compute P3=P1+P2. Then, quick search for P3 O(log n). Repeatedly pick P1 until one runs out of positive numbers or finds P3.

- Venkat March 16, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void Main(string[] args)
{
// first sort A (left out here)
int[] A = new int[] { -3, -2, 0, 2, 4 };

for (int i = 0; i < A.Length; i++)
{
int j = i+1; //start where i is
int k = A.Length - 1; // start at the end of array

while (k >= j)
{
if (A[i] + A[k] + A[j] == 0)
{
Console.WriteLine("{0}, {1}, {2}", A[i], A[j], A[k]);
return;
}

// no match.
// if sum is too big, decrement k
// if sum is too small, increment j
if (A[i] + A[j] + A[k] > 0) k--;
else j++;
}
}

Console.WriteLine("not found");

}

- Gohawks March 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ThreeNumSum {
public static boolean areThreeNumPresent(int[] arr, int sum) {
int len = arr.length;

Arrays.sort(arr);
for(int i=0;i<len - 2;i++) {
int j = i + 1;
int m = len-1;

while(j < m) {
if(arr[i] + arr[j] + arr[m] == sum) {
return true;
} else if (arr[i] + arr[j] + arr[m] < sum) {
j++;
} else if (arr[i] + arr[j] + arr[m] > sum) {
m--;
}
}
}
return false;
}
public static void main(String[] args) {
int[] arr = {3,5,2,7,15,3};
int sum = 25;

if(areThreeNumPresent(arr,sum)){
System.out.println("Elements are present");
} else {
System.out.println("Elements are not present");
}

}
}

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

public class ThreeNumSum {
    public static boolean areThreeNumPresent(int[] arr, int sum) {
        int len = arr.length;

        Arrays.sort(arr);
        for(int i=0;i<len - 2;i++) {
            int j = i + 1;
            int m = len-1;

            while(j < m) {
                if(arr[i] + arr[j] + arr[m] == sum) {
                    return true;
                } else if (arr[i] + arr[j] + arr[m] < sum) {
                    j++;
                } else if (arr[i] + arr[j] + arr[m] > sum) {
                    m--;
                }
            }
        }
        return false;
    }
    public static void main(String[] args) {
        int[] arr = {3,5,2,7,15,3};
        int sum = 25;

        if(areThreeNumPresent(arr,sum)){
            System.out.println("Elements are present");
        } else {
            System.out.println("Elements are not present");
        }

    }
}

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

This almost gives the requried result.

import java.util.Arrays;

public class FindSumIsZeroFromThreeArrayElements {

	public static void main(String[] args) {
		int [] array = new int[] {-7, -3, 2, 10, 3, 4, 6, 7,0};
		Arrays.sort(array);
		System.out.println("Sorted Array Elements : ");
		for (int i = 0 ; i < array.length ; i++) {
			System.out.print(array[i] + " ,");	
		}
		System.out.println("\n\nSum Of Zero from three array elements : ");
		isSumZero(array);
	}

	public static void isSumZero(int[] array){
		for (int i = 0; i < array.length; i++){
			int iter = i + 1;
			int reviter = array.length - 1;
			int tmp = 0;
			while ( reviter >= 0 && iter < array.length){
				tmp = array[iter] + array[reviter] + array[i];
				if( tmp > 0){
					reviter--;
				}
				else if( tmp < 0) {
					iter++;
				}
				else {
					System.out.println(array[i] + ", "+ array[iter] +", "+ array[reviter]  );
					break;
				}
			}
		}
	}
}

Execution Result:
---------------------------

Sorted Array Elements :
-7 ,-3 ,0 ,2 ,3 ,4 ,6 ,7 ,10 ,

Sum Of Zero from three array elements :
-7, -3, 10
-3, 0, 3
0, 3, -3
3, 4, -7

- Gemsbond April 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private void checkArrayAndCalculateSmartForce(int[] numbersArray) {
Set<Integer> numbersSet = new HashSet<Integer>();
for(int digits:numbersArray) {
numbersSet.add(digits);
}
Integer[] uniqueNumbersArray = numbersSet.toArray(new Integer[0]);
boolean numberFound=false;
int firstNumber=0, secondNumber=1, thirdNumber=2, total=0,loopCounter=3;
for(firstNumber=0;firstNumber<uniqueNumbersArray.length;firstNumber++,loopCounter++) {
for(secondNumber=1;secondNumber<uniqueNumbersArray.length;secondNumber++,loopCounter++) {
for(thirdNumber=2;thirdNumber<uniqueNumbersArray.length;thirdNumber++,loopCounter++) {
total=uniqueNumbersArray[firstNumber]+uniqueNumbersArray[secondNumber]+uniqueNumbersArray[thirdNumber];
if(total ==0){
System.out.println("1st."+uniqueNumbersArray[firstNumber]);
System.out.println("2nd."+uniqueNumbersArray[secondNumber]);
System.out.println("3rd."+uniqueNumbersArray[thirdNumber]);
numberFound=true;
break;
}
}
if(numberFound) break;
}
if(numberFound) {
System.out.println("loop ran for "+loopCounter);
break;
}
}

}

- Bhumir Jhaveri May 09, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Complexity: n logn + nlogn = nlogn

1- Sort array (nlo1g n)
2- start from both ends low and high,

sort(a);
int low =0,high = a.Length-1;
while(low<high)
{
	int s = low + high;
	if(BinarySearch(low,high,-s))
		print(low,high,-s);

	if(sum > 0)
		 high--;
	else
	 	low++;
}

print("elements not found");

- iA May 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How are you calculating the list of numbers?

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

try your solution with input as the following
{-17, -13, -5, 5, 9, 12, 16, 23}

- 1337yogesh September 17, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ThreeSumZero {

    /**
     * @param args
     */
    public static void main(String[] args) {


        int[] A = new int[] { -3, -2, 1, 2, 4 };

        HashMap<Integer,Integer> allVal=new HashMap<Integer,Integer>();



        for (int i = 0; i < A.length; i++) {

            allVal.put(Integer.valueOf(A[i]),Integer.valueOf(i));


        }

      for (int i = 0,j=1; i < A.length-1; i++) {

         int temp= -A[i]-A[j];


        if(allVal.containsKey(Integer.valueOf(temp)) )
         {

             int idx= allVal.get(Integer.valueOf(temp));
             if ( idx!=i&&idx !=j)
              System.out.println("Locations form threesum zero i,j,k :"+i+" :"+j+" :"+allVal.get(Integer.valueOf(temp)) );
         }
        j++;

    }


    }

}

- Coder September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

wrong solution

- careerCupguy10 March 21, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class CareerCup {

public static void main(String[] args) {
int sum=0;
int a,b,c;
int[] arr=new int[]{-5,3,2,5,0,8,9};
List<Integer>list = new LinkedList<Integer>();
Set<String>set = new TreeSet<String>();
for(int i=0;i<arr.length;i++)
{
list.add(arr[i]);
}
Collections.sort(list);
System.out.println(list);
for(int i=0;i<arr.length;i++)
{

for(int j=1;j<arr.length;j++)
{
a=list.get(i);
b=list.get(j);
sum=a+b;
if(list.contains(-sum))
{
if((-sum>a)&&(-sum>b))
{
set.add(a+" "+b+" "+(-sum));
}
else if((-sum<a)&&(-sum>b))
{
set.add(+b+" "+(-sum)+" "+a);

}
else if((b>-sum)&&(a>b))
{
set.add((-sum)+" "+b+" "+a);
}
}

}

}
System.out.println("The values the give a sum of zero are:"+set);
}
}

- Srinivas July 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class CareerCup {

public static void main(String[] args) {
int sum=0;
int a,b,c;
int[] arr=new int[]{-5,3,2,5,0,8,9};
List<Integer>list = new LinkedList<Integer>();
Set<String>set = new TreeSet<String>();
for(int i=0;i<arr.length;i++)
{
list.add(arr[i]);
}
Collections.sort(list);
System.out.println(list);
for(int i=0;i<arr.length;i++)
{

for(int j=1;j<arr.length;j++)
{
a=list.get(i);
b=list.get(j);
sum=a+b;
if(list.contains(-sum))
{
if((-sum>a)&&(-sum>b))
{
set.add(a+" "+b+" "+(-sum));
}
else if((-sum<a)&&(-sum>b))
{
set.add(+b+" "+(-sum)+" "+a);

}
else if((b>-sum)&&(a>b))
{
set.add((-sum)+" "+b+" "+a);
}
}

}

}
System.out.println("The values the give a sum of zero are:"+set);
}
}

- Srinivas July 07, 2015 | 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