Count numbers with exactly k digits
Filed under HSBC
Free read 1 of 3Iterate through each element in the input array using a standard loop or list comprehension.
The question
Given an array of integers and an integer k, count how many numbers in the array have exactly k digits.
Constraints
- 1 <= array length <= 10^5
- 1 <= k <= 10
- Numbers can be negative
Examples
- Input
- arr = [12, 345, 2, 67], k = 2
- Output
- 2
- Why
- 12 and 67 have exactly 2 digits.
Approach
Iterate through each element in the input array using a standard loop or list comprehension.
For each number, take the absolute value and convert it to a string to check its length against k.
Increment a counter whenever a number's digit count matches k and return the final count.
Solution
O(N * D) time where D is max digits, O(D) space
class Solution:
def countKDigitNumbers(self, arr: list, k: int) -> int:
count = 0
for num in arr:
# Use absolute value to ignore negative signs
if len(str(abs(num))) == k:
count += 1
return count
Tips
- What they are testing: Tests array iteration and the ability to determine the magnitude of a number.
- Common mistake: Not handling negative numbers correctly; the minus sign should not be counted as a digit.
Related HSBC questions
Collected from public candidate posts and coding forums. Updated Nov 2026.