Nth Digit — LeetCode 400 Python Solution

MediumMathBinary Search
Problem
#400
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

Python
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

MeasureComplexity
TimeO(\log_{10} n)
SpaceO(1) auxiliary

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

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.

Get Stealth Interview