400. Nth Digit LeetCode Solution

In this guide, you will get 400. Nth Digit LeetCode Solution with the best time and space complexity. The solution to Nth Digit problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Nth Digit solution in C++
  4. Nth Digit solution in Java
  5. Nth Digit solution in Python
  6. Additional Resources
400. Nth Digit LeetCode Solution image

Problem Statement of Nth Digit

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 1:

Input: n = 3
Output: 3

Example 2:

Input: n = 11
Output: 0
Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, … is a 0, which is part of the number 10.

Constraints:

1 <= n <= 231 – 1

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(1)

400. Nth Digit LeetCode Solution in C++

class Solution {
 public:
  int findNthDigit(int n) {
    int digitSize = 1;
    int startNum = 1;
    long count = 9;

    while (digitSize * count < n) {
      n -= digitSize * count;
      ++digitSize;
      startNum *= 10;
      count *= 10;
    }

    const int targetNum = startNum + (n - 1) / digitSize;
    const int index = (n - 1) % digitSize;
    return to_string(targetNum)[index] - '0';
  }
};
/* code provided by PROGIEZ */

400. Nth Digit LeetCode Solution in Java

class Solution {
  public int findNthDigit(int n) {
    int digitSize = 1;
    int startNum = 1;
    long count = 9;

    while (digitSize * count < n) {
      n -= digitSize * count;
      ++digitSize;
      startNum *= 10;
      count *= 10;
    }

    final int targetNum = startNum + (n - 1) / digitSize;
    final int index = (n - 1) % digitSize;
    return String.valueOf(targetNum).charAt(index) - '0';
  }
}
// code provided by PROGIEZ

400. Nth Digit LeetCode Solution in Python

class Solution:
  def findNthDigit(self, n: int) -> int:
    def getDigit(num: int, pos: int, digitSize: int):
      if pos == 0:
        return num % 10
      for _ in range(digitSize - pos):
        num //= 10
      return num % 10

    digitSize = 1
    startNum = 1
    count = 9

    while digitSize * count < n:
      n -= digitSize * count
      digitSize += 1
      startNum *= 10
      count *= 10

    targetNum = startNum + (n - 1) // digitSize
    pos = n % digitSize

    return getDigit(targetNum, pos, digitSize)
# code by PROGIEZ

Additional Resources

See also  816. Ambiguous Coordinates LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.