DDSA Solutions

Validate an IP Address

Advertisement

Intuition

Validate IPv4: four octets 0-255 separated by dots, no leading zeros.

Algorithm

  1. 1Split on ".". Must have exactly 4 parts. Each part: numeric, no leading zero, value 0-255.

Common Pitfalls

  • Empty parts, leading zeros (except "0" itself), non-numeric chars are all invalid. Same as LC 468.
Validate an IP Address.java
Java
// Approach: Split by '.' for IPv4 or ':' for IPv6. Validate each octet/hextet via regex or manual check.
// Time: O(1) bounded Space: O(1)
class Solution {

    public boolean isValid(String str) {
        String[] arr = str.split("\\.", -1);

        for (String s : arr) {
            if (s.length() <= 0 || s.length() > 3)
                return false;

            int num = Integer.parseInt(s);
            if (num > 255)
                return false;
        }

        return true;
    }
}
Advertisement
Was this solution helpful?