Coding problem · Easy · Basics
Valid Username
Easy Algorithms & data structures
A username is valid when:
- it is 3 to 16 characters long,
- it contains only letters, digits and underscores (
_), - it starts with a letter.
Return true if name is valid.
Example 1
Input: name = "ana_dev" Output: true
Example 2
Input: name = "1ana" Output: false Explanation: Starts with a digit.
Example 3
Input: name = "a b" Output: false
Hints
Hint 1
Check each rule separately and return false as soon as one fails.
Hint 2
A regular expression can express all three rules in one line: ^[A-Za-z][A-Za-z0-9_]{2,15}$
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(1)
Either check the rules in code (length, first character, allowed characters) or use one regular expression: a letter followed by 2 to 15 letters, digits or underscores.
Reference solution
function isValidUsername(name) {
return /^[A-Za-z][A-Za-z0-9_]{2,15}$/.test(name);
}
function isValidUsername(name: string): boolean {
return /^[A-Za-z][A-Za-z0-9_]{2,15}$/.test(name);
}
import re
def is_valid_username(name: str) -> bool:
return re.fullmatch(r'[A-Za-z][A-Za-z0-9_]{2,15}', name) is not None
<?php
function isValidUsername(string $name): bool
{
return preg_match('/^[A-Za-z][A-Za-z0-9_]{2,15}$/', $name) === 1;
}
class Solution {
public boolean isValidUsername(String name) {
return name.matches("[A-Za-z][A-Za-z0-9_]{2,15}");
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy