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›binary search›on answers

Find Nth Root of M

# Question

Given two integers NNN and MMM, find the NNNth root of MMM. The NNNth root of MMM is defined as an integer XXX such that XN=MX^N = MXN=M. If the NNNth root is not an integer, return -1.

# Solution

# Pattern

Binary Search on Answer Space with Safe Evaluation We search the numerical range [1,M][1, M][1,M] for the correct root. Because raising a number to the power of NNN can easily overflow standard data types, we must implement a custom evaluation function that halts multiplication immediately if the running product exceeds MMM.

# How to Identify

  • The problem asks for an exact numerical value satisfying a monotonic mathematical condition (XN=MX^N = MXN=M).
  • A linear scan from 1 to MMM is too slow, demanding a logarithmic approach.
  • The combination of exponents and large bounds strongly signals that preventing integer overflow is the primary hidden challenge.

# Description

Step-by-step explanation:

  1. Handle base cases: If M=1M=1M=1 or N=1N=1N=1, return MMM.
  2. Initialize search boundaries: left = 1 and right = M.
  3. Loop while left <= right. Calculate mid safely.
  4. Call a helper function evaluatePower(mid, N, M) to safely calculate midNmid^NmidN.
    • Inside the helper: Loop NNN times, multiplying ans * mid.
    • The Safety Valve: After every multiplication, check if ans > M. If it is, return a flag indicating "Too Large" immediately. This prevents the number from growing out of bounds and crashing the program.
  5. Based on the helper's return value:
    • If exact match: Return mid.
    • If too small: Search higher (left = mid + 1).
    • If too large: Search lower (right = mid - 1).
  6. If the loop breaks without finding an exact match, return -1.

# The Intuition

Finding a root is a guessing game. If you want the 4th root of 10000, you know it's between 1 and 10000. If you guess 50, you need to calculate 50450^4504. But 50×50×50×50=6,250,00050 \times 50 \times 50 \times 50 = 6,250,00050×50×50×50=6,250,000. The trick is, you don't need to calculate the exact massive number. After just the second multiplication (50×50=250050 \times 50 = 250050×50=2500), you already know 2500 < 10000, but on the third multiplication (2500×50=125,0002500 \times 50 = 125,0002500×50=125,000), it dramatically exceeds 10,000. You stop right there. You don't need the fourth multiplication to know that 50 is too big. This early stopping is what prevents systems from crashing due to integer overflow during mathematical binary searches.

# Complexity

LabelWorstAverage
Time ComplexityO(Nlog⁡M)O(N \log M)O(NlogM)O(Nlog⁡M)O(N \log M)O(NlogM)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

The binary search takes O(log⁡M)O(\log M)O(logM) iterations. In each iteration, we multiply mid by itself up to NNN times. The total time is O(Nlog⁡M)O(N \log M)O(NlogM). (Note: NNN is usually small in these constraints. If NNN were massive, you would use Binary Exponentiation to reduce this to O(log⁡Nlog⁡M)O(\log N \log M)O(logNlogM)).

# Space Complexity

We only allocate primitive scalar variables. Auxiliary space is strictly O(1)O(1)O(1).

# Code

class Solution {
    public int NthRoot(int N, int M) {
        if (M == 1 || N == 1) return M;
 
        int left = 1;
        int right = M;
 
        while (left <= right) {
            int mid = left + (right - left) / 2;
            int state = evaluatePower(mid, N, M);
 
            if (state == 1) {
                return mid; // Exact match found
            } else if (state == 0) {
                left = mid + 1; // Mid is too small
            } else {
                right = mid - 1; // Mid is too large
            }
        }
 
        return -1; 
    }
 
    // Helper to safely evaluate mid^n relative to m
    // Returns: 0 if < m, 1 if == m, 2 if &gt; m
    private int evaluatePower(int mid, int n, int m) {
        long ans = 1;
        for (int i = 1; i &lt;= n; i++) {
            ans *= mid;
            
            // HALT EARLY: Prevents overflow and wasted cycles
            if (ans &gt; m) return 2; 
        }
        
        if (ans == m) return 1;
        return 0; // ans &lt; m
    }
}

# Caveats

  • The Math.pow() Trap: Do not use Math.pow(mid, N). Math.pow uses floating-point arithmetic (double), which loses precision on large integers, causing exact equality checks to fail. Furthermore, it does not halt early, meaning it will calculate massive numbers, eventually hitting Infinity and breaking comparison logic entirely.
  • Binary Exponentiation: While the linear multiplication loop is sufficient if N≤30N \le 30N≤30, if the constraints allowed N≥105N \ge 10^5N≥105, you would be forced to use a modified Binary Exponentiation (Fast Power) algorithm to evaluate the threshold in O(log⁡N)O(\log N)O(logN) time instead of O(N)O(N)O(N).

# Concepts to Think About

  • Safe Mathematics: In software engineering, preventing overflow is often more critical than theoretical execution speed. Early halting is a standardized pattern when validating upper limits.
  • Search Space Reduction: You can mathematically optimize the initial right bound. The NNNth root of MMM is bounded by M/NM / NM/N or min⁡(M,reasonable maximum)\min(M, \text{reasonable maximum})min(M,reasonable maximum). However, initializing right = M is perfectly safe because binary search eliminates bloated spaces logarithmically fast anyway.
  • Integer vs. Double: When the problem asks for an integer root, avoid double to prevent precision errors.
  • Early Exit Pattern: In the check function, we don't need the full value of XNX^NXN if it's already larger than M. This is an L5 optimization.
  • Binary Exponentiation: Could you make the check function O(logN)O(logN)O(logN) instead of O(N)O(N)O(N)?
  • Overflow Limits: What is the maximum value mid can take before midNmid^NmidN overflows a long? (In Java, Long.MAX_VALUE is ≈9×1018≈9×10^18≈9×1018).

# Logical Follow-up

Question: Suppose you needed to return a decimal approximation of the NNNth root accurate to 5 decimal places. How does the algorithm change?

Solution: The binary search bounds become left = 1.0 and right = (double) M. The loop condition changes to a precision threshold: while (right - left &gt; 1e-6). We cannot use early halting for the multiplication since we need exact decimal comparisons to pinpoint the float, so we would use Math.pow or a custom double multiplier. Update bounds via left = mid or right = mid (no +1 or -1). Time complexity depends on the precision required PPP.

Question: "What if the problem asked for the NthN^{th}Nth root of MMM as a decimal with 10−610^{-6}10−6 precision?"

Solution:

  1. Change the search range to double.
  2. The while condition becomes while (high - low &gt; 1e-7).
  3. The result would be low (or high).
  4. Binary search works perfectly for continuous values as long as the function remains monotonic.

Question (Koko Eating Bananas): "Koko loves to eat bananas. There are n piles of bananas, the ithi^{th}ith pile has piles[i] bananas. The guards will be back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile and eats k bananas from it. If the pile has less than k bananas, she eats them all and does not eat any more bananas during that hour. Return the minimum integer k such that she can eat all the bananas within h hours."

Solution:

  1. Search Range: The minimum speed is 111, the maximum speed is max(piles)max(piles)max(piles).
  2. Monotonicity: If Koko can finish at speed KKK, she can definitely finish at speed K+1K+1K+1. If she cannot finish at speed KKK, she definitely cannot finish at speed K−1K-1K−1.
  3. Check Function: For a given speed mid, calculate the total hours: ∑⌈piles[i]/mid⌉\sum \lceil piles[i] / mid \rceil∑⌈piles[i]/mid⌉.
  4. Optimization: This is the same "Answer Space" pattern. You are searching for the "Lower Bound" of speed KKK such that totalHours <= h.
PreviousCapacity To Ship Packages Within D DaysNextFind Square Root of a Number
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up