11 Javascript Beginner Level Implementation Interview Questions & Answers
1. Validate a square.
You are given four points in 2-D space. Return true if they form a square, false otherwise. The points are integer coordinates and are given in any order.
Valid square- A quadrilateral with all sides equal and both diagonal equal. Also, each interior angle is equal to 90°.
/* Example */
Input- [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Expected output- true
Input- [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
Expected output- false
Solution:
For four points, we can find distances between them. There are a total of 6 distances possible. To be a valid square, 4 of them should be equal (the sides) and 2 should be equal (diagonals), and satisfies the following condition (Pythagoras theorem)-
diagonal2 = 2 * side^2
Instead of storing actual sides or diagonal, we are storing their square to avoid precision loss due to imperfect squares.
/**
* @param {number[]} p1
* @param {number[]} p2
* @param {number[]} p3
* @param {number[]} p4
* @return {boolean}
*/
function isValidSquare(p1, p2, p3, p4) {
const points = [p1, p2, p3, p4]
const distances = []
// find distances between all points
for (let i = 0; i < 4; i++) {
const p1 = points[i]
for (let j = i + 1; j < 4; j++) {
const p2 = points[j]
const d = getDistanceSquared(p1, p2)
distances.push(d)
}
}
// make two partitions, one with equal to the first distance,
// and one with not-equal to the first distance
let a1 = distances.filter(a => a === distances[0])
let a2 = distances.filter(a => a !== distances[0])
// filter a2 such that it contains only equal distances
a2 = a2.filter(a => a === a2[0])
return areValidSides(a1, a2) || areValidSides(a2, a1)
};
function areValidSides(diagonals, sides) {
if(diagonals.length !== 2 || sides.length !== 4) return false
// check if 2 * square(side) equal to square(diagonal)
return 2 * sides[0] === diagonals[0]
}
function getDistanceSquared(p1, p2) {
const diffXSquared = Math.pow(p1[0] - p2[0], 2)
const diffYSquared = Math.pow(p1[1] - p2[1], 2)
return diffXSquared + diffYSquared
}
Time complexity - O(1) // only four points
Space complexity - O(1)
Written by S. Kumar on June 27th, 2021
2. Format a string by grouping characters found in the string into similar lengths.
You are given a string named string consisting of alphanumeric characters. It contains some dashes - at random places dividing the string into groups. These groups can be different or the same length. Your task is to format the string as such that the dashes divide the string into groups of equal length K. The first group may have a length of less than or equal to K but the rest of the groups must have length K.
/* Example */
#1: Given - “abc-def†and K = 2
Expected output - “ab-cd-efâ€
All groups have the same length 2.
#2: Given - “abc-def-abdj-k†and K = 3
Expected output - “ab-cde-fab-djkâ€
All groups have except the first group has the same length 3.
Solution:
Given string - string
Let, the normal length of groups (except for the first group) be K
Let, the length of the given string be L
Let, the count of alphanumeric characters be N
If K divides N, then there are exactly K / N such groups in the formatted string each of length K.
If K does not divide N, then there are floor(K / N) groups each of length K and one group with remaining characters. The first group will have fewer than K characters and the rest will have exactly K characters. It is guaranteed that its length will be at least 1 because K does not divide N.
Let’s understand the sample inputs.
Given string- “abc-defâ€
Given K = 2
N = 6
Since K divides N, there will be 6 / 2 = 3 groups in the formatted string.
---
Given string- “abc-def-abdjkâ€
Given K = 3
N = 11
Since K does not divide N, there will be floor(11 / 3) = 3 groups in the formatted string with length K = 3 viz. cde, fab, djk. The remaining two characters ab will form the first group with length <= K = 3.
It can be seen there will be a dash - after every K places in the given string (with dashes removed). Thus we can iterate on the given string in the backward direction and place a dash after every K alphanumeric character.
/**
* @param {string} string
* @param {number} K
* @return {string}
*/
function formatLicenseKey(string, K) {
// array to contain the formatted string
const characters = []
// iterate backwards
for (let i = string.length - 1; i >= 0; i--) {
const char = string[i]
// if the current character is a dash skip it
if (char === '-') continue
// if the `characters` array contains a group
// of size `K` in its tail, push a dash
// marking the start of a new group
if (characters.length % (K + 1) === K) {
characters.push('-')
}
// transform and push the character
characters.push(char.toUpperCase())
}
// since we were iterating and pushing chars
// from backward direction, reverse the array
// and join it to form a string
return characters.reverse().join("")
}
Written by S. Kumar on June 27th, 2021
3. Determine if str1 is a subsequence of str2.
You are given two strings str1 and str2. Your task is to find if str1 is a subsequence of str2.
A subsequence of a string is a string that is created from the original by deleting zero or more characters with the order of remaining characters the same as the original string.
So if the original string is “abcdeâ€, the possible subsequences are-
“abcdeâ€:- deleting no zero characters.
“abdeâ€:- deleting “câ€
“bdeâ€:- deleting “a†and “câ€
but these are not valid subsequences-
“aebâ€:- the relative order is not the same
“cbzâ€:- contains another character “z†which is not in the original string
/* Example */
str1 = “abcâ€, st2 = “ahbgdcâ€
expected output- true
str1 = “axcâ€, st2 = “ahbgdcâ€
expected output- false
Solution:
We will iterate over each character of str1. We will find the index of each character of str1 in str2 starting from the index of the last character in str1. If the found index is -1, we return false, because it does not exist in str2. Otherwise, we continue to the next character of str1. For example-
str1 = “abcâ€, st2 = “ahbgdcâ€
start with the first character of str1 => “aâ€
=> index of “a†in str2 = 0
=> which is not -1
=> continue with next character
=> next character of str1 => “bâ€
=> index of “b†in str2 after index 0 (index of last character “aâ€) = 2
=> which is not -1
=> continue with next character
=> index of “c†in str2 after index 2 (index of last character “bâ€) = 5
=> which is not -1
=> all characters of str1 found in str2 with correct positions
=> return true
Another example-
str1 = “aghâ€, st2 = “ahbgdc
start with the first character of str1 => “aâ€
=> index of “a†in str2 = 0
=> which is not -1
=> continue with next character
=> next character of str1 => “gâ€
=> index of “g†in str2 after index 0 (index of last character “aâ€) = 3
=> which is not -1
=> continue with next character
=> index of “h†in str2 after index 3 (index of last character “gâ€) = -1
=> which is -1
=> return false
One thing to note here is that “h†did exist in str2, but it was before the index “gâ€, and we wanted it after the index “g†which is not the case. So we return -1.
We will use String.prototype.indexOf function to find the index of the character in str2. The function takes two arguments-
1) searchValue:- the string/character whose index we want to find
2) fromIndex (optional):- the index at which we want to start the search (default is 0)
/**
* @param {string} str1
* @param {string} str2
* @return {boolean}
*/
function isSubsequence(str1, str2) {
let lastIndex = -1
// iterate over each character of str1
for (const char of str1) {
// find index of char in str2 starting from
// index of last character
lastIndex = str2.indexOf(char, lastIndex + 1)
if (lastIndex === -1) return false
}
return true
}
m = length of string str1
n = length of string str2
Time complexity- O(m + n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
4. Find the largest two numbers in an array without sorting them.
You are given an unsorted array of integers. Your task is to find the two largest elements in the array without sorting them. Return the two integers in the array of size two, the largest at index-0 and the second-largest at index-1.
/* Example */
Given- [1, 3, 2, 5, 4]
Expected output- [5, 4]
Solution:
We will iterate over each number of the given array. We will maintain two variables largest and secondLargest for the largest and the second-largest element seen so far. When we encounter a new number, we check if it is greater than largest, then the previous value of largest becomes secondLargest, and the new number becomes largest.
For example:-
let previously, largest = 10 secondLargest = 7
let the new number is 12 which is greater than largest. So updated values are:-
largest = 12 and secondLargest = 10
if it is greater than secondLargest (and smaller than largest), then the new number becomes secondLargest. We don’t need to change largest.
For example:-
let previously, largest = 10 secondLargest = 7
let the new number is 8 which is greater than secondLargest. So updated values are:-
largest = 10 and secondLargest = 8
/**
* @param {number[]} nums
* @return {number[]}
*/
function findTwoLargest(mat) {
let largest = -Infinity
let secondLargest = -Infinity
for (const num of nums) {
if (num > largest) {
secondLargest = largest
largest = num
} else if (num > secondLargest) {
secondLargest = num
}
}
return [largest, secondLargest]
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
5. Find unique vanishing numbers.
You are given an integer n. Your task is to generate and return an array consisting of unique integers such that they all add up to 0. You can return any array that satisfies the property.
/* Example */
Given n = 5
expected output:- [1, 2, -3, 4, -4]
other possible answers:-
[0, 1, 2, -1, -2]
[-4, -3, 5, 2, 0] and many more...
Solution:
As we can see, there are many possible ways to generate the array. Some of these are:
Fill from left and right with additive identities (x and -x). For example-
for n = 5, [-1, -2, 0, 2, 1]
for n = 6, [-1, -2, -3, 3, 2, 1]
Fill n - 1 positive integers, and put minus of sum all those positive integer as nth integer. For example-
for n = 5, [1, 2, 3, 4, -10]
for n = 6, [1, 2, 3, 4, 5, -15]
The second solution seems easier. So we will code it.
/**
* @param {number} n
* @return {number[]}
*/
function generateArray(mat) {
const result = new Array(n)
let sum = 0
for (let i = 0; i < n - 1; i++) {
result[i] = i + 1
sum += result[i]
}
result[n - 1] = -sum
return result
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
6. How do you find two integers in the array such that their sum is 'target'?
This question focuses on the developer's knowledge of loops.
You are given an array 'nums' and an integer 'target'. Your task is to find two integers in the array such that their sum is 'target'. You need to return their indices. It is guaranteed that exactly one solution exists.
/*Example*/
nums = [17, 15, 2, 9] target = 24
expected output:- [1, 3]
explanation:- The sum of integers at indices at 1 and 3 is 24 (15 + 9).
nums = [7, 8, 5, 3, 1] target = 4
expected output:- [3, 4]
explanation:- The sum of integers at indices at 3 and 4 is 4 (3 + 1).
Solution:
We will iterate over the array. We will maintain a map to store the number and their indices. The numbers will be the keys and their indices will be the values of the map.
Let curr be the current number. We will check if target - curr exists in the map, which means we have got our two required numbers and will return their indices.
If target - curr does not exist, we will save curr to the map.
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
function findTwoSum(nums, target) {
const map = new Map()
for (let i = 0; i < nums.length; i++) {
const curr = nums[i]
const diff = target - curr
if (map.has(diff)) {
return [map.get(diff), i]
}
map.set(curr, i)
}
}
Time complexity- O(n) where n is the number of elements of the array
Space complexity- O(n)
Written by S. Kumar on June 27th, 2021
7. How do you determine if a string is valid or not?
This interview question focuses on JavaScript methods.
You are given string str. The string consists of characters “(“, “)â€, “{“, “}â€, “[“ and “]â€. Your task is to determine if str is valid or not. A string consisting of valid if it contains:
◠every opening bracket is closed by a closing bracket of the same type (“(){}[()]†is valid while “(){[]†is not valid), and
◠the opening and closing brackets are in the correct order (“()[]†is valid but “)(†and “({)}†are not valid).
/*Example*/
str = “()â€
expected output = true
str = “()[]{}â€
expected output = true
str = “(]â€
expected output = false
str = “({)}â€
expected output = false
Solution:
We will iterate over the passed string. We will use a stack to track the opening brackets. If the current bracket is an opening bracket i.e. one of “(“, “{“, and “[“, we will push it to the stack. If the current bracket is a closing bracket, then:
â— If the stack is empty, it means there is no matching opening bracket in the stack. So return false.
â— If the stack is not empty. we will pop an opening bracket from the stack. The popped opening bracket and the current closing bracket are of the same type, we will continue with the next bracket. If they are not of the same type, we will return false.
After iterating over all the brackets, if the stack is empty, we return true. If it is not empty, we return false because there are some opening brackets that are not matched yet.
/**
* @param {string} str
* @return {boolean}
*/
function isValidString(str) {
const stack = []
const opens = "({["
for (const char of s) {
if (opens.includes(char)) {
stack.push(char)
continue
}
if (stack.length === 0) return false
const ch = stack.pop()
if (!areMatching(ch, char)) return false
}
return stack.length === 0
}
function areMatching(opening, closing) {
const map = {
"(": ")",
"{": "}",
"[": "]",
}
return map[opening] === closing
}
Time complexity- O(n) where n is the length of string
Space complexity- O(n)
Written by S. Kumar on June 27th, 2021
8. How can you find the third largest number in an array?
This question works with JavaScript methods and loops.
You are given an array of integers. Your task is to find the third-largest number in the array. It is guaranteed that the answer always exists.
/*Example*/
nums = [5, 9, 1, 7, 8]
expected output = 7
Solution:
We will iterate over all the numbers. We will have three variables:- firstMax, secondMax, and thirdMax. They all are initialized to -Infinity. Let curr be the current number:-
â— If curr is larger than firstMax, the new value of firstMax will be curr, and the new value of secondMax will be old value firstMax, and the new value of thirdMax will be old value secondMax.
â— If curr is larger than secondMax (and smaller than firstMax), the new value of secondMax will be old value curr, and the new value of thirdMax will be old value secondMax.
â— If curr is larger than thirdMax (and smaller than secondMax), the new value of thirdMax will be the old value curr.
â— If curr is smaller than thirdMax, all values will be unchanged.
/**
* @param {number[]} nums
* @return {number}
*/
function findThirdLargets(nums) {
let firstMax = -Infinity
let secondMax = -Infinity
let thirdMax = -Infinity
for (const num of nums) {
if (num > firstMax) {
thirdMax = secondMax
secondMax = firstMax
firstMax = num
} else if (num > secondMax) {
thirdMax = secondMax
secondMax = num
} else if (num > thirdMax) {
thirdMax = num
}
}
return thirdMax
}
Time complexity- O(n) where n is the number of integers in the array
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
9. Find if the array contains a unique number of occurrences for each value in the array or not.
This interview question shows the developer's knowledge of filtering in JavaScript.
You are given an array of integers. Your task is to find if the array contains a unique number of occurrences for each value in the array or not.
/*Example*/
arr = [1, 2, 2, 1, 1, 3]
expected output = true
freq of 1 = 3
freq of 2 = 2
freq of 3 = 1
The frequencies are unique for each value, so we return true.
arr = [1,2]
expected output = false
freq of 1 = 1
freq of 2 = 1
The frequencies are not unique for each value, so we return false.
Solution:
We store the frequencies for each value in a map. The keys of the map will be the integers and the values will be the frequency of those integers. Then we create a set from those frequencies (using map.values()). If the size of the set is equal to the size of the map, it means all frequencies were unique, if the sizes are not equal, it means some frequencies were not unique.
/**
* @param {number[]} arr
* @return {boolean}
*/
function hasUniqueFreq(arr) {
let map = new Map()
for (const num of arr) {
const prevOccurence = map.get(num) || 0
map.set(num, prevOccurence + 1)
}
const values = Array.from(map.values())
const occurrences = new Set(values)
return occurrences.size === map.size
}
Time complexity- O(n) where n is the number of integers in the array
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
10. Create a running sum of a 1-D array.
This question focuses on JavaScript functions.
You are given an array num of integers. Your task is to find a new array runningSum such that runningSum[i] = sumOf(nums[0], nums[1], …, nums[i]).
/*Example*/
Given nums = [1, 2, 3, 4]
Expected output:- [1, 3, 6, 10]
Explanation: runningSum = [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4] = [1, 3, 6, 10]
Given nums = [4, 3, 2, 1]
Expected output:- [4, 7, 9, 10]
Explanation: runningSum = [4, 4 + 3, 4 + 3 + 2, 4 + 3 + 2 + 1] = [4, 7, 9, 10]
Solution:
We will create a new array runningSum. We will set runningSum[0] = nums[0] because the first element in both the array is the same. Now,
runningSum[i] = sum of all elements in nums from 0 to i
runningSum[i + 1] = sum of all elements in nums from 0 to (i + 1)
= (sum of all elements in nums from 0 to i) + nums[i + 1]
runningSum[i + 1] = runningSum[i] + nums[i + 1]
/**
* @param {number[]} nums
* @return {number[]}
*/
function findRunningSum(nums) {
const runningSum = new Array(nums.length)
runningSum[0] = nums[0]
for (let i = 1; i < nums.length; i++) {
runningSum[i] = nums[i] + runningSum[i - 1]
}
return runningSum
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
11. Find if the robot returns to its home after given instructions or not.
This question focuses on JavaScript functions.
There is a robot initially at its home- the origin on a 2D plane. It is given some instructions to move to either left or right or up or down. The robot moves the same distance at each instruction in any direction. You are given a string of moves consisting of letters “Lâ€, “Râ€, “U†and “D†corresponding to left, right, up, and down respectively. The string moves tell the series of instructions given to the robot. Your task is to find if the robot returns to its home after these instructions or not.
/*Example*/
Given moves = “LUDRâ€
expected output = true
Given moves = “LLRâ€
expected output = false
Solution:
The solution is quite simple after making an observation. The origin is x = 0 and y = 0. We will store the current coordinate of the robot.
â— For R, the x coordinate increases by one.
â— For L, the x coordinate decreases by one.
â— For U, the y coordinate increases by one.
â— For D, the y coordinate decreases by one.
The robot will be at the origin if and only if the x and y coordinates are both 0 i.e. the robot must be on both the axis to be on origin i.e at point (0, 0).
/**
* @param {string} moves
* @return {boolean}
*/
function isAtHome(moves) {
let x = 0
let y = 0
for (const char of moves) {
switch(char) {
case "R":
x++
break
case "L":
x--
break
case "U":
y++
break
case "D":
y--
break
}
}
return x === 0 && y === 0
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021