String coding interview questions and answers
Questions
Write a function to compress a string using the counts of repeated characters. If the compressed string is longer than the original, return the original.
Example Input:
“aabcccccaaa”
Example Output:
“a2b1c5a3”
Write a function that validates a username based on the following criteria:
- Must start with a letter.
- Can contain only alphanumeric characters and underscores (_).
- Must be between 5 and 15 characters long.
Example Input:
“user_123”
Example Output:
Valid username.
Write a function that takes a phone number in any format (e.g., 1234567890, (123) 456-7890, 123-456-7890) and formats it as (123) 456-7890.
Example Input:
“1234567890”
Example Output:
“(123) 456-7890”
Write a function to count the number of words in a given sentence. A word is any sequence of non-space characters.
Example Input:
“Hello, how are you?”
Example Output:
4
Write a function that takes a full name and returns the initials in uppercase.
Example Input:
“john doe smith”
Example Output:
“J.D.S”
Write a function to mask all but the last four characters of a credit card number or phone number. Use * for masking.
Example Input:
“1234567812345678”
Example Output:
“************5678”
Write a function to find the word that appears most frequently in a string.
Example Input:
“apple banana apple orange banana apple”
Example Output:
“apple”
Write a function to reverse the order of words in a sentence while keeping the characters in each word intact.
Example Input:
“Hello World”
Example Output:
“World Hello”
Write a function to find all the duplicate characters in a string.
Example Input:
“programming”
Example Output:
[“r”, “g”, “m”]
Questions & Answers
- Compress a string using counts of repeated characters
function compressString(s) {
let compressed = “”;
let count = 1;
for (let i = 1; i < s.length; i++) {
if (s[i] === s[i – 1]) {
count++;
} else {
compressed += s[i – 1] + count;
count = 1;
}
}
compressed += s[s.length – 1] + count;
return compressed.length < s.length ? compressed : s;
}
- Validate a username
function validateUsername(username) {
const regex = /^[A-Za-z][A-Za-z0-9_]{4,14}$/;
return regex.test(username) ? “Valid username.” : “Invalid username.”;
}
- Format a phone number
function formatPhoneNumber(phone) {
const digits = phone.replace(/\D/g, “”);
if (digits.length === 10) {
return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
}
return “Invalid phone number”;
}
- Count the number of words in a sentence
function countWords(sentence) {
return sentence.trim().split(/\s+/).length;
}
- Return initials from a full name
function getInitials(fullName) {
return fullName
.split(” “)
.map(name => name[0].toUpperCase())
.join(“.”) + “.”;
}
- Mask all but the last four characters of a number
function maskNumber(number) {
return “*”.repeat(number.length – 4) + number.slice(-4);
}
- Find the most frequent word in a string
function mostFrequentWord(s) {
const words = s.split(/\s+/);
const wordCounts = {};
let maxCount = 0;
let mostFrequent = “”;
words.forEach(word => {
wordCounts[word] = (wordCounts[word] || 0) + 1;
if (wordCounts[word] > maxCount) {
maxCount = wordCounts[word];
mostFrequent = word;
}
});
return mostFrequent;
}
- Reverse the order of words in a sentence
function reverseWords(sentence) {
return sentence.split(” “).reverse().join(” “);
}
- Find duplicate characters in a string
function findDuplicates(s) {
const charCounts = {};
const duplicates = [];
for (const char of s) {
charCounts[char] = (charCounts[char] || 0) + 1;
}
for (const char in charCounts) {
if (charCounts[char] > 1) {
duplicates.push(char);
}
}
return duplicates;
}
Example Usage
console.log(compressString(“aabcccccaaa”)); // Output: “a2b1c5a3”
console.log(validateUsername(“user_123”)); // Output: “Valid username.”
console.log(formatPhoneNumber(“1234567890”)); // Output: “(123) 456-7890”
console.log(countWords(“Hello, how are you?”)); // Output: 4
console.log(getInitials(“john doe smith”)); // Output: “J.D.S.”
console.log(maskNumber(“1234567812345678”)); // Output: “************5678”
console.log(mostFrequentWord(“apple banana apple orange banana apple”)); // Output: “apple”
console.log(reverseWords(“Hello World”)); // Output: “World Hello”
console.log(findDuplicates(“programming”)); // Output: [“r”, “g”, “m”]