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
Calculate Floor & CeilingFind Nth Root Of MFlatten A Linked ListImplement Lower BoundImplement Upper BoundNumber of occurrence
Code Scratch/leetcode/misc

Find Nth Root Of M

1 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

We know that raising a number to a power grows steadily (monotonically). This makes it perfect for binary search. Instead of checking every number, we can narrow down the possible root quickly using this method.

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(log⁡N)\text{O}(\log{N})O(logN)

# Code

public static int NthRoot(int n, int m) {
    int left = 1, right = m, possibleRoot = 1;
 
    // Binary search to find potential nth root
    while (left <= right) {
        int mid = left + (right - left) / 2;
 
        long powerResult = mid;
        for (int i = 1; i < n; ++i) {
            powerResult *= mid;
        }
 
        if (powerResult <= m) {
            // mid is a possible root; try to find a larger one
            possibleRoot = mid;
            left = mid + 1;
        } else {
            // mid^n is too large
            right = mid - 1;
        }
    }
 
    // Verify if the found root actually satisfies the condition
    long finalCheck = possibleRoot;
    for (int i = 1; i < n; ++i) {
        finalCheck *= possibleRoot;
    }
 
    return finalCheck == m ? possibleRoot : -1;
}
 
←PreviousCalculate Floor & CeilingNext→Flatten A Linked List

On this page

IntuitionComplexityCode