Given a string logs containing Apache access log entries separated by newline characters, identify and return the IP address that appears most frequently.
Each log line follows the Apache Common Log Format, where the first whitespace-separated token of every line is the client IP address. For example: 127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326.
If there is a tie between two or more IPs for the highest frequency, return the IP that appears first in the log.
Function Signature
def most_frequent_ip(logs: str) -> str:
Rules
-
Lines are separated by
"\n"
. The IP is the first whitespace-separated token of a line, and the rest of the line does not affect the answer.
-
Skip empty or whitespace-only lines, such as the empty line a trailing newline leaves behind.
-
A tie is decided by the position of each IP's first line in
logs
, never by comparing the IP strings.
-
logs
contains at least one non-blank line, so the answer is always a non-empty string.
Constraints
-
1 <= len(logs) <= 10^5
-
Each log line follows the Apache Common Log Format and starts with an IPv4 address.
-
IP addresses consist of four octets separated by dots (for example,
192.168.1.1
).
Examples
Input: logs = "127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /index.html HTTP/1.0\" 200 2326\n192.168.1.1 - - [10/Oct/2000:13:56:01 -0700] \"GET /a HTTP/1.0\" 200 100\n127.0.0.1 - mary [10/Oct/2000:13:56:30 -0700] \"GET /b HTTP/1.0\" 404 50"
Output: "127.0.0.1"
127.0.0.1 appears 2 times while 192.168.1.1 appears 1 time, so 127.0.0.1 is the most frequent IP.
Input: logs = "10.0.0.1 - - [11/Oct/2000:08:00:00 -0700] \"GET / HTTP/1.0\" 200 10\n10.0.0.2 - - [11/Oct/2000:08:00:01 -0700] \"GET / HTTP/1.0\" 200 10\n10.0.0.1 - - [11/Oct/2000:08:00:02 -0700] \"GET / HTTP/1.0\" 200 10\n10.0.0.2 - - [11/Oct/2000:08:00:03 -0700] \"GET / HTTP/1.0\" 200 10"
Output: "10.0.0.1"
Both 10.0.0.1 and 10.0.0.2 appear 2 times. 10.0.0.1 is on the first line and 10.0.0.2 first shows up on the second, so the tie goes to 10.0.0.1.
Input: logs = "8.8.8.8 - - [12/Oct/2000:09:00:00 -0700] \"GET / HTTP/1.0\" 200 5\n1.1.1.1 - - [12/Oct/2000:09:00:05 -0700] \"GET /x HTTP/1.0\" 200 7\n1.1.1.1 - - [12/Oct/2000:09:00:09 -0700] \"GET /y HTTP/1.0\" 304 0\n"
Output: "1.1.1.1"
1.1.1.1 appears 2 times and 8.8.8.8 once. The trailing newline leaves an empty last line, which is skipped.