progress

~/problems / Arrays & hashing / Python toolkit

Newest first, then by user

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~10 min

An activity log holds entries (date, user, action), where date is a string like "2026-03-01" (YYYY-MM-DD). Write order_log(entries: list[tuple[str, str, str]]) -> list[tuple[str, str, str]] that returns the entries in this order:

  1. the newest date first;
  2. on the same date, users in alphabetical order (plain string comparison);
  3. on the same date and user, entries keep their original order in entries.
order_log([
    ("2026-03-01", "zoe", "upload"),
    ("2026-03-02", "max", "share"),
    ("2026-03-01", "ann", "login"),
    ("2026-03-01", "zoe", "login"),
])
# [("2026-03-02", "max", "share"),
#  ("2026-03-01", "ann", "login"),
#  ("2026-03-01", "zoe", "upload"),
#  ("2026-03-01", "zoe", "login")]

Zoe's two entries stay as they were (upload, then login), even though "login" sorts before "upload".

  • 0 <= len(entries) <= 10^5. Every date is a valid YYYY-MM-DD string; users and actions are lower-case letters.
  • Return a new list and don't modify entries.
Show hint

you can't negate a string to sort it in reverse, but Python's sort is stable: items with equal keys keep their order, and that stays true with reverse=True. Two sorts in a row, the less important key first, give you all three rules.

Topic: Python toolkit. Counter, deque, heapq, bisect, itertools: the standard library to know cold, and its traps.

0:00
Ctrl ' run · Ctrl ↵ submit
esc