JS PROGRAMMING QUESTIONS
const array = [35, 34, 4, 1];
const bubbleSort = (array) => {
let length = array.length;
let swapping = true;
while (swapping) {
swapping = false;
let i = 0;
while (i < length) {
if (array[i] > array[i + 1]) {
let temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
swapping = true;
}
i++
}
length--;
}
return array;
}
const list = [752, 600, 999, 1, 15];
const target = 615;
// [0 , 1]
const twoSum = (list, target) => {
let heapMap = {};
for (index = 0; index < list.length; index++) {
let difference = target - list[index];
if (heapMap.hasOwnProperty(difference)) {
return [heapMap[difference], index]
}
heapMap[list[index]] = index;
}
}
const missingNumberList = [3, 2, 4, 5];
const findMissingNumber = (list) => {
const length = list.length + 1;
const missingNumberListUnique = new Set([...missingNumberList]);
for (let i = 1; i < length; i++) {
if (!missingNumberListUnique.has(i)) {
return i;
}
}
}
// console.log(findMissingNumber(missingNumberList) , 'RESULT');
const input = "Stephen";
const reverseString = (input) => {
return input.split('').reverse().join('')
}
// console.log(reverseString(input)); // nehpetS
const checkPalindrome = (string) => {
const actualString = string.replace(/[\W_]/g, '').toLowerCase();
const reversedString = actualString.split('').reverse().join('');
return actualString === reversedString
}
// console.log(checkPalindrome('A man, a plan, a canal, Panama'));
function removeDuplicates(array) {
return [...new Set(array)]
}
// console.log(removeDuplicates([3,54,66,432,2,2,2,5]));
function checkAnagram(text1, text2) {
const normalizeText = (string) => string.replace(/[\W_]/g, '').split('').sort().join('');
return normalizeText(text1) === normalizeText(text2)
}
// console.log(checkAnagram('listen', 'silent'));
// Flatten a Deeply Nested Array
// This function flattens an array that may have nested arrays at multiple levels.
function flattenArray(array) {
return array.reduce((acc, val) => {
return (Array.isArray(val)) ? acc.concat(flattenArray(val)) : acc.concat(val)
}, [])
}
// console.log(flattenArray([1, [2, [3, [4]], 5]])); // [1, 2, 3, 4, 5]
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj
}
if (Array.isArray(obj)) return obj.map((e) => deepClone(e));
let clonedObject = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObject[key] = deepClone(obj[key]);
}
}
return clonedObject;
}
const original = {
name: "John",
address: {
city: "New York",
zip: "10001"
},
hobbies: ["reading", "sports"]
};
console.log(JSON.parse(JSON.stringify(original))); // Deep Clone Using JSON.parse() and JSON.stringify()
const clone = deepClone(original);
clone.address.city = "San Francisco";
clone.hobbies.push("music");
console.log(clone, 'clone');
console.log(original, 'original');
const findLargestNumber = (array) => {
if (array.length === 0) throw Error('Array Should not be Empty');
let largest = array[0];
for (let index = 0; index < array.length; index++) {
if (array[index] > largest) {
largest = array[index];
}
}
return largest;
}
console.log(findLargestNumber([4,7,8,10,33,100,35,1000])); // 1000
// The Fibonacci sequence is the series of numbers where each number is the sum of the two preceding numbers.
// For example, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610
const fibonacciNumber = (n) => {
if (n < 0) {
throw Error('Non Integer');
}
let a = 0;
let b = 1;
for (let index = 0; index < n; index++) {
let temp = a;
a = b;
b = temp + b
}
return a
}
console.log(fibonacciNumber(10))
function mergeSortedArrays(arr1, arr2) {
const mergedArray = [];
arr1.sort((a, b) => a - b);
arr2.sort((a, b) => a - b);
let i = 0;
let j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
mergedArray.push(arr1[i]);
i++
} else {
mergedArray.push(arr2[j]);
j++
}
}
while (i < arr1.length) {
mergedArray.push(arr1[i]);
i++;
}
while (j < arr2.length) {
mergedArray.push(arr2[j]);
j++;
}
return mergedArray;
}
const array1 = [1, 3, 5, 7,3];
const array2 = [2, 4, 6, 80];
const merged = mergeSortedArrays(array1, array2);
function longestCommonPrefix(strings) {
if (strings.length === 0) return '';
let prefix = strings[0];
for (let index = 0; index < strings.length; index++) {
console.log(strings[index] , prefix);
while (strings[index].indexOf(prefix) !== 0) {
prefix = prefix.substring(0 , prefix.length - 1);
if (prefix === '') return ''
}
}
return prefix
}
const strings = ["flower", "flow", "flight"];
console.log(longestCommonPrefix(strings)); //fl
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
console.log(reverseString('hello')); // 'olleh'
// Find the Second Largest Number in an Array
// Write a function that finds the second largest number in a given array.
function secondLargest(arr) {
if (arr.length < 2) return null;
let first = -Infinity, second = -Infinity;
for (let num of arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num < first) {
second = num;
}
}
return second;
}
console.log(secondLargest([1, 3, 7, 4, 2])); // 4
function findLargest(arr) {
return Math.max(...arr);
}
console.log(findLargest([1, 2, 3, 4, 5])); // 5
function manualSortString(str) {
let arr = str.split('');
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i].charCodeAt(0) > arr[j].charCodeAt(0)) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr.join('');
}
const inputString = "javas8cript3";
const sortedString = manualSortString(inputString);
console.log(sortedString); // Output: "38aacijprstv"
const str1 = "hello"
const str2 = "world 123";
const mergeStrings = (str1, str2) => {
let finalString = "";
const maxLength = Math.max(str1.length , str2.length);
for (let index = 0; index < maxLength; index++) {
if (index < str1.length) {
finalString += str1[index]
}
if (index < str2.length) {
finalString += str2[index]
}
}
return finalString
}
console.log(mergeStrings(str1, str2)); // hweolrllod 123
// To efficiently find the peak, we use binary search
const peakIndexStrings = (arr) => {
let left = 0;
let right = arr.length - 1;
while (left < right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] < arr[mid + 1]) {
left = mid + 1
} else {
right = mid
}
}
return left;
}
console.log(peakIndexStrings([0, 2, 4, 5, 3, 1])); // 3
const arr = [10, 20, 30, 40, 50];
const element = 30;
const index = arr.indexOf(element);
console.log(index); // Output: 2
const indexResult = arr.findIndex(element => element === 30);
console.log(indexResult); // Output: 2
// Brute-force Approach Explanation
// The brute-force approach involves systematically checking every possible subarray in the given array
const maxSubArraySum = (arr) => {
let n = arr.length
let maxSum = -Infinity;
for (let i = 0; i < n; i++) {
let currentSum = 0;
for (let j = i; j < n; j++) {
currentSum += arr[j];
if (currentSum > maxSum) {
maxSum = currentSum
}
}
}
return maxSum;
}
console.log(maxSubArraySum([-1,4,7,2,5]));
function findFirstAndLast(arr, k) {
let first = -1;
let last = -1;
// Function to find the first occurrence of k
const findFirst = (arr, k) => {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === k) {
first = mid; // Update the first occurrence
right = mid - 1; // Continue searching in the left half
} else if (arr[mid] < k) {
left = mid + 1; // Search in the right half
} else {
right = mid - 1; // Search in the left half
}
}
};
// Function to find the last occurrence of k
const findLast = (arr, k) => {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === k) {
last = mid; // Update the last occurrence
left = mid + 1; // Continue searching in the right half
} else if (arr[mid] < k) {
left = mid + 1; // Search in the right half
} else {
right = mid - 1; // Search in the left half
}
}
};
findFirst(arr, k);
findLast(arr, k);
return [first, last]; // Return the first and last occurrence
}
// Example usage
const k = 2;
const result = findFirstAndLast([1, 2, 2, 2, 3, 4, 5], k);
console.log(result); // Output: [1, 3] (first and last occurrences of 2)
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid; // Found
} else if (arr[mid] < target) {
left = mid + 1; // Search right
} else {
right = mid - 1; // Search left
}
}
return -1; // Not found
}
function findLeaders(array) {
const leaders = [];
let maxFromRight = array[array.length - 1];
leaders.push(maxFromRight);
for (let index = array.length - 2; index >= 0; index--) {
if (array[index] > maxFromRight) {
leaders.push(array[index]);
maxFromRight = array[index]
}
}
return leaders.reverse();
}
const leaders = findLeaders([16, 17, 4, 3, 5, 2]);
console.log(leaders); // Output: [17, 5, 2]