In web servers and load balancers, logs contain records of every incoming network connection. A common task is finding which IP address sent the most requests, which is crucial for identifying denial-of-service (DDoS) attacks.
Real-World Analogy: Counting Votes on a Blackboard
Imagine you are the class president in a school election. Students walk past and drop **paper ballots (IP addresses)** with names on them into a box.
To count the votes, you stand in front of a **blackboard (the HashMap ledger)**. For each ballot you pull:
- If the name is not on the board yet, you write it down and write a tally mark
1next to it. - If the name is already there, you erase the old number, add 1, and write the new count.
At the end, you look at the board and find the name with the **highest tally count** to declare the winner!
Step-by-Step Logic Trace
- Read the list of IP addresses from the file or string input.
- Set up a `HashMap
` where the key is the IP address and the value is the occurrence count. - For each IP, fetch its current count using
map.getOrDefault(ip, 0), increment by 1, and save it back usingmap.put(ip, newCount). - Keep a running tracker of the `maxCount` and the corresponding `frequentIp` string. If the newCount exceeds maxCount, update your tracker.
Java Implementation
package io.practise.myPractice;
import java.util.HashMap;
import java.util.Map;
public class FrequentIPAddress {
public static void main(String[] args) {
String[] logs = {
"192.168.1.1", "10.0.0.5", "192.168.1.1",
"172.16.254.1", "10.0.0.5", "192.168.1.1"
};
Map ipCounts = new HashMap<>();
String frequentIp = "";
int maxCount = 0;
for (String ip : logs) {
int count = ipCounts.getOrDefault(ip, 0) + 1;
ipCounts.put(ip, count);
if (count > maxCount) {
maxCount = count;
frequentIp = ip;
}
}
System.out.println("Most frequent IP: " + frequentIp + " (" + maxCount + " requests)");
}
}
Conclusion
By executing counting and max checks concurrently inside a single loop, we achieve O(N) linear time complexity and find the target IP in one pass.