logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
Generate ParenthesesPower Function: pow(x, n)Subsets (The Power Set)
Code Scratch/take u forward/recursion/implementation problems

Power Function: pow(x, n)

5 min read
On this pageQuestion
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeConcepts to Think AboutLogical Follow-up

# Question

Implement the power function pow(x,n)pow(x, n)pow(x,n), which calculates xxx raised to the power nnn (xnx^nxn). The solution must handle negative exponents (x−n=1/xnx^{-n} = 1/x^nx−n=1/xn) and be efficient enough for very large values of nnn. The output should be formatted to 4 decimal places.

# Solution

# Pattern

Binary Exponentiation (Fast Power) Instead of multiplying xxx by itself nnn times (O(n)O(n)O(n)), we use the mathematical property xn=(xn/2)2x^n = (x^{n/2})^2xn=(xn/2)2 to reduce the number of multiplications to O(log⁡n)O(\log n)O(logn).

# How to Identify

  • Calculating large powers where nnn can be up to 231−12^{31}-1231−1.
  • Problems involving modular exponentiation (crucial for Cryptography/RSA).
  • Scenarios where you need to perform an associative operation nnn times (e.g., Matrix Exponentiation).
  • Any "growth" problem where a linear loop would exceed a 1-second time limit.

# Description

Imagine you want to calculate 2102^{10}210. Instead of doing 2×2×2...2 \times 2 \times 2...2×2×2... ten times, we use a "halving" strategy:

  1. The Core Logic: We know 210=25×252^{10} = 2^5 \times 2^5210=25×25. If we find 252^525 once, we can just square it to get 2102^{10}210.
  2. Handling Parity: If the exponent is odd, like 2112^{11}211, it’s simply 210×212^{10} \times 2^1210×21. We calculate the even "half" and multiply by the base one extra time.
  3. Negative Exponents: If nnn is negative, x−nx^{-n}x−n is the same as (1/x)n(1/x)^{n}(1/x)n. We flip the base and treat the exponent as positive.
  4. Overflow Safety: Because the absolute value of Integer.MIN_VALUE exceeds Integer.MAX_VALUE, we convert nnn to a 64-bit long to safely negate it.
  5. Termination: We continue halving the power until it reaches 000, where x0=1x^0 = 1x0=1.

# The Intuition

Think of this as the Binary Representation of the exponent. Every number nnn can be broken down into powers of 2. For example, 131313 is 8+4+18 + 4 + 18+4+1 (Binary: 1101). Therefore: x13=x8⋅x4⋅x1x^{13} = x^8 \cdot x^4 \cdot x^1x13=x8⋅x4⋅x1 Instead of 13 steps, we just keep squaring the base (x1→x2→x4→x8x^1 \to x^2 \to x^4 \to x^8x1→x2→x4→x8) and "pick up" the value whenever the corresponding binary bit of nnn is set to 111.

This "halving" intuition—where you only need to know the result of a sub-problem to solve the larger one—is a common optimization pattern for any problem involving associative operations (like matrix multiplication or finding the nthn^{th}nth Fibonacci number).

# Complexity

LabelWorstAverage
Time ComplexityO(log⁡n)O(\log n)O(logn)O(log⁡n)O(\log n)O(logn)
Space ComplexityO(log⁡n)O(\log n)O(logn)O(log⁡n)O(\log n)O(logn)

# Time Complexity

We divide the exponent nnn by 222 at every recursive step. The total number of steps is ⌈log⁡2n⌉\lceil \log_2 n \rceil⌈log2​n⌉. Since each step involves O(1)O(1)O(1) multiplication, the total time is logarithmic.

# Space Complexity

In the recursive approach, each halving adds a new frame to the recursion stack. The stack depth is equal to the number of steps, O(log⁡n)O(\log n)O(logn). Note: An iterative version reduces this to O(1)O(1)O(1).

# Code

class Solution {
    public double myPow(double x, int n) {
        // 1. Use long to handle Integer.MIN_VALUE overflow (-2147483648)
        long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
 
        double result = fastPow(x, N);
 
        // 2. Note: For 4 decimal places, you would use:
        // return Double.parseDouble(String.format("%.4f", result));
        return result;
    }
 
    private double fastPow(double x, long n) {
        // Base case
        if (n == 0) return 1.0;
 
        // Recursive step: Divide problem into half
        double half = fastPow(x, n / 2);
 
        // Combine step
        if (n % 2 == 0) {
            return half * half;
        } else {
            return half * half * x;
        }
    }
}

# Concepts to Think About

  • Integer Overflow: Always check the boundaries of int when dealing with absolute values or negation. For example, n=−2,147,483,648n = -2,147,483,648n=−2,147,483,648 becomes positive by overflow if not handled with a long.
  • Tail Recursion: Is this function tail-recursive? (No, because we perform multiplication after the recursive call returns, requiring the stack to stay open).
  • Iterative Logic: How to use bitwise operators (n & 1, n >>= 1) to solve this in O(1)O(1)O(1) space by processing the bits of the exponent from right to left.
  • Floating Point Precision: Be aware that repeated multiplication of small doubles can lead to underflow, where the value becomes too small to be represented.
  • Modular Exponentiation: This same pattern is used for (xn)(modm)(x^n) \pmod m(xn)(modm), which is vital in RSA cryptography for encrypting and decrypting data.
  • Base Cases: What happens if x=0x = 0x=0? Usually, 000^000 is defined as 1 in many programming libraries, but mathematically it can be an indeterminate form.

# Logical Follow-up

Question: How can you optimize the space complexity to O(1)O(1)O(1)?

Solution: Use an iterative approach. While n>0n > 0n>0, if nnn is odd, multiply the result by xxx. Then square xxx (x=x⋅xx = x \cdot xx=x⋅x) and right-shift nnn (n=n/2n = n / 2n=n/2).

Question: How would you handle the case where nnn is so large it doesn't fit in a 64-bit long? Solution: If nnn is passed as a string (BigInt), we use the property (xn)(modm)(x^n) \pmod m(xn)(modm) or process the string digit by digit, using the rule: x123=(x12)10⋅x3x^{123} = (x^{12})^{10} \cdot x^3x123=(x12)10⋅x3.

Question: If you had to compute xnx^nxn for many different nnn values but the same xxx, how would you optimize?

Solution: Precompute powers of xxx in the form x2kx^{2^k}x2k (e.g., x1,x2,x4,x8...x^1, x^2, x^4, x^8...x1,x2,x4,x8...) and then combine them based on the binary representation of each nnn.

←PreviousGenerate ParenthesesNext→Subsets (The Power Set)

On this page

QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeConcepts to Think AboutLogical Follow-up