Validate IP Address
Updated
Problem statement
Given a string queryIP, return "IPv4" if it is a valid IPv4 address, "IPv6" if it is a valid IPv6 address, or "Neither" otherwise.
IPv4 rules
- The address contains exactly four decimal segments separated by
.. - Each segment is an integer from
0through255. - A segment has no leading zero unless it is exactly
0. - Every character in a segment is a decimal digit.
IPv6 rules
- The address contains exactly eight groups separated by
:. - Each group contains one to four hexadecimal characters.
- Hexadecimal letters may be lowercase or uppercase.
- Leading zeroes are allowed, but an empty group is not.
Function
validIPAddress(queryIP: String) → StringExamples
Example 1
queryIP = "172.16.254.1"return = "IPv4"The address has four decimal segments, each is in range, and none has an invalid leading zero.
Example 2
queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"return = "IPv6"The address has eight non-empty hexadecimal groups, and every group contains at most four characters.
Example 3
queryIP = "256.256.256.256"return = "Neither"Every segment is greater than 255, so this is not a valid IPv4 address.
Constraints
queryIPis a non-empty string.queryIPcontains only English letters, decimal digits,., and:.
More Motive Onsite Interview questions
- Group AnagramsPHONE SCREEN · ONSITE INTERVIEW · Seen Jan 2026
- Longest Equal-Zero-One SubarrayPHONE SCREEN · ONSITE INTERVIEW · Seen Jan 2026
- Maximum Weighted Sum After Left RotationsONSITE INTERVIEW · Seen Jan 2026
- Valid Parenthesis StringPHONE SCREEN · ONSITE INTERVIEW · Seen Jan 2026
- Best Time to Buy and Sell StockONSITE INTERVIEW · Seen Dec 2025
- Target Triplet SumONSITE INTERVIEW · Seen Dec 2025
- Generate Palindromic PermutationsONSITE INTERVIEW · Seen Dec 2025
- Minimum Swaps to Group Circular OnesONSITE INTERVIEW · Seen Dec 2025
- Staircase Search In A Sorted MatrixONSITE INTERVIEW · Seen Dec 2025
- Search in Rotated Sorted ArrayPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2025
Similar questions at other companies
- Invoice / Payment ReconciliationStripe · PHONE SCREEN · ONSITE INTERVIEWStripe interview questions
- Single-Pass S-Expression ParserBaseten · ONSITE INTERVIEWBaseten interview questions
- Flatten a Mixed JSON ListNike, Inc. · ONSITE INTERVIEWNike, Inc. interview questions
- Transform Dotted Keys into a Nested MapProofpoint · ONSITE INTERVIEW
- Serialize and Deserialize a String Key-Value StoreByteDance · ONSITE INTERVIEWByteDance interview questions
- Molecular Weight of a Grouped FormulaAgoda · ONSITE INTERVIEWAgoda interview questions
- Calculate a Token-List ExpressionCollege Vine · ONSITE INTERVIEW
- Rich Text Parser Part 3 (Depth Tokens)Figma · PHONE SCREEN · ONSITE INTERVIEWFigma interview questions
- Parse Nested HTML into a TreeApple · ONSITE INTERVIEWApple interview questions
- Calculator with ParenthesesGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions