Skip to content

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:

Input
5
apple
orange
pineapple
mango
kiwi
Output
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

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])
        print(lines[i])
    else:
        print(lines[i][::-1])
n = int(input())
lines = [input() for _ in range(n)]
result = []
for i in range(0, n, 2):
    result.append(lines[i+1][::-1] if i+1 < n else lines[i][::-1])
    if i + 1 < n:
        result.append(lines[i])
print('\n'.join(result))
from itertools import zip_longest

n = int(input())
lines = [input() for _ in range(n)]
evens = lines[0::2]
odds  = lines[1::2]
for a, b in zip_longest(evens, odds):
    if b is not None:
        print(b[::-1])
        print(a)
    else:
        print(a[::-1])
n = int(input())
lines = [input() for _ in range(n)]
process = lambda i: (
    [lines[i+1][::-1], lines[i]] if i+1 < n else [lines[i][::-1]]
)
print('\n'.join(line for i in range(0, n, 2) for line in process(i)))

Key takeaways

01

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.

02

[::-1] reversal slice

The cleanest way to reverse any string in Python. No function call, no import - just a step-slice.

03

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.