Skip to content

S2Q2 · Make Word from Last Characters of Qualifying Words

⚡ Quick Reference

Type: Full I/O problem

Core idea: filter words by minimum length and starting character, collect their last characters, print concatenated.

l, c = input().split()
l = int(l)
n = int(input())
result = ""
for _ in range(n):
    word = input()
    if len(word) >= l and word[0] == c:
        result += word[-1]
print(result)

Key rules: - Word qualifies if len(word) >= l AND word[0] == c (case-sensitive) - Collect word[-1] for each qualifying word in order - Print the concatenation - empty string if no words qualify (prints an empty line)


Problem Statement

Problem (I/O type)

Read minimum length l and starting character c. Read n words. Print the concatenation of the last characters of all words with len >= l and starting with c.

Example:

Input
3 a
5
apple
ant
banana
anchor
cat
Output
etr

Tracing the example

l=3, c="a"

Word len >= 3? word[0] == 'a'? Qualifies? Last char
apple ✅ (5) e
ant ✅ (3) t
banana ✅ (6) ❌ (starts with 'b') -
anchor ✅ (6) r
cat ✅ (3) ❌ (starts with 'c') -

Result: "e" + "t" + "r" = "etr"


Solution approaches

l, c = input().split()
l = int(l)
n = int(input())

result = "".join(
    input()
    for _ in range(n)
    if (word := input()) and len(word) >= l and word[0] == c
)
print(result)

Walrus operator reads input twice

The above has a bug - input() is called twice per iteration (once in the generator expression and once in the condition). Use the explicit loop below instead.

l, c = input().split()
l = int(l)
n = int(input())
result = ""

for _ in range(n):
    word = input()
    if len(word) >= l and word[0] == c:
        result += word[-1]

print(result)
l_str, c = input().split()
l = int(l_str)
n = int(input())

last_chars = []
for _ in range(n):
    word = input()
    length_ok  = len(word) >= l
    starts_ok  = word[0] == c
    if length_ok and starts_ok:
        last_chars.append(word[-1])

print("".join(last_chars))
l, c = input().split()
l = int(l)
n = int(input())
words = [input() for _ in range(n)]

result = "".join(w[-1] for w in words if len(w) >= l and w[0] == c)
print(result)

Read all words first into a list, then filter in a generator expression. Cleaner separation of input and processing.


Key takeaways

01

Two conditions - length AND starting character

Both len(word) >= l and word[0] == c must be true. Short-circuit and skips the character check if the word is already too short.

02

Case-sensitive - c is used as-is

The problem specifies case-sensitive matching. word[0] == c distinguishes 'a' from 'A'. No .lower() should be applied.

03

print("") outputs an empty line

When no words qualify, result is an empty string. print("") outputs a blank line - exactly the required output for the no-results case.