FastPrepFastPrep
Problem Brief

Find Valid IP Addresses

FULLTIMEPHONE SCREEN

You are given a root directory path and a representation of files in a file system. Each file is represented as [path, content], where path is the full path to the file and content is the file's text.

Consider only files whose path lies under the given root directory. Scan those files recursively and collect every whitespace-separated token that is a valid IPv4 address.

A token is a valid IPv4 address if it has exactly four decimal octets separated by dots, each octet is in the range 0 to 255, and no octet has a leading zero unless the octet is exactly 0.

Return all valid IPv4 addresses found in the scanned files, sorted in lexicographic order. If the same valid address appears multiple times, keep each occurrence.

Function Description

Complete the function findValidIpAddresses in the editor below.

findValidIpAddresses has the following parameters:

  1. String rootPath: the directory whose descendant files should be scanned
  2. String[][] files: each row is [path, content]

Returns

String[]: the valid IPv4 addresses discovered under rootPath, in lexicographic order.

1Example 1

Input
rootPath = "/var/log", files = [["/var/log/a.txt", "client 10.1.1.1 backup 256.1.1.1"], ["/var/log/sub/b.txt", "gateway 192.168.0.1 bad 01.2.3.4"], ["/tmp/ignore.txt", "8.8.8.8"]]
Output
["10.1.1.1", "192.168.0.1"]
Explanation

Only files under /var/log are scanned. 10.1.1.1 and 192.168.0.1 are valid IPv4 addresses. 256.1.1.1 is invalid because 256 is out of range, and 01.2.3.4 is invalid because of the leading zero.

2Example 2

Input
rootPath = "/data", files = [["/data/r1.txt", "hosts 1.1.1.1 0.0.0.0"], ["/data/archive/r2.txt", "bad 1.1.1 999.0.0.1 10.10.10.10"], ["/data/r3.txt", "repeat 1.1.1.1"]]
Output
["0.0.0.0", "1.1.1.1", "1.1.1.1", "10.10.10.10"]
Explanation

All three files are descendants of /data. The valid IPv4 tokens are 1.1.1.1, 0.0.0.0, 10.10.10.10, and another 1.1.1.1. They are returned in lexicographic order, with duplicates preserved.

Constraints

Limits and guarantees your solution can rely on.

The source thread did not provide explicit numeric bounds.

  • Each row of files contains exactly two strings: the file path and the file content.
  • Only descendant files of rootPath are considered.
  • File contents are scanned as whitespace-separated tokens.
public String[] findValidIpAddresses(String rootPath, String[][] files) {
    // write your code here
}
Input

rootPath

"/var/log"

files

[["/var/log/a.txt", "client 10.1.1.1 backup 256.1.1.1"], ["/var/log/sub/b.txt", "gateway 192.168.0.1 bad 01.2.3.4"], ["/tmp/ignore.txt", "8.8.8.8"]]

Output

["10.1.1.1", "192.168.0.1"]

Sign in to submit your solution.