Skip to main content
DSA patterns

Validate IP Address

mediumStrings Must-doCloudflarePalo Alto NetworksCisco

Problem statement

You're given a string queryIP. Decide what kind of address it is: return "IPv4" if it's a correctly formatted IPv4 address, "IPv6" if it's a correctly formatted IPv6 address, or "Neither" if it doesn't match either format.

A valid IPv4 address looks like x1.x2.x3.x4 — four numbers separated by dots, where every number is between 0 and 255, and none of them has a leading zero (so "01" and "00" are not allowed, but a lone "0" is fine).

A valid IPv6 address looks like x1:x2:x3:x4:x5:x6:x7:x8 — eight groups separated by colons, where each group is 1 to 4 hexadecimal characters (0–9, a–f, A–F). Leading zeros are fine here ("0000" is a normal IPv6 group).

This is exactly the kind of check a config loader or an admission controller runs before it trusts a string as a real address — reject anything malformed rather than pass it downstream.

Examples

Example 1

Input: queryIP = "172.16.254.1"

Output: IPv4

Explanation: Four dot-separated numbers, each between 0 and 255, none with a leading zero.

Example 2

Input: queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"

Output: IPv6

Explanation: Eight colon-separated groups, each 1–4 hex characters. Groups can be short ("0") or mix upper and lower case ("8A2E").

Example 3

Input: queryIP = "256.256.256.256"

Output: Neither

Explanation: There are 4 dot-separated parts, so it looks like it could be IPv4 — but 256 is bigger than the allowed maximum of 255, so every part fails and the whole string is neither.

Hints

Hint 1: Handle IPv4 and IPv6 as two completely separate checks — a string can't satisfy both, since one uses dots and the other uses colons.

Approach

Optimal: Regex

Intuition

Everything the manual approach checks by hand — digit count, range, no leading zero, hex characters — can be written as one regular expression per format. This trades a few lines of validation code for one dense pattern, which is a fair alternative to know for an interview, as long as you can explain what each piece of the pattern does.

The trickiest part is the "no leading zero" rule for IPv4: you can't just say "1 to 3 digits", because that would accept "099". Instead, each octet is written as an explicit choice between four shapes: 250–255, 200–249, 100–199, or a plain 1–2 digit number that doesn't start with 0.

Steps

  1. Build one piece of pattern for a single valid IPv4 octet: 25[0-5] (250–255) OR 2[0-4]\d (200–249) OR 1\d{2} (100–199) OR [1-9]?\d (0–9 or 10–99, no leading zero).
  2. Chain 4 of those together with literal dots between them, anchored at the start and end of the string.
  3. Build a second pattern for IPv6: 1–4 hex characters, chained 8 times with literal colons between them, also anchored.
  4. Try the IPv4 pattern first; if it matches, return "IPv4".
  5. Otherwise try the IPv6 pattern; if it matches, return "IPv6".
  6. If neither matched, return "Neither".

Dry run

Matching "01" against the octet piece [1-9]?\d: the optional [1-9] can't consume the leading 0 (it isn't 1–9), so it matches nothing there, which leaves only \d to consume a single character — just the "0". That leaves the "1" unconsumed with no dot after it, so the overall anchored pattern can never match the full string "01" this way, and none of the other three octet alternatives start with 0 either. The whole match fails, exactly like the manual leading-zero check.

Edge cases: the empty string fails to match either anchored pattern (there's nothing for the first group to consume). A value like "1000" in an IPv6 group correctly fails since [0-9a-fA-F]{1,4} allows at most 4 characters.

Complexity

Time O(n) - A regex engine still has to look at every character once to match the pattern; for a fixed, small pattern like this one there's no backtracking blow-up.

Space O(1) - extra — The pattern is compiled once and reused; matching itself doesn't build new data structures.

import re


class Solution:
    IPV4_PART = r"(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)"
    IPV4_PATTERN = re.compile(rf"^{IPV4_PART}(\.{IPV4_PART}){{3}}$")
    IPV6_PART = r"[0-9a-fA-F]{1,4}"
    IPV6_PATTERN = re.compile(rf"^{IPV6_PART}(:{IPV6_PART}){{7}}$")

    def validIPAddress(self, queryIP: str) -> str:
        if self.IPV4_PATTERN.match(queryIP):
            return "IPv4"
        if self.IPV6_PATTERN.match(queryIP):
            return "IPv6"
        return "Neither"


if __name__ == "__main__":
    s = Solution()
    print(s.validIPAddress("172.16.254.1"))  # IPv4
    print(s.validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7334"))  # IPv6
    print(s.validIPAddress("256.256.256.256"))  # Neither
RecapThe whole problem in a few lines, for the night before
  • Spot it: "is this string a correctly formatted IPv4 or IPv6 address?"
  • Idea: split on the separator for each format, then check every rule (count, length, leading zero, range or hex digits) against every piece
  • Cost: O(n) time, O(n) space, where n is the length of the address string
  • Trap: a leading zero ("01") is invalid for IPv4 but a leading zero is completely normal for IPv6 ("00a1") — don't apply the same rule to both

Interview follow-ups

  • What if queryIP might be null, or have leading/trailing whitespace?

    Guard for null (or an empty string) before running either check and return "Neither" immediately — both split-based checks already fail safely on an empty string, so the main risk is a null reference. For whitespace, either trim it first if the caller says stray whitespace is acceptable input noise, or leave it as a validation failure if the format should be exact — the digit and hex-character checks already reject spaces on their own since a space isn't a digit or a hex character.

  • How would you extend this to accept CIDR notation, like "192.168.1.0/24"?

    Split off the /mask suffix first, then run the normal IPv4 check on the part before the slash. Separately, check the mask: it must be all digits, with no leading zero (except the single digit "0"), and its value must be between 0 and 32 inclusive. Both checks are O(n) just like before, so the overall cost doesn't change.

  • Millions of addresses need validating from a log stream — what changes?

    Nothing about the algorithm itself; the win is in how you run it. Compile the regex once (or reuse one Solution instance for the manual approach) instead of rebuilding it per address, and process the stream line by line rather than loading every address into memory at once. Each address is still checked in O(n) time and O(n) space, so the total cost stays linear in the number of characters across the whole stream.

Frequently asked questions

No. IPv4 needs exactly 4 dot-separated parts and no colons; IPv6 needs exactly 8 colon-separated parts and no dots (a colon isn't a digit or a dot, so it fails the IPv4 split, and vice versa). The two checks are mutually exclusive by construction, so the order you check them in doesn't change the answer.

"01" and "1" mean the same number, but some older tools read a leading-zero number as octal, so "010" could silently mean 8, not 10. IPv4's canonical form bans leading zeros to remove that ambiguity entirely — a rule the LeetCode problem enforces strictly. IPv6 doesn't have this issue because its groups are already hexadecimal, where "00a1" and "a1" are unambiguously the same value.

Anywhere a raw string becomes part of a config — a firewall rule, a DNS record, a load balancer's allow-list — it's worth validating that string looks like a real address before it's written down or acted on. Rejecting "192.168.01.1" or a stray "999.1.1.1" at the door is cheaper than debugging why a downstream system misbehaved on a malformed value.

It could if a part had, say, 20 digits, but the length check (> 3 characters for IPv4, > 4 for IPv6) runs first and rejects those before any conversion happens. That ordering matters in Java and C++ especially, where parsing an overly long digit string into an int can throw or overflow — checking the length first sidesteps the problem entirely.

Mostly, with one caveat: Python's \d in a regex matches some non-ASCII digit characters by default, not just 0–9. For this problem the surrounding character classes and anchors mean it still behaves correctly in practice, but a hardened version would use [0-9] explicitly (or the re.ASCII flag) instead of \d to remove any doubt.