惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tailwind CSS Blog
MyScale Blog
MyScale Blog
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
雷峰网
雷峰网
罗磊的独立博客
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
V2EX
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
博客园 - 司徒正美
Last Week in AI
Last Week in AI
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
量子位
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
N-th root of a number | Binary Search on Answer
Jaspreet singh · 2026-06-21 · via DEV Community

Jaspreet singh

N-th root of a number - GeeksforGeeks

Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.

favicon geeksforgeeks.org

Problem Statement

Given two integers:

  • n → root value
  • m → number

Find the integer x such that:

xⁿ = m

Return:

x

if it exists, otherwise return:

-1


Brute Force Intuition

In an interview, you can explain it like this:

We can try every number from 1 to m and calculate its nth power. If any number's nth power becomes equal to m, we have found our answer. Although straightforward, it unnecessarily checks many values.

Complexity

  • Time Complexity: O(M × N)
  • Space Complexity: O(1)

Brute Force Code

class Solution {

    public int nthRoot(int n, int m) {

        for (int i = 1; i <= m; i++) {

            long value = 1;

            for (int j = 0; j < n; j++) {
                value *= i;
            }

            if (value == m)
                return i;
        }

        return -1;
    }
}


Moving Towards the Optimal Approach

Notice:

If midⁿ < m

then the answer must lie on the right.

And if:

midⁿ > m

the answer must lie on the left.

This is exactly the Binary Search pattern.

Instead of searching indices, we are searching the answer itself.


Pattern Recognition

Whenever you see:

  • Find minimum/maximum possible answer
  • Answer lies in a range
  • Monotonic behaviour

Think:

Binary Search on Answer


Optimal Approach

Search in the range:

[1, m]

For every middle value:

midⁿ

Compare with:

m

Cases:

midⁿ == m → Found Answer

midⁿ < m  → Search Right

midⁿ > m  → Search Left


Optimal Java Solution

class Solution {

    public int nthRoot(int n, int m) {

        int low = 1;
        int high = m;

        while (low <= high) {

            int mid = low + (high - low) / 2;

            long value = power(mid, n);

            if (value == m)
                return mid;

            if (value < m)
                low = mid + 1;
            else
                high = mid - 1;
        }

        return -1;
    }

    private long power(long base, int n) {

        long ans = 1;

        for (int i = 0; i < n; i++) {

            ans *= base;

            if (ans > Integer.MAX_VALUE)
                return ans;
        }

        return ans;
    }
}


Dry Run

Input

n = 3
m = 27

Iteration 1

low = 1
high = 27

mid = 14

14³ = 2744

2744 > 27

Move Left


Iteration 2

low = 1
high = 13

mid = 7

7³ = 343

343 > 27

Move Left


Iteration 3

low = 1
high = 6

mid = 3

3³ = 27

Found Answer ✅

3


Why Binary Search Works?

The function:

f(x) = xⁿ

is monotonic increasing.

That means:

If x increases,
xⁿ also increases.

So we can safely eliminate half of the search space every time.


Complexity Analysis

Metric Complexity
Time Complexity O(log M × N)
Space Complexity O(1)

Where:

  • log M comes from Binary Search.
  • N comes from calculating midⁿ.

Interview One-Liner

Since xⁿ increases monotonically with x, we can binary search the answer space and compare midⁿ with m.


Pattern Learned

Answer Lies in a Range
+
Monotonic Function

=> Binary Search on Answer

Similar Problems

  • Nth Root of a Number
  • Square Root of X
  • Koko Eating Bananas
  • Minimum Days to Make Bouquets
  • Capacity to Ship Packages
  • Aggressive Cows

Memory Trick

Think:

midⁿ

Less than m ?
→ Go Right

Greater than m ?
→ Go Left

Equal ?
→ Answer Found

Mental Model

Sorted Array
→ Binary Search on Index

Nth Root
→ Binary Search on Answer

Whenever you hear:

"Find an exact root"

your brain should immediately think:

Binary Search on Answer Space