11 Javascript Beginner Level Strings Interview Questions & Answers
Below is a list of our Javascript Beginner Level Strings interview questions. Click on any interview question to view our answer advice and answer examples. You may view 5 answer examples before our paywall loads. Afterwards, you'll be asked to upgrade to view the rest of our answers.
1. Is the sentence a pangram or not?
This interview question tests the developer's skills with JavaScript strings and loops.
You are given a sentence with no white space. The sentence contains only lowercase English letters. You need to check if the sentence is Pangram or not.
Pangram- A pangram is a sentence where every letter of the English alphabet appears at least once.
/*Example*/
given string- “thequickbrownfoxjumpsoverthelazydogâ€
expected output- true
given string- “mynameisjohnâ€
expected output- false
Solution:
The solution is pretty easy. We will track the occurrence of every alphabet. If there is at least one letter that does not occur in the given sentence, we return false. We will use an array of size 26 with all values equal to false. Then we will iterate over each letter in the given sentence and will put true to the array corresponding to that letter.
In the array,
“a†will have index 0,
“b†will have index 1,
….
“z†will have index 25,
To find the index from the letter, we can subtract 97 from its ASCII value (character code).
“a†has code 97, so will have index 0,
“b†has code 98, so will have index 1,
...
“z†has code 122, so will have index 25,
/**
* @param {string} sentence
* @return {boolean}
*/
function isPangram(sentence) {
const chars = new Array(26).fill(false)
for (const char of sentence) {
const index = char.charCodeAt(0) - 97
chars[index] = true
}
for (const c of chars) {
if (!c) return false
}
return true
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
2. Return the string in lowercase.
This interview question tests the developer's skills with JavaScript strings and loops.
You are given a string. The string contains the English alphabets. You need to implement a function toLowerCase which returns the same string in lowercase letters. You can not use the inbuilt function String.prototype.toLowerCase.
/*Example*/
given string- “abcAGiHkjâ€
expected output- “abcagihkjâ€
given string- “qwertâ€
expected output- “qwertâ€
Solution:
We will iterate over each character of the given string and convert it into lowercase. Then we will push the resulting character into a result array. After iterating the string, we will join the result array and return it. Now the problem remaining is to convert a character to lowercase.
The lowercase letters have character codes from 97 to 122 (both inclusive) and uppercase have from 65 to 90 (both inclusive). We will check the code of the letter. If it is between 97 and 122, we need not change the character. If it is between 65 and 90, we will add 32 (= 97 - 65) to convert to lowercase. So if-
the letter is “jâ€
-> its code is 106
-> between 97 and 122
-> already a lowercase letter
the letter is “Bâ€
-> its code is 66
-> between 65 and 90
-> add 31
-> 66 + 32 = 98
-> 98 is “bâ€
/**
* @param {string} sentence
* @return {string}
*/
function toLowerCase(str) {
const result = []
for (const char of str) {
let charCode = char.charCodeAt(0)
// if it uppercase
if (charCode >= 65 && charCode <= 90) {
charCode += 32
}
const lowerChar = String.fromCharCode(charCode)
result.push(lowerChar)
}
return result.join(“â€)
}
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on May 21st, 2021
3. How many jewels are there?
This interview question tests the developer's skills with JavaScript strings and loops.
You are two given strings- jewels and stones. A jewel is a special and precious stone. All jewels are stones but not vice-versa. Each character of stones represents the type of stones that you have. So if,
stones = “aAAqbbâ€, you have-
â— one stone of type “aâ€
â— two stones of type “Aâ€
â— one stone of type “qâ€
â— two stones of type “bâ€
Each character in jewels represents the type of stone that is a jewel. So if,
jewels = “aAâ€, then-
◠stone of type “a†is a jewel
◠stone of type “A†is a jewel
Your task is to find how many stones you have that are jewels
/*Example*/
stones = “aAAqbbâ€
jewels = “aAâ€
expected output = 3 // (“aAA†are all jewels)
Solution:
The solution is simple. We will iterate over each character in the stones and will check if it is a jewel. To check if a stone is a jewel, we will check if the character is contained in the string jewels.
/**
* @param {string} jewels
* @param {string} stones
* @return {number}
*/
function findJewels(jewels, stones) {
let count = 0
for (const char of stones) {
const isJewel = jewels.includes(char)
if (isJewel) {
count++
}
}
return count
}
m = length of string jewels
n = length of string stones
Time complexity- O(m * n)
Space complexity- O(1)
There is one optimization we can do. The time complexity of the includes() function is O(m). Instead of checking if char is a jewel using includes, we can have a set of stones that are jewels made from string jewels.
[...jewels] converts the string jewels to an array of characters.
So if jewels = “aAâ€,
[...jewels] = [“aâ€, “Aâ€]
new Set([...jewels]) converts the string jewels to a set.
/**
* @param {string} jewels
* @param {string} stones
* @return {number}
*/
function findJewels(jewels, stones) {
let count = 0
jewels = new Set([...jewels])
for (const char of stones) {
const isJewel = jewels.has(char)
if (isJewel) {
count++
}
}
return count
}
m = length of string jewels
n = length of string stones
Time complexity- O(n + m)
Space complexity- O(m)
Written by S. Kumar on May 21st, 2021
4. Can you get a string from the binary tree?
This question shows the developer's ability to work with JavaScript recursion.
You are given a binary tree. Your task is to get a string representation of the binary tree. The string consists of parentheses and the values of the nodes in the tree. The representations are as follows:
1. the string representation of a leaf node is the node value itself,
2. the string representation of a null node is “()â€,
3. for a parent node,
a. its value is written first,
b. the value is followed by the string representation of the left subtree enclosed in pair of
parentheses,
c. then it is followed by the string representation of the right subtree enclosed in pair of
parentheses,
4. you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.
/*Example*/
1.
1
/ \
2 3
/
4
expected output = “1(2(4))(3)â€
We didn’t add “()†right child of 2 because those are unnecessary.
2.
1
/ \
2 3
\
4
expected output = “1(2()(4))(3)â€
We didn’t omit “()†left child of 2 because omitting those parentheses will 4 as the left child of 2 i.e. same as example-1
Solution:
We can use recursion for this. The required string is the pre-order traversal of the tree. We will get the string representation of both left and right subtrees. If the node is null, we will return an empty string. When we have string representations of left and right subtrees, 4 cases arise-
1. When both left and right children are present i.e. non-empty strings
In this case, the answer will be:
node.val + “(“ + left-string + “)†+ “(“ + right + “)â€
2. When both left and right children are absent i.e. empty strings
In this case, the answer will be:
node.val
3. When only the left child is present i.e. right string is an empty string (example 1)
In this case, we don’t need empty parentheses for the right child:
node.val + “(“ + left-string + “)â€
4. When only the right child is present i.e. left string is an empty string (example 2)
In this case, we must add empty parentheses for the left child:
node.val + “()†+ “(“ + right + “)â€
class TreeNode {
constructor(val, left, right) {
this.val = val || 0
this.left = left || null
this.right = right || null
}
}
/**
* @param {TreeNode} t
* @return {string}
*/
function toString(t) {
if (t === null) return ""
let left = tree2str(t.left)
let right = tree2str(t.right)
let result = t.val.toString()
// atleast one of the child is present
if (left !== "" || right !== "") {
result += "(" + left + ")"
}
// right child is present
if (right !== "") {
result += "(" + right + ")"
}
return result
}
n = number of nodes in the tree
Time complexity - O(n)
Space complexity - O(n)
The worst-case space complexity is O(n) in the case where the tree is skewed. For example-
1
/
2
/
4
/
3
In this case, there are 4 nodes, and the recursion stack will contain four calls to toString function. Thus O(n) space complexity.
Written by S. Kumar on May 21st, 2021
5. Are the string arrays equivalent?
This interview question concentrates on the developer's abilities with JavaScript join.
You are given two arrays of strings word1 and word2. A string is obtained from an array of strings by joining all the strings in the array. Your task is to check whether the string obtained from both arrays word1 and word2 are equal or not.
/*Example*/
word1 = ["ab", "c"]
word2 = ["a", "bc"]
expected output = true
string from word1 = “abcâ€
string from word2 = “abcâ€
thus they are equal
word1 = ["ab", "c"]
word2 = ["a", "cbâ€]
expected output = false
string from word1 = “abcâ€
string from word2 = “acbâ€
thus they are not equal
Solution:
In javascript, the solution is quite easy. We will join all the strings in the array by using Array.prototype.join method. We will get two strings from the two given arrays. Then, we will compare the strings directly.
/**
* @param {string[]} word1
* @param {string[]} word2
* @return {boolean}
*/
function areEqual(word1, word2) {
const str1 = word1.join("")
const str2 = word2.join("")
return str1 === str2
}
n = total number of characters in word1
m = total number of characters in word2
Time complexity- O(n + m)
Space complexity- O(n + m)
Written by S. Kumar on May 21st, 2021
6. Decipher the string.
This question shows the developer's knowledge of JavaScript strings.
You are given a string consisting of digits and the letter “#â€. Your task is to map this given string to a lowercase English string with the following mapping rules:
◠Characters from “a†to “i†are represented by “1†to “9†-- (Type I)
◠Characters from “j†to “z†are represented by “10#†to “26#†-- (Type II)
/*Example*/
Given string- “12316#â€
expected output- “abcpâ€
“1†-> “aâ€
“2†-> “bâ€
“3†-> “câ€
“16#†-> “pâ€
Given string- “12#13#14#â€
expected output- “lmnâ€
“12#†-> “lâ€
“13#†-> “mâ€
“14#†-> “nâ€
Solution:
We will traverse over each character of the given string.
The problem is to determine whether the current character forms a digit from “1†to “9†or from “10#†to “26#â€.
We are currently at character at index i. We will check the character at index i + 2.
If it is “#â€, then the characters from index i to i + 2 represent a letter of type II (“10#†to “26#â€)
if it is not “#â€, then the character at index i represents a letter of type II (“1†to “9â€).
After we got the number (in string form for example “1â€),
-> we will parse it to number,
-> then, we will get the ASCII code of the character by adding 96 to it,
-> then we will get the English letter form code using String.fromCharCode
So, for “1â€
-> 1 -> 96 + 1 = 97 -> “aâ€
for “2â€
-> 2 -> 96 + 2 = 98 -> “bâ€
…
for “26â€
-> 26 -> 96 + 26 = 122 -> “zâ€
We will store all the letters obtained in an array. After getting all the letters, we join the array to form the required string.
/**
* @param {string} s
* @return {string}
*/
function decipherIt(s) {
const res = []
for (let i = 0; i < s.length; i++) {
let code
if (s[i + 2] === '#') {
code = s.slice(i, i + 2)
i += 2
} else {
code = s[i]
}
code = parseInt(code)
const char = String.fromCharCode(code + 96)
res.push(char)
}
return res.join("")
}
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on May 21st, 2021
7. Remove vowels from the string.
This question focuses on the developer's ability to manipulate strings in JavaScript.
You are given a string. Your task is to remove vowels from the string and return it.
/*Example*/
Given string = “abcdEFGhâ€
expected output = “bcdFGhâ€
Solution:
We will have a new array result that will store the characters of the resulting string. We will iterate over each character in the string. If the character is a vowel, we will discard it. If it is not a vowel, we will push the character in the result array.
To check if a character is a vowel, we will have another function:- isVowel. It will take a character as input. We will check the character if it is included in a string of vowels or not.
/**
* @param {string} str
* @return {string}
*/
function removeVowels(str) {
const result = []
for (const char of str) {
if (!isVowel(char)) {
result.push(char)
}
}
return result.join(“â€)
}
function isVowel(char) {
const vowels = “aeiouAEIOUâ€
return vowels.includes(char)
}
Time complexity- O(10 * n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
8. What is the number of consistent words?
This interview question tests the developer's skills with JavaScript arrays and loops.
You are given an array of words. You are also given another string allowed. A word is consistent if it contains letters that are present in the string allowed. Your task is to count the number of consistent words. The words and the string allowed contain only lowercase English for the ith flower letters.
/*Example*/
words = ["ad","bd","aaab","baa","badabe"] allowed = “abâ€
expected output = 2
Only “aaab†and “baa†are consistent because they contain only “a†and “b†letters.
“ad†is not consistent because it contains “d†which is not allowed.
“bd†is not consistent because it contains “d†which is not allowed.
“badabe†is not consistent because it contains “d†and “e†which are not allowed.
Solution:
We can traverse over each character of each word. For a particular word, if all the characters exist in the string allowed, then we say the word is consistent, otherwise not.
Initially, we assume, all the words are consistent (let count = words.length). Then we check if the word is consistent or not. If not, we reduce the count by 1.
To check if the word is consistent, first create an array allowedChars, to track which character is allowed and which are not. Its size is 26 for every 26 letters. Then we traverse over each character of the word and if it is allowed or not. If it is not allowed, we simply decrease the count, break the loop and check the next word.
/**
* @param {string[]} words
* @param {string} allowed
* @return {number}
*/
function countConsistent(head) {
let count = words.length
const allowedChars = new Array(26).fill(false)
// track which letters are allowed
for (const char of allowed) {
const charIndex = characterIndex(char)
allowedChars[charIndex] = true
}
for (const word of words) {
// check if the word is consistent or not
for (const char of word) {
const charIndex = characterIndex(char)
// the char is not allowed, so the word
// is not consistent, decrease the count
if (!allowedChars[charIndex]) {
count--
break
}
}
}
return count
}
function characterIndex(char) {
const charCode = char.charCodeAt(0)
return charCode - 97
}
n = number of words
m = max length of a word
Time complexity- O(n * m)
Space complexity- O(26) = O(1)
Written by S. Kumar on May 21st, 2021
9. Make an anagram.
This question concentrates on a developer's knowledge of JavaScript functions.
You are given two string src and dest of the same length. The strings contain only lowercase English letters. In one operation, you can choose a character of dest string, and replace it with any other character. Your task is to calculate the minimum number of operations required to make string dest an anagram of src.
A string a is an anagram of b if a contains the same characters with a different (or the same) ordering which are in b.
/*Example*/
src = “bab†dest = “abaâ€
expected output = 1
explanation:- we can dest[0] with “b†to make anagram of src.
Solution:
We will calculate the frequency of each character in both strings. Then we will compare the frequency of each character for both strings. If for some character, dest has lesser frequency than src, (say the difference is diff), we need to perform a diff number of operations to make the frequency of that character equal. In the above example:
frequency of “b†in dest = 1
frequency of “b†in src = 2
So we will perform (2 - 1 = 1) operations to make the frequency of “b†equal. For the character “a†the frequencies are already equal.
/**
* @param {string} src
* @param {string} dest
* @return {number}
*/
function operationsForAnagram(src, dest) {
const srcCount = lettersFrequency(src)
const destCount = lettersFrequency(dest)
let operationCount = 0
for (let i = 0; i < 26; i++) {
const diffCount = srcCount[i] - destCount[i]
if(diffCount > 0) {
operationCount += diffCount
}
}
return operationCount
}
function lettersFrequency(str) {
const count = new Array(26).fill(0)
for (const char of str) {
const code = char.charCodeAt(0)
const index = code - 97
count[index]++
}
return count
}
Time complexity- O(length of strings)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
10. Count the matching items.
This question focuses on JavaScript iterations.
You are given a 2-D array of items of size n x 3. The array contains n rows of size 3 each. The ith row represents the ith item. The ith item has 3 properties i.e. items[i] = [typei, colori, namei], where typei, color, and namei represent the type, color, and the name of the ith item.
You are also given two variables- prop and targetValue. The argument prop is a string with possible values “typeâ€, “color†and “nameâ€. Your task is to find the number of items that have the value of prop equal to targetValue.
/*Example*/
Given-
items = [
["phone", "blue","pixel"],
["computer", "silver", "lenovo"],
["phone", "gold", "iphone"]
]
prop = “colorâ€
targetValue = “silverâ€
Expected output:- 1
Explanation:- There is only one item that has “color†equal to “silverâ€.
Given-
items = [
["phone", "blue","pixel"],
["computer", "silver", "lenovo"],
["phone", "gold", "iphone"]
]
prop = “typeâ€
targetValue = “phoneâ€
Expected output:- 2
Solution:
We will iterate over the array items and will see if the current item has the value of prop equal to targetValue. The value of prop passed is a string with possible values:- “typeâ€, “color†and “name†but the properties of the items are indices. So we will map the prop to indices in the items[i] array using the map propsMapping.
/**
* @param {string[][]} items
* @param {string} prop
* @param {string} targetValue
* @return {number}
*/
function countMatching(items, prop, targetValue) {
let count = 0;
const propsMapping = {
"type": 0,
"color": 1,
"name": 2,
}
prop = propsMapping[prop]
for (const item of items) {
if (item[prop] === targetValue) {
count++
}
}
return count
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
11. Convert string path to canonical path.
This interview question shows the developer's skills to simplify paths in JavaScript.
You are given a string path which is an absolute path (a path starting from “/â€) to a file or a directory in the Unix-style file system. Your task is to convert it to a canonical path.
In a Unix-style file system, a single period “.†refers to the current directory, a double period “..†refers to the directory up one level, and multiple slashes “//â€, “///†etc are treated as single slash “/â€. For this problem, assume any more periods (three or more) are treated as file or directory names.
A canonical path is a path which:
â— starts from single slash “/â€,
â— any two directories (or directory and file) names are separated by a single slash,
â— the path does not end with a trailing slash,
â— it does not contain any period (single or double period).
/*Example*/
Given path = “/home/â€
Expected output:- “/homeâ€
Explanation:- no trailing slash
Given path = “/home///foo/â€
Expected output:- “/home/fooâ€
Explanation:- no trailing slash and only single slashes
Given path = “/a//./b/../../c/â€
Expected output:- “/câ€
Explanation: the canonical paths for accumulated paths are:-
“/a†-> “/aâ€
“/a//.†-> “/a†(single slash and current directory so no change)
“/a//./b†-> “/a/bâ€
“/a//./b/..†-> “/a†(one level up, so “b†is removed from path)
“/a//./b/../..†-> “/†(one more level up, so “a†is removed from path)
“/a//./b/../../c†-> “/câ€
“/a//./b/../../c/†-> “/c†(no trailing slash)
Solution:
The solution is pretty easy. First, we will get the names of directories and files including single and double periods. We will do this using String.prototype.split. This method takes a separator string and splits the given string by separator and returns the result in an array. So, for example path = “/a//./b/../../c/â€, the value of names after the statement
let names = path.split("/") is:-
names = [“aâ€, “â€, “.â€, “bâ€, “..â€, “..â€, “câ€, “â€]
There is nothing (empty string) between two slashes, so there is an empty string at index 1 of names. The same is for the last slash.
To remove these empty strings, we will use the Array.prototype.filter method. This method is applied on an array and takes a predicate function as the only argument. This is used to filter out some of the values from the array based on the predicate function. The predicate function takes the element of the array and SHOULD return true if we wish to keep that element or false if we wish to filter out that element. In our case, we want to filter out empty strings. So we use a => a !== "" in the predicate function.
We maintain an array result, which will store the final names in the canonical path. Then we iterate over each directory/file name in the names array.
◠If it is a single period, we don’t do anything;
â— if it is a double period, we move one level up, that is, we remove the last entry from the result array;
â— otherwise, we push that name to the result array.
In the end, we will join all the names in the result array with a single slash.
/**
* @param {string} path
* @return {string}
*/
function simplifyPath(path) {
let names = path.split("/")
names = names.filter(a => a !== "")
const result = []
for (const name of names) {
if (name === ".") continue
if (name === "..") result.pop()
else result.push(name)
}
return "/" + result.join("/")
}
n = length of path
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on May 21st, 2021