img

You can tap to unblur the code solution.

However, we strongly recommend that you try it out yourself first in your code editor.

The sole purpose of such questions is to exercise and enhance your logical and reasoning abilities.

All the best.

Last updated on: 19th June 2023


HIGHER PRIME
1.
Write a function that takes a natural number 'n' as an arguement and returns the number itself if it is a prime number. If not, return the next higher prime number.
Example 1
Input:
n = 7
Output:
7
Example 2
Input:
n = 14
Output:
17

Code :

function higherPrime(n) {
  count = 0;
  for (i = 1; i <= n; i++) {
    if (n % i == 0) {
      count++;
    }
  }
  if (count == 2) {
    return n;
  } else {
    return higherPrime(n + 1);
  }
}

console.log(higherPrime(7)); // 7
console.log(higherPrime(14)); // 17

LONGEST STRING
2.
Write a function that takes an array as arguement and returns the longest string amongst the elements.
Example 1
Input:
arr = ['bit', 'coin']
Output:
'coin'
Example 2
Input:
arr = ['jon', 'snow']
Output:
'snow'

Code :

function longestStr(arr) {
  let result = '';
  for (i = 0; i < arr.length; i++) {
    if (arr[i].length > result.length) {
      result = arr[i];
    }
  }
  return console.log(result);
}

longestStr(['bit', 'coin']); // coin
longestStr(['jon', 'snow']); // snow

POWER OF 2
3.
Write a function that takes a natural number 'n' as an arguement. Determine if the number is a power of 2 or not. Return true/false accordingly.
Example 1
Input:
n = 16
Output:
true
Example 2
Input:
n = 10
Output:
false

Code :

function powerOf2(n) {
  if (n % 2 == 0) {
    for (i = 1; i <= n; i++) {
      if (n == 2 ** i) {
        return true;
      }
    }
    return false;
  } else return false;
}

console.log(powerOf2(16)); // true
console.log(powerOf2(10)); // false

LENGTH OF LAST WORD
4.
Given a string 's' consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only.
Example 1
Input:
s = 'Hey JavaScript '
Output:
10
Example 2
Input:
s = 'Ask padhAI'
Output:
6

Code :

function lengthOfLastWord(s) {

  // Remove leading & trailing spaces
  let trimmedStr = s.trim();

  // Split string into an array
  let arr = trimmedStr.split(' ');
  // Get the last word
  let result = arr[arr.length - 1];

  return console.log(result.length);
}

lengthOfLastWord('Hey JavaScript  '); // 10
lengthOfLastWord('Ask padhAI'); // 6

STACK REVERSE
5.
Write a function to reverse a string using stack. The function will take a string as an arguement and returns the reversed string. Do not use any in-built methods like .reverse(), .split(), .join()
Example 1
Input:
str = 'pikachu'
Output:
'uhcakip'
Example 2
Input:
arr = 'ash'
Output:
'hsa'

Code :

function stackReverse(str) {
  let stack = [];
  let result = '';

  // turn string into stack
  for (i = 0; i < str.length; i++) {
    stack[i] = str[i];
  }

  let length = stack.length;

  for (i = length - 1; i >= 0; i--) {
    // add every i'th element to result
    result = result + stack[i];

    // pop last element
    length = i;
  }

  return console.log(result);
}

stackReverse('pikachu'); // uhcakip
stackReverse('ash'); // hsa

REMOVE DUPLICATES
6.
Write a function that takes 2 arrays as arguements. Return a merged array with all the duplicate elements removed
Example 1
Input:
arr1 = [3, 1, 4] ​ ​ arr2 = [2, 7, 3]
Output:
[ 1, 2, 3, 4, 7 ]
Example 2
Input:
arr1 = [9, 22, 2] ​ ​ arr2 = [22, 6, 9]
Output:
[ 2, 6, 9, 22 ]

Code :

function removeDuplicates(arr1, arr2) {

    // merging two arrays using destructuring
    let merge = [...arr1, ...arr2];
    // sorting the merged array in ascending order
    merge.sort((a, b) => a - b);

    let result = [];
    for (i = 0; i < merge.length; i++) {
        if (merge[i] !== merge[i + 1]) {
            result.push(merge[i]);
        }
    }

    return console.log(result);
}

removeDuplicates([3, 1, 4], [2, 7, 3]); // [ 1, 2, 3, 4, 7 ]
removeDuplicates([9, 22, 2], [22, 6, 9]); // [ 2, 6, 9, 22 ]

THE LCM
7.
Write a function that takes 2 numbers as arguements. Return the LCM ( Lowest Common Multiple ) of these numbers.
Example 1
Input:
n1 = 3 ​ ​ n2 = 4
Output:
12
Example 2
Input:
n1 = 17 ​ ​ n2 = 8
Output:
136

Code :

function theLcm(n1, n2) {
    
    for (i = 1; i <= n2; i++) {
        let result = n1 * i;
        if (result % n2 == 0) {
            return result;
        }
    }
}

console.log(theLcm(3, 4)); // 12
console.log(theLcm(17, 8)); // 136;

COUNT CONSONANTS
8.
Write a function that takes a string as an arguement and returns the number of consonants in it.
Example 1
Input:
str = 'padhAI'
Output:
3
Example 2
Input:
str = 'padhakoo'
Output:
4

Code :

function consonant(str) {
  let count = 0;
  str = str.toLowerCase();
  for (i = 0; i < str.length; i++) {
    if (str[i] == 'a') {
      count++;
    }
    if (str[i] == 'e') {
      count++;
    }
    if (str[i] == 'i') {
      count++;
    }
    if (str[i] == 'o') {
      count++;
    }
    if (str[i] == 'u') {
      count++;
    }
  }
  let result = str.length - count;
  return console.log(result);
}

consonant('padhakoo'); // 4
consonant('padhAI'); // 3

TWO SUM
9.
Write a function that takes an array and an integer as parameters. Find a pair from the array elements such that their sum equals to the given integer. Return the indices of those array elements.
Example 1
Input:
arr = [2, 7, 11, 15] ​ ​ n = 9
Output:
[ 0, 1 ]
Example 2
Input:
arr = [25, 19, 8, 31] ​ ​ n = 27
Output:
[ 1, 2 ]

Code :

function twoSum(arr, n) {
  let result = [];

  for (i = 0; i < arr.length; i++) {
    for (j = i + 1; j < arr.length; j++) {
      if (arr[i] + arr[j] == n) {
        result.push(i, j);
      }
    }
  }
  return console.log(result);
};

twoSum([2, 7, 11, 15], 9); // [ 0, 1 ]
twoSum([25, 19, 8, 31], 27); //  [1, 2 ]

INSERT STRING
10.
Write a function that takes 2 strings: 'str1' and 'str2' as arguements. Starting from the end of str1, insert str2 in str1 after every 3rd character of str1. Return the resultant string.
Example 1
Input:
str1 = '1234567' ​ ​ str2 = '.'
Output:
1.234.567
Example 2
Input:
str1 = 'avengers' ​ ​ str2 = '*'
Output:
av*eng*ers

Code :

function insertString(str1, str2) {
    
    // converting a string into array using destructuring
    let arr = [...str1];
    arr.reverse();

    let newArr = [];
    newArr.push(arr[0]);

    for (i = 1; i < arr.length; i++) {
        if (i % 3 != 0) {
            newArr.push(arr[i]);
        }
        else {
            newArr.push(str2);
            newArr.push(arr[i]);
        }
    }

    return newArr.reverse().join('');
}

console.log(insertString('1234567', '.')); // 1.234.567
console.log(insertString('avengers', '*')); // av*eng*ers

ROMAN TO INTEGER
11.
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer.
Example 1
Input:
n = IX
Output:
9
Example 2
Input:
n = MCMXCIV
Output:
1994

Code :

function romanToInteger(n) {
  const romanSymbols = {
    I: 1,
    V: 5,
    X: 10,
    L: 50,
    C: 100,
    D: 500,
    M: 1000,
    IV: 4,
    IX: 9,
    XL: 40,
    XC: 90,
    CD: 400,
    CM: 900,
  };

  let result = 0;

  n.replace(/IV|IX|XL|XC|CD|CM|I|V|X|L|C|D|M/g,
    (match) => { result += romanSymbols[match];
    }
  );

  return console.log(result);
}

romanToInteger('III'); // 3
romanToInteger('IX'); // 9
romanToInteger('LVIII'); // 58
romanToInteger('MCMXCIV'); // 1994

LONGEST COMMON PREFIX
12.
Given an array of strings, find the Longest Common Prefix amongst the strings.
Example 1
Input:
arr = ['padhakoo', 'padhAI', 'paradox']
Output:
pa
Example 2
Input:
arr = ['java', 'javascript', 'javelin']
Output:
jav

Code :

function longestCommonPrefix(arr) {
    
    // Return nothing if arr is empty
    if (arr.length == 0) {
        return '';
    }

    for (let i = 0; i <= arr[0].length; i++) {
        for (let j = 1; j < arr.length; j++) {
            // Check if this character is also present in the same position of each string
            if (arr[0][i] !== arr[j][i]) {
                // If not, return the string up to and including the previous character
                return arr[0].slice(0, i);
            }
        }
    }

    return arr[0];
}

console.log(longestCommonPrefix(['padhakoo', 'padhAI', 'paradox'])); // pa
console.log(longestCommonPrefix(['java', 'javascript', 'javelin'])); // jav

MAX PRODUCT
13.
Given an array of strings. Return the maximum value of 'length(word[i]) * length(word[j])' where the two words do not share common letters. If no such two words exist, return '0'.
Example 1
Input:
arr = ['abcw', 'foo', 'bar', 'xytf', 'abcdef']
Output:
16
Example 2
Input:
arr = ['ab', 'bc', 'aca', 'abaa']
Output:
0

Code :

function maxProduct(arr) {
    
    let result = 0;

    for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (!hasCommonLetters(arr[i], arr[j])) {
                const product = arr[i].length * arr[j].length;
                result = Math.max(result, product);
            }
        }
    }

    return console.log(result);
}

function hasCommonLetters(word1, word2) {

    const set1 = new Set(word1);

    for (let char of word2) {
        if (set1.has(char)) {
            return true;
        }
    }
    
    return false;
}

maxProduct(['abcw', 'foo', 'bar', 'xytf', 'abcdef']); // 16
maxProduct(['ab', 'bc', 'aca', 'abaa']); // 0

REVERSE VOWELS
14.
Given a string 's', reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.
Example 1
Input:
s = 'padhAI'
Output:
pIdhAa
Example 2
Input:
s = 'padhakoo'
Output:
podhokaa

Code :

function reverseVowels(s) {

    const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
    const chars = s.split('');
    let start = 0;
    let end = chars.length - 1;
  
    while (start < end) {
      if (vowels.includes(chars[start]) && vowels.includes(chars[end])) {
        [chars[start], chars[end]] = [chars[end], chars[start]];
        start++;
        end--;
      }
      
      else if (vowels.includes(chars[start])) {
        end--;
      }
      
      else {
        start++;
      }
    }
  
    return chars.join('');
  }
  
  console.log(reverseVowels('padhAI')); // pIdhAa
  console.log(reverseVowels('padhakoo')); // podhokaa
  console.log(reverseVowels('OpenAI')); // IpAneO

IS PALINDROME
15.
Given a string 's', return true if it is a palindrome, or false otherwise. A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Example 1
Input:
s = 'A man, a plan, a canal: Panama'
Output:
true
Example 2
Input:
s = 'Was it a car or a cat I saw'
Output:
true

Code :

function isPalindrome(s) {
    
    // Convert the string to lowercase and remove non-alphanumeric characters
    const str = s.toLowerCase().replace(/[^a-z0-9]/g, '');
  
    // Check if the string is a palindrome
    for (let i = 0; i < str.length / 2; i++) {
      if (str[i] !== str[str.length - 1 - i]) {
        return false;
      }
    }
  
    return true;
  }
  
  console.log(isPalindrome('A man, a plan, a canal: Panama')); // true
  console.log(isPalindrome('Was it a car or a cat I saw')); // true
  console.log(isPalindrome('padhAI works on GPT 3.5')); // false

VALID PARENTHESES
16.
You are given a string consisting of parentheses, square brackets, and curly braces. Your task is to determine if the string is balanced. A string is considered balanced if every opening bracket has a corresponding closing bracket of the same type, and they are properly nested. Write a function that takes a string consisting of parentheses, square brackets, and curly braces. Return true or false based on whether the string is balanced or not.
Example 1
Input:
s = '([])'
Output:
true
Example 2
Input:
s = '{[()]}('
Output:
false

Code :

function validParentheses(s) {
    const stack = [];

    for (let i = 0; i < s.length; i++) {
        const char = s[i];
        if (char === '(' || char === '[' || char === '{') {
            stack.push(char);
        } else if (char === ')' || char === ']' || char === '}') {
            if (stack.length === 0) {
                return false;
            }

            const top = stack.pop();
            if (
                (char === ')' && top !== '(') ||
                (char === ']' && top !== '[') ||
                (char === '}' && top !== '{')
            ) {
                return false;
            }
        }
    }

    return stack.length === 0;
}

console.log(validParentheses('()')); // true
console.log(validParentheses('([])')); // true
console.log(validParentheses('{[()]}')); // true
console.log(validParentheses('([)]')); // false
console.log(validParentheses('{[()]}(')); // false
console.log(validParentheses('(([{[]}]))')); // true
console.log(validParentheses('')); // true
console.log(validParentheses('[(])')); // false
img

"Embrace curiosity, unlock knowledge"

Copyright © 2023 - Some rights reserved

Made with

in INDIA