Convert Dotted Decimal Subnet Mask To CIDR Prefix Length

Last updated: November 29, 2026

Quick Overview

Given a subnet mask string such as 255.255.254.0, return its prefix length (23), or -1 if the string is not a valid IPv4 mask. A valid mask is four octets in 0 to 255 whose binary form is a run of ones followed only by zeros.

Cisco
Coding & Algorithms
Software Engineer
Cisco
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

0

0

0 solved


Given a subnet mask string such as 255.255.254.0, return its prefix length (23), or -1 if the string is not a valid IPv4 mask. A valid mask is four octets in 0 to 255 whose binary form is a run of ones followed only by zeros.

Network engineers at Cisco type masks into IOS XE and Meraki configs every day, and tools that parse configs must reject masks like 255.255.0.255 that a careless operator might enter. This warm-up checks clean parsing, bit manipulation, and whether you remember the contiguity rule rather than just counting ones.

What the Interviewer Expects
  • Validates exactly four numeric octets, each in range
  • Builds a 32-bit integer from the octets
  • Checks contiguity with a bit trick instead of string scanning
  • Returns prefix length via bit counting
  • Handles 0.0.0.0 and 255.255.255.255 correctly
Key Topics to Cover
bit manipulation
IPv4 addressing
subnet masks
input validation
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you go the other direction, prefix length to dotted mask?
  • How would you convert a wildcard mask used in ACLs into a prefix length?
  • What changes for IPv6 prefixes?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input is a string. Output is an integer 0 to 32, or -1 for invalid input. Invalid cases: wrong number of octets, non-digits, values over 255, leading zeros (I reject them to avoid octal ambiguity, and...

High-Level Design

Pack the four octets into a 32-bit integer. A valid mask has the form 1...10...0. Invert it (within 32 bits) to get the host bits 0...01...1. A number of the form 2^k - 1 has the property `x & (...


Submit Your Answer
Markdown supported

Related Questions