MediumNo. 0400

Nth Digit — LeetCode 400 Python Solution

Topics
Math, Binary Search
Reading time
2 min

The problem

Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].

Example

Input
n = 3
Output
3

Python solution

PythonSolution
class Solution:
    def findNthDigit(self, n: int) -> int:
        k, cnt = 1, 9
        while k * cnt < n:
            n -= k * cnt
            k += 1
            cnt *= 10
        num = 10 ** (k - 1) + (n - 1) // k
        idx = (n - 1) % k
        return int(str(num)[idx])

Complexity

Time
O(log_10 n)
Space · auxiliary
O(1)

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 400. Nth Digit is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0069Sqrt(x)Easy
0367Valid Perfect SquareEasy
0441Arranging CoinsEasy
0483Smallest Good BaseHard
0497Random Point in Non-overlapping RectanglesMedium
0528Random Pick with WeightMedium

Frequently asked questions

How hard is LeetCode 400. Nth Digit?

LeetCode 400. Nth Digit is rated Medium on LeetCode.

What is the time complexity of LeetCode 400. Nth Digit?

The Python solution on this page runs in O(log_10 n).

What is the space complexity of LeetCode 400. Nth Digit?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 400. Nth Digit cover?

LeetCode 400. Nth Digit is tagged Math and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.