# Top JavaScript Coding Interview Questions And Answers (2024)

Below is the steps and function to print character and its occurences. Steps to get the solution: 1. Create an object named 'exists', which can be used as a hashMap in JavaScript 2. Loop over the items of string, add characters as key exists object with value as 1 which are not already present. 3. If character key is already present in exists object, increment the value for that key by 1. 4.Loop over the exists object and print the occurences using 'exists[item]' syntax, where 'item' is current item in exists object iteration. Code:
``````
const countOccurences=(str)=> {
let exists={}
for (let i= 0; i < str.length; i++) {
if(exists[str[i]]) {
exists[str[i]]+=1;
}
else {
exists[str[i]]=1;
}
}
for(let item in exists) {
console.log("occurences of "+item+" is :"+exists[item])
}
}
countOccurences('malayalam')

// output
occurences of m is :2
occurences of a is :4
occurences of l is :2
occurences of y is :1
```
```
Steps to get the solution: 1. We have take two pointer,one starting from start of the string and second one from end of string 2. Loop first pointer from 0th index to middle of the string and second pointer from end to 0th index 3. Compare value at first pointer's index with value at second pointer's index, when the values are not same , set Flag as 1, which means string is not a palindrome 4. If flag is 0 and we come out of the loop, it means string values till the middle indexe's are same, so they are palindrome. Code e.g
``````
function palindrome(str)
{
var flag=0;
for(var i=0,j=str.length-1;i<(str.length/2)&&j>0; i++,j--)
{
if(str[i]!=str[j])
flag=1;

}
if(flag==1) {
console.log("string "+str+" is not a palindrome");
} else {
console.log("string "+str+" is a palindrome");
}
}
palindrome("malayalam"); //string malayalam is a palindrome
palindrome("malaam"); //string malaam is not a palindrome
```
```
Time complexity :- As there is only one for loop ,the time complexity is O(n)
Steps to get the solution: 1. Here we can use summation of first N natural number i.e n(n+1)/2 2. Loop over the items of array and add the items value in Sum variable 3. Now we have current sum in 'sum' variable and sum of all numbers can be found by using n(n+1)/2 4. We can find the missing number by subtracting 'sum' variable value from summation of n natural numbers. Code snippet:
``````
/*---------code -----------*/
function returnMissingNumber(arr) {
let n=arr.length+1;
let sum=0;
for(let item of arr) {
sum+=item;
}
x=(n*(n+1)/2)-sum;
return x;
}
let arr=[1,2,3,5];
console.log(returnMissingNumber(arr));  //4
```
```
Steps to get the solution: 1. Create a variable named start with value is 0 for start Index. 2. Loop over the string until we find a space i.e ' ' 3. Reverse the string starting from start value till the index where we found the space i.e ' ' and store the value in result string. 4. Once the loop is over, we will have all words reversed in result string. Code snippet:
``````
/*------------code---------*/
function reverse(str) {
let result="";
for(let i=str.length-1;i>=0;i--) {
result+=str[i];
}
return result;
}
function reverseAllWords(str) {
let result="";
let start=0,end;
for (let i=0;i<str.length;i++)) {
if(str[i]==" ") {
result+=reverse(str.slice(start,i))+str[i];
start=result.length;
}
else if(i==str.length-1){
result+=reverse(str.slice(start,i+1));
}
}
return result;
}

console.log(reverseAllWords('how are you')) // woh era uoy
```
```
Steps to get the solution: 1) Count the number of 0's using 'for' loop and store it in a variable e.g zeroCount. 2) Now we know that remaining items will be 1's. 3) Run 'for' loop till zeroCount, and replace the array items with 0. 4) Run one more 'for' loop to fill the remaining items with 1. Below is the code to segregate 0s and 1s in an array:
``````
function arrangeNumber(arr) {
let zeroCount =0;
for(let i=0;i < arr.length;i++) {
if(arr[i]==0) {
zeroCount += 1;
}
}

for(let i=0;i < zeroCount;i++) {
arr[i] = 0;
}

for(let i=zeroCount;i < arr.length;i++) {
arr[i] = 1;
}

return arr;
}

const nums = [1,0,0,1,0,1,1];
const finalres= arrangeNumber(nums);
console.log('final result', finalres); // output : [0,0,0,1,1,1,1]
```
```
Time complexity and Space complexity:
``````
Time complexity :- O(n) // as we dont have nested for loops
Space complexity: O(1) // as we are only storing values in variable and not storing anything in array etc
```
```
An anagram of a string is another string that contains the same characters, only the order of characters can be different. So here we have to check whether rearranging string characters can make the string as palindrome or not Steps to get the solution : 1.Loop over the characters of string and keep the count in exists Object 2.Check how any characters have odd count using variable oddCount 3.If string length is even and oddCount is 0, then it can be made as palindrome e.g maam 4.If string length is odd and oddCount is 1, then it can be made a palidrome e.g madam
``````
function checkPalindromeForAnagram(str) {
const exists={};
let oddCount=0;
for(let i=0;i<str.length;i++) {
if(exists[str[i]]) {
exists[str[i]]++;
}
else {
exists[str[i]]=1;
}
}

for(let key in exists) {
if(exists[key]%2!==0) {
oddCount++;
}
}
if((str.length%2==0 && oddCount ==0) || (str.length%2!==0 && oddCount == 1)) {
return true;
}
else {
return false;
}
}
let str2= 'caat';
let result = checkPalindromeForAnagram(str);
let result2 = checkPalindromeForAnagram(str2)
console.log('result', result); //result will be true as rearranging string 'adamm' can be made as madam which is a palindrome
console.log('result2', result2); //result will be false as rearranging string 'caat' cant be made as palindrome
```
```
Steps to get the solution: 1. Take two objects existsStr1 and existsStr2 to store count of characters of two strings 2 .Loop over the characters of both the strings and keep the count in existsStr1 Object for first string and existsStr2 for second string. 3. Loop over existsStr1 using for in loop and check if the count of current character in existsStr1 and existsStr2 are same or not. 4. If the count of current character is not same, it means strings are not anagram of each other 5. If the count for all the characters in existsStr1 and existsStr2 is same, it means strings are anagram of each other. Code :
``````
function anagram(str1, str2) {
let existsStr1 = {};
let existsStr2 ={};

for(let i=0;i<str1.length;i++) {
if(existsStr1[str1[i]]) {
existsStr1[str1[i]]++;
} else {
existsStr1[str1[i]]=1;
}
}

for(let i=0;i<str2.length;i++) {
if(existsStr2[str2[i]]) {
existsStr2[str2[i]]++;
} else {
existsStr2[str2[i]]=1;
}
}

for(let key in existsStr1) {
if(existsStr1[key] != existsStr2[key]) {
return false;
}
}
return true;
}

let str1 = 'test'
let str2 = 'estt'
let result = anagram(str1, str2);
console.log('result', result); // true
```
```
Steps to get the solution: 1.Create an object named objMap and set empty data 2. Loop over array items and check objMap contains the category or not 3.If objMap doesnt contain the current category, add category name to objMap as key and assign an empty array 4.If objMap already have the category, append the category details into the array. Code :
``````
function groupByCategory(arr) {
const objMap={};
arr.forEach(data => {
if(objMap[data.category]) {
objMap[data.category].push(data);
} else {
objMap[data.category] = [data];
}
});
return objMap;
}

const products = [
{ name: 'apples', category: 'fruits' },
{ name: 'oranges', category: 'fruits' },
{ name: 'potatoes', category: 'vegetables' }
];

let result = groupByCategory(products);
console.log('result', result);

/* ---output ----

const products = {
fruits: [
{ name: 'apples', category: 'fruits' },
{ name: 'oranges', category: 'fruits' },
],
vegetables: [
{ name: 'potatoes', category: 'vegetables' }]

};
*/
```
```
Steps to get the solution: 1. Create two variables 'currentCount' and 'maxCount' and initialise them with 0 2. Loop over array items 3. if array item value is 1 then increment currentCount 4. Set maxCount as maximum of currentCount and maxCount 5. if array item value is not 1, then make currentCount as 0 6. return maxCount after the end of loop Code :
``````
function maxCount(arr) {
let maxCount = 0;
let currentCount=0;
for(let i=0;i<arr.length;i++) {
if(arr[i]==1) {
currentCount += 1;
maxCount = Math.max(currentCount, maxCount);
}
else {
currentCount = 0;
}
}
return maxCount;
}

let arr = [1,0,0,1,1,1,0,0,1,0,1,1,0,0,1];
let result = maxCount(arr);
console.log('result', result); //output:  3
```
```
Steps to get the solution: 1. We have to take exit condition considering that factorial of 0 or 1 is 1 2. In each recursive call we will return num*factorial(num-1) as factorial of number for e.g 3 is 3*2*1 3. In first pass 3*factorial(2) is returned 4. In next pass we will have 3*2*factorial(1) 5. As we know factorial of 1 is 1, so we will get 3*2*1 i.e 6 Code:
``````
function factorial(num) {
if(num ==0 || num==1) {
return 1;
}
return num*factorial(num-1);
}

let result = factorial(3)
console.log(result) // output:  6
```
```