Goal: to practice array manipulation, sorting, and data grouping.
Set from the array and then convert it back to an array.current + 1).start-end.const range = (numbers) => {
// Step 1: Handle empty array.
// If the array is empty, return an empty string as required.
if (numbers.length === 0) return '';
// Step 2: Prepare the data.
// Create a `Set` from the array to automatically remove duplicates.
// `Array.from` converts the `Set` back to an array.
// `.sort((a, b) => a - b)` sorts the numbers in ascending order.
const sortedUniqNumbers = Array.from(new Set(numbers))
.sort((a, b) => a - b);
// Step 3: Initialize variables.
// `ranges` is an array to store the final strings (numbers and ranges).
const ranges = [];
// `start` stores the starting number of the current range.
let start = sortedUniqNumbers[0];
// `prev` stores the previous number to check for sequence.
let prev = start;
// Step 4: Iterate through the array to find ranges.
// Start from the second element (i=1) and go to the end of the array (including a "virtual" element after the last one).
// This allows processing the last range without extra code after the loop.
for (let i = 1; i <= sortedUniqNumbers.length; i++) {
// `current` is the number being considered.
const current = sortedUniqNumbers[i];
// Step 5: Check if the sequence continues.
// If the current number is 1 greater than the previous, we are still in a range.
if (current === prev + 1) {
// Update `prev` and move to the next number.
prev = current;
continue;
}
// Step 6: The sequence is broken. Format the string for the completed range.
// If `start` and `prev` are equal, the range consisted of a single number.
if (start === prev) {
ranges.push(String(start));
}
// If the range had two numbers (e.g., 5, 6), they do not form a "5-6" range.
// Add them as two separate numbers.
else if (start + 1 === prev) {
ranges.push(String(start), String(prev));
}
// If there are three or more numbers in the range, format it as `start-prev`.
else {
ranges.push(`${start}-${prev}`);
}
// Step 7: Reset variables for the next potential range.
// The new start is `current`, the number that broke the previous sequence.
start = current;
prev = current;
}
// Step 8: Return the result.
// Join all strings from the `ranges` array into one, separated by commas.
return ranges.join(',');
};Solution Analysis:
This approach to solving the problem can be broken down into several key stages:
Edge Case Handling: The function first checks if the input array is empty. If so, it immediately returns an empty string as required. This is a simple but important optimization that prevents unnecessary code execution.
Data Preparation (Cleaning and Sorting):
Set, which by its nature stores only unique values. Creating new Set(numbers) and then converting it back to an array with Array.from() is an elegant and efficient way to remove duplicates..sort((a, b) => a - b) method ensures that the numbers are arranged in ascending order, which is a necessary condition for our algorithm.Iterative Range Finding:
ranges to store the final strings, start to mark the beginning of the current range, and prev to store the previous element.current) with the previous one (prev).current is one greater than prev, it means the sequence continues. We simply update prev and move to the next iteration.start and prev are equal, it was a single number.start + 1 === prev), we add them separately, not as a range (e.g., 5,6 instead of 5-6).start-prev.Result Assembly: After the loop completes, the ranges array contains all the necessary strings ('0-5', '8', '9', '11'). The join(',') method combines them into the final string, which the function returns.
.sort()). The loop itself iterates through the array once, which is O(N), but sorting dominates.ranges array with the results. In the worst case (when there are no ranges), both arrays will have a size comparable to the original array.Write a function range that takes an array of integers and returns a string representing the sorted and grouped ranges of these numbers.
The numbers in the string should be sorted in ascending order. Consecutive numbers should be grouped into a range, for example, 1, 2, 3, 4 becomes 1-4. If a number is not part of any range, it remains as is.
range([1, 4, 5, 2, 3, 9, 8, 11, 0]);
// Returns: '0-5,8,9,11'
range([-1, 0, 1, 5, 6]);
// Returns: '-1-1,5,6'
range([1, 3, 5]);
// Returns: '1,3,5'range.Goal: to practice array manipulation, sorting, and data grouping.
Set from the array and then convert it back to an array.current + 1).start-end.const range = (numbers) => {
// Step 1: Handle empty array.
// If the array is empty, return an empty string as required.
if (numbers.length === 0) return '';
// Step 2: Prepare the data.
// Create a `Set` from the array to automatically remove duplicates.
// `Array.from` converts the `Set` back to an array.
// `.sort((a, b) => a - b)` sorts the numbers in ascending order.
const sortedUniqNumbers = Array.from(new Set(numbers))
.sort((a, b) => a - b);
// Step 3: Initialize variables.
// `ranges` is an array to store the final strings (numbers and ranges).
const ranges = [];
// `start` stores the starting number of the current range.
let start = sortedUniqNumbers[0];
// `prev` stores the previous number to check for sequence.
let prev = start;
// Step 4: Iterate through the array to find ranges.
// Start from the second element (i=1) and go to the end of the array (including a "virtual" element after the last one).
// This allows processing the last range without extra code after the loop.
for (let i = 1; i <= sortedUniqNumbers.length; i++) {
// `current` is the number being considered.
const current = sortedUniqNumbers[i];
// Step 5: Check if the sequence continues.
// If the current number is 1 greater than the previous, we are still in a range.
if (current === prev + 1) {
// Update `prev` and move to the next number.
prev = current;
continue;
}
// Step 6: The sequence is broken. Format the string for the completed range.
// If `start` and `prev` are equal, the range consisted of a single number.
if (start === prev) {
ranges.push(String(start));
}
// If the range had two numbers (e.g., 5, 6), they do not form a "5-6" range.
// Add them as two separate numbers.
else if (start + 1 === prev) {
ranges.push(String(start), String(prev));
}
// If there are three or more numbers in the range, format it as `start-prev`.
else {
ranges.push(`${start}-${prev}`);
}
// Step 7: Reset variables for the next potential range.
// The new start is `current`, the number that broke the previous sequence.
start = current;
prev = current;
}
// Step 8: Return the result.
// Join all strings from the `ranges` array into one, separated by commas.
return ranges.join(',');
};Solution Analysis:
This approach to solving the problem can be broken down into several key stages:
Edge Case Handling: The function first checks if the input array is empty. If so, it immediately returns an empty string as required. This is a simple but important optimization that prevents unnecessary code execution.
Data Preparation (Cleaning and Sorting):
Set, which by its nature stores only unique values. Creating new Set(numbers) and then converting it back to an array with Array.from() is an elegant and efficient way to remove duplicates..sort((a, b) => a - b) method ensures that the numbers are arranged in ascending order, which is a necessary condition for our algorithm.Iterative Range Finding:
ranges to store the final strings, start to mark the beginning of the current range, and prev to store the previous element.current) with the previous one (prev).current is one greater than prev, it means the sequence continues. We simply update prev and move to the next iteration.start and prev are equal, it was a single number.start + 1 === prev), we add them separately, not as a range (e.g., 5,6 instead of 5-6).start-prev.Result Assembly: After the loop completes, the ranges array contains all the necessary strings ('0-5', '8', '9', '11'). The join(',') method combines them into the final string, which the function returns.
.sort()). The loop itself iterates through the array once, which is O(N), but sorting dominates.ranges array with the results. In the worst case (when there are no ranges), both arrays will have a size comparable to the original array.Write a function range that takes an array of integers and returns a string representing the sorted and grouped ranges of these numbers.
The numbers in the string should be sorted in ascending order. Consecutive numbers should be grouped into a range, for example, 1, 2, 3, 4 becomes 1-4. If a number is not part of any range, it remains as is.
range([1, 4, 5, 2, 3, 9, 8, 11, 0]);
// Returns: '0-5,8,9,11'
range([-1, 0, 1, 5, 6]);
// Returns: '-1-1,5,6'
range([1, 3, 5]);
// Returns: '1,3,5'range.The code editor is intentionally hidden on mobile.
Believe me, it's for the best: I am protecting you from the temptation to code in less-than-ideal conditions. A small screen and a virtual keyboard are not the best tools for a programmer.
📖 Now: Study the task, think through the solution. Act like a strategist.
💻 Later: Sit down at your computer, open the site, and implement all your ideas comfortably. Act like a code-jedi!