Magicsheet logo

Validate IP Address

Medium
39.8%
Updated 6/1/2025

Validate IP Address

What is this problem about?

The "Validate IP Address" interview question asks you to check if a given string is a valid IPv4 address, a valid IPv6 address, or neither. IPv4 addresses consist of four decimal numbers (0-255) separated by dots, while IPv6 addresses consist of eight hexadecimal groups separated by colons. Each type has its own strict formatting rules regarding leading zeros, character types, and group lengths.

Why is this asked in interviews?

This "Validate IP Address" coding problem is a staple at companies like Apple, Cisco, and Microsoft. It's an "industry-standard" test of string parsing and detail-oriented programming. Interviewers want to see if you can handle complex validation logic without getting lost in nested if statements and if you can write clean, modular code.

Algorithmic pattern used

The primary pattern is the "String interview pattern" using splitting and individual group validation. You first check if the string contains . or :. If it contains . (and exactly 3 of them), you split by . and validate each of the 4 groups as IPv4 segments. If it contains : (and exactly 7 of them), you split by : and validate each of the 8 groups as IPv6 segments.

Example explanation

String: "172.16.254.1"

  1. Contains .. Count is 3. Split into ["172", "16", "254", "1"].
  2. Group "172": All digits, 0-255, no leading zero. OK.
  3. Group "16": All digits, 0-255, no leading zero. OK.
  4. Group "254": All digits, 0-255, no leading zero. OK.
  5. Group "1": All digits, 0-255, no leading zero. OK.
  6. Result: "IPv4".

String: "2001:0db8:85a3:0:0:8A2E:0370:7334"

  1. Contains :. Count is 7. Split into 8 segments.
  2. Segment "0db8": Hex characters, length 1-4. OK.
  3. (Repeat for all segments).
  4. Result: "IPv6".

Common mistakes candidates make

For IPv4, a common mistake is allowing leading zeros (like "01") or numbers greater than 255. For IPv6, candidates often forget that groups can be 1 to 4 characters long and can contain both numbers and letters (a-f, A-F). Another frequent error is not handling trailing or consecutive separators (like "1.1.1.1.") which result in empty strings during splitting.

Interview preparation tip

For the "Validate IP Address" coding problem, avoid using complex Regular Expressions unless you are extremely confident in your regex skills. In a high-pressure interview, a clear, iterative split-and-check approach is much less prone to errors and easier to explain to the interviewer.

Similar Questions