The IP Validator
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- Meta
Problem
Given a string, return True if it is a valid IPv4 address: exactly four decimal octets separated by dots, each in range 0..255, with no leading zeros (except '0' itself).
Real and fake, mixed together.
Example
Input:
ip = "192.168.1.1"
Output:
true
Worked solution and explanation
Why this problem exists in real interviews
This tests string validation with multiple rules, a pattern common in data quality and input sanitization. It probes whether a candidate can enumerate all validation criteria and check them systematically.
Break down the requirements
Step 1: Split by dots and check for exactly 4 parts
A valid IPv4 address has exactly 4 octets separated by dots.
Step 2: Validate each octet
Each must be a numeric string representing an integer between 0 and 255.
Step 3: Check for leading zeros
Octets like '01' or '00' are invalid (except '0' itself).
The solution
def is_valid_ipv4(ip: str) -> bool:
parts = ip.split('.')
if len(parts) != 4:
return False
for part in parts:
if not part:
return False
if not part.isdigit():
return False
if len(part) > 1 and part[0] == '0':
return False
num = int(part)
if num < 0 or num > 255:
return False
return TrueCommon follow-up questions
- How would you validate IPv6 addresses? (Tests hexadecimal validation, colon separators, and shorthand expansion.)
- What about CIDR notation like 192.168.1.0/24? (Tests splitting on `/` first, then validating the IP and prefix length separately.)
- Would you use regex for this in production? (Tests tradeoff: regex is more concise but harder to debug and extend.)