logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›recursion›implementation problems

Power Function: pow(x, n)

# 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 ParenthesesNextSubsets (The Power Set)
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeConcepts to Think AboutLogical Follow-up