Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding pandigital numbers using JavaScript
A pandigital number is a number that contains all digits (0-9) at least once. In this tutorial, we'll create a JavaScript function to check if a given number string is pandigital.
What is a Pandigital Number?
A pandigital number must contain every digit from 0 to 9 at least once. For example, "1234567890" is pandigital, while "123456789" is not (missing 0).
Example
Let's implement a function to check if a number string is pandigital:
const numStr1 = '47458892414';
const numStr2 = '53657687691428890';
const isPandigital = numStr => {
let legend = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
for(let i = 0; i
false
true
How the Algorithm Works
The function works by:
- Creating an array
legend containing all digits '0' to '9'
- Iterating through each character in the input string
- If the character exists in
legend, removing it from the array
- Returning
true if all digits were found (legend is empty)
Alternative Approach Using Set
Here's a more efficient implementation using JavaScript Set:
const isPandigitalSet = numStr => {
const digits = new Set(numStr);
return digits.size === 10 && digits.has('0') && digits.has('1') &&
digits.has('2') && digits.has('3') && digits.has('4') &&
digits.has('5') && digits.has('6') && digits.has('7') &&
digits.has('8') && digits.has('9');
};
// Test with same examples
console.log(isPandigitalSet('47458892414'));
console.log(isPandigitalSet('53657687691428890'));
console.log(isPandigitalSet('1234567890'));
false
true
true
Comparison of Methods
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Array with splice | O(n²) | O(1) | Good |
| Set approach | O(n) | O(1) | Better |
Conclusion
Both methods effectively check for pandigital numbers, but the Set approach is more efficient with O(n) time complexity. Choose the array method for learning purposes and the Set method for production code.
Advertisements
