Implement the logic behind the docker ps command. You are given a list containers, where each container is a dictionary with at least two fields: createdAt (a Unix timestamp in seconds) and status (a string such as "Running" or "Exited"). You are also given an integer current_time, the current Unix timestamp in seconds.
Return a new list that excludes every container whose status equals "Exited" and whose createdAt is more than 86400 seconds (24 hours) before current_time. Keep all other containers.
The result must be sorted by createdAt in descending order (most recently created first).
Function Signature
def docker_ps(containers: list[dict], current_time: int) -> list[dict]:
Rules
-
A container is removed only when both conditions hold: its
status
is exactly
"Exited"
(case-sensitive) and
current_time - createdAt > 86400
. A container that is exactly 86400 seconds old is kept.
-
Containers with any other status, such as
"Running"
or
"Paused"
, are always kept, whatever their age.
-
Containers with equal
createdAt
keep their relative order from the input.
-
Return the container dictionaries unchanged, including any extra fields they carry.
Constraints
-
1 <= len(containers) <= 10^4
-
Each container has a
createdAt
field (integer Unix timestamp in seconds) and a
status
field (string).
-
0 <= createdAt <= current_time
-
0 <= current_time <= 2 * 10^9
-
status
is a non-empty string of length at most 20.
Examples
Example 1
Input: containers = [{"createdAt": 1700000000, "status": "Running"}, {"createdAt": 1699800000, "status": "Exited"}, {"createdAt": 1700050000, "status": "Exited"}, {"createdAt": 1700100000, "status": "Paused"}], current_time = 1700100000
Output: [{"createdAt": 1700100000, "status": "Paused"}, {"createdAt": 1700050000, "status": "Exited"}, {"createdAt": 1700000000, "status": "Running"}]
The container created at 1699800000 is Exited and 300000 seconds old (more than 86400), so it is filtered out. The Exited container at 1700050000 is only 50000 seconds old, so it stays, and the remaining three are sorted by createdAt descending.
Example 2
Input: containers = [{"createdAt": 1000, "status": "Exited"}, {"createdAt": 2000, "status": "Running"}, {"createdAt": 3000, "status": "Running"}], current_time = 100000
Output: [{"createdAt": 3000, "status": "Running"}, {"createdAt": 2000, "status": "Running"}]
The Exited container at 1000 is 99000 seconds old (more than 86400), so it is removed. The two Running containers are sorted by createdAt descending.
Example 3
Input: containers = [{"createdAt": 500, "status": "Exited"}, {"createdAt": 400, "status": "Exited"}, {"createdAt": 500, "status": "Running"}], current_time = 86900
Output: [{"createdAt": 500, "status": "Exited"}, {"createdAt": 500, "status": "Running"}]
The Exited container at 500 is exactly 86400 seconds old, which is not more than 86400, so it is kept. The one at 400 is 86500 seconds old and is removed. The two containers created at 500 tie, so they keep their input order.