Katkat

Validate IPv4 Address List

OktaSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to parse strings and apply conditional logic to validate technical data against specific constraints.

Validate IPv4 Address List

Given a list of strings, write a function that returns a new list containing only the strings that represent valid IPv4 addresses.

An IPv4 address is valid if it meets the following criteria:

  1. It is in the form 'A.B.C.D', where A, B, C, and D are integers.
  2. Each integer must be between 0 and 255, inclusive.
  3. The integers cannot have leading zeros unless the number itself is exactly '0'.
  4. The string must contain exactly three periods separating four segments.

Function Signature

def filter_valid_ipv4(ip_list: List[str]) -> List[str]:

Constraints

  • 1 <= len(ip_list) <= 1000
  • Each string in ip_list has a length between 1 and 20.
  • Input strings consist of digits and dots only.

Examples

Example 1: Input: ["192.168.1.1", "256.0.0.1", "172.16.254.01"] Output: ["192.168.1.1"] Explanation: '256.0.0.1' is invalid (256 > 255), and '172.16.254.01' is invalid (leading zero).

Example 2: Input: ["0.0.0.0", "1.2.3", "..1.1"] Output: ["0.0.0.0"] Explanation: '1.2.3' lacks the fourth octet and '..1.1' contains empty segments.

Edge Cases

  • Empty strings or strings with only dots.
  • Segments that are non-numeric or empty (e.g., '192..1.1').
  • Values exceeding the 255 limit.

Hints

Hint 1

Consider splitting each string by the period character and checking if the resulting list has exactly four segments.

Hint 2

For each segment, check if it is non-empty, contains only digits, and represents an integer in the range [0, 255].

Hint 3

To handle leading zeros, check if the segment length is greater than 1 while the first character is '0'.

Follow-up questions

  • How would you modify your solution to support IPv6 address validation?
  • What is the time complexity of your solution in terms of the number of strings and the maximum length of an IP address?
  • If you were asked to validate millions of IP addresses, how could you optimize the performance or memory usage?