S2Q2 · Swap Every Alternate Line and Reverse Odd Lines¶
⚡ Quick Reference
Type: Full I/O problem
Core idea: read all lines, loop in steps of 2, swap each pair, reverse the first of each pair (odd output position).
n = int(input())
lines = [input() for _ in range(n)]
for i in range(0, n, 2):
if i + 1 < n:
print(lines[i + 1][::-1]) # odd output pos → reversed
print(lines[i]) # even output pos → as-is
else:
print(lines[i][::-1]) # lone last line → reversed
Key rules:
- Read all lines first - swapping pairs requires lookahead
- After swapping, output positions 1, 3, 5… are reversed
- A lone unpaired last line is always at an odd position → reversed
- [::-1] reverses any string in Python
Problem Statement¶
Problem (I/O type)
Given n lines, swap every pair of consecutive lines, then reverse every odd-positioned output line (1st, 3rd, 5th…). A lone unpaired last line is also reversed.
Example:
5
apple
orange
pineapple
mango
kiwi
egnaro
apple
ognam
pineapple
iwik
Tracing the example¶
Original: ["apple", "orange", "pineapple", "mango", "kiwi"]
i |
Pair | Output pos | Printed |
|---|---|---|---|
| 0 | (apple, orange) | Out[1] - odd | orange[::-1] = egnaro |
| 0 | (apple, orange) | Out[2] - even | apple |
| 2 | (pineapple, mango) | Out[3] - odd | mango[::-1] = ognam |
| 2 | (pineapple, mango) | Out[4] - even | pineapple |
| 4 | (kiwi - lone) | Out[5] - odd | kiwi[::-1] = iwik |
Solution approaches¶
Key takeaways¶
Read all lines before printing
Swapping requires seeing the next line before printing the current one. Always buffer the full input when processing requires lookahead.
[::-1] reversal slice
The cleanest way to reverse any string in Python. No function call, no import - just a step-slice.
Odd position = first of each swapped pair
After swapping, the second original line becomes the first output line - landing at an odd position and getting reversed. The original first line lands at an even position unchanged.