← Meta (Facebook) bank

Meta (Facebook) · Question 35

Power Function

Pythoncode⏱ O(logn)💾 O(logn)
Product-based

Problem

You are given base x and exponent n. Calculate x^n using recursion efficiently.

Approach

Halve the exponent each call; square the half-power and multiply once more when odd.

Time O(logn)Space O(logn)

How it works

  1. 1Flip negative exponents by inverting the base.
  2. 2Recurse on half the exponent and square.
  3. 3Multiply once more by x for odd exponents.

Sample input / output

Input:
2.0 10
Output:
1024.0

Constraints

-100 <= x <= 100; -2^31 <= n < 2^31; result within 10^4.

Solution — read it, then walk it

Time O(logn)Space O(logn)Branches 4Returns 4source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesnoSTARTx, nif n == 0RETURN 1.0if n < 0x = 1 / xn = -(n + 1)RETURN x * myPow(x, n)half = myPow(x, n // 2)if n % 2 == 0RETURN half * halfRETURN x * half * halfDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)x = float(next(it)); n =int(next(it))print(myPow(x, n))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/20

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits