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
Determining beautiful number string in JavaScript
A numeric string is called a beautiful string if it can be split into a sequence of two or more positive integers, satisfying the following conditions:
arr[i] - arr[i - 1] = 1, for any i in the sequence, i.e., each element is exactly one more than the previous element.
No element should contain a leading zero. For example, '50607' can be split into [5, 06, 07], but it's not beautiful because 06 and 07 have leading zeros.
The sequence order cannot be rearranged.
Example
For the string '91011', it can be split into [9, 10, 11], which forms a consecutive sequence, making it a beautiful string.
const str = '91011';
console.log("Input string:", str);
console.log("Can be split into: [9, 10, 11]");
console.log("Is consecutive sequence: 9 ? 10 ? 11");
Input string: 91011 Can be split into: [9, 10, 11] Is consecutive sequence: 9 ? 10 ? 11
Implementation
const str = '91011';
const isBeautiful = (str) => {
let i = 1;
let count = 0;
const { length } = str;
while(i <= length / 2) {
let check = true;
let j = i;
let left = BigInt(str.substring(0, j));
let nextRange = (left + 1n).toString().length;
while(j + nextRange <= length) {
let right = BigInt(str.substring(j, j + nextRange));
if(left === right - 1n) {
left = right;
j += nextRange;
nextRange = (left + 1n).toString().length;
count = j;
} else {
check = false;
break;
}
}
if(check === true && count === length) {
return true;
}
i++;
}
return false;
};
console.log(isBeautiful(str));
true
How It Works
The algorithm tries different split positions for the first number, then checks if the remaining string can form a consecutive sequence:
- Try each possible length for the first number (1 to half of string length)
- Extract the first number and calculate the expected next number
- Check if the next substring matches the expected consecutive number
- Continue until the entire string is processed or a mismatch occurs
- Use BigInt to handle large numbers without precision loss
Additional Examples
// Test different cases
const testCases = ['91011', '1234', '050607', '99100101', '123'];
testCases.forEach(test => {
console.log(`"${test}": ${isBeautiful(test)}`);
});
"91011": true "1234": true "050607": false "99100101": true "123": true
Conclusion
A beautiful string must form consecutive integers when split properly, with no leading zeros. The algorithm systematically tries different split patterns to find a valid consecutive sequence.
