Walmart Labs Interview Question for Software Engineer / Developers


Team: Services
Country: India
Interview Type: In-Person




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

def findclosestsquare(num):
    num_sqrt = sqrt(num)
    num_prev = int(num_sqrt)
    num_next = int(num_sqrt + 1)
    sqr_prev = num_prev * num_prev
    sqr_next = num_next * num_next
    if(num - sqr_prev < sqr_next - num):
        return sqr_prev
    else:
        return sqr_next

print findclosestsquare(99)

- Zonito August 26, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

add a condition to check if the number itself is a perfect square

- Geek January 16, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

This function takes care of a case where given number itself is perfect square. No need to add extra check for that.

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

int res = (int)( sqrt( (float)num ) + .5f);

cout<<res;

will solve all the problem. No need to write a big program :)

- utpal October 15, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

take the square root of the number.

1- take the floor of the number and calculate the square.
2- take next higher number and caluculate the square.
3- whichever number is closer , print that.

- neel August 02, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

To get the square root of a number if a float operation, it will be slower than other operation.What we need is an integer which is close to it's square root.We can use an algorithm like binary search to do this.

int get_closest_int_root(int n){
    int low = 0 ,high = INT_MAX;
    while(low < high){
        int mid = ((low + high) >> 1);
         if (mid * mid > n){
             high = mid - 1;
         }else if ( mid * mid < n){
             low = mid + 1;
         }else 
             return mid;
    }
    if (high*high > mid){
        return (high*high - mid < mid - (high-1)*(high-1))?high:(high-1);
    }else{
        return ((high+1)*(high+1) - mid < mid - high*high)?(high+1):high;

}

- notbad August 03, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Might overflow mid*mid

- qincongfu October 15, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Replace 'mid' with 'n' in last if else block.

- slayer November 11, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Use divide and conquer to find the minimum square root.

public class ClosestPerfectSquare {

    public int getClosestPerfectSquare(int x) {
        int min = findMinSquareRoot(x, 1, x);

        int a = min * min;
        int b = (min + 1) * (min + 1);

        if (x - a < b - x) {
            return a;
        } else if (x - a > b - x) {
            return b;
        } else {
            return x;
        }
    }

    private int findMinSquareRoot(int x, int left, int right) {
        if (left > right) {
            return -1;
        }
        if (left * left <= x && x <= (left + 1) * (left + 1)) {
            return left;
        }

        int mid = left + (right - left) / 2;
        int midSquare = mid * mid;
        int midOneSquare = (mid + 1) * (mid + 1);

        if (x > midOneSquare) {
            return findMinSquareRoot(x, mid + 1, right);
        } else if (x < midSquare) {
            return findMinSquareRoot(x, left + 1, mid);
        } else {
            return mid;
        }
    }

    public static void main(String... args) throws Exception {
        for (int i = 1; i <= 100; i++) {
            int result = new ClosestPerfectSquare().getClosestPerfectSquare(i);
            System.out.println(String.format("%3d : %3d : %3d", i, result, (result - i)));
        }
    }
}

- Anonymous September 25, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

1. Take square root of the number.
2. if(decimal part of num >=.5)
3. take floor
4. else
5. take ceiling
6. square the number to get the desired result.

- gg August 02, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is close, but doesn't work all the time. Take the number 10,100.49. The square root is 100.501~, so according to these steps we should round up to 101 and square it.

However 10,100.49 is actually closer to the square of 100 (10,000) then the square of 101 (10,201).

I am still trying to figure out the formula to mathematically get the correct number.

- Shawn Goertzen August 02, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

You could look at both numbers, check the square of both, and pick the closer one.

- eugene.yarovoi August 03, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

for(i = 1, sum = 0; sum+i < num; sum += i,i+=2);
cout<<((num-sum) < (sum+i - num) ? sum : sum+i);

- shani August 03, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

for(double i=p+1;;i++)
{
double y=Math.sqrt(i);
if(y==(int)y)
{
System.out.println(i);break;
}

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

def Nearest_Square(x):
	x_root = pow(x,0.5)
	floor =int(x_root)
	ciel=int(floor+1)
	floor_sqr=floor**2;
	ceil_sqr=ciel**2;
	if(abs(floor_sqr-x)<abs(ceil_sqr-x)):
		return floor_sqr
	else:
		return ceil_sqr

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

public class ClosestSquare{

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		  System.out.println("Enter the number here: ");
		  double x;
	      Scanner scanIn = new Scanner(System.in); //Wrap the System In with a SCANNER
	      x = Integer.valueOf(scanIn.nextLine());
	      scanIn.close();            
	      
	      if (Math.floor(Math.sqrt(x)) == Math.ceil(Math.sqrt(x))){
	    	  System.out.println("The given number x: " + x + " is a perfect square...");
	      }else{// The given number is NOT a perfect square so let's find the closest one
	    	  double xSmall = Math.floor(Math.sqrt(x))*Math.floor(Math.sqrt(x));
	    	  double xLarge = Math.ceil(Math.sqrt(x))*Math.ceil(Math.sqrt(x));
	    	  if (Math.abs((x-xSmall)) > Math.abs(x-xLarge)){
	    		  System.out.println(("The closest perfect square is: " + xLarge));
	    	  }else{
	    		  System.out.println(("The closest perfect square is: " + xSmall));
	    	  }
	      }
	 }
}

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

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,t=m=0;
clrscr();
printf("Enter the number");
scanf("%d",&n);
while(1)
{
i=n;
j=n;
i++;
j--;
t=sqrt(i);
m=sqrt(j);
if(i==t*t)
{
printf("Nearest Perfect Square is:%d",i);
break;
}
if(j==m*m)
{
printf("Nearest Perfect Square is:%d",j);
break;
}
}
getch();
}

- Raja July 01, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Is there any problem with this approach

int i,j,n,avg1;
float avg2;
scanf("%d",&n);
i=n;
j=n;
while(1)
{
i++;
j--;
avg1=sqrt(i);
avg2=sqrt(i);
if(avg1==avg2)
{
printf("the near perfect square is %d ",i);
break;
}
avg1=sqrt(j);
avg2=sqrt(j);
if(avg1==avg2)
{
printf("the nearest perfect square is %d ",j);
break;
}
}

- Antrix October 09, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int main()
{
	int n;
	cin>>n;
	double x = sqrt(n);
	n = (x+0.5);
	cout<<n*n<<endl;
	return 0;
}

- Sunny Jain April 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int main()
{
	int n;
	cin>>n;
	double x = sqrt(n);
	n = (x+0.5);
	cout<<n*n<<endl;
	return 0;
}

- Sunny Jain April 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int main()
{
	int n;
	cin>>n;
	double x = sqrt(n);
	n = (x+0.5);
	cout<<n*n<<endl;
	return 0;
}

- Sunny Jain April 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int main()
{
	int n;
	cin>>n;
	double x = sqrt(n);
	n = (x+0.5);
	cout<<n*n<<endl;
	return 0;
}

- Sunny Jain April 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int main()
{
	int n;
	cin>>n;
	double x = sqrt(n);
	n = (x+0.5);
	cout<<n*n<<endl;
	return 0;
}

- Sunny Jain April 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int main()
{
	int n;
	cin>>n;
	double x = sqrt(n);
	n = (x+0.5);
	cout<<n*n<<endl;
	return 0;
}

- Sunny Jain April 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Binary search. Find the perfect squares just below and above and pick the closest.

- Anonymous August 02, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I have the same idea, and I think time is O(logn). Correct me

- Anonymous June 19, 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