medium
1 views
Print Numbers & Ranges
Given N unique integers, print integers and integer ranges in sorted order, where consecutive integers are represented as ranges.
Understand the Problem
Problem Statement
Print Numbers & Ranges: The program must accept N unique integers as the input. The program must print the integers and the integer ranges present in the given N integers in sorted order separated by a comma as the output. The integer range must be represented by the starting value and the ending value separated by a hyphen.
Constraints
- 2 <= N <= 100
- 0 <= Each integer value <= 10^5
- All integers are unique
- Output must be comma-separated
Examples
Example 1
Input
10
1 0 25 24 3 45 2 15 4 6Output
0-4,6,15,24-25,45Explanation
After sorting: [0,1,2,3,4,6,15,24,25,45]. Consecutive sequences are 0-4, single 6, single 15, 24-25, single 45.
Example 2
Input
5
1 3 4 6 5Output
1,3-6Explanation
After sorting: [1,3,4,5,6]. Single 1, consecutive sequence 3-6.
Solution
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
void printRanges(int arr[], int n) {
qsort(arr, n, sizeof(int), compare);
int i = 0;
while (i < n) {
int start = arr[i];
// Find the end of current consecutive sequence
while (i < n - 1 && arr[i + 1] == arr[i] + 1) {
i++;
}
int end = arr[i];
// Print range or single number
if (start == end) {
printf("%d", start);
} else {
printf("%d-%d", start, end);
}
// Print comma if not last element
if (i < n - 1) {
printf(",");
}
i++;
}
printf("\n");
}
int main() {
int n;
scanf("%d", &n);
int arr[100];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printRanges(arr, n);
return 0;
}Time:O(N log N)
Space:O(1)
Approach:
C Solution Explanation:
- Read N and the array of integers
- Sort array using qsort() with custom comparator
- Iterate through sorted array:
- For each position, find the end of consecutive sequence by checking if next element equals current + 1
- Print either single number or range format
- Add comma separator (except for last element)
- Time complexity: O(N log N) due to sorting
- Space complexity: O(1) additional space
Visual Explanation
Loading diagram...