0% found this document useful (0 votes)
4 views7 pages

Js Problem Solving

The document contains a series of JavaScript problem-solving questions along with their solutions. Each problem focuses on common programming challenges such as finding missing numbers, reversing strings, checking for palindromes, and more. Additionally, a bonus question addresses merging intervals, showcasing various techniques and functions in JavaScript.

Uploaded by

Zeeshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

Js Problem Solving

The document contains a series of JavaScript problem-solving questions along with their solutions. Each problem focuses on common programming challenges such as finding missing numbers, reversing strings, checking for palindromes, and more. Additionally, a bonus question addresses merging intervals, showcasing various techniques and functions in JavaScript.

Uploaded by

Zeeshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

JavaScript Problem Solving Questions & Answers

1. Find the Missing Number in an Array

function findMissingNumber(arr, n) {

const totalSum = (n * (n + 1)) / 2;

const arrSum = arr.reduce((acc, curr) => acc + curr, 0);

return totalSum - arrSum;

console.log(findMissingNumber([1, 2, 4, 5, 6], 6)); // Output: 3

2. Reverse a String

function reverseString(str) {

return str.split('').reverse().join('');

console.log(reverseString("hello")); // Output: "olleh

3. Find the Longest Substring Without Repeating Characters

function longestSubstring(str) {

let longest = 0;

let start = 0;

let map = {};

for (let end = 0; end < str.length; end++) {

if (map[str[end]] !== undefined && map[str[end]] >= start) {

start = map[str[end]] + 1;

map[str[end]] = end;
longest = Math.max(longest, end - start + 1);

return longest;

console.log(longestSubstring("abcabcbb")); // Output: 3

4. Fibonacci Sequence

function fibonacci(n, memo = {}) {

if (n <= 1) return n;

if (memo[n]) return memo[n];

memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);

return memo[n];

console.log(fibonacci(6)); // Output: 8

5. Check for Palindrome

function isPalindrome(str) {

return str === str.split('').reverse().join('');

console.log(isPalindrome("racecar")); // Output: true

6. Sum of Two Numbers in an Array

function twoSum(arr, target) {

const map = new Map();

for (let i = 0; i < arr.length; i++) {

const complement = target - arr[i];

if (map.has(complement)) {

return [map.get(complement), i];


}

map.set(arr[i], i);

console.log(twoSum([2, 7, 11, 15], 9)); // Output: [0, 1]

7. Count Vowels and Consonants

function countVowelsAndConsonants(str) {

const vowels = 'aeiouAEIOU';

let vowelCount = 0;

let consonantCount = 0;

for (let char of str) {

if (/[a-zA-Z]/.test(char)) {

if (vowels.includes(char)) vowelCount++;

else consonantCount++;

return { vowels: vowelCount, consonants: consonantCount };

console.log(countVowelsAndConsonants("Hello World")); // Output: { vowels: 3, consonants: 7 }

8. Flatten a Nested Array

function flattenArray(arr) {

return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flattenArray(val) : val), []);

console.log(flattenArray([1, [2, 3], [4, [5, 6]]])); // Output: [1, 2, 3, 4, 5, 6]


9. Find the Largest and Smallest Elements in an Array

function findLargestAndSmallest(arr) {

let largest = Math.max(...arr);

let smallest = Math.min(...arr);

return { largest, smallest };

console.log(findLargestAndSmallest([3, 5, 1, 9, 2])); // Output: { largest: 9, smallest: 1 }

10. Remove Duplicates from an Array

function removeDuplicates(arr) {

return [...new Set(arr)];

console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Output: [1, 2, 3, 4, 5]

11. Find All Prime Numbers in a Range

function findPrimesInRange(start, end) {

const primes = [];

for (let num = start; num <= end; num++) {

let isPrime = true;

for (let i = 2; i <= Math.sqrt(num); i++) {

if (num % i === 0) {

isPrime = false;

break;

if (isPrime && num > 1) primes.push(num);

}
return primes;

console.log(findPrimesInRange(10, 50)); // Output: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

12. Find the Intersection of Two Arrays

function intersection(arr1, arr2) {

return arr1.filter(value => arr2.includes(value));

console.log(intersection([1, 2, 2, 1], [2, 2])); // Output: [2, 2]

13. Balanced Parentheses

function isBalanced(str) {

const stack = [];

const pairs = { '(': ')', '[': ']', '{': '}' };

for (let char of str) {

if (pairs[char]) {

stack.push(char);

} else if (Object.values(pairs).includes(char)) {

if (pairs[stack.pop()] !== char) return false;

return stack.length === 0;

console.log(isBalanced("((()))")); // Output: true

14. Sum of All Digits in a Number

function sumDigits(num) {
return num.toString().split('').reduce((acc, curr) => acc + Number(curr), 0);

console.log(sumDigits(12345)); // Output: 15

15. Find All Anagrams in a String

function findAnagrams(str, target) {

let result = [];

let targetSorted = target.split('').sort().join('');

for (let i = 0; i <= str.length - target.length; i++) {

if (str.slice(i, i + target.length).split('').sort().join('') === targetSorted) {

result.push(i);

return result;

console.log(findAnagrams("cbaebabacd", "abc")); // Output: [0, 6]

Bonus Question (Advanced) - Merge Intervals

function mergeIntervals(intervals) {

if (intervals.length === 0) return [];

intervals.sort((a, b) => a[0] - b[0]);

let result = [intervals[0]];

for (let i = 1; i < intervals.length; i++) {

let last = result[result.length - 1];

let current = intervals[i];


if (last[1] >= current[0]) {

last[1] = Math.max(last[1], current[1]);

} else {

result.push(current);

return result;

console.log(mergeIntervals([[1, 3], [2, 4], [5, 7], [6, 8]])); // Output: [[1, 4], [5, 8]]

You might also like