js coding question

// https://github.com/TanvirHasanPrince/Coderbyte-Challenge-Library-Solutions
// https://youtu.be/v7JdUO8LH9M?si=3GB2WNd7z2PYx2LJ

function findLongestWordFromString(str){
    if(str.trim().length === 0) return
    let obj={}
    str.split(' ').forEach((word)=>{
        obj[word] = word.length
    })
    // console.log(obj)
    const maxKey = Object.keys(obj).reduce((a, b) => obj[a] > obj[b] ? a : b);
    console.log(maxKey);
}

function findLongestWordFromString(str){
    if(str.trim().length === 0) return
    let sortedWords = str.split(' ').sort((a,b)=>b.length-a.length)
    console.log(sortedWords[0]); // katemaliveli
}

function findLongestWordFromString(str){
    if(str.trim().length === 0) return
    let sortedWords = str.split(' ').reduce((acc,current)=> current.length > acc.length ? current : acc  ,'')
    console.log(sortedWords); // katemaliveli
}

findLongestWordFromString('hi my name is gokul and i live in katemaliveli kalyan')
function hashtagFirstLetterCapitalize(str){
    if(str.trim().length === 0) return
    let arr = str.split(' ')
    let newArr=arr.map((ele)=>ele.charAt(0).toUpperCase()+ele.slice(1))
    console.log(`#${newArr.join('')}`); // #HiMyNameIsGokulAndILiveInKatemaliveliKalyan
}
hashtagFirstLetterCapitalize('hi my name is gokul and i live in katemaliveli kalyan')
function countLetterInWord(str,letter){
    if(str.trim().length === 0) return
    let count =0
    for(let l of str.toLowerCase()){
        if(l === letter.toLowerCase()) count+=1
        // else console.log('leter is not found in word given')
    } 
    console.log(count) // 5
}
countLetterInWord('mIssingiii', 'i')
function SpacesAndComma(str){
   let removedComma = str.toLowerCase().split(', ').join('')
   let removedSpace = removedComma.split(' ').join('')
   return removedSpace
}

function isPalindrome(str){
    let customStr = SpacesAndComma(str)
    let copyCustomStr = customStr
    if(customStr === copyCustomStr.split('').reverse().join('')) console.log('yes')
    else  console.log('false')
}

isPalindrome('raceca')
function findMax(arr){
    let max =0
   if(Array.isArray(arr)){
       arr.forEach((ele)=>{
           if(ele>max) max = ele
       })
   }else{
       console.log('not an array')
   }
   console.log(max)
}

findMax([4])

Certainly! Here are the solutions for each of the listed coding interview questions:

Arrays:

  1. Remove duplicate elements from an array:
function removeDuplicates(nums) {
    return [...new Set(nums)];
}
// or
function removeDuplicates(nums) {
    const uniqueNums = [];
    for (const num of nums) {
        if (!uniqueNums.includes(num)) {
            uniqueNums.push(num);
        }
    }
    return uniqueNums;
}

function removeDuplicates(nums) {
    const uniqueNums = [];
    for (const num of nums) {
        if (uniqueNums.indexOf(num) === -1) {
            uniqueNums.push(num);
        }
    }
    return uniqueNums;
}

function removeDuplicates(nums) {
    return nums.filter((num, index) => nums.indexOf(num) === index);
}

function removeDuplicates(nums) {
    const map = new Map();
    nums.forEach(num => map.set(num, num));
    return Array.from(map.values());
}

function removeDuplicates(nums) {
    return nums.reduce((uniqueNums, num) => {
        if (!uniqueNums.includes(num)) {
            uniqueNums.push(num);
        }
        return uniqueNums;
    }, []);
}
  1. Find the maximum and minimum elements in an array:
function findMinMax(nums) {
    const max = Math.max(...nums);
    const min = Math.min(...nums);
    return { max, min };
}
  1. Reverse an array:
function reverseArray(nums) {
    return nums.reverse();
}
  1. Check if two arrays are equal:
function arraysAreEqual(arr1, arr2) {
    return JSON.stringify(arr1) === JSON.stringify(arr2);
}
  1. Find the intersection of two arrays:
function arrayIntersection(nums1, nums2) {
    return nums1.filter(num => nums2.includes(num));
}
  1. Find the union of two arrays:
function arrayUnion(nums1, nums2) {
    return [...new Set([...nums1, ...nums2])];
}
  1. Rotate an array to the right by k steps:
function rotateArray(nums, k) {
    const n = nums.length;
    const rotated = [];
    for (let i = 0; i < n; i++) {
        rotated[(i + k) % n] = nums[i];
    }
    return rotated;
}
  1. Implement a stack using an array:
class Stack {
    constructor() {
        this.items = [];
    }
    push(element) {
        this.items.push(element);
    }
    pop() {
        return this.items.pop();
    }
    peek() {
        return this.items[this.items.length - 1];
    }
    isEmpty() {
        return this.items.length === 0;
    }
    size() {
        return this.items.length;
    }
}
  1. Implement a queue using an array:
class Queue {
    constructor() {
        this.items = [];
    }
    enqueue(element) {
        this.items.push(element);
    }
    dequeue() {
        return this.items.shift();
    }
    front() {
        return this.items[0];
    }
    isEmpty() {
        return this.items.length === 0;
    }
    size() {
        return this.items.length;
    }
}
  1. Sort an array of 0s, 1s, and 2s (Dutch National Flag problem):
function sortColors(nums) {
    let low = 0, high = nums.length - 1, i = 0;
    while (i <= high) {
        if (nums[i] === 0) {
            [nums[i], nums[low]] = [nums[low], nums[i]];
            low++;
            i++;
        } else if (nums[i] === 2) {
            [nums[i], nums[high]] = [nums[high], nums[i]];
            high--;
        } else {
            i++;
        }
    }
    return nums;
}
  1. Find the majority element in an array:
function majorityElement(nums) {
    const counts = {};
    for (const num of nums) {
        counts[num] = (counts[num] || 0) + 1;
        if (counts[num] > nums.length / 2) {
            return num;
        }
    }
}
  1. Find the missing number in an array of integers from 1 to n:
function missingNumber(nums) {
    const n = nums.length;
    const totalSum = (n * (n + 1)) / 2;
    const actualSum = nums.reduce((acc, curr) => acc + curr, 0);
    return totalSum - actualSum;
}
  1. Given an array of integers, return indices of the two numbers such that they add up to a specific target:
function twoSum(nums, target) {
    const numMap = new Map();
    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];
        if (numMap.has(complement)) {
            return [numMap.get(complement), i];
        }
        numMap.set(nums[i], i);
    }
}
  1. Remove a specific element from an array:
function removeElement(nums, val) {
    return nums.filter(num => num !== val);
}
  1. Implement binary search in a sorted array:
function binarySearch(nums, target) {
    let left = 0;
    let right = nums.length - 1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] === target) {
            return mid;
        } else if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;
}

Certainly! Here are the solutions for the string-related questions:

  1. Reverse a string:
function reverseString(str) {
    return str.split('').reverse().join('');
}
  1. Check if a string is a palindrome:
function isPalindrome(str) {
    const reversed = str.split('').reverse().join('');
    return str === reversed;
}
  1. Find the longest palindrome substring in a string:
function longestPalindromeSubstring(str) {
    let longest = '';
    for (let i = 0; i < str.length; i++) {
        for (let j = i + 1; j <= str.length; j++) {
            const substring = str.slice(i, j);
            if (isPalindrome(substring) && substring.length > longest.length) {
                longest = substring;
            }
        }
    }
    return longest;
}
  1. Remove spaces from a string:
function removeSpaces(str) {
    return str.replace(/\s/g, '');
}
  1. Check if two strings are anagrams:
function areAnagrams(str1, str2) {
    const sortedStr1 = str1.split('').sort().join('');
    const sortedStr2 = str2.split('').sort().join('');
    return sortedStr1 === sortedStr2;
}
  1. Count the occurrences of a character in a string:
function countOccurrences(str, char) {
    return str.split('').reduce((count, currentChar) => {
        return currentChar === char ? count + 1 : count;
    }, 0);
}
  1. Check if a string contains only digits:
function containsOnlyDigits(str) {
    return /^\d+$/.test(str);
}
  1. Capitalize the first letter of each word in a string:
function capitalizeFirstLetter(str) {
    return str.replace(/\b\w/g, char => char.toUpperCase());
}
  1. Check if a string is a valid IPv4 address:
function isValidIPv4(str) {
    const pattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    return pattern.test(str);
}
  1. Remove vowels from a string:
function removeVowels(str) {
    return str.replace(/[aeiouAEIOU]/g, '');
}

Here are the solutions for the object-related questions:

  1. Check if a given key exists in an object:
function keyExists(obj, key) {
    return obj.hasOwnProperty(key);
}
  1. Merge two objects:
function mergeObjects(obj1, obj2) {
    return { ...obj1, ...obj2 };
}
  1. Deep clone an object:
function deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}
  1. Convert an object to an array of key-value pairs:
function objectToArray(obj) {
    return Object.entries(obj);
}
  1. Find the most frequent element in an array of objects:
function mostFrequentElement(arr) {
    const counts = {};
    arr.forEach(obj => {
        const key = JSON.stringify(obj);
        counts[key] = (counts[key] || 0) + 1;
    });
    let maxCount = 0;
    let mostFrequent;
    for (const key in counts) {
        if (counts[key] > maxCount) {
            maxCount = counts[key];
            mostFrequent = key;
        }
    }
    return JSON.parse(mostFrequent);
}
  1. Implement a cache with a limited capacity using an object:
class LRUCache {
    constructor(capacity) {
        this.capacity = capacity;
        this.cache = {};
        this.order = [];
    }
    get(key) {
        if (this.cache[key] !== undefined) {
            const index = this.order.indexOf(key);
            this.order.splice(index, 1);
            this.order.unshift(key);
            return this.cache[key];
        } else {
            return -1;
        }
    }
    put(key, value) {
        if (this.cache[key] === undefined) {
            if (this.order.length === this.capacity) {
                const leastUsed = this.order.pop();
                delete this.cache[leastUsed];
            }
        } else {
            const index = this.order.indexOf(key);
            this.order.splice(index, 1);
        }
        this.cache[key] = value;
        this.order.unshift(key);
    }
}
  1. Check if two objects have the same structure and values:
function objectsAreEqual(obj1, obj2) {
    return JSON.stringify(obj1) === JSON.stringify(obj2);
}
  1. Flatten an object (convert nested objects into a flat object):
function flattenObject(obj, prefix = '') {
    return Object.keys(obj).reduce((acc, key) => {
        const propName = prefix ? `${prefix}.${key}` : key;
        if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
            Object.assign(acc, flattenObject(obj[key], propName));
        } else {
            acc[propName] = obj[key];
        }
        return acc;
    }, {});
}
  1. Check if an object is empty:
function isEmptyObject(obj) {
    return Object.keys(obj).length === 0;
}
  1. Implement a function to calculate the factorial of a number using memoization:
function factorialMemoization() {
    const memo = {};
    return function calculateFactorial(num) {
        if (num === 0 || num === 1) return 1;
        if (memo[num]) return memo[num];
        memo[num] = num * calculateFactorial(num - 1);
        return memo[num];
    };
}

const memoizedFactorial = factorialMemoization();

Here are the solutions for the combining data structures-related questions:

  1. Find the longest substring without repeating characters:
function longestSubstringWithoutRepeating(s) {
    let longest = '';
    let current = '';
    for (let char of s) {
        const index = current.indexOf(char);
        if (index === -1) {
            current += char;
            if (current.length > longest.length) {
                longest = current;
            }
        } else {
            current = current.slice(index + 1) + char;
        }
    }
    return longest.length;
}
  1. Find the first non-repeating character in a string:
function firstNonRepeatingCharacter(s) {
    const counts = {};
    for (const char of s) {
        counts[char] = (counts[char] || 0) + 1;
    }
    for (const char of s) {
        if (counts[char] === 1) {
            return char;
        }
    }
    return null;
}
  1. Group anagrams together in an array of strings:
function groupAnagrams(strs) {
    const map = {};
    for (const str of strs) {
        const sorted = str.split('').sort().join('');
        if (!map[sorted]) map[sorted] = [];
        map[sorted].push(str);
    }
    return Object.values(map);
}
  1. Implement a LRU (Least Recently Used) cache using objects and arrays:
class LRUCache {
    constructor(capacity) {
        this.capacity = capacity;
        this.cache = {};
        this.order = [];
    }
    get(key) {
        if (this.cache[key] !== undefined) {
            const index = this.order.indexOf(key);
            this.order.splice(index, 1);
            this.order.unshift(key);
            return this.cache[key];
        } else {
            return -1;
        }
    }
    put(key, value) {
        if (this.cache[key] === undefined) {
            if (this.order.length === this.capacity) {
                const leastUsed = this.order.pop();
                delete this.cache[leastUsed];
            }
        } else {
            const index = this.order.indexOf(key);
            this.order.splice(index, 1);
        }
        this.cache[key] = value;
        this.order.unshift(key);
    }
}
  1. Implement a priority queue using objects:
class PriorityQueue {
    constructor() {
        this.queue = [];
    }
    enqueue(element, priority) {
        this.queue.push({ element, priority });
        this.sort();
    }
    dequeue() {
        return this.queue.shift().element;
    }
    sort() {
        this.queue.sort((a, b) => a.priority - b.priority);
    }
    isEmpty() {
        return this.queue.length === 0;
    }
}
  1. Find the longest common prefix among an array of strings:
function longestCommonPrefix(strs) {
    if (strs.length === 0) return '';
    let prefix = strs[0];
    for (let i = 1; i < strs.length; i++) {
        while (strs[i].indexOf(prefix) !== 0) {
            prefix = prefix.substring(0, prefix.length - 1);
            if (prefix === '') return '';
        }
    }
    return prefix;
}
  1. Determine if there is a path in a matrix from top-left to bottom-right corner:
function hasPath(matrix) {
    const rows = matrix.length;
    const cols = matrix[0].length;
    const visited = Array.from({ length: rows }, () => Array(cols).fill(false));
    const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]];

    function dfs(row, col) {
        if (row < 0 || row >= rows || col < 0 || col >= cols || matrix[row][col] === 0 || visited[row][col]) {
            return false;
        }
        if (row === rows - 1 && col === cols - 1) {
            return true;
        }
        visited[row][col] = true;
        for (const [dx, dy] of directions) {
            if (dfs(row + dx, col + dy)) {
                return true;
            }
        }
        return false;
    }

    return dfs(0, 0);
}
  1. Serialize and deserialize a binary tree:
class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

function serialize(root) {
    if (!root) return 'null';
    return root.val + ',' + serialize(root.left) + ',' + serialize(root.right);
}

function deserialize(data) {
    const values = data.split(',');
    let index = 0;

    function buildTree() {
        if (values[index] === 'null') {
            index++;
            return null;
        }
        const node = new TreeNode(parseInt(values[index++]));
        node.left = buildTree();
        node.right = buildTree();
        return node;
    }

    return buildTree();
}
  1. Count the number of islands in a matrix:
function numIslands(grid) {
    if (!grid || grid.length === 0) return 0;

    const rows = grid.length;
    const cols = grid[0].length;
    let count = 0;

    function dfs(row, col) {
        if (row < 0 || col < 0 || row >= rows || col >= cols || grid[row][col] === '0') {
            return;
        }
        grid[row][col] = '0'; // Marking as visited
        dfs(row - 1, col);
        dfs(row + 1, col);
        dfs(row, col - 1);
        dfs(row, col + 1);
    }

    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (grid[i][j] === '1') {
                count++;
                dfs(i, j);
            }
        }
    }

    return count;
}
  1. Implement a trie (prefix tree) data structure:
class TrieNode {
    constructor() {
        this.children = {};
        this.isEndOfWord = false;
    }
}

class Trie {
    constructor() {
        this.root = new TrieNode();
    }
    insert(word) {
        let node = this.root;
        for (const char of word) {
            if (!node.children[char]) {
                node.children[char] = new TrieNode();
            }
            node = node.children[char];
        }
        node.isEndOfWord = true;
    }
    search(word) {
        let node = this.root;
        for (const char of word) {
            if (!node.children[char]) {
                return false;
            }
            node = node.children[char];
        }
        return node.isEndOfWord;
    }
    startsWith(prefix) {
        let node = this.root;
        for (const char of prefix) {
            if (!node.children[char

]) {
                return false;
            }
            node = node.children[char];
        }
        return true;
    }
}
  1. Convert a binary search tree to a sorted doubly linked list:
class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

function treeToDoublyList(root) {
    if (!root) return null;

    let prev = null;
    let head = null;

    function inorder(node) {
        if (!node) return;
        inorder(node.left);
        if (!head) head = node;
        if (prev) {
            prev.right = node;
            node.left = prev;
        }
        prev = node;
        inorder(node.right);
    }

    inorder(root);

    head.left = prev;
    prev.right = head;

    return head;
}
  1. Find the kth largest element in an unsorted array:
function findKthLargest(nums, k) {
    nums.sort((a, b) => b - a);
    return nums[k - 1];
}
  1. Merge k sorted arrays:
function mergeKSortedArrays(arrays) {
    return arrays.reduce((acc, arr) => acc.concat(arr), []).sort((a, b) => a - b);
}
  1. Determine if a Sudoku is valid:
function isValidSudoku(board) {
    const rows = Array.from({ length: 9 }, () => new Set());
    const cols = Array.from({ length: 9 }, () => new Set());
    const boxes = Array.from({ length: 9 }, () => new Set());

    for (let i = 0; i < 9; i++) {
        for (let j = 0; j < 9; j++) {
            const num = board[i][j];
            if (num === '.') continue;

            if (rows[i].has(num) || cols[j].has(num) || boxes[Math.floor(i / 3) * 3 + Math.floor(j / 3)].has(num)) {
                return false;
            }

            rows[i].add(num);
            cols[j].add(num);
            boxes[Math.floor(i / 3) * 3 + Math.floor(j / 3)].add(num);
        }
    }

    return true;
}
  1. Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary):
function insertInterval(intervals, newInterval) {
    const result = [];
    let i = 0;
    while (i < intervals.length && intervals[i][1] < newInterval[0]) {
        result.push(intervals[i]);
        i++;
    }
    while (i < intervals.length && intervals[i][0] <= newInterval[1]) {
        newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
        newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
        i++;
    }
    result.push(newInterval);
    while (i < intervals.length) {
        result.push(intervals[i]);
        i++;
    }
    return result;
}

Certainly! Here are some basic math-related coding questions along with their solutions in JavaScript:

  1. Factorial of a number:
function factorial(n) {
    if (n === 0 || n === 1) {
        return 1;
    }
    return n * factorial(n - 1);
}
  1. Prime number check:
function isPrime(n) {
    if (n <= 1) {
        return false;
    }
    for (let i = 2; i <= Math.sqrt(n); i++) {
        if (n % i === 0) {
            return false;
        }
    }
    return true;
}
  1. Check if a number is even or odd:
function isEven(n) {
    return n % 2 === 0;
}

function isOdd(n) {
    return !isEven(n);
}
  1. Check if a number is a perfect square:
function isPerfectSquare(n) {
    const sqrt = Math.sqrt(n);
    return sqrt === Math.floor(sqrt);
}
  1. Greatest Common Divisor (GCD) of two numbers:
function gcd(a, b) {
    if (b === 0) {
        return a;
    }
    return gcd(b, a % b);
}
  1. Least Common Multiple (LCM) of two numbers:
function lcm(a, b) {
    return (a * b) / gcd(a, b);
}
  1. Sum of digits of a number:
function sumOfDigits(n) {
    let sum = 0;
    while (n > 0) {
        sum += n % 10;
        n = Math.floor(n / 10);
    }
    return sum;
}
  1. Reverse digits of a number:
function reverseNumber(n) {
    let reversed = 0;
    while (n > 0) {
        reversed = reversed * 10 + (n % 10);
        n = Math.floor(n / 10);
    }
    return reversed;
}
  1. Leap Year or not

     function isLeapYear(year) {
         // Leap year condition:
         // 1. If the year is divisible by 4
         // 2. If the year is not divisible by 100, except when it's divisible by 400
         return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
     }