Valid Digit Number Problem
#3908
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3908.
You are given an integer n and a digit x.
A number is considered valid if:
- It contains at least one occurrence of digit
x, and - It does not start with digit
x.
Return true if n is valid, otherwise return false.
Example 1:
Input: n = 101, x = 0
Output: true
Explanation:
The number contains digit 0 at index 1. It does not start with 0, so it satisfies both conditions. Thus, the answer is true.
Example 2:
Input: n = 232, x = 2
Output: false
Explanation:
The number starts with 2, which violates the condition. Thus, the answer is false.
Example 3:
Input: n = 5, x = 1
Output: false
Explanation:
The number does not contain digit 1. Thus, the answer is false.
Constraints:
0 <= n <= 10^50 <= x <= 9
Solution
Approach: Simulation
Strip digits from the right and remember whether any of them equals x.
While n > 9, compare the last digit n % 10 with x and record a match in hasX, then drop the last digit with n //= 10. When the loop ends, n is the first digit. The number is valid when hasX is true and the first digit is not x.
A single-digit n skips the loop, so hasX stays false and the answer is false: the only digit is also the first one.
Complexity: time O(log n), space O(1), where n is the input integer.
class Solution:
def validDigit(self, n: int, x: int) -> bool:
has_x = False
while n > 9:
has_x = has_x or n % 10 == x
n //= 10
return has_x and n != x