Table of contents
- Question 1: Sum of all natural numbers from 1 to n
- Question 2: Sum of digits of a number
- Question 3: Count the number of digits of a number
- Question 4: Check if a number is palindrome
- Question 5: Find nth Fibonacci number
- Question 5.2 Tribonacci Number
- Question 6: Missing Number in an Array
- Question 7: Leap Year
- Condition 1: y % 400 === 0
- Condition 2: y % 4 === 0 && y % 100 !== 0
- Question 8: Find Largest of 3 Numbers
- Question 9: Swapping (using 3rd Variable & without using)
- Concept: Comparison between iterative and recursive approaches
- Question 10: Factorial - (iterative & recursive method)
- Question 11: Print all the factors of a number & SUM OF ALL FACTOR
- Question 12: Perfect Number // 6, 28, 496, 8128, ...
- Question 13: Prime Number // 2, 3, 5, 7, 11, 13, 17, 19, ...
- Question 14: Armstrong Number
- Question 15: Check for Perfect Square:
- Question 16: Binary to Decimal to conversion & vice versa
- Question 18: Reverse Number
- Practice Questions
Practice Loop, functions & Math Problems:- π Loops in JavaScript | Math Interview Problems Solved
DSA definition - interview question
Question 1: Sum of all natural numbers from 1 to n
function sumOfNaturalNumber(num){
let sum = 0;
for(let i=1; i<=num; i++){
sum = sum + i;
}
return sum;
}
console.log(sumOfNaturalNumber(5)); // 15
console.log(sumOfNaturalNumber(10)); // 55
console.log(sumOfNaturalNumber(8)); // 36
Question 2: Sum of digits of a number
function sumOfDigits(num){
let sum = 0;
while(num > 0){
sum += num%10;
num = Math.floor(num / 10);
}
return sum;
}
console.log(sumOfDigits(1287)); // 18
Question 3: Count the number of digits of a number
function countDigits(num){
num = Math.abs(num);
let count = 0;
do {
count++;
num = Math.floor(num / 10);
} while (num > 0);
return count;
}
console.log(countDigits(121)); // 3
console.log(countDigits(-1211413131)); // 10
Question 4: Check if a number is palindrome
let isPalindrome = function(x) {
let copyNum = x, reverseNum = 0;
while(copyNum > 0){
const lastDigit = copyNum % 10;
reverseNum = reverseNum * 10 + lastDigit;
copyNum = Math.floor(copyNum / 10);
}
return x === reverseNum;
};
console.log(isPalindrome(121)); // true
console.log(isPalindrome(1234)); // false
Question 5: Find nth Fibonacci number
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.
let fib = function(n) {
if(n < 2){
return n;
}
let prev = 0, curr = 1, next;
for(let i=2; i<= n; i++){
next = prev + curr;
prev = curr;
curr = next;
}
return next;
};
// Fibonacci Sequence: 0 1 1 2 3 5 8...
console.log(fib(5)); // 5
console.log(fib(10)); // 55
function fibRecursive(n) {
if (n < 2) {
return n;
}
return fibRecursive(n - 1) + fibRecursive(n - 2);
}
console.log(fibRecursive(5));
// To print 'n' fibonaci number
for (let i = 0; i <= 10; i++) {
console.log(fib(i));
console.log(fibRecursive(i));
}
Question 5.2 Tribonacci Number
class Solution {
public int tribonacci(int n) {
int t0 = 0, t1 = 1, t2=1, next=-1;
// Brute force approach
if(n==0 || n==1)
return n;
else if(n==2)
return n-1;
for(int i=3; i<=n; i++){
next = t0 + t1 + t2;
t0 = t1;
t1 = t2;
t2 = next;
}
return next;
}
}
Feature | map Function | forEach Method |
Purpose | Transforms each element of an array and returns a new array. | Executes a provided function once for each array element. |
Return Value | Returns a new array containing the results of the mapping. | Does not return any value (undefined ). |
Functional vs. Imperative | Typically used in functional programming paradigms. | Typically used in imperative programming. |
Usage | Use when transforming data and creating a new array. | Use when performing actions on array elements. |
Question 6: Missing Number in an Array
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
/* arr = [0,1,3];
sum = 4;
n = arr.length = 3
sigma = n * (n + 1) / 2 = 3 * 4 / 2 = 6
missingNumber(?) = sigma - sum;
? = 6 - 4 = 2 Ans */
let missingNum = function (arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return (arr.length * (arr.length + 1) / 2) - sum;
}
// One Line Solution:
let missingNum2 = (arr) => arr.length * (arr.length + 1) / 2 - arr.reduce((acc, val) => val + acc);
console.log(missingNum([3,0,1])); // 2
console.log(missingNum2([9,6,4,2,3,5,7,0,1])); // 8
Question 7: Leap Year
function isLeapYr(y) {
return (y % 400 === 0) || (y % 4 === 0 && y % 100 !== 0);
}
console.log(isLeapYr(2022));
Condition 1: y % 400 === 0
Purpose: Checks if the year
y
is divisible by 400.Explanation: If
y
is divisible by 400, it is a leap year. For example, 2000 is a leap year.
Condition 2: y % 4 === 0 && y % 100 !== 0
Purpose: Checks if the year
y
is divisible by 4 but not by 100.Explanation: If
y
is divisible by 4 but not by 100, it is a leap year, unless itβs also divisible by 400. For example, 1996 is a leap year, while 1900 is not.
Question 8: Find Largest of 3 Numbers
let a = 110, b = 105, c = 17;
if (a > b && a > c) {
console.log(a, ' A is greater');
}
else if (b > a && b > c) {
console.log(b, " B is greater");
}
else {
console.log(c, " C is greater");
}
Question 9: Swapping (using 3rd Variable & without using)
let n1 = 16, n2 = 64, temp;
console.log(`a: ${n1} and b: ${n2}`);
temp = n1;
n1 = n2;
n2 = temp;
console.log(`a: ${n1} and b: ${n2}`);
// WITHOUT USING THIRD VARIABLE
console.log(`a: ${n1} and b: ${n2}`);
n1 = n1 + n2;
n2 = n1 - n2;
n1 = n1 - n2;
console.log(`a: ${n1} and b: ${n2}`);
Concept: Comparison between iterative and recursive approaches
Aspect | Iterative Approach | Recursive Approach |
Control Flow | Loop constructs | Function calls |
Memory Usage | Low | Potentially higher due to call stack |
Performance | Generally faster | May be slower due to function call overhead |
Readability | Straightforward | Can be elegant but less intuitive |
Termination | Condition-based loop termination | Base case triggering termination |
Question 10: Factorial - (iterative & recursive method)
// Iterative method
let factorial = function (n) {
let result = 1;
for (let i = 2; i <= 5; i++) {
result *= i;
}
return result;
}
console.log(factorial(5)); // 120
// Recursive Method
let fact = function (n) {
// Base case: if n is 0 or 1, factorial is 1
if (n === 0 || n === 1) {
return 1;
}
// Recursive case: calculate factorial by multiplying 'n' with factorial of (n-1)
else {
return n * fact(n - 1);
}
};
console.log(fact(4)); // 24
Question 11: Print all the factors of a number & SUM OF ALL FACTOR
let factors = function (n) {
let result = [];
for (let i = 1; i < n; i++) {
if (n % i === 0) {
// console.log(i);
result.push(i);
}
}
return result;
}
console.log(factors(15)); // [1, 3, 5]
// One Line Solution: SUM OF ALL FACTORS
console.log( factors(15).reduce((acc, item) => acc + item) ); // 9
Question 12: Perfect Number // 6, 28, 496, 8128, ...
A positive integer that is equal to the sum of its proper divisors, excluding itself.
let perfectNum = function (n) {
let result = 0;
for (let i = 1; i < n; i++) {
if (n % i === 0)
result += i;
}
return result === n;
}
console.log(perfectNum(28)); // true
Question 13: Prime Number // 2, 3, 5, 7, 11, 13, 17, 19, ...
A prime number is a number divisible only by 1 and itself.
let isPrime = function (n) {
for (let i = 2; i <= Math.sqrt(n); i++){
if (n % i === 0)
return false;
}
return true;
}
console.log(isPrime(3));
// List all Prime Number till 100
for (let i = 2; i <= 50; i++){
(isPrime(i) ? console.log(i) : null);
}
Question 14: Armstrong Number
abcdβ¦ = an + bn + cn + dn + β¦
Where, n = order(length/digits in number)
Eg. 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, ...
let isArmstrong = function (n) {
let sum = 0, originalNum = n, count = String(n).length;
for (let i = 0; i < count; i++){
let remainder = n % 10;
sum += Math.pow(remainder, count)
n = Math.floor(n/10);
}
return sum === originalNum;
}
console.log(isArmstrong(407)); // true
// List some 'n' armstrong numbers
for (let i = 1; i < 1700; i++){
if (isArmstrong(i))
console.log(i);
}
Question 15: Check for Perfect Square:
A perfect square number is a non-negative integer that is the square of an integer.
// To check for perfect square
let isPerfectSquare = function (n) {
let sr = Math.floor(Math.sqrt(n));
return sr * sr === n;
}
console.log(isPerfectSquare(25));
// To print some 'n' perfect square numbers
for (let i = 1; i <= 100; i++){
isPerfectSquare(i) ? console.log(i) : null;
}
Question 16: Binary to Decimal to conversion & vice versa
let decimalToBinnary = function (decimal) {
let binary = [], remainder;
while (decimal>0) {
remainder = Math.floor(decimal % 2);
// console.log(remainder);
binary.unshift(remainder);
decimal = Math.floor(decimal / 2);
// console.log(decimal);
}
return binary.join('');;
}
console.log(decimalToBinnary(16)); // 10000
let BinToDec = function (bin) {
let decimal = 0;
bin = String(bin).split('').reverse();
console.log(bin);
bin.forEach((elem, i) => {
if (elem === '1')
decimal += Math.pow(2, i);
})
return decimal;
}
console.log(BinToDec(1100)); // 12
Question 18: Reverse Number
let reverseNum = function (n) {
let sum = 0, digit;
while (n > 0) {
digit = n % 10;
sum = sum * 10 + digit;
n = Math.floor(n / 10);
}
return sum;
}
console.log(reverseNum(123));
// ONE LINE SOLUTION:
let reverseNum2 = function(n) {
return +String(n).split('').reverse().join('');
}
console.log(reverseNum2(123));