Magicsheet logo

Valid Phone Numbers

Easy
55.5%
Updated 6/1/2025

Asked by 4 Companies

Topics

Valid Phone Numbers

What is this problem about?

The "Valid Phone Numbers" interview question is a text processing task often framed in the context of shell scripting or regular expressions. You are given a text file containing many phone numbers and must output only those that follow specific formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. This problem focuses on pattern matching and string validation.

Why is this asked in interviews?

Meta and Amazon use the "Valid Phone Numbers" coding problem to test a candidate's proficiency with "Shell interview patterns" and Regular Expressions (Regex). In many backend or DevOps roles, the ability to quickly filter logs or process formatted text files using command-line tools is a highly valued skill.

Algorithmic pattern used

The primary pattern is "Regular Expression Matching." Whether using grep in a shell or a regex library in a language like Python or Java, you need to construct a pattern that strictly adheres to the two allowed formats. The pattern must handle the literal parentheses, the hyphen separators, and the specific number of digits in each group.

Example explanation

Imagine a file with these entries:

  • 987-123-4567
  • 123 456 7890
  • (555) 555-5555

The regex pattern would look for:

  1. A group of 3 digits, a hyphen, 3 digits, a hyphen, and 4 digits.
  2. OR a literal (, 3 digits, a literal ), a space, 3 digits, a hyphen, and 4 digits.

Output:

  • 987-123-4567 (Matches format 2)
  • (555) 555-5555 (Matches format 1)
  • 123 456 7890 is ignored because it uses spaces instead of hyphens.

Common mistakes candidates make

One common mistake is not escaping the parentheses ( and ) in the regex, which are special characters used for grouping. Another is failing to account for the exact number of digits, allowing numbers that are too long or too short. Candidates also sometimes forget that there must be a space after the closing parenthesis in the first format.

Interview preparation tip

Practice using grep -P or sed for the "Valid Phone Numbers" coding problem. Even if the interview is for a general software role, showing you know how to solve a string parsing task in one line of shell script demonstrates versatility and efficiency.

Similar Questions