S2Q2 · Longest String Among Entries¶
⚡ Quick Reference
Type: Full I/O problem
Core idea: Read all (int, string) pairs, then use max() with key=len on the string to find the longest. max() returns the first maximum by default.
n = int(input())
entries = [input().split() for _ in range(n)]
best = max(entries, key=lambda e: len(e[1]))
print(best[0])
print(best[1])
Key rules:
- First occurrence wins on tie -- max() returns the first max it encounters
- Output: integer on line 1, string on line 2
- No type conversion needed for the integer in the output (it stays a string from split())
Problem Statement¶
Problem
Read n entries, each a pair of an integer and a string. Print the integer and string of the entry whose string is longest. If multiple entries tie, print the one that appears first in the input.
Example:
4
1 apple
2 banana
3 kiwi
4 mango
2
banana
3
10 abc
20 xyz
30 cat
10
abc
Understanding the problem¶
String lengths for the first example:
| Integer | String | Length |
|---|---|---|
| 1 | apple |
5 |
| 2 | banana |
6 ← max |
| 3 | kiwi |
4 |
| 4 | mango |
5 |
Output: integer 2, string banana.
max() with key= picks the first maximum
Python's max() scans left to right and returns the first element that achieves the maximum key value. When two strings tie in length, the one that appears earlier in the list is returned -- exactly the tie-breaking rule required here.
No need to convert the integer for output
input().split() produces strings. Since the integer is printed as-is (not used in arithmetic), it can stay as a string: print(best[0]) works without int(). Converting to int and back is unnecessary here.
Solution approaches¶
Key takeaways¶
max(iterable, key=...) for custom comparison
The key parameter tells max() what to measure. Here key=lambda e: len(e[1]) measures the length of the string in each pair. max() then returns the whole pair, not just the key value.
First-maximum tie-breaking is built in
max() returns the first element that achieves the maximum during a left-to-right scan. No extra logic is needed to handle ties -- the natural scanning order gives first-occurrence priority automatically.
Keep pairs together as a list of lists
Storing each entry as [integer_str, word] keeps the associated values together throughout. When max() returns the winning pair, both the integer and the string are immediately accessible by index.