Valid Phone Numbers — LeetCode 193 Python Solution

EasyShell
Problem
#193
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

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

Python solution

Python
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

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Related problems

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.

Get Stealth Interview