13 Javascript Beginner Level Arrays Interview Questions & Answers
Below is a list of our Javascript Beginner Level Arrays 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. Find integers smaller than the current number.
This question proves the developer's ability to work with array elements.
You are given an array of integers num. Your task is to find the count of integers that are less than num[i] for every integer num[i] in the array num. You need to return these counts in an array count, with count[i] representing the count of integers less than num[i].
/*Example*/
num = [5, 1, 2, 2, 4, 3, 10, 3]
expected result- [6, 0, 1, 1, 5, 3, 7, 3]
for num[0] = 5 //there are 6 integers smaller than 5 (1, 2, 2, 4, 3, 3)
for num[1] = 1 //there are 0 integers smaller than 1
for num[2] = 2 //there is 1 integer smaller than 2 (1)
for num[2] = 2 //there is 1 integer smaller than 2 (1)
for num[3] = 4 //there are 5 integers smaller than 4 (1, 2, 2, 3, 3)
for num[4] = 3 //there are 3 integers smaller than 3 (1, 2, 2)
for num[5] = 10 //there are 7 integers smaller than 10 (5, 1, 2, 2, 4, 3, 3)
for num[6] = 3 //there are 3 integers smaller than 3 (1, 2, 2)
Solution:
First, we need to count the number of integers that are less than integer num[i]. To find this, we can make a copy of the given and sort it. Then, the count of integers less than sorted[i] will be equal to i:
Given array- num = [5, 1, 2, 2, 4, 3, 10, 3]
Sorted array- sorted = [1, 2, 2, 3, 3, 4, 5, 10]
For 1, index = 0, so count of integers less than 1 = 0
For 2, index = 1 (we will see smallest index), so count of integers less than 2 = 1
For 3, index = 3 (we will see smallest index), so count of integers less than 3 = 3
For 4, index = 5, so count of integers less than 4 = 5
For 5, index = 6, so count of integers less than 5 = 6
For 10, index = 7, so count of integers less than 10 = 7
We will store these counts in a map, where the keys will be integer itself and the values will be the count of integers less than that integer. So resulting map will be-
{
1 -> 0
2 -> 1
3 -> 3
4 -> 5
5 -> 6
10 -> 7
}
Then, we will create a result array count and will store counts corresponding to each element num[i].
/**
* @param {number[]} num
* @return {number[]}
*/
function findSmallerIntegers(num) {
const length = nums.length
// copy the original array and sort it
const sorted = [...nums]
sorted.sort((a, b) => a - b)
// create a map to store counts
// and store count 0 for smallest number
const counts = new Map()
counts.set(sorted[0], 0)
for (let i = 1; i < length; i++) {
const n = sorted[i]
// if current number is different from
// last number
if (n !== sorted[i - 1]) {
counts.set(n, i)
}
}
const result = new Array(length)
for (let i = 0; i < length; i++) {
const n = nums[i]
result[i] = counts.get(n)
}
return result
}
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on May 21st, 2021
2. Create a solution to return a rearranged array.
This interview question concentrates on JavaScript functions.
You are given array nums. It contains 2*n elements in form of-
[x1, x2, x3, …, xn, y1, y2, y3, …, yn]
Rearrange the given array to make in form of-
[x1, y1, x2, y2, x3, y3, …, xn, yn]
You have to return the solution in a new array.
/*Example*/
nums = [1,2,3,4,4,3,2,1], n = 4
expected = [1,4,2,3,3,2,4,1]
Solution:
We need to place the first n number to even indices (0-indexed) of the result array, and place next n elements to odd indices. This makes the solution pretty straightforward.
Create a new result array of size 2*n. Copy first n number to even indices, that is 2 * i and other n elements to odd indices, that is 2 * i + 1.
/**
* @param {number[]} nums
* @param {number} n
* @return {number[]}
*/
function rearrageArray(nums, n) {
const result = new Array(2 * n)
for (let i = 0; i < n; i++) {
// first n elements to even indices
result[2 * i] = nums[i]
// other n elements to even indices
result[2 * i + 1] = nums[n + i]
}
return result
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
3. How do you find the sum of unique elements?
This interview question concentrates on using JavaScript occurrences in arrays.
You are given an array of integers. You have to find the sum of all those elements which occur exactly once.
/*Example*/
nums = [1, 3, 4, 3]
expected output = 1 + 4 = 5 (3 occurs two times, so will be neglected)
nums = [2, 2, 3, 2, 3]
expected output = 0 (all numbers occur more one time)
Solution:
We will count the occurrences of each number on a map. The keys of the map will be the numbers and the values will be the count of their occurrences. Then we will iterate over every key of the map and will add the sum to it if its occurrence is equal to 1,
/**
* @param {number[]} nums
* @return {number[]}
*/
function sumUnique(nums) {
let sum = 0
const counts = new Map()
for (let i = 0; i < nums.length; i++) {
const n = nums[i]
if (counts.has(n)) {
const count = counts.get(n) + 1
counts.set(n, count)
} else {
counts.set(n, 1)
}
}
for (const key of counts.keys()) {
const count = counts.get(key)
if (count == 1) sum += key
}
return sum
}
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on May 21st, 2021
4. Can you find the richest person and return their wealth?
This interview question focuses on working with JavaScript objects.
You are given a 2-D array accounts of size n x m. The row accounts[i] represent an array of bank accounts of the ith person. The accounts[i][j] represent the wealth of ith person in the jth bank. Your task is to find the richest person and return their wealth. The total wealth of a person is the sum of all money they have in their bank accounts. The richest person is the person with the highest wealth.
/*Example*/
accounts = [[2,8,7],[7,1,3],[1,9,5]]
wealth of 0th person = 17 (sum of 0th row)
wealth of 1st person = 11 (sum of 1st row)
wealth of 2nd person = 15 (sum of 2nd row)
wealth of richest person = 17
Solution:
We will calculate the wealth of each person and then will find the person with the highest wealth.
/**
* @param {number[][]} accounts
* @return {number}
*/
function findRichest(accounts) {
const n = accounts.length
const m = accounts[0].length
const totalWealths = new Array(n)
for (let i = 0; i < n; i++) {
let wealth = 0
for (let j = 0; j < m; j++) {
wealth += accounts[i][j]
}
totalWealths[i] = wealth
}
return Math.max(...totalWealths)
}
Time complexity- O(n2)
Space complexity- O(n)
There is one optimization. We can reduce the space required. We can calculate the maximum wealth on the fly when calculating individual wealth.
/**
* @param {number[][]} accounts
* @return {number}
*/
function findRichest(accounts) {
const n = accounts.length
const m = accounts[0].length
let maxWealth = -Infinity
for (let i = 0; i < n; i++) {
let wealth = 0
for (let j = 0; j < m; j++) {
wealth += accounts[i][j]
}
if(wealth > maxWealth) maxWealth = wealth
}
return maxWealth
}
Time complexity- O(n2)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
5. Create a target array in a given order.
This question focuses on the developer's knowledge of JavaScript methods.
You are given two arrays nums and indices of the same size. Your task is to create a new array from these given arrays.
Let the resulting array be res. res is empty at first.
You iterate over the given arrays from left to right (i.e. from lower index to higher index).
Let i be the current index.
You will insert the number nums[i] at index indices[i]
/*Example*/
nums = [1, 2, 3, 4, 5]
indices = [0, 1, 2, 2, 1]
expected = [1, 5, 2, 4, 3]
explanation:
i nums[i] index[i] res
0 1 0 [1]
1 2 1 [1, 2]
2 2 2 [1, 2, 3]
3 4 2 [1, 2, 4, 3]
4 5 1 [1, 5, 2, 4, 3]
Solution:
We will create a new empty array res. We will iterate over each element of given arrays from index 0. We will insert nums[i] at index[i] directly. We will use Array.prototype.splice method for this.
The splice method takes 3 arguments-
1. index- the index from where to insert the elements (index[i] in our case)
2. deleteCount- the number of elements to delete (0 in our case as we don’t want to delete any number)
3. element- the number we want to insert (nums[i] in our case)
/**
* @param {number[]} nums
* @param {number[]} indices
* @return {number[]}
*/
function createTargetArray(nums, indices) {
const res = []
for (let i = 0; i < nums.length; i++) {
res.splice(indices[i], 0, nums[i])
}
return res
}
Time complexity- O(n2)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
6. How do you sort by parity?
This question concentrates on JavaScript loops and sorting.
You have an array of positive numbers. Your task is to rearrange the array so that all odd numbers follow all even numbers. The order of the even numbers or odd numbers is not important.
/*Example*/
Given array- [1, 2, 3, 4, 5, 6]
expected = [2, 4, 6, 1, 3, 5]
also accepted = [4, 6, 2, 1, 5, 3]
Solution:
Approach I (sort):
We can sort the array using a custom function passed to the sort function (Array.prototype.sort). There two arguments a and b passed to the custom function. The function should return-
â— -1 if a is less than b, i.e. a is at a lower index than b in the sorted array,
â— 1 if a is greater than b, i.e. a is at a higher index than b in the sorted array,
â— 0 if a is equal to b, i.e. index of a and b does not matter in the sorted array.
We want to have even numbers before odd numbers, which means all numbers are “less than†all odd numbers.
/**
* @param {number[]} nums
* @return {number[]}
*/
function sortByParity(nums) {
nums.sort((a, b) => {
// a is even, return -1 irrespective of parity of b
// because order of elements does no matter
if (a % 2 === 0) return -1
// if a is odd and b is even
// a is "greater than" b
if (b % 2 === 0) return 1
// both a and b are odd
return 0
})
return nums
}
Time complexity- O(n logn)
Space complexity- O(n) // for sort function depending on implementation of sort in the JavaScript engine
Approach II (Two-pass):
We can create a new empty result array. Then we run two loops.
1. In the first loop, we will push only even numbers.
2. In the second loop, we will push only odd numbers.
/**
* @param {number[]} nums
* @return {number[]}
*/
function sortByParity(nums) {
const result = []
for (const num of nums) {
if (num % 2 === 0) {
result.push(num)
}
}
for (const num of nums) {
if (num % 2 === 1) {
result.push(num)
}
}
return result
}
Time complexity- O(n)
Space complexity- O(n)
Approach III (Two pointers):
We will start at the two ends of the given array nums. i on the left (index 0), and j on right (index size - 1).
â— from the left side, we will find the first odd number i.e. first i such that nums[i] is odd,
â— from the right side, we will find the first even number i.e. first j (while decreasing j from size - 1 to 0) such that nums[j] is even,
â— then we will swap nums[i] and nums[j] so that index i has an even number and index j has an odd number after the wap. After the swap, all the numbers from index 0 to index i are even number, and all the numbers from j to size - 1 are all odd,
â— then we will increase i by 1 and decrease j by -1 and repeat the process until i and j cross each other.
2 4 3 1 6 8 5 7 9 11
--> i j <--
After swap-
2 4 8 1 6 3 5 7 9 11
--> i j <--
Next iteration-
2 4 8 1 6 3 5 7 9 11
--> i j <--
After swap
2 4 8 6 1 3 5 7 9 11
--> i j <--
Next iteration-
2 4 8 1 6 3 5 7 9 11
j<-- -->i (i and j cross each other, stop here)
/**
* @param {number[]} nums
* @return {number[]}
*/
function sortByParity(nums) {
let i = 0
let j = nums.length - 1
while (i < j) {
while(i < j && nums[i] % 2 === 0) i++
while(i < j && nums[j] % 2 === 1) j--
const temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
i++
j--
}
return nums
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
7. What ways can you reach the top of the steps?
This question works with a JavaScript algorithm.
You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
/*Example 1*/
Given n = 3
Expected output = 3
Explanation: There are in total 3 distinct ways to go the top
1. 1 step + 1 step + 1 step
2. 2 steps + 1 step
3. 1 step + 2 steps
/*Example 2*/
Given n = 5
Expected Output = 8
Explanation: For n as 5 there are 8 distinct ways to go the top
1. 1 step + 1 step + 1 step + 1 step + 1 step
2. 1 step +1 step + 1 step + 2 steps
3. 1 step + 1 step + 2 steps + 1 step
4. 1 step + 2 steps + 1 step + 1 step
5. 2 steps + 1 step + 1 step + 1 step
6. 1 step + 2 step + 2 step
7. 2 steps + 2 steps + 1 step
8. 2 steps +1 steps + 2 steps
Solution:
For n = 2 Expected Output = 2
â— We can go to Level 2 in 2 ways.
â—‹ Either we take the single step two times.
â—‹ We take two steps one time.
For n = 3 Expected Output = 3
â— We can go to Level 2 in 2 ways.
â—‹ Either we take the single step three times.
â—‹ We first take two steps one time and then a single step.
â—‹ We take one step first then two steps.
After we have taken the first step notice how the larger problem of taking 3 steps have now reduced to
â— waysToTake3Steps = 1 + waysToTake2Steps + 2 + waysToTake1Step
We can thus see how the number of ways to take any step for (n>=3) is the sum of the number of ways to take the (n-1) steps + the number of ways to take (n-2) steps.
Approach I (Recursive):
The first approach is fairly simple. First, we will check if n is 1 return 1 if it is 2 return 2.If n >= 3 we find the sum of n - 1 and n - 2 recursively.
But this solution becomes very slow for larger values since we are doing a lot of recalculations.
/**
* @param {number} n
* @return {number}
*/
function distinctWays(n) {
if (n == 1) return 1;
if (n == 2) return 2;
const totalWays = distinctWays(n - 1) + distinctWays(n - 2);
return totalWays;
}
Time complexity- O(2n) where n is the number of nodes
Space complexity- O(n)
Approach II (Iterative):
With recursion, we are recalculating a lot of values. To optimize we maintain a cache array. First, we need to set the values of arr[1] = 1 and arr[2] = 2. In each iteration, arr[n] becomes equal to the sum of arr[n - 1] and arr[n - 2].
/**
* @param {number} n
* @return {number}
*/
function distinctWays(n) {
let arr = [];
arr[1] = 1, arr[2] = 2;
for (let i = 3; i <= n; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
return arr[n];
}
Time complexity- O(n) where n is the number of steps
Space complexity- O(n)
Written by S. Kumar on May 21st, 2021
8. Create a code to return the maximized sum.
This question shows the developer's understanding of JavaScript functions.
You have given an array nums of size 2 * n. Group these integers into n pairs (a1, b1), (a2, b2), …, (an, bn) such that the sum of min(ai, bi) for all i is maximized. Your task is to return the maximized sum.
/*Example*/
Given nums = [1, 4, 3, 2]
expected output = 4
Explanation:
â— (1, 4) + (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
â— (1, 2) + (4, 3) -> min(1, 2) + min(4, 3) = 1 + 3 = 4
â— (1, 3) + (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
Solution:
The key observation here is:- we can not pair the smallest number with the greatest number, or the second smallest with the second greatest and so on.
Let’s say we have 4 numbers a, b, c and d in sorted order. We have to pair a with another number. Since a is the smallest number, there will be the contribution of 'a' in the final sum irrespective of the other number we choose:-
â— min(a, b) = a
â— min(a, c) = a
â— min(a, d) = a
So it is optimal to choose 'b' out of b, c and d to pair with a. A similar argument holds for other numbers.
In the solution, first, we sort all the numbers in ascending order. Then we pair even-indexed numbers with odd-indexed numbers i.e. index 0 with index 1, index 2 with index 3, and so on. The resulting answer will be the sum of all numbers at even indices because
nums[0] <= nums[1]
=> min(nums[0], nums[1]) = nums[0]
/**
* @param {number[]} nums
* @return {number[]}
*/
function pairSum(nums) {
nums.sort((a, b) => a - b)
let result = 0
for (let i = 0; i < nums.length; i += 2) {
result += nums[i]
}
return result
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
9. Find which kids can be happy after extra candy.
This interview question concentrates on using JavaScript methods and arrays.
n kids are having some candies. You are given an array of 'candies'. The ith kid has candies[i] number of candies. There are some extraCandies. You want to distribute extraCandies to the kids. A kid is happy if she has the greatest number of candies among all the kids. Your task is to find which kids can be happy after distributing extraCandies to them. A kid may get possibly all or none of the extraCandies.
/*Example*/
Given candies = [2,3,5,1,3] extraCandies = 3
Expected output = [true, true, true, false, true]
Explanation:-
kid with the maximum number of candies has 5 candies
kid 0 is happy if she gets all the 3 extraCandies
kid 1 is happy if she gets at least 2 extraCandies
kid 2 has already the greatest number of candies
kid 3 can never be happy even if she gets all the 3 extraCandies
kid 4 is happy if she gets at least 2 extraCandies
Solution:
The solution is pretty easy. First, we will find the maximum number of candies a kid has. After we will try to give all the extra candies to one kid then check if she is happy or not.
/**
* @param {number[]} candies
* @param {number} extraCandies
* @return {boolean[]}
*/
function happyKids(candies, extraCandies) {
const max = Math.max(...candies)
const result = new Array(candies.length).fill(false)
for (let i = 0; i < candies.length; i++) {
result[i] = (candies[i] + extraCandies) >= max
}
return result
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
10. Can you find the highest altitude?
This interview question focuses on JavaScript loops.
A biker is on a road trip in a hilly area. There are a total of n + 1 stops where the rider stops. The biker starts at stop 0 at an altitude of 0.
You are given an array gain of size n. It represents the gain in altitude of the current stop from the previous stop. More formally,
gain[i] = (altitude of stop [i + 1]) - (altitude of stop [i])
Your task is to find the stop with the highest altitude and return its altitude.
/*Example*/
gain = [-5, 1, 5, 0, -7]
expected output = 1
explanation:- The altitudes are [0, -5, -4, 1, 1, -6]. The highest altitude is 1.
Solution:
The solution is pretty simple. We will traverse over each gain. We will find the altitude of the current stop using the gain and the altitude of the previous stop (calculated in the previous iteration). We will check it with the maximum altitude we got so far.
/**
* @param {number[]} gain
* @return {number}
*/
function getHighestAltitude(gain) {
let max = 0
let currAltitude = 0
for (const g of gain) {
currAltitude += g
max = Math.max(max, currAltitude)
}
return max
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
11. What is the diagonal sum?
This interview question concentrates on the developer's ability to work with JavaScript functions.
You are given a square matrix mat. Your task is to calculate the sum of all the diagonal elements of the array.
/*Example*/
Given mat =
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
expected output = 25 (1 + 5 + 9 + 3 + 7)
Given mat =
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]
expected output = 8
Solution:
The solution is pretty simple. We will iterate over all the matrix diagonal elements and add them to the sum. One thing to note is that, when the matrix is of odd dimension, the middle diagonal element is counted twice. So we will subtract at last.
/**
* @param {number[][]} mat
* @return {number}
*/
function diagonalSum(mat) {
let sum = 0
const n = mat.length
for (let i = 0; i < n; i++) {
sum += mat[i][i]
sum += mat[i][n - i - 1]
}
// if the matrix is of odd size
// subtract the middle element
if (n % 2 === 1) {
const half = Math.floor(n / 2)
sum -= mat[half][half]
}
return sum
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
12. What is the maximum number of ice cream bars?
This interview question tests the developer's skills with JavaScript arrays and loops.
You have coins number of coins. There is an ice cream store nearby. There are 'n' ice-cream bars in the store. The cost of ith ice-cream bar is given costs[i]. Your task is to determine the maximum number of ice-cream bars that you can buy.
/*Example*/
coins = 7 costs = [1, 3, 2, 4, 1]
expected output = 4
explanations:- you can buy ice cream bars at index 0, 1, 2 and 4
Solution:
The solution is pretty easy. We can sort the array in ascending order. Then we will iterate over each cost and will check if we can buy this ice cream. If yes, we will buy it, decrease the coins left, and will check the next ice cream. If not, we can not buy this and the ice-creams after this cream too. So we will return it.
/**
* @param {number[]} costs
* @param {number} coins
* @return {number}
*/
function maximumIceCreams(costs, coins) {
costs.sort((a, b) => a - b)
for (let i = 0; i < costs.length; i++) {
// if we can by ith ice cream bar, buy it
// and update the number of coins left
if (coins >= costs[i]) {
coins -= costs[i]
} else {
// if we can not but this bar, we also can
// not buy other bars after it, because they
// are sorted already
return i
}
}
// if we can buy all the bars
return costs.length
}
Time complexity- O(n logn)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
13. Find squares of a sorted array.
This question tests the developer's ability to work with JavaScript sort and pointers.
You are given a sorted array of integers in ascending order. Your task is to find the square of each integer and return them in a sorted array.
/*Example*/
Given array = [1, 2, 3, 4, 5]
expected output = [1, 4, 9, 16, 25]
Given array = [-4, -1, 0, 3, 10]
expected output = [0, 1, 9, 16, 100]
Solution:
Approach I (using sort):
This is the easiest approach. We will create a new result array. We will iterate over the given numbers. For each number, we will push its square to the result. After that, we will sort the result array.
/**
* @param {number[]} nums
* @return {number[]}
*/
function getSortedSquares(nums) {
const result = []
for (const num of nums) {
result.push(num * num)
}
result.sort((a, b) => a - b)
return result
}
Time complexity- O(n logn)
Space complexity- O(1)
Approach II (two pointers):
In this approach, we will find the index of the smallest non-negative number (numbers greater than or equal to zero). Let the index is idx. Then we will have two pointers i and j (pointers mean indices of the array here). The i will run on all non-negative numbers (from idx to last of the array) and j will run on the negative numbers in the backward direction (from idx - 1 to 0). We will compare numbers at indices i and j, and will push the square of the smaller number and advance its pointer. For example, for given array [-4, -1, 0, 3, 10],
-4 -1 0 3 10
|
idx
-4 -1 0 3 10
| |
j i result = []
-4 -1 0 3 10
| |
j i result = [0]
-4 -1 0 3 10
| |
j i result = [0, 1]
-4 -1 0 3 10
| |
j i result = [0, 1, 9]
-4 -1 0 3 10
| |
j (value of j is -1 here) i result = [0, 1, 9, 16]
-4 -1 0 3 10
| |
j (value of j is -1 here) i result = [0, 1, 9, 16, 100]
When the value of j is -1, it means we have traversed all negative numbers and pushed their squares in the correct order. In this case nums[j] = num[-1] = undefined. So we put a default value Infinity using the ternary operator.
When the value of i is 5 (length of the array), it means we have traversed all non-negative numbers and pushed their squares in the correct order. In this case nums[i] = num[5] = undefined. So we put a default value Infinity using the ternary operator.
/**
* @param {number[]} nums
* @return {number[]}
*/
function getSortedSquares(nums) {
const result = []
let idx
for (idx = 0; idx < nums.length; idx++) {
if (nums[idx] >= 0) break
}
let i = idx
let j = i - 1
while(j >= 0 || i < nums.length) {
const numI = nums[i] === undefined ? Infinity : nums[i]
const numJ = nums[j] === undefined ? Infinity : nums[j]
if (numI < Math.abs(numJ)) {
result.push(numI * numI)
i++
} else {
result.push(numJ * numJ)
j--
}
}
return result
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021