EasyNo. 0193

Valid Phone Numbers — LeetCode 193 Python Solution

Topics
Shell
Reading time
2 min

The problem

Given a text file file.txt that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers. You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx.

Example

Example
987-123-4567
123 456 7890
(123) 456-7890

Python solution

PythonSolution
import re

def print_valid_numbers(path: str = "file.txt") -> None:
    pattern = re.compile(r"^(\(\d{3}\) |\d{3}-)\d{3}-\d{4}$")
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.rstrip("\n")
            if pattern.match(line):
                print(line)

Complexity

Time
O(n)
Space · auxiliary
O(1) to O(n)

Related problems

Related problems
No.ProblemDifficulty
0192Word FrequencyMedium
0194Transpose FileMedium
0195Tenth LineEasy
0057Insert IntervalMedium
0228Summary RangesEasy
0485Max Consecutive OnesEasy

Frequently asked questions

How hard is LeetCode 193. Valid Phone Numbers?

LeetCode 193. Valid Phone Numbers is rated Easy on LeetCode.

What topics does LeetCode 193. Valid Phone Numbers cover?

LeetCode 193. Valid Phone Numbers is tagged Shell on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.