Python Program for Interlace odd / even from A to B
Print odd numbers from A to B interlaced with even numbers from B to A
Understand the Problem
Problem Statement
Two numbers A and B are passed as input. The program must print the odd numbers from A to B (inclusive of A and B) interlaced with the even numbers from B to A.
Constraints
- 1 <= A <= 9999999
- A < B <= 9999999
- Input values are positive integers
- Output must be space-separated numbers
Examples
5
115 10 7 8 9 6 11Odd numbers from 5 to 11: 5, 7, 9, 11. Even numbers from 11 to 5: 10, 8, 6. Since odd count (4) > even count (3), start with odd: 5 → 10 → 7 → 8 → 9 → 6 → 11.
4
1414 5 12 7 10 9 8 11 6 13 4Odd numbers from 4 to 14: 5, 7, 9, 11, 13 (count=5). Even numbers from 14 to 4: 14, 12, 10, 8, 6, 4 (count=6). Since even count > odd count, start with even: 14 → 5 → 12 → 7 → 10 → 9 → 8 → 11 → 6 → 13 → 4.
3
123 12 5 10 7 8 9 6 11 4Odd numbers from 3 to 12: 3, 5, 7, 9, 11 (count=5). Even numbers from 12 to 3: 12, 10, 8, 6, 4 (count=5). Since counts are equal, start with odd: 3 → 12 → 5 → 10 → 7 → 8 → 9 → 6 → 11 → 4.
Solution
#include <stdio.h>
int main() {
int a, b;
scanf("%d", &a);
scanf("%d", &b);
int odd[10000000], even[10000000];
int odd_count = 0, even_count = 0;
// Generate odd numbers from A to B
for (int i = a; i <= b; i++) {
if (i % 2 != 0) {
odd[odd_count++] = i;
}
}
// Generate even numbers from B to A
for (int i = b; i >= a; i--) {
if (i % 2 == 0) {
even[even_count++] = i;
}
}
int i = 0, j = 0;
int start_with_even = (even_count > odd_count) ? 1 : 0;
// Interlace the numbers
while (i < odd_count || j < even_count) {
if (start_with_even) {
if (j < even_count) {
printf("%d ", even[j++]);
}
if (i < odd_count) {
printf("%d ", odd[i++]);
}
} else {
if (i < odd_count) {
printf("%d ", odd[i++]);
}
if (j < even_count) {
printf("%d ", even[j++]);
}
}
}
return 0;
}C Solution Explanation:
- Read input values A and B using scanf
- Create arrays to store odd and even numbers
- First loop: iterate from A to B, collect odd numbers into odd[] array
- Second loop: iterate from B to A, collect even numbers into even[] array
- Count the number of odd and even numbers
- Determine which sequence to start with: if even_count > odd_count, start with even numbers
- Use a while loop to interlace the numbers, alternating between the two arrays
- Print each number followed by a space
The solution uses arrays to store the numbers and simple index manipulation to interlace them.