Linkedin Interview Question for Software Engineer / Developers


Country: United States
Interview Type: Phone Interview




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

double _power(double x, int y)
{
	if(y==0) return 1;

	double t = _power(x, y/2);
	t *= t;

	return t * ( (y%2)?x:1 );
}

double power(double x, int y)
{
	if(y<0) return - _power(x,-y);
	else return _power(x,y);
}

- SENBOTDRON the Transformer from Autobots actually dinobots February 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Can you explain how this takes only log(n)? I'm a little rusty with the _functionName() syntax.

- Jay March 12, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

private static double powerBinary(double a, int b){
		
		if(b == 0)
			return 1;
		if(b == 1)
			return a;
		else if(b%2 == 0)
			return powerBinary(a,b/2) * powerBinary(a,b/2);
		else
			return a* powerBinary(a,b/2) * powerBinary(a,b/2);
		
	}

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

Doesnt your code return -125 for power(5,-3) ? It should return 1.0/125 right?

- Learner November 10, 2014 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 vote

Look at this:

double power(double x, int y)
{
    if (y == 0)
        return 1.0;
    if (y == 1)
        return x;

    if (y < 0)
        return 1.0 / power(x, -y);

    if (y & 0x1 == 0) {
        double t = power(x, y/2);
        return t * t;
    }

    return x * power(x, y - 1);
}

double power_iterative(double x, int y)
{
    double result = 1.0;

    if (y == 0)
        return result;

    bool neg = false;

    if (y < 0) {
        neg = true;
        y = -y;
    }

    while (y) {
        if (y & 0x1)
            result *= x;
        x *= x;
        y >>= 1;
    }

    return neg ? 1.0 / result : result;
}

- Westlake February 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Improving on CPTjack's solution. Basically log2(b) will not always be an integer, hence the solution will have to multiply the base for any remainder. For example, if a=2 and b=6, log2(6) = 2.xx, hence the solution has to multiply the base for 6-4 = 2 more times.

double pow(double a, int b) {

        int exp=Math.abs(b),i;
        double base=a;

        if(exp==0) return 1.0;

        i=1;

        while((exp>=1) && (i< Math.abs(b)) ){
            if(exp > 1) {
                exp = exp/2;
                i= i*2;
                base = base*base;
            } else {
                i=i+1;
                base = base*a;
            }
        }

        if(b<0)
            return 1/base;
        else
            return base;

    }

- luca30 February 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public double pow(double a, int b) {

	while(b!=0)
	{
	int c = b%3;
	if(c==0)
	{
		a=a*a*a;
		b=b-3;
	}
	else if(c==1)
	{
		a=a*a*a*a;
		b=b-4;
	}
	else if(c==2)
	{
		a=a*a*a*a*a;
		b=b-5;
	}
	}
	
	return a;
	}

Is this O(log n) and how do you deduce that ?

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

Your algo is O(b): every time you decrease b by 3,4 or 5, you perform 3,4 or 5 MULTIPLY operations...

In fact, your solution is wrong! Example pow(2,6) should give 2^6, while your function gives 2^9.

- ninhnnsoc February 24, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

en.wikipedia.org/wiki/Exponentiation_by_squaring

def double(a, b):
        print str(a) + str(" ") + str(b)
        a = int(a)
        b = int(b)
        if b == 0:
                return 1
        if b == 1:
                return a
        if b%2 == 0:
                return double(a*a, b/2)
        else:
                return a*double(a*a, (b-1)/2)

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

public static long power(int base, int raise) {
		long res = 1;
		for (int mask = 1; mask <= raise; base *= base, mask <<= 1) {
			if ((mask & raise) > 0) {
				res *= base;
			}
		}
		return res;
	}

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

static long powerNotUsingPower(int base, int raise) {
		long res = 1;
		for (; raise > 0; base *= base, raise >>= 1) {
			if ((raise & 1) > 0) {
				res *= base;
			}
		}
		return res;
	}

- Anonymous February 24, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static float power(int x,int y){
		float temp;
		if(y==0)
			return 1;
		temp = power(x,y/2);
		if(y%2 ==0)
			return temp*temp;
		else
		{
			return x*temp*temp;
		}
		
	}

- kiran March 13, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static double pow(double a, int b){
boolean isNegative = false;
if( b < 0 ){
b = b *-1 ;
isNegative = true;
}
if( b ==0 ) return 1;

double result = pow(a,b/2);
result = b%2 == 0? result*result : result*result*a;
return isNegative ? 1/result : result;
}


static double powNonReecursive(double a, int b){
boolean isNegative = false;
if( b < 0 ) {
b=b*-1;
isNegative = true;
}
double result = 1.0;
while( b != 0){
if(b%2 == 0){
a=a*a;
b= b/2;
}else{
result*=a;
b=b-1;
}
}
return isNegative ?1/result: result;
}

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

although its NP complete (en.wikipedia.org/wiki/Addition-chain_exponentiation)

here is the binary exponentiation version:

public static double pow(int a,int b){
                if(b==0 || a==1) return 1;
                if(b==1) return a;

                if(b<0)
                        return 1/pow(a,-b);

                return b % 2 == 0 ? pow(a,b/2) * pow(a,b/2) : a * pow(a,b-1);
        }

- bubba March 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Solution:
    # @param x, a float
    # @param n, a integer
    # @return a float
    def pow(self, x, n):
        if n == 0:
            return 1.0
        elif n == 1:
            return x
        elif n > 0:
            return pow(x, n // 2) * pow(x, n - n // 2)
        else:
            #n < 0:
            return 1.0 / pow(x, -n)

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

class Solution:
    # @param x, a float
    # @param n, a integer
    # @return a float
    def pow(self, x, n):
        if n == 0:
            return 1.0
        elif n == 1:
            return x
        elif n > 0:
            return pow(x, n // 2) * pow(x, n - n // 2)
        else:
            #n < 0:
            return 1.0 / pow(x, -n)

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

/** 
    * Returns a^b, as the standard mathematical exponentiation function 
    */ 
    public double pow(double a, int b) {
        double result = 1.0d;
        double square = a;
        while (b > 0) {
            if ((b & 1) == 1) {
                result *= square;
            }
            square = square * square;
            b = b >> 1;
        }
        return result;
    }

Negative b will require square root instead of square, but the idea is same.
I like bit operator over recursive call.

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

def custom_pow(a, b):
    if b < 0:
        return 1.0 / custom_pow(a, -b)
    exponent_to_value_map = collections.OrderedDict()
    current_exponent = 1
    current_value = a
    exponent_to_value_map[current_exponent] = current_value
    while 2 * current_exponent < b:
        current_exponent *= 2
        current_value = current_value * current_value
        exponent_to_value_map[current_exponent] = current_value
    residual_exponent = b - current_exponent
    while residual_exponent != 0:
        tmp_exp, tmp_val = 0, 1
        for exponent, value in exponent_to_value_map.iteritems():
            if exponent <= residual_exponent:
                tmp_exp = exponent
                tmp_val = value
            else:
                break
        residual_exponent -= tmp_exp
        current_value *= tmp_val
    return current_value

- Rahul Paul May 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This will not work for (2,4) the expected output is 16 but your code will generate 32 because 2/2 is 1

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

public static int power(int a, int b) {
	    boolean isEven = true;
	    if(b == 0) return 1;
	    if(b == 1) return a;
	    else {
	          int result = a*a;
	          b = b-2;
	          while(b > 1) {
	                 result = result * result;
	                 int i = b%2;
	                 if(i > 0) {
	                	 isEven = false;
	                 }
	                 b = b/2;
	           }
	           if(b == 1 && !isEven)  return result * a;
		return result;
	     }    
	}

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

I had the same question asked....
I first gave a solution using DP (like fibonacci) with complexity N/2 = O(n)
Then I told him I can improve on this I gave another solution which was Log(n) (using memoization + recursion) something similar to top comment.

:( I guess I won't make it

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

int[] result = new int[b/2];

public double pow(double a, int b, int[] result) {
    if (b == 0) {
        return 1;
    }
    if (b == 1) {
        return a;
    }
    if (INTEGER.MAX_VALUE != result[b]) return result[b];
    if (b % 2 != 0) {
        result[b] = result[b - 1] * a;
        return result[b];
    }
    else {
        double _result = pow(a, b/2, result); 
        result[b] = _result * _result;
        return result[b];
    }

}

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

public class FindPowerOptimum {

	private double power(double a, int b) {
		// TODO Auto-generated method stub
		if (b == 0)
			return 1;
		if (a == 0)
			return 0;
		double output = 1;
		boolean isNegative = false;
		if (b < 0) {
			isNegative = true;
			b = -b;
		}
		output = findPowerR(a, b);
		if (isNegative) {
			output = 1 / output;
		}
		return output;
	}

	private double findPowerR(double a, int n) {
		// TODO Auto-generated method stub
		if (n == 0)
			return 1;
		if (n == 1)
			return a;
		double output = 1;
		output = findPowerR(a, n / 2);
		if (n % 2 == 0)
			return output * output;
		else
			return a * output * output;
	}

	public static void main(String[] args) {
		FindPowerOptimum fp = new FindPowerOptimum();
		System.out.println(fp.power(6, -6));
	}
}

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

int power(int a,int b)
{
 int x=a;
int ans=1;
while(b>0)
{
   if(b%2!=0)
   ans*=x;
   b>>=1;
   x*=x;
}
return ans;
}

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

private static double powerBinary(double a, int b){
		
		if(b == 0)
			return 1;
		if(b == 1)
			return a;
		else if(b%2 == 0)
			return powerBinary(a,b/2) * powerBinary(a,b/2);
		else
			return a* powerBinary(a,b/2) * powerBinary(a,b/2);
		
	}

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

b = 2^n1 + 2^n2 + ..... + 2^nx and we can easily get a, a^2, a^4, a^8.....

- spy February 22, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 3 vote

power(int a, int b) {
    if(b == 0) return 1;
    if(b == 1) return a;
    else {
          int result = a*a;
          b = b-2;
          while(b > 1) {
                 result = result * result;
                 b = b/2;
           }
           if(b == 1)  return result * a;
	return result;
     }    
}

- cptjack February 22, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Time Complexity : O(log n)
Example: power(a, 5)
step 1: result = a * a;
step 2: result = result * result => a * a * a * a;
step 3: return result * a => a * a * a * a * a;

- cptjack February 22, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

This solution is incorrect. Counterexample: any even exponent higher than 2.

The idea is ok but wrongly implemented.
http://en.wikipedia.org/wiki/Exponentiation_by_squaring

- pawel.janus@student.uw.edu.pl February 22, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@pawel.janus@student.uw.edu.pl :

This is correct. Assuming you are not blind, there is a statement as (return result;) which returns solution for even powers greater than 2.

Understand the code and then make any rational statement

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

Incorrect: 2 ^ 13
leads to the following.
before loop : 2 ^ 2
then
2 ^ 2 11
2^ 4 5
2^ 8 2
2^ 16 1
2 ^17 is returned

- Ka January 19, 2015 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

function logPow(a,b) {
	if (b === 0) {
		return 1;		
	}
	
	if (b === 1) {
		return a;
	}
	
	if (b===2) {
		return a*a;
	}
		
	var count = Math.floor(b/2);
	var rest = b%2;
	var part1 = logPow(a,count);
	var partAns = part1 * part1;	
	
	if (rest === 1) {
	 	partAns *= a;
	}
	return partAns;
	
}

console.log(logPow(5,4));

- jsdude February 22, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

You can do this on O(n) using bytes opertation:

int pow(int b, int exp)
{
int res = 0;

while(exp != 0)
{
if ((exp & 1) != 0)
{
res *= b;
}
exp >>= 1;
b *= b;
}
return res;
}

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

private double process(int a, int b) {
        boolean neg = false;
        if (a == 0) {
            return 0;
        } else if (b == 0) {
            return 1;
        }

        int result = a;
        if (b < 0) {
            b = -b;
            neg = true;
        }

        int pow = 1;
        while (b > 1 && (2 * pow) <= b) {
            int temp = result;
            result = temp * temp;
            pow *= 2;
        }

        int tempR = result;
        int tempP = pow;
        while (tempP > 0) {
            tempR /= 2;
            tempP /= 2;
            if ((pow + tempP) <= b) {
                pow += tempP;
                result *= tempR;
            }
        }

        return neg?1.0/result:result;
    }

- krishna September 07, 2014 | 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