Data Structure and Algorithm
Logic Building

Logic Building - DSA Exercises

Welcome to the logic-building curriculum. This guide contains exercises designed to strengthen your problem-solving skills before diving into advanced Data Structures and Algorithms.

Phase 1

Level 1

1. Take a number and print whether it’s positive, negative, or zero.
function checkNumberType(num) {
  if (num > 0) {
    console.log("Positive");
  } else if (num < 0) {
    console.log("Negative");
  } else {
    console.log("Zero");
  }
}
 
// Test cases
checkNumberType(10);  // Positive
checkNumberType(-5);  // Negative
checkNumberType(0);   // Zero
2. Check if a number is even or odd.
function checkEvenOdd(num) {
  if (num % 2 === 0) {
    console.log("Even");
  } else {
    console.log("Odd");
  }
}
 
// Test cases
checkEvenOdd(4); // Even
checkEvenOdd(7); // Odd
3. Check if a number is divisible by 5.
function isDivisibleBy5(num) {
  if (num % 5 === 0) {
    console.log("Divisible by 5");
  } else {
    console.log("Not divisible by 5");
  }
}
 
// Test cases
isDivisibleBy5(25); // Divisible by 5
isDivisibleBy5(12); // Not divisible by 5
4. Check if a number is divisible by both 3 and 5.
function isDivisibleBy3And5(num) {
  if (num % 3 === 0 && num % 5 === 0) {
    console.log("Divisible by both 3 and 5");
  } else {
    console.log("Not divisible by both 3 and 5");
  }
}
 
// Test cases
isDivisibleBy3And5(15); // Divisible by both 3 and 5
isDivisibleBy3And5(10); // Not divisible by both 3 and 5
5. Check if a given year is a leap year.
function isLeapYear(year) {
  if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
    console.log(year + " is a leap year");
  } else {
    console.log(year + " is not a leap year");
  }
}
 
// Test cases
isLeapYear(2000); // Leap year
isLeapYear(1900); // Not a leap year
isLeapYear(2024); // Leap year
6. Take two numbers and print the larger one.
function printLarger(a, b) {
  if (a > b) {
    console.log(a);
  } else if (b > a) {
    console.log(b);
  } else {
    console.log("Both are equal");
  }
}
 
// Test cases
printLarger(10, 20); // 20
printLarger(50, 30); // 50
7. Take three numbers and print the largest.
function printLargestOfThree(a, b, c) {
  if (a >= b && a >= c) {
    console.log(a);
  } else if (b >= a && b >= c) {
    console.log(b);
  } else {
    console.log(c);
  }
}
 
// Test cases
printLargestOfThree(10, 20, 30); // 30
printLargestOfThree(50, 10, 20); // 50
8. Take a temperature value and print “Cold”, “Warm”, or “Hot” using range conditions.
function checkTemperature(temp) {
  if (temp < 15) {
    console.log("Cold");
  } else if (temp >= 15 && temp <= 30) {
    console.log("Warm");
  } else {
    console.log("Hot");
  }
}
 
// Test cases
checkTemperature(10); // Cold
checkTemperature(22); // Warm
checkTemperature(35); // Hot
9. Take a character and check if it’s a vowel or consonant.
function checkVowelConsonant(char) {
  char = char.toLowerCase();
  if ("aeiou".includes(char)) {
    console.log("Vowel");
  } else if (char >= 'a' && char <= 'z') {
    console.log("Consonant");
  } else {
    console.log("Not an alphabet");
  }
}
 
// Test cases
checkVowelConsonant('a'); // Vowel
checkVowelConsonant('B'); // Consonant
10. Take a character and check whether it’s uppercase, lowercase, a digit, or a special character.
function checkCharType(char) {
  if (char >= 'A' && char <= 'Z') {
    console.log("Uppercase");
  } else if (char >= 'a' && char <= 'z') {
    console.log("Lowercase");
  } else if (char >= '0' && char <= '9') {
    console.log("Digit");
  } else {
    console.log("Special Character");
  }
}
 
// Test cases
checkCharType('G'); // Uppercase
checkCharType('m'); // Lowercase
checkCharType('5'); // Digit
checkCharType('$'); // Special Character

Level 2

1. Take three sides and check if they form a valid triangle.
function isValidTriangle(s1, s2, s3) {
  if (s1 + s2 > s3 && s1 + s3 > s2 && s2 + s3 > s1) {
    console.log("Valid Triangle");
  } else {
    console.log("Not a valid Triangle");
  }
}
 
// Test cases
isValidTriangle(3, 4, 5); // Valid
isValidTriangle(1, 1, 5); // Not valid
2. If the sides form a valid triangle, determine whether it is equilateral, isosceles, or scalene.
function checkTriangleType(s1, s2, s3) {
  if (s1 + s2 > s3 && s1 + s3 > s2 && s2 + s3 > s1) {
    if (s1 === s2 && s2 === s3) {
      console.log("Equilateral");
    } else if (s1 === s2 || s2 === s3 || s1 === s3) {
      console.log("Isosceles");
    } else {
      console.log("Scalene");
    }
  } else {
    console.log("Not a valid Triangle");
  }
}
 
// Test cases
checkTriangleType(5, 5, 5); // Equilateral
checkTriangleType(5, 5, 3); // Isosceles
checkTriangleType(3, 4, 5); // Scalene
3. Take marks (0–100) and print the corresponding grade (A/B/C/D/F).
function getGrade(marks) {
  if (marks >= 90) console.log("A");
  else if (marks >= 80) console.log("B");
  else if (marks >= 70) console.log("C");
  else if (marks >= 60) console.log("D");
  else console.log("F");
}
 
// Test cases
getGrade(95); // A
getGrade(75); // C
4. Check if one of two given numbers is a multiple of the other.
function isMultiple(a, b) {
  if (a % b === 0 || b % a === 0) {
    console.log("Multiple of each other");
  } else {
    console.log("Not a multiple");
  }
}
 
// Test cases
isMultiple(10, 5); // Multiple
isMultiple(3, 7);  // Not
5. Take the hour of the day (0–23) and print “Good Morning”, “Good Afternoon”, “Good Evening”, or “Good Night”.
function getGreeting(hour) {
  if (hour >= 5 && hour < 12) console.log("Good Morning");
  else if (hour >= 12 && hour < 17) console.log("Good Afternoon");
  else if (hour >= 17 && hour < 21) console.log("Good Evening");
  else console.log("Good Night");
}
 
// Test cases
getGreeting(10); // Morning
getGreeting(15); // Afternoon
getGreeting(23); // Night
6. Check voting eligibility for a given age (18+).
function canVote(age) {
  if (age >= 18) {
    console.log("Eligible to vote");
  } else {
    console.log("Not eligible");
  }
}
 
// Test cases
canVote(20); // Eligible
canVote(16); // Not
7. Take two numbers and determine whether both are even, both are odd, or one is even and one is odd.
function checkEvenOddPair(a, b) {
  if (a % 2 === 0 && b % 2 === 0) console.log("Both are even");
  else if (a % 2 !== 0 && b % 2 !== 0) console.log("Both are odd");
  else console.log("One is even and one is odd");
}
 
// Test cases
checkEvenOddPair(2, 4); // Both even
checkEvenOddPair(3, 5); // Both odd
checkEvenOddPair(2, 3); // Mixed
8. Take an alphabet character and check if it lies between ‘a’ and ‘m’ or ‘n’ and ‘z’.
function checkAlphabetRange(char) {
  char = char.toLowerCase();
  if (char >= 'a' && char <= 'm') console.log("Range a-m");
  else if (char >= 'n' && char <= 'z') console.log("Range n-z");
  else console.log("Not an alphabet");
}
 
// Test cases
checkAlphabetRange('d'); // a-m
checkAlphabetRange('p'); // n-z
9. Take a day number (1–7) and print the corresponding day name.
function getDayName(dayNum) {
  const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
  if (dayNum >= 1 && dayNum <= 7) {
    console.log(days[dayNum - 1]);
  } else {
    console.log("Invalid day number");
  }
}
 
// Test cases
getDayName(1); // Monday
getDayName(5); // Friday
10. Take a month number (1–12) and print the number of days in that month (ignore leap years).
function getDaysInMonth(month) {
  if (month === 2) console.log(28);
  else if ([4, 6, 9, 11].includes(month)) console.log(30);
  else if (month >= 1 && month <= 12) console.log(31);
  else console.log("Invalid month");
}
 
// Test cases
getDaysInMonth(1); // 31
getDaysInMonth(2); // 28
getDaysInMonth(4); // 30

Level 3

1. Take a 3-digit number and check if all digits are distinct.
function areDigitsDistinct(num) {
  if (num < 100 || num > 999) {
    console.log("Not a 3-digit number");
    return;
  }
  const s = num.toString();
  if (s[0] !== s[1] && s[0] !== s[2] && s[1] !== s[2]) {
    console.log("Distinct");
  } else {
    console.log("Not distinct");
  }
}
 
// Test cases
areDigitsDistinct(123); // Distinct
areDigitsDistinct(121); // Not distinct
2. Take a 3-digit number and determine if the middle digit is the largest, smallest, or neither.
function checkMiddleDigit(num) {
  if (num < 100 || num > 999) return;
  const s = num.toString();
  const d1 = parseInt(s[0]), d2 = parseInt(s[1]), d3 = parseInt(s[2]);
  if (d2 > d1 && d2 > d3) console.log("Largest");
  else if (d2 < d1 && d2 < d3) console.log("Smallest");
  else console.log("Neither");
}
 
// Test cases
checkMiddleDigit(152); // Largest
checkMiddleDigit(516); // Smallest
checkMiddleDigit(123); // Neither
3. Take a 4-digit number and check if the first and last digits are equal.
function isFirstLastEqual(num) {
  if (num < 1000 || num > 9999) return;
  const s = num.toString();
  if (s[0] === s[s.length - 1]) {
    console.log("Equal");
  } else {
    console.log("Not equal");
  }
}
 
// Test cases
isFirstLastEqual(1221); // Equal
isFirstLastEqual(1234); // Not equal
4. Check whether a given integer is single-digit, double-digit, or multi-digit.
function checkDigitType(num) {
  const absNum = Math.abs(num);
  if (absNum < 10) console.log("Single-digit");
  else if (absNum < 100) console.log("Double-digit");
  else console.log("Multi-digit");
}
 
// Test cases
checkDigitType(5);   // Single
checkDigitType(45);  // Double
checkDigitType(123); // Multi
5. Check if a number is a multiple of 7 or ends with 7.
function checkSevenCondition(num) {
  if (num % 7 === 0 || num % 10 === 7) {
    console.log("Matches condition");
  } else {
    console.log("Does not match");
  }
}
 
// Test cases
checkSevenCondition(14); // Multiple of 7
checkSevenCondition(17); // Ends with 7
checkSevenCondition(15); // Neither
6. Take coordinates (x, y) and determine which quadrant the point lies in.
function findQuadrant(x, y) {
  if (x > 0 && y > 0) console.log("Quadrant 1");
  else if (x < 0 && y > 0) console.log("Quadrant 2");
  else if (x < 0 && y < 0) console.log("Quadrant 3");
  else if (x > 0 && y < 0) console.log("Quadrant 4");
  else console.log("On axis or origin");
}
 
// Test cases
findQuadrant(5, 5);   // Q1
findQuadrant(-5, 5);  // Q2
findQuadrant(0, 5);   // Axis
7. Check if an amount can be evenly divided into 2000, 500, and 100 currency notes.
function canBeDividedEqually(amount) {
  if (amount % 100 === 0) {
    console.log("Can be divided");
  } else {
    console.log("Cannot be divided evenly by 100, 500, or 2000 notes");
  }
}
 
// Test cases
canBeDividedEqually(2500); // Yes
canBeDividedEqually(2550); // No
8. Check if a number lies within the range [100, 999].
function isInRange(num) {
  if (num >= 100 && num <= 999) {
    console.log("In range");
  } else {
    console.log("Out of range");
  }
}
 
// Test cases
isInRange(500); // In
isInRange(50);  // Out
9. Take two angles of a triangle and compute the third angle.
function findThirdAngle(a1, a2) {
  if (a1 + a2 < 180) {
    console.log(180 - (a1 + a2));
  } else {
    console.log("Invalid angles");
  }
}
 
// Test cases
findThirdAngle(60, 60); // 60
findThirdAngle(90, 45); // 45
10. Check whether a number is a perfect square (without using the square root function).
function isPerfectSquare(num) {
  if (num < 0) return false;
  let i = 0;
  while (i * i <= num) {
    if (i * i === num) {
      console.log("Perfect Square");
      return;
    }
    i++;
  }
  console.log("Not a perfect square");
}
 
// Test cases
isPerfectSquare(16); // Perfect
isPerfectSquare(20); // Not

Level 4

1. Take a character and check if it is a letter, a digit, or neither.
function classifyChar(char) {
  if ((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z')) {
    console.log("Letter");
  } else if (char >= '0' && char <= '9') {
    console.log("Digit");
  } else {
    console.log("Neither");
  }
}
 
// Test cases
classifyChar('a'); // Letter
classifyChar('5'); // Digit
classifyChar('#'); // Neither
2. Take a number and print “Fizz” if divisible by 3, “Buzz” if divisible by 5, and “FizzBuzz” if divisible by both.
function fizzBuzz(num) {
  if (num % 3 === 0 && num % 5 === 0) console.log("FizzBuzz");
  else if (num % 3 === 0) console.log("Fizz");
  else if (num % 5 === 0) console.log("Buzz");
  else console.log(num);
}
 
// Test cases
fizzBuzz(15); // FizzBuzz
fizzBuzz(3);  // Fizz
fizzBuzz(5);  // Buzz
3. Take three numbers and print the median value (neither maximum nor minimum).
function findMedian(a, b, c) {
  if ((a > b && a < c) || (a < b && a > c)) console.log(a);
  else if ((b > a && b < c) || (b < a && b > c)) console.log(b);
  else console.log(c);
}
 
// Test cases
findMedian(10, 20, 30); // 20
findMedian(5, 15, 10);  // 10
4. Take 24-hour time (hours and minutes) and print whether it is AM or PM.
function checkAmPm(hours, minutes) {
  if (hours >= 0 && hours < 12) {
    console.log("AM");
  } else if (hours >= 12 && hours < 24) {
    console.log("PM");
  } else {
    console.log("Invalid time");
  }
}
 
// Test cases
checkAmPm(10, 30); // AM
checkAmPm(14, 0);  // PM
5. Take income and age, and check if eligible for tax (age > 18 and income > 5 L).
function checkTaxEligibility(age, income) {
  if (age > 18 && income > 500000) {
    console.log("Eligible for tax");
  } else {
    console.log("Not eligible");
  }
}
 
// Test cases
checkTaxEligibility(25, 600000); // Eligible
checkTaxEligibility(17, 700000); // Not eligible
6. Take two numbers and check if both are positive and their sum is less than 100.
function checkSumCondition(a, b) {
  if (a > 0 && b > 0 && (a + b) < 100) {
    console.log("Condition met");
  } else {
    console.log("Condition not met");
  }
}
 
// Test cases
checkSumCondition(30, 40); // Met
checkSumCondition(60, 50); // Not met
7. Take a single digit (0–9) and print its word form (“Zero” to “Nine”).
function digitToWord(digit) {
  const words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];
  if (digit >= 0 && digit <= 9) {
    console.log(words[digit]);
  } else {
    console.log("Not a single digit");
  }
}
 
// Test cases
digitToWord(5); // Five
digitToWord(0); // Zero
8. Take a weekday number (1–7) and determine if it is a weekday or weekend.
function checkDayType(dayNum) {
  if (dayNum >= 1 && dayNum <= 5) {
    console.log("Weekday");
  } else if (dayNum === 6 || dayNum === 7) {
    console.log("Weekend");
  } else {
    console.log("Invalid day");
  }
}
 
// Test cases
checkDayType(3); // Weekday
checkDayType(7); // Weekend
9. Take electricity units consumed and calculate the bill as per slabs (using if-else).
function calculateBill(units) {
  let bill = 0;
  if (units <= 100) {
    bill = units * 5;
  } else if (units <= 200) {
    bill = (100 * 5) + ((units - 100) * 8);
  } else {
    bill = (100 * 5) + (100 * 8) + ((units - 200) * 10);
  }
  console.log("Total Bill: " + bill);
}
 
// Test cases
calculateBill(50);  // 250
calculateBill(150); // 500 + 400 = 900
10. Take a password string and check basic rules (length ≥ 8 and contains at least one digit).
function validatePassword(password) {
  if (password.length >= 8 && /[0-9]/.test(password)) {
    console.log("Valid Password");
  } else {
    console.log("Invalid Password");
  }
}
 
// Test cases
validatePassword("pass1234"); // Valid
validatePassword("password"); // Invalid (no digit)

Level 5

1. Take coordinates (x, y) and check if the point lies on the X-axis, Y-axis, or at the origin.
function checkAxisPosition(x, y) {
  if (x === 0 && y === 0) console.log("Origin");
  else if (x === 0) console.log("Y-axis");
  else if (y === 0) console.log("X-axis");
  else console.log("Neither");
}
 
// Test cases
checkAxisPosition(0, 0); // Origin
checkAxisPosition(0, 5); // Y-axis
checkAxisPosition(5, 0); // X-axis
2. Take three numbers and check if they can form a Pythagorean triplet.
function isPythagoreanTriplet(a, b, c) {
  const [x, y, z] = [a, b, c].sort((m, n) => m - n);
  if (x * x + y * y === z * z) {
    console.log("Pythagorean Triplet");
  } else {
    console.log("Not a triplet");
  }
}
 
// Test cases
isPythagoreanTriplet(3, 4, 5); // Triplet
isPythagoreanTriplet(5, 12, 13); // Triplet
isPythagoreanTriplet(1, 2, 3); // Not
3. Take day and month and check if it forms a valid calendar date (ignoring leap years).
function isValidDate(day, month) {
  if (month < 1 || month > 12 || day < 1) return false;
  let maxDays = 31;
  if (month === 2) maxDays = 28;
  else if ([4, 6, 9, 11].includes(month)) maxDays = 30;
  
  if (day <= maxDays) {
    console.log("Valid Date");
  } else {
    console.log("Invalid Date");
  }
}
 
// Test cases
isValidDate(29, 2);  // Invalid
isValidDate(31, 10); // Valid
4. Take time (hours and minutes) and print the smaller angle between the hour and minute hands.
function getClockAngle(h, m) {
  if (h === 12) h = 0;
  if (m === 60) m = 0;
  const hourAngle = 0.5 * (h * 60 + m);
  const minuteAngle = 6 * m;
  let angle = Math.abs(hourAngle - minuteAngle);
  angle = Math.min(360 - angle, angle);
  console.log("Smaller Angle: " + angle + " degrees");
}
 
// Test cases
getClockAngle(3, 30); // 75
getClockAngle(12, 0); // 0
5. Take three numbers and check if they are in arithmetic progression.
function isAP(a, b, c) {
  if (b - a === c - b) {
    console.log("Arithmetic Progression");
  } else {
    console.log("Not AP");
  }
}
 
// Test cases
isAP(2, 4, 6); // AP
isAP(1, 4, 9); // Not
6. Take three numbers and check if they are in geometric progression.
function isGP(a, b, c) {
  if (a !== 0 && b !== 0 && (b / a === c / b)) {
    console.log("Geometric Progression");
  } else {
    console.log("Not GP");
  }
}
 
// Test cases
isGP(2, 4, 8); // GP
isGP(1, 2, 4); // GP
isGP(1, 3, 5); // Not
7. Take a 3-digit number and check if the sum of the first and last digit equals the middle digit.
function checkDigitSumMiddle(num) {
  if (num < 100 || num > 999) return;
  const s = num.toString();
  if (parseInt(s[0]) + parseInt(s[2]) === parseInt(s[1])) {
    console.log("Sum matches middle");
  } else {
    console.log("Sum does not match");
  }
}
 
// Test cases
checkDigitSumMiddle(132); // 1+2=3
checkDigitSumMiddle(123); // 1+3!=2
8. Take an integer (1–9999) and check if the sum of its digits is greater than the product of its digits.
function sumGreaterThanProduct(num) {
  const digits = num.toString().split('').map(Number);
  const sum = digits.reduce((a, b) => a + b, 0);
  const product = digits.reduce((a, b) => a * b, 1);
  if (sum > product) {
    console.log("Sum > Product");
  } else {
    console.log("Sum <= Product");
  }
}
 
// Test cases
sumGreaterThanProduct(123); // Sum=6, Prod=6 -> No
sumGreaterThanProduct(111); // Sum=3, Prod=1 -> Yes
9. Take two dates (day and month) and determine which one comes first in the calendar.
function compareDates(d1, m1, d2, m2) {
  if (m1 < m2) console.log("First date comes first");
  else if (m1 > m2) console.log("Second date comes first");
  else {
    if (d1 < d2) console.log("First date comes first");
    else if (d1 > d2) console.log("Second date comes first");
    else console.log("Both are same");
  }
}
 
// Test cases
compareDates(10, 5, 12, 5); // First
compareDates(15, 6, 10, 5); // Second
10. Take a year and print the corresponding century (e.g., “19th century”, “20th century”)
function getCentury(year) {
  const century = Math.ceil(year / 100);
  console.log(century + "th century");
}
 
// Test cases
getCentury(1999); // 20th
getCentury(2024); // 21st

Phase 2

Level 1

1. Print numbers from 1 to 10.
function print1To10() {
  for (let i = 1; i <= 10; i++) {
    console.log(i);
  }
}
 
print1To10();
2. Print all even numbers between 1 and 100.
function printEven1To100() {
  for (let i = 2; i <= 100; i += 2) {
    console.log(i);
  }
}
 
printEven1To100();
3. Print all odd numbers between 1 and 100.
function printOdd1To100() {
  for (let i = 1; i <= 100; i += 2) {
    console.log(i);
  }
}
 
printOdd1To100();
4. Print numbers from 10 down to 1.
function print10To1() {
  for (let i = 10; i >= 1; i--) {
    console.log(i);
  }
}
 
print10To1();
5. Print the table of a given number (n × 1 to n × 10).
function printTable(n) {
  for (let i = 1; i <= 10; i++) {
    console.log(n + " x " + i + " = " + (n * i));
  }
}
 
printTable(5);
6. Print the sum of first n natural numbers.
function sumFirstN(n) {
  let sum = 0;
  for (let i = 1; i <= n; i++) {
    sum += i;
  }
  console.log("Sum: " + sum);
}
 
sumFirstN(10);
7. Print the sum of all even numbers up to n.
function sumEvenToN(n) {
  let sum = 0;
  for (let i = 2; i <= n; i += 2) {
    sum += i;
  }
  console.log("Sum of Evens: " + sum);
}
 
sumEvenToN(10);
8. Print the sum of all odd numbers up to n.
function sumOddToN(n) {
  let sum = 0;
  for (let i = 1; i <= n; i += 2) {
    sum += i;
  }
  console.log("Sum of Odds: " + sum);
}
 
sumOddToN(10);
9. Print the factorial of a given number.
function factorial(n) {
  let fact = 1;
  for (let i = 1; i <= n; i++) {
    fact *= i;
  }
  console.log("Factorial: " + fact);
}
 
factorial(5);
10. Print the product of digits of a given number.
function productOfDigits(n) {
  let product = 1;
  let temp = Math.abs(n);
  if (temp === 0) {
    product = 0;
  } else {
    while (temp > 0) {
      product *= (temp % 10);
      temp = Math.floor(temp / 10);
    }
  }
  console.log("Product: " + product);
}
 
productOfDigits(1234);

Level 2

1. Count the number of digits in a given number.
function countDigits(n) {
  let count = 0;
  let temp = Math.abs(n);
  if (temp === 0) count = 1;
  while (temp > 0) {
    count++;
    temp = Math.floor(temp / 10);
  }
  console.log("Count: " + count);
}
 
countDigits(12345);
2. Print the reverse of a given number.
function reverseNumber(n) {
  let rev = 0;
  let temp = Math.abs(n);
  while (temp > 0) {
    rev = rev * 10 + (temp % 10);
    temp = Math.floor(temp / 10);
  }
  if (n < 0) rev *= -1;
  console.log("Reverse: " + rev);
}
 
reverseNumber(1234);
3. Check if a number is a palindrome.
function isPalindrome(n) {
  let rev = 0;
  let temp = Math.abs(n);
  while (temp > 0) {
    rev = rev * 10 + (temp % 10);
    temp = Math.floor(temp / 10);
  }
  if (rev === Math.abs(n)) {
    console.log("Palindrome");
  } else {
    console.log("Not a palindrome");
  }
}
 
isPalindrome(121);
4. Find the sum of digits of a number.
function sumOfDigits(n) {
  let sum = 0;
  let temp = Math.abs(n);
  while (temp > 0) {
    sum += temp % 10;
    temp = Math.floor(temp / 10);
  }
  console.log("Sum: " + sum);
}
 
sumOfDigits(123);
5. Check if a number is an Armstrong number.
function isArmstrong(n) {
  let temp = Math.abs(n);
  const digits = n.toString().split('').map(Number);
  const p = digits.length;
  const sum = digits.reduce((acc, d) => acc + Math.pow(d, p), 0);
  if (sum === Math.abs(n)) {
    console.log("Armstrong Number");
  } else {
    console.log("Not an Armstrong Number");
  }
}
 
isArmstrong(153);
6. Check if a number is a perfect number.
function isPerfect(n) {
  if (n <= 1) return false;
  let sum = 1;
  for (let i = 2; i * i <= n; i++) {
    if (n % i === 0) {
      sum += i;
      if (i * i !== n) sum += n / i;
    }
  }
  if (sum === n) {
    console.log("Perfect Number");
  } else {
    console.log("Not a perfect number");
  }
}
 
isPerfect(28); // 1 + 2 + 4 + 7 + 14 = 28
7. Print all prime numbers between 1 and 100.
function printPrimes() {
  for (let i = 2; i <= 100; i++) {
    let isPrime = true;
    for (let j = 2; j * j <= i; j++) {
      if (i % j === 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) console.log(i);
  }
}
 
printPrimes();
8. Check if a number is prime or not.
function checkPrime(n) {
  if (n <= 1) {
    console.log("Not Prime");
    return;
  }
  let isPrime = true;
  for (let i = 2; i * i <= n; i++) {
    if (n % i === 0) {
      isPrime = false;
      break;
    }
  }
  if (isPrime) console.log("Prime");
  else console.log("Not Prime");
}
 
checkPrime(29);
9. Print Fibonacci series up to n terms.
function printFibonacci(n) {
  let a = 0, b = 1;
  for (let i = 1; i <= n; i++) {
    console.log(a);
    let next = a + b;
    a = b;
    b = next;
  }
}
 
printFibonacci(10);
10. Print sum of first n terms of Fibonacci series.
function sumFibonacci(n) {
  let a = 0, b = 1, sum = 0;
  for (let i = 1; i <= n; i++) {
    sum += a;
    let next = a + b;
    a = b;
    b = next;
  }
  console.log("Sum: " + sum);
}
 
sumFibonacci(10);

Level 3

1. Print the squares of numbers from 1 to n.
function printSquares(n) {
  for (let i = 1; i <= n; i++) {
    console.log(i * i);
  }
}
 
printSquares(10);
2. Print cubes of numbers from 1 to n.
function printCubes(n) {
  for (let i = 1; i <= n; i++) {
    console.log(Math.pow(i, 3));
  }
}
 
printCubes(5);
3. Print all numbers between a and b divisible by 7.
function printDivisibleBy7(a, b) {
  for (let i = a; i <= b; i++) {
    if (i % 7 === 0) console.log(i);
  }
}
 
printDivisibleBy7(10, 50);
4. Find HCF (GCD) of two numbers using loops.
function findGCD(a, b) {
  let gcd = 1;
  const min = Math.min(a, b);
  for (let i = 1; i <= min; i++) {
    if (a % i === 0 && b % i === 0) {
      gcd = i;
    }
  }
  console.log("GCD: " + gcd);
}
 
findGCD(12, 18);
5. Find LCM of two numbers using loops.
function findLCM(a, b) {
  let max = Math.max(a, b);
  while (true) {
    if (max % a === 0 && max % b === 0) {
      console.log("LCM: " + max);
      break;
    }
    max++;
  }
}
 
findLCM(12, 18);
6. Print all factors of a given number.
function printFactors(n) {
  for (let i = 1; i <= n; i++) {
    if (n % i === 0) console.log(i);
  }
}
 
printFactors(12);
7. Find the sum of all factors of a number.
function sumFactors(n) {
  let sum = 0;
  for (let i = 1; i <= n; i++) {
    if (n % i === 0) sum += i;
  }
  console.log("Sum: " + sum);
}
 
sumFactors(12);
8. Check if a number is a strong number (sum of factorials of digits = number).
function isStrong(n) {
  const factorial = (num) => {
    let f = 1;
    for (let i = 1; i <= num; i++) f *= i;
    return f;
  };
  let sum = 0;
  let temp = Math.abs(n);
  while (temp > 0) {
    sum += factorial(temp % 10);
    temp = Math.floor(temp / 10);
  }
  if (sum === Math.abs(n)) console.log("Strong Number");
  else console.log("Not a strong number");
}
 
isStrong(145); // 1! + 4! + 5! = 1 + 24 + 120 = 145
9. Print first n terms of an arithmetic progression (a, d).
function printAP(a, d, n) {
  for (let i = 0; i < n; i++) {
    console.log(a + i * d);
  }
}
 
printAP(2, 3, 10);
10. Print first n terms of a geometric progression (a, r).
function printGP(a, r, n) {
  let term = a;
  for (let i = 0; i < n; i++) {
    console.log(term);
    term *= r;
  }
}
 
printGP(2, 2, 10);

Level 4

1. Rectangular Star Pattern
function printRectangle(rows, cols) {
  for (let i = 0; i < rows; i++) {
    console.log("*".repeat(cols));
  }
}
 
printRectangle(5, 5);
2. Right Angled Triangle (Stars)
function printRightTriangle(n) {
  for (let i = 1; i <= n; i++) {
    console.log("*".repeat(i));
  }
}
 
printRightTriangle(5);
3. Inverted Right Angled Triangle
function printInvertedTriangle(n) {
  for (let i = n; i >= 1; i--) {
    console.log("*".repeat(i));
  }
}
 
printInvertedTriangle(5);
4. Pyramid Pattern
function printPyramid(n) {
  for (let i = 1; i <= n; i++) {
    let spaces = " ".repeat(n - i);
    let stars = "*".repeat(2 * i - 1);
    console.log(spaces + stars);
  }
}
 
printPyramid(5);
5. Diamond Pattern
function printDiamond(n) {
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - i) + "*".repeat(2 * i - 1));
  }
  for (let i = n - 1; i >= 1; i--) {
    console.log(" ".repeat(n - i) + "*".repeat(2 * i - 1));
  }
}
 
printDiamond(5);
6. Half Pyramid (Numbers)
function printNumberTriangle(n) {
  for (let i = 1; i <= n; i++) {
    let line = "";
    for (let j = 1; j <= i; j++) {
      line += j + " ";
    }
    console.log(line);
  }
}
 
printNumberTriangle(5);
7. Floyd's Triangle
function printFloydsTriangle(n) {
  let num = 1;
  for (let i = 1; i <= n; i++) {
    let line = "";
    for (let j = 1; j <= i; j++) {
      line += num + " ";
      num++;
    }
    console.log(line);
  }
}
 
printFloydsTriangle(5);
8. Pascal's Triangle (Simplified loop version)
function printPascalsTriangle(n) {
  for (let i = 0; i < n; i++) {
    let line = " ".repeat(n - i);
    let val = 1;
    for (let j = 0; j <= i; j++) {
      line += val + " ";
      val = val * (i - j) / (j + 1);
    }
    console.log(line);
  }
}
 
printPascalsTriangle(5);
9. Hollow Square Pattern
function printHollowSquare(n) {
  for (let i = 1; i <= n; i++) {
    if (i === 1 || i === n) {
      console.log("*".repeat(n));
    } else {
      console.log("*" + " ".repeat(n - 2) + "*");
    }
  }
}
 
printHollowSquare(5);
10. Inverted Pyramid
function printInvertedPyramid(n) {
  for (let i = n; i >= 1; i--) {
    let spaces = " ".repeat(n - i);
    let stars = "*".repeat(2 * i - 1);
    console.log(spaces + stars);
  }
}
 
printInvertedPyramid(5);

Level 5

1. Print all numbers whose sum of digits is even (1–100).
function printEvenDigitSumNumbers() {
  for (let i = 1; i <= 100; i++) {
    let sum = 0;
    let temp = i;
    while (temp > 0) {
      sum += temp % 10;
      temp = Math.floor(temp / 10);
    }
    if (sum % 2 === 0) console.log(i);
  }
}
 
printEvenDigitSumNumbers();
2. Count how many numbers between 1–500 are divisible by 7 but not by 5.
function countDivisible7Not5() {
  let count = 0;
  for (let i = 1; i <= 500; i++) {
    if (i % 7 === 0 && i % 5 !== 0) count++;
  }
  console.log("Count: " + count);
}
 
countDivisible7Not5();
3. Print all numbers that are palindromes between 1–500.
function printPalindromes() {
  for (let i = 1; i <= 500; i++) {
    let rev = 0;
    let temp = i;
    while (temp > 0) {
      rev = rev * 10 + (temp % 10);
      temp = Math.floor(temp / 10);
    }
    if (rev === i) console.log(i);
  }
}
 
printPalindromes();
4. Print numbers between 1–100 whose digits add up to a multiple of 3.
function printMultipleOf3Sum() {
  for (let i = 1; i <= 100; i++) {
    let sum = 0;
    let temp = i;
    while (temp > 0) {
      sum += temp % 10;
      temp = Math.floor(temp / 10);
    }
    if (sum % 3 === 0) console.log(i);
  }
}
 
printMultipleOf3Sum();
5. Find the smallest and largest digit in a given number.
function findMinMaxDigit(n) {
  let temp = Math.abs(n);
  if (temp === 0) {
    console.log("Min: 0, Max: 0");
    return;
  }
  let min = 9, max = 0;
  while (temp > 0) {
    let d = temp % 10;
    if (d < min) min = d;
    if (d > max) max = d;
    temp = Math.floor(temp / 10);
  }
  console.log("Min: " + min + ", Max: " + max);
}
 
findMinMaxDigit(14529);
6. Print all numbers from 1–n whose binary representation has an even number of 1s.
function printEvenBinaryOnes(n) {
  for (let i = 1; i <= n; i++) {
    let binary = i.toString(2);
    let count = (binary.match(/1/g) || []).length;
    if (count % 2 === 0) console.log(i + " (" + binary + ")");
  }
}
 
printEvenBinaryOnes(20);
7. Print a pattern where each row i prints i
function printSquarePattern(n) {
  for (let i = 1; i <= n; i++) {
    console.log((i * i).toString().repeat(i));
  }
}
 
printSquarePattern(5);
8. Print factorial of each number from 1 to n.
function printFactorials(n) {
  let fact = 1;
  for (let i = 1; i <= n; i++) {
    fact *= i;
    console.log("Factorial of " + i + " is " + fact);
  }
}
 
printFactorials(10);
9. Print the sum of all odd digits and even digits separately in a number.
function sumOddEvenDigits(n) {
  let oddSum = 0, evenSum = 0;
  let temp = Math.abs(n);
  while (temp > 0) {
    let d = temp % 10;
    if (d % 2 === 0) evenSum += d;
    else oddSum += d;
    temp = Math.floor(temp / 10);
  }
  console.log("Odd Sum: " + oddSum + ", Even Sum: " + evenSum);
}
 
sumOddEvenDigits(123456);
10. Take 5 numbers as input. If the user enters 0, skip it using continue. At the end, print the sum of all non-zero numbers entered.
function sumNonZeros(nums) {
  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === 0) continue;
    sum += nums[i];
  }
  console.log("Sum: " + sum);
}
 
sumNonZeros([10, 0, 20, 0, 30]);

Phase 3

Level 1

1. Print numbers from 1 to n using recursion.
function print1ToN(n) {
  if (n < 1) return;
  print1ToN(n - 1);
  console.log(n);
}
 
print1ToN(10);
2. Print numbers from n down to 1 using recursion.
function printNTo1(n) {
  if (n < 1) return;
  console.log(n);
  printNTo1(n - 1);
}
 
printNTo1(10);
3. Print only even numbers from 1 to n recursively.
function printEven(n) {
  if (n < 1) return;
  printEven(n - 1);
  if (n % 2 === 0) console.log(n);
}
 
printEven(10);
4. Print only odd numbers from 1 to n recursively.
function printOdd(n) {
  if (n < 1) return;
  printOdd(n - 1);
  if (n % 2 !== 0) console.log(n);
}
 
printOdd(10);
5. Print sum of first n natural numbers recursively.
function sumRecursion(n) {
  if (n <= 1) return n;
  return n + sumRecursion(n - 1);
}
 
console.log("Sum: " + sumRecursion(10));
6. Print factorial of a number recursively.
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
 
console.log("Factorial: " + factorial(5));
7. Calculate power of a number (xⁿ) using recursion.
function power(x, n) {
  if (n === 0) return 1;
  return x * power(x, n - 1);
}
 
console.log("Power (2^3): " + power(2, 3));
8. Find nth Fibonacci number recursively.
function nthFibonacci(n) {
  if (n <= 1) return n;
  return nthFibonacci(n - 1) + nthFibonacci(n - 2);
}
 
console.log("5th Fibonacci: " + nthFibonacci(5));
9. Print Fibonacci series up to n terms recursively.
function fibonacci(n) {
  if (n <= 0) return;
  function getFib(i) {
    if (i <= 1) return i;
    return getFib(i - 1) + getFib(i - 2);
  }
  for(let i=0; i<n; i++) {
    console.log(getFib(i));
  }
}
 
fibonacci(10);
10. Find sum of digits of a number recursively.
function sumOfDigits(n) {
  n = Math.abs(n);
  if (n === 0) return 0;
  return (n % 10) + sumOfDigits(Math.floor(n / 10));
}
 
console.log("Sum of Digits: " + sumOfDigits(1234));

Level 2

1. Count the number of digits in a number recursively.
function countDigits(n) {
  n = Math.abs(n);
  if (n < 10) return 1;
  return 1 + countDigits(Math.floor(n / 10));
}
 
console.log("Digits in 12345: " + countDigits(12345));
2. Reverse a number recursively.
function reverseNumber(n, rev = 0) {
  if (n === 0) return rev;
  rev = (rev * 10) + (n % 10);
  return reverseNumber(Math.floor(n / 10), rev);
}
 
console.log("Reverse of 123: " + reverseNumber(123));
3. Check if a number is a palindrome using recursion.
function isPalindrome(n) {
  const s = n.toString();
  function check(str) {
    if (str.length <= 1) return true;
    if (str[0] !== str[str.length - 1]) return false;
    return check(str.substring(1, str.length - 1));
  }
  return check(s);
}
 
console.log("Is 121 palindrome? " + isPalindrome(121));
4. Find product of digits of a number recursively.
function productOfDigits(n) {
  n = Math.abs(n);
  if (n === 0) return 0;
  if (n < 10) return n;
  return (n % 10) * productOfDigits(Math.floor(n / 10));
}
 
console.log("Product of digits of 123: " + productOfDigits(123));
5. Find GCD (HCF) of two numbers using Euclid’s algorithm recursively.
function findGCD(a, b) {
  if (b === 0) return a;
  return findGCD(b, a % b);
}
 
console.log("GCD of 12, 18: " + findGCD(12, 18));
6. Convert a number to binary recursively.
function decimalToBinary(n) {
  if (n === 0) return "0";
  if (n === 1) return "1";
  return decimalToBinary(Math.floor(n / 2)) + (n % 2);
}
 
console.log("Binary of 10: " + decimalToBinary(10));
7. Print digits of a number in words recursively (e.g., 123 → “one two three”).
function digitsToWords(n) {
  const words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
  if (n < 10) {
    return words[n];
  }
  return digitsToWords(Math.floor(n / 10)) + " " + words[n % 10];
}
 
console.log("123 in words: " + digitsToWords(123));
8. Calculate the sum of first n even numbers recursively.
function sumFirstNEven(n) {
  if (n <= 1) return 2;
  return (2 * n) + sumFirstNEven(n - 1);
}
 
console.log("Sum of first 5 even numbers: " + sumFirstNEven(5));
9. Calculate the sum of first n odd numbers recursively.
function sumFirstNOdd(n) {
  if (n <= 1) return 1;
  return (2 * n - 1) + sumFirstNOdd(n - 1);
}
 
console.log("Sum of first 5 odd numbers: " + sumFirstNOdd(5));
10. Find nCr (Combination formula) recursively using Pascal’s relation.
function nCr(n, r) {
  if (r === 0 || r === n) return 1;
  return nCr(n - 1, r) + nCr(n - 1, r - 1);
}
 
console.log("5C2: " + nCr(5, 2));

Level 3

1. Print a line of n stars recursively.
function printStarsLine(n) {
  if (n <= 0) {
    process.stdout.write("\n");
    return;
  }
  process.stdout.write("*");
  printStarsLine(n - 1);
}
 
printStarsLine(5);
2. Print a square of stars recursively (n×n).
function printStarsSquare(n, rows = n) {
  if (rows <= 0) return;
  console.log("*".repeat(n));
  printStarsSquare(n, rows - 1);
}
 
printStarsSquare(5);
3. Print a triangle of stars recursively (top-down).
function printTriangleTopDown(n) {
  if (n <= 0) return;
  console.log("*".repeat(n));
  printTriangleTopDown(n - 1);
}
 
printTriangleTopDown(5);
4. Print a triangle of stars recursively (bottom-up).
function printTriangleBottomUp(n) {
  if (n <= 0) return;
  printTriangleBottomUp(n - 1);
  console.log("*".repeat(n));
}
 
printTriangleBottomUp(5);
5. Print pattern of numbers recursively (1 to n each row).
function printNumberPattern(n, rows = 1) {
  if (rows > n) return;
  let line = "";
  for (let i = 1; i <= rows; i++) line += i + " ";
  console.log(line);
  printNumberPattern(n, rows + 1);
}
 
printNumberPattern(5);
6. Print reverse triangle pattern recursively.
function printReverseTriangle(n) {
  if (n <= 0) return;
  console.log("*".repeat(n));
  printReverseTriangle(n - 1);
}
 
printReverseTriangle(5);
7. Print multiplication table of n recursively.
function printTableRecursion(n, i = 1) {
  if (i > 10) return;
  console.log(n + " x " + i + " = " + (n * i));
  printTableRecursion(n, i + 1);
}
 
printTableRecursion(5);
8. Print numbers in increasing and decreasing order in same function.
function printIncDec(n) {
  if (n === 0) {
    console.log(0);
    return;
  }
  console.log(n);
  printIncDec(n - 1);
  console.log(n);
}
 
printIncDec(3);
9. Print sum of series 1 + 2 + 3 + ... + n recursively and display each step.
function sumSeries(n) {
  if (n <= 1) {
    console.log("Step 1: 1");
    return 1;
  }
  let sum = n + sumSeries(n - 1);
  console.log("Step " + n + ": " + sum);
  return sum;
}
 
sumSeries(5);
10. Print pattern of characters (A, AB, ABC, ...) recursively.
function printCharPattern(n, current = 1) {
  if (current > n) return;
  let line = "";
  for (let i = 0; i < current; i++) {
    line += String.fromCharCode(65 + i);
  }
  console.log(line);
  printCharPattern(n, current + 1);
}
 
printCharPattern(5);

Level 4

1. Reverse a string using recursion.
function reverseString(str) {
  if (str === "") return "";
  return reverseString(str.substring(1)) + str[0];
}
 
console.log("Reverse of 'hello': " + reverseString("hello"));
2. Check if a string is palindrome using recursion.
function isPalindrome(str) {
  if (str.length <= 1) return true;
  if (str[0] !== str[str.length - 1]) return false;
  return isPalindrome(str.substring(1, str.length - 1));
}
 
console.log("Is 'racecar' palindrome? " + isPalindrome("racecar"));
3. Count vowels in a string recursively.
function countVowels(str) {
  if (str === "") return 0;
  const isVowel = "aeiouAEIOU".includes(str[0]) ? 1 : 0;
  return isVowel + countVowels(str.substring(1));
}
 
console.log("Vowels in 'hello world': " + countVowels("hello world"));
4. Remove all spaces from a string recursively.
function removeSpaces(str) {
  if (str === "") return "";
  const first = str[0] === " " ? "" : str[0];
  return first + removeSpaces(str.substring(1));
}
 
console.log("Remove spaces: " + removeSpaces("h e l l o"));
5. Replace all occurrences of a character (say ‘a’ → ‘x’) recursively.
function replaceChar(str, oldChar, newChar) {
  if (str === "") return "";
  const first = str[0] === oldChar ? newChar : str[0];
  return first + replaceChar(str.substring(1), oldChar, newChar);
}
 
console.log("Replace 'a' with 'x': " + replaceChar("banana", "a", "x"));
6. Remove all occurrences of a character from a string recursively.
function removeChar(str, charToRemove) {
  if (str === "") return "";
  const first = str[0] === charToRemove ? "" : str[0];
  return first + removeChar(str.substring(1), charToRemove);
}
 
console.log("Remove 'a': " + removeChar("banana", "a"));
7. Print all characters of a string one by one recursively.
function printChars(str) {
  if (str === "") return;
  console.log(str[0]);
  printChars(str.substring(1));
}
 
printChars("abc");
8. Print the string in reverse order recursively (without using loops).
function printReverse(str) {
  if (str === "") return;
  printReverse(str.substring(1));
  console.log(str[0]);
}
 
printReverse("abc");
9. Convert a string to uppercase recursively.
function toUpperCaseRecursive(str) {
  if (str === "") return "";
  return str[0].toUpperCase() + toUpperCaseRecursive(str.substring(1));
}
 
console.log("Uppercase 'hello': " + toUpperCaseRecursive("hello"));
10. Count consonants and vowels separately using recursion.
function countVowelsAndConsonants(str, vowels = 0, consonants = 0) {
  if (str === "") return { vowels, consonants };
  const char = str[0].toLowerCase();
  if ("aeiou".includes(char)) {
    vowels++;
  } else if (char >= 'a' && char <= 'z') {
    consonants++;
  }
  return countVowelsAndConsonants(str.substring(1), vowels, consonants);
}
 
console.log("Vowels & Consonants in 'hello': ", countVowelsAndConsonants("hello"));

Phase 4

Level 1

1. Input n and take n integers into an array; print them.
function inputPrintArray(arr) {
  const n = arr.length;
  for (let i = 0; i < n; i++) {
    console.log(arr[i]);
  }
}
 
inputPrintArray([1, 2, 3, 4, 5]);
2. Find the sum of all elements in an array.
function sumArray(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
  }
  console.log("Sum: " + sum);
}
 
sumArray([1, 2, 3, 4, 5]);
3. Find the average of array elements.
function averageArray(arr) {
  if (arr.length === 0) return 0;
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
  }
  console.log("Average: " + (sum / arr.length));
}
 
averageArray([10, 20, 30, 40, 50]);
4. Find the maximum element in an array.
function findMax(arr) {
  if (arr.length === 0) return;
  let max = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > max) max = arr[i];
  }
  console.log("Max: " + max);
}
 
findMax([5, 12, 8, 20, 7]);
5. Find the minimum element in an array.
function findMin(arr) {
  if (arr.length === 0) return;
  let min = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < min) min = arr[i];
  }
  console.log("Min: " + min);
}
 
findMin([5, 12, 8, 20, 7]);
6. Count how many elements are positive, negative, or zero.
function countTypes(arr) {
  let pos = 0, neg = 0, zero = 0;
  for (let x of arr) {
    if (x > 0) pos++;
    else if (x < 0) neg++;
    else zero++;
  }
  console.log("Pos: " + pos + ", Neg: " + neg + ", Zero: " + zero);
}
 
countTypes([1, -2, 0, 5, -8, 0]);
7. Count how many elements are even and odd.
function countEvenOdd(arr) {
  let even = 0, odd = 0;
  for (let x of arr) {
    if (x % 2 === 0) even++;
    else odd++;
  }
  console.log("Even: " + even + ", Odd: " + odd);
}
 
countEvenOdd([1, 2, 3, 4, 5, 6]);
8. Find the index of the maximum element.
function findMaxIndex(arr) {
  if (arr.length === 0) return -1;
  let maxIdx = 0;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > arr[maxIdx]) maxIdx = i;
  }
  console.log("Max Index: " + maxIdx);
}
 
findMaxIndex([5, 12, 8, 20, 7]);
9. Find the index of the minimum element.
function findMinIndex(arr) {
  if (arr.length === 0) return -1;
  let minIdx = 0;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < arr[minIdx]) minIdx = i;
  }
  console.log("Min Index: " + minIdx);
}
 
findMinIndex([5, 12, 8, 2, 7]);
10. Take n elements and print only those greater than a given value k.
function printGreaterThanK(arr, k) {
  for (let x of arr) {
    if (x > k) console.log(x);
  }
}
 
printGreaterThanK([5, 12, 8, 20, 7], 10);

Level 2

1. Input an element x — check if it exists in the array.
function existsInArray(arr, x) {
  let found = false;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === x) {
      found = true;
      break;
    }
  }
  console.log(x + " exists: " + found);
}
 
existsInArray([1, 2, 3, 4, 5], 3);
2. Count how many times a given element appears.
function countOccurrence(arr, x) {
  let count = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === x) count++;
  }
  console.log("Count: " + count);
}
 
countOccurrence([1, 2, 3, 2, 5, 2], 2);
3. Find the first occurrence of a given number.
function firstOccurrence(arr, x) {
  let idx = -1;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === x) {
      idx = i;
      break;
    }
  }
  console.log("First Occurrence Index: " + idx);
}
 
firstOccurrence([1, 2, 3, 2, 5, 2], 2);
4. Find the last occurrence of a given number.
function lastOccurrence(arr, x) {
  let idx = -1;
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] === x) {
      idx = i;
      break;
    }
  }
  console.log("Last Occurrence Index: " + idx);
}
 
lastOccurrence([1, 2, 3, 2, 5, 2], 2);
5. Check if all elements in an array are unique.
function areAllUnique(arr) {
  let unique = true;
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) {
        unique = false;
        break;
      }
    }
    if (!unique) break;
  }
  console.log("All unique: " + unique);
}
 
areAllUnique([1, 2, 3, 4, 5]);
areAllUnique([1, 2, 3, 2, 5]);
6. Find the sum of even elements only.
function sumEven(arr) {
  let sum = 0;
  for (let x of arr) {
    if (x % 2 === 0) sum += x;
  }
  console.log("Sum of Evens: " + sum);
}
 
sumEven([1, 2, 3, 4, 5, 6]);
7. Find the sum of odd elements only.
function sumOdd(arr) {
  let sum = 0;
  for (let x of arr) {
    if (x % 2 !== 0) sum += x;
  }
  console.log("Sum of Odds: " + sum);
}
 
sumOdd([1, 2, 3, 4, 5, 6]);
8. Find the count of prime numbers in the array.
function countPrimes(arr) {
  function isPrime(n) {
    if (n <= 1) return false;
    for (let i = 2; i * i <= n; i++) {
      if (n % i === 0) return false;
    }
    return true;
  }
  let count = 0;
  for (let x of arr) {
    if (isPrime(x)) count++;
  }
  console.log("Prime Count: " + count);
}
 
countPrimes([2, 3, 4, 5, 6, 7, 8, 9, 11]);
9. Count how many numbers are divisible by 3 and 5 both.
function countDiv3And5(arr) {
  let count = 0;
  for (let x of arr) {
    if (x % 3 === 0 && x % 5 === 0) count++;
  }
  console.log("Count: " + count);
}
 
countDiv3And5([15, 30, 10, 5, 45]);
10. Count how many elements are perfect squares.
function countPerfectSquares(arr) {
  function isPerfectSquare(n) {
    if (n < 0) return false;
    let s = Math.round(Math.sqrt(n));
    return s * s === n;
  }
  let count = 0;
  for (let x of arr) {
    if (isPerfectSquare(x)) count++;
  }
  console.log("Perfect Squares Count: " + count);
}
 
countPerfectSquares([1, 4, 5, 9, 16, 20]);

Level 3

1. Create a new array containing squares of all numbers.
function getSquares(arr) {
  const result = [];
  for (let x of arr) {
    result.push(x * x);
  }
  console.log("Squares:", result);
  return result;
}
 
getSquares([1, 2, 3, 4, 5]);
2. Create a new array containing only even elements.
function getEvens(arr) {
  const result = [];
  for (let x of arr) {
    if (x % 2 === 0) result.push(x);
  }
  console.log("Evens:", result);
  return result;
}
 
getEvens([1, 2, 3, 4, 5, 6]);
3. Replace every negative number with 0.
function replaceNegatives(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < 0) arr[i] = 0;
  }
  console.log("Result:", arr);
}
 
replaceNegatives([1, -2, 3, -4, 5]);
4. Replace all even numbers with 1 and all odd with 0.
function binaryReplace(arr) {
  for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[i] % 2 === 0 ? 1 : 0;
  }
  console.log("Result:", arr);
}
 
binaryReplace([1, 2, 3, 4, 5]);
5. Swap the first and last elements of the array.
function swapFirstLast(arr) {
  if (arr.length < 2) return;
  let temp = arr[0];
  arr[0] = arr[arr.length - 1];
  arr[arr.length - 1] = temp;
  console.log("Swapped:", arr);
}
 
swapFirstLast([1, 2, 3, 4, 5]);
6. Reverse an array (without using built-in reverse).
function reverseArray(arr) {
  let start = 0, end = arr.length - 1;
  while (start < end) {
    let temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    start++;
    end--;
  }
  console.log("Reversed:", arr);
}
 
reverseArray([1, 2, 3, 4, 5]);
7. Rotate an array by one position to the left.
function rotateLeft(arr) {
  if (arr.length < 2) return;
  let first = arr[0];
  for (let i = 0; i < arr.length - 1; i++) {
    arr[i] = arr[i + 1];
  }
  arr[arr.length - 1] = first;
  console.log("Rotated Left:", arr);
}
 
rotateLeft([1, 2, 3, 4, 5]);
8. Rotate an array by one position to the right.
function rotateRight(arr) {
  if (arr.length < 2) return;
  let last = arr[arr.length - 1];
  for (let i = arr.length - 1; i > 0; i--) {
    arr[i] = arr[i - 1];
  }
  arr[0] = last;
  console.log("Rotated Right:", arr);
}
 
rotateRight([1, 2, 3, 4, 5]);
9. Swap alternate elements (1st ↔ 2nd, 3rd ↔ 4th, etc.).
function swapAlternate(arr) {
  for (let i = 0; i < arr.length - 1; i += 2) {
    let temp = arr[i];
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
  }
  console.log("Swapped Alternate:", arr);
}
 
swapAlternate([1, 2, 3, 4, 5]);
10. Copy one array to another manually.
function copyArray(arr) {
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    result[i] = arr[i];
  }
  console.log("Copied Array:", result);
  return result;
}
 
copyArray([1, 2, 3, 4, 5]);

Level 4

1. Compare two arrays — check if they are equal (same elements & order).
function compareEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    console.log("Not Equal");
    return;
  }
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) {
      console.log("Not Equal");
      return;
    }
  }
  console.log("Equal");
}
 
compareEqual([1, 2, 3], [1, 2, 3]);
2. Compare two arrays — check if they contain the same elements (ignore order).
function compareIgnoreOrder(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    console.log("Not Same Elements");
    return;
  }
  const sorted1 = [...arr1].sort();
  const sorted2 = [...arr2].sort();
  for (let i = 0; i < sorted1.length; i++) {
    if (sorted1[i] !== sorted2[i]) {
      console.log("Not Same Elements");
      return;
    }
  }
  console.log("Same Elements");
}
 
compareIgnoreOrder([1, 2, 3], [3, 2, 1]);
3. Merge two arrays into a third array.
function mergeArrays(arr1, arr2) {
  const result = [];
  for (let x of arr1) result.push(x);
  for (let x of arr2) result.push(x);
  console.log("Merged:", result);
  return result;
}
 
mergeArrays([1, 2], [3, 4]);
4. Find the common elements between two arrays.
function findCommon(arr1, arr2) {
  const common = [];
  for (let x of arr1) {
    if (arr2.includes(x) && !common.includes(x)) {
      common.push(x);
    }
  }
  console.log("Common:", common);
}
 
findCommon([1, 2, 3], [2, 3, 4]);
5. Find elements that are in one array but not in the other.
function findDifference(arr1, arr2) {
  const diff = [];
  for (let x of arr1) {
    if (!arr2.includes(x)) diff.push(x);
  }
  console.log("Difference (A-B):", diff);
}
 
findDifference([1, 2, 3], [2, 3, 4]);
6. Count how many elements are common between two arrays.
function countCommon(arr1, arr2) {
  let count = 0;
  const seen = [];
  for (let x of arr1) {
    if (arr2.includes(x) && !seen.includes(x)) {
      count++;
      seen.push(x);
    }
  }
  console.log("Common Count: " + count);
}
 
countCommon([1, 2, 3], [2, 3, 4]);
7. Find element-wise sum of two arrays (A[i] + B[i]).
function elementWiseSum(arr1, arr2) {
  const len = Math.min(arr1.length, arr2.length);
  const result = [];
  for (let i = 0; i < len; i++) {
    result.push(arr1[i] + arr2[i]);
  }
  console.log("Element-wise Sum:", result);
}
 
elementWiseSum([1, 2, 3], [4, 5, 6]);
8. Find element-wise product of two arrays.
function elementWiseProduct(arr1, arr2) {
  const len = Math.min(arr1.length, arr2.length);
  const result = [];
  for (let i = 0; i < len; i++) {
    result.push(arr1[i] * arr2[i]);
  }
  console.log("Element-wise Product:", result);
}
 
elementWiseProduct([1, 2, 3], [4, 5, 6]);
9. Create a frequency array of numbers (count occurrence of each number).
function frequencyMap(arr) {
  const freq = {};
  for (let x of arr) {
    freq[x] = (freq[x] || 0) + 1;
  }
  console.log("Frequency:", freq);
}
 
frequencyMap([1, 2, 2, 3, 3, 3]);
10. Print all elements that appear more than once.
function printDuplicates(arr) {
  const freq = {};
  const dups = [];
  for (let x of arr) {
    freq[x] = (freq[x] || 0) + 1;
  }
  for (let key in freq) {
    if (freq[key] > 1) dups.push(key);
  }
  console.log("Duplicates:", dups);
}
 
printDuplicates([1, 2, 2, 3, 4, 4, 5]);

Level 5

1. Check if the array is sorted in ascending order.
function isSortedAsc(arr) {
  let sorted = true;
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] > arr[i + 1]) {
      sorted = false;
      break;
    }
  }
  console.log("Sorted Ascending:", sorted);
}
 
isSortedAsc([1, 2, 3, 4, 5]);
isSortedAsc([1, 3, 2, 4, 5]);
2. Check if the array is sorted in descending order.
function isSortedDesc(arr) {
  let sorted = true;
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] < arr[i + 1]) {
      sorted = false;
      break;
    }
  }
  console.log("Sorted Descending:", sorted);
}
 
isSortedDesc([5, 4, 3, 2, 1]);
isSortedDesc([5, 4, 6, 2, 1]);
3. Find the second largest element in an array.
function findSecondLargest(arr) {
  if (arr.length < 2) return;
  let first = -Infinity, second = -Infinity;
  for (let x of arr) {
    if (x > first) {
      second = first;
      first = x;
    } else if (x > second && x !== first) {
      second = x;
    }
  }
  console.log("Second Largest:", second);
}
 
findSecondLargest([5, 12, 8, 20, 7]);
4. Find the second smallest element in an array.
function findSecondSmallest(arr) {
  if (arr.length < 2) return;
  let first = Infinity, second = Infinity;
  for (let x of arr) {
    if (x < first) {
      second = first;
      first = x;
    } else if (x < second && x !== first) {
      second = x;
    }
  }
  console.log("Second Smallest:", second);
}
 
findSecondSmallest([5, 12, 8, 20, 7]);
5. Find the difference between the largest and smallest element.
function maxMinDiff(arr) {
  if (arr.length === 0) return 0;
  let max = arr[0], min = arr[0];
  for (let x of arr) {
    if (x > max) max = x;
    if (x < min) min = x;
  }
  console.log("Difference:", max - min);
}
 
maxMinDiff([5, 12, 8, 20, 7]);
6. Find the sum of all elements except the largest and smallest.
function sumExceptExtremes(arr) {
  if (arr.length <= 2) return 0;
  let max = arr[0], min = arr[0], sum = 0;
  for (let x of arr) {
    if (x > max) max = x;
    if (x < min) min = x;
    sum += x;
  }
  console.log("Sum except extremes:", sum - max - min);
}
 
sumExceptExtremes([5, 12, 8, 20, 7]);
7. Count how many pairs of elements have a sum equal to a given number k.
function countPairSum(arr, k) {
  let count = 0;
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] + arr[j] === k) count++;
    }
  }
  console.log("Pair Sum Count:", count);
}
 
countPairSum([1, 2, 3, 4, 5], 5); // (1,4), (2,3) -> 2
8. Count how many elements are greater than the average of the array.
function greaterThanAverage(arr) {
  if (arr.length === 0) return 0;
  let sum = 0;
  for (let x of arr) sum += x;
  const avg = sum / arr.length;
  let count = 0;
  for (let x of arr) {
    if (x > avg) count++;
  }
  console.log("Count:", count);
}
 
greaterThanAverage([10, 20, 30, 40, 50]);
9. Print the frequency of each distinct element.
function printDistinctFrequency(arr) {
  const freq = {};
  for (let x of arr) freq[x] = (freq[x] || 0) + 1;
  for (let key in freq) {
    console.log(key + ": " + freq[key]);
  }
}
 
printDistinctFrequency([1, 2, 2, 3, 3, 3]);
10. Print all unique elements (those that occur exactly once).
function printUniqueElements(arr) {
  const freq = {};
  for (let x of arr) freq[x] = (freq[x] || 0) + 1;
  const unique = [];
  for (let key in freq) {
    if (freq[key] === 1) unique.push(key);
  }
  console.log("Unique elements:", unique);
}
 
printUniqueElements([1, 2, 2, 3, 4, 4, 5]);

Phase 5

Category 1

1. Take a string input and print its length.
function printStringLength(str) {
  console.log("Length: " + str.length);
}
 
printStringLength("Hello World");
2. Print the first and last character of a string.
function printFirstLast(str) {
  if (str.length === 0) return;
  console.log("First: " + str[0] + ", Last: " + str[str.length - 1]);
}
 
printFirstLast("JavaScript");
3. Convert all characters of a string to uppercase.
function toUpperCase(str) {
  console.log(str.toUpperCase());
}
 
toUpperCase("hello");
4. Convert all characters of a string to lowercase.
function toLowerCase(str) {
  console.log(str.toLowerCase());
}
 
toLowerCase("HELLO");
5. Count how many characters (excluding spaces) are in the string.
function countCharsNoSpaces(str) {
  let count = 0;
  for (let char of str) {
    if (char !== ' ') count++;
  }
  console.log("Character Count: " + count);
}
 
countCharsNoSpaces("Hello World");
6. Count how many words are in a sentence.
function countWords(str) {
  const words = str.trim().split(/\s+/);
  console.log("Word Count: " + (str.trim() === "" ? 0 : words.length));
}
 
countWords("This is a test sentence.");
7. Take two strings and print them concatenated.
function concatenate(str1, str2) {
  console.log(str1 + str2);
}
 
concatenate("Hello", "World");
8. Compare two strings lexicographically (like dictionary order).
function compareLexicographical(str1, str2) {
  if (str1 < str2) console.log(str1 + " comes before " + str2);
  else if (str1 > str2) console.log(str2 + " comes before " + str1);
  else console.log("Both are equal");
}
 
compareLexicographical("apple", "banana");
9. Print the ASCII value of each character in a string.
function printASCII(str) {
  for (let i = 0; i < str.length; i++) {
    console.log(str[i] + ": " + str.charCodeAt(i));
  }
}
 
printASCII("ABC");
10. Check whether the string is empty or not.
function isEmpty(str) {
  if (str.length === 0) {
    console.log("Empty");
  } else {
    console.log("Not Empty");
  }
}
 
isEmpty("");
isEmpty("Not empty");

Category 2

1. Count how many vowels and consonants are in a string.
function countVowelsConsonants(str) {
  let vowels = 0, consonants = 0;
  const s = str.toLowerCase();
  for (let char of s) {
    if ("aeiou".includes(char)) vowels++;
    else if (char >= 'a' && char <= 'z') consonants++;
  }
  console.log("Vowels: " + vowels + ", Consonants: " + consonants);
}
 
countVowelsConsonants("Hello World");
2. Count the number of digits, letters, and special characters in a string.
function countTypes(str) {
  let digits = 0, letters = 0, special = 0;
  for (let char of str) {
    if (/[a-zA-Z]/.test(char)) letters++;
    else if (/[0-9]/.test(char)) digits++;
    else special++;
  }
  console.log("Letters: " + letters + ", Digits: " + digits + ", Special: " + special);
}
 
countTypes("Hello123!@#");
3. Count how many uppercase and lowercase letters a string has.
function countCase(str) {
  let upper = 0, lower = 0;
  for (let char of str) {
    if (char >= 'A' && char <= 'Z') upper++;
    else if (char >= 'a' && char <= 'z') lower++;
  }
  console.log("Uppercase: " + upper + ", Lowercase: " + lower);
}
 
countCase("Hello World");
4. Find the frequency of each character in a string (without using a map).
function charFrequency(str) {
  const chars = str.split('').sort();
  let i = 0;
  while (i < chars.length) {
    let count = 1;
    let char = chars[i];
    while (i + 1 < chars.length && chars[i + 1] === char) {
      count++;
      i++;
    }
    console.log(char + ": " + count);
    i++;
  }
}
 
charFrequency("banana");
5. Count how many spaces are there in a sentence.
function countSpaces(str) {
  let count = 0;
  for (let char of str) {
    if (char === ' ') count++;
  }
  console.log("Spaces: " + count);
}
 
countSpaces("This is a test sentence.");
6. Count how many times a given character appears in a string.
function charOccurrence(str, target) {
  let count = 0;
  for (let char of str) {
    if (char === target) count++;
  }
  console.log("Occurrence of '" + target + "': " + count);
}
 
charOccurrence("hello world", 'l');
7. Count how many alphabets are before ‘m’ and after ‘m’ in a given string.
function countBeforeAfterM(str) {
  let before = 0, after = 0;
  const s = str.toLowerCase();
  for (let char of s) {
    if (char >= 'a' && char < 'm') before++;
    else if (char > 'm' && char <= 'z') after++;
  }
  console.log("Before 'm': " + before + ", After 'm': " + after);
}
 
countBeforeAfterM("JavaScript");
8. Count how many substrings start and end with the same character (simple logic - O(n^2)).
function countSubstringsSameStartEnd(str) {
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    for (let j = i; j < str.length; j++) {
      if (str[i] === str[j]) count++;
    }
  }
  console.log("Count: " + count);
}
 
countSubstringsSameStartEnd("abcab");
9. Print how many words start with a vowel in a sentence.
function countWordsStartVowel(str) {
  const words = str.toLowerCase().split(/\s+/);
  let count = 0;
  for (let word of words) {
    if ("aeiou".includes(word[0])) count++;
  }
  console.log("Count: " + count);
}
 
countWordsStartVowel("An apple a day keeps the doctor away");
10. Count how many words end with ‘s’.
function countWordsEndS(str) {
  const words = str.toLowerCase().split(/\s+/);
  let count = 0;
  for (let word of words) {
    if (word.endsWith('s')) count++;
  }
  console.log("Count: " + count);
}
 
countWordsEndS("cats and dogs play with toys");

Category 3

1. Reverse a string without using built-in reverse.
function reverseString(str) {
  let rev = "";
  for (let i = str.length - 1; i >= 0; i--) {
    rev += str[i];
  }
  console.log("Reversed: " + rev);
}
 
reverseString("hello");
2. Reverse each word in a sentence.
function reverseEachWord(str) {
  const result = str.split(' ').map(word => {
    return word.split('').reverse().join('');
  }).join(' ');
  console.log("Result: " + result);
}
 
reverseEachWord("hello world");
3. Reverse the order of words in a sentence.
function reverseWordOrder(str) {
  const result = str.split(' ').reverse().join(' ');
  console.log("Result: " + result);
}
 
reverseWordOrder("hello world from js");
4. Check whether a string is a palindrome.
function isPalindrome(str) {
  const rev = str.split('').reverse().join('');
  const result = str === rev;
  console.log("Is Palindrome: " + result);
}
 
isPalindrome("racecar");
5. Check if two strings are the reverse of each other.
function isReversePair(s1, s2) {
  const result = s1 === s2.split('').reverse().join('');
  console.log("Is Reverse Pair: " + result);
}
 
isReversePair("abc", "cba");
6. Print the middle character(s) of a string.
function printMiddle(str) {
  const n = str.length;
  if (n === 0) return;
  const mid = Math.floor(n / 2);
  if (n % 2 !== 0) {
    console.log("Middle: " + str[mid]);
  } else {
    console.log("Middle: " + str[mid - 1] + str[mid]);
  }
}
 
printMiddle("abc");  // b
printMiddle("abcd"); // bc
7. Print the second half of the string in reverse.
function printSecondHalfReverse(str) {
  const mid = Math.floor(str.length / 2);
  const secondHalf = str.substring(mid);
  const result = secondHalf.split('').reverse().join('');
  console.log("Result: " + result);
}
 
printSecondHalfReverse("JavaScript"); // Script -> tpircS
8. Remove the first and last character and print the remaining string.
function removeExtremes(str) {
  if (str.length <= 2) {
    console.log("");
  } else {
    console.log(str.substring(1, str.length - 1));
  }
}
 
removeExtremes("Hello"); // ell
9. Reverse only characters, keeping digits in place.
function reverseCharsKeepDigits(str) {
  let chars = str.split('').filter(c => isNaN(c) || c === ' ');
  chars.reverse();
  let result = "";
  let j = 0;
  for (let i = 0; i < str.length; i++) {
    if (isNaN(str[i]) || str[i] === ' ') {
      result += chars[j++];
    } else {
      result += str[i];
    }
  }
  console.log("Result: " + result);
}
 
reverseCharsKeepDigits("a1b2c"); // c1b2a
10. Reverse string but skip spaces.
function reverseSkipSpaces(str) {
  let chars = str.split('').filter(c => c !== ' ');
  chars.reverse();
  let result = "";
  let j = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === ' ') {
      result += ' ';
    } else {
      result += chars[j++];
    }
  }
  console.log("Result: " + result);
}
 
reverseSkipSpaces("hello world"); // dlrow olleh

Category 4

1. Remove all vowels from a string.
function removeVowels(str) {
  const result = str.replace(/[aeiouAEIOU]/g, '');
  console.log("Result: " + result);
}
 
removeVowels("Hello World");
2. Remove all spaces from a string.
function removeSpaces(str) {
  const result = str.replace(/\s+/g, '');
  console.log("Result: " + result);
}
 
removeSpaces("H e l l o");
3. Replace all vowels with ‘
function replaceVowels(str) {
  const result = str.replace(/[aeiouAEIOU]/g, '*');
  console.log("Result: " + result);
}
 
replaceVowels("Javascript");
4. Replace all spaces with ‘_’.
function replaceSpaces(str) {
  const result = str.replace(/\s+/g, '_');
  console.log("Result: " + result);
}
 
replaceSpaces("hello world from js");
5. Print the string after removing all digits.
function removeDigits(str) {
  const result = str.replace(/[0-9]/g, '');
  console.log("Result: " + result);
}
 
removeDigits("abc123def456");
6. Remove duplicate characters from a string.
function removeDuplicateChars(str) {
  let result = "";
  for (let char of str) {
    if (!result.includes(char)) result += char;
  }
  console.log("Result: " + result);
}
 
removeDuplicateChars("banana");
7. Keep only the first occurrence of each character.
function keepFirstOccurrence(str) {
  let result = "";
  for (let char of str) {
    if (result.indexOf(char) === -1) result += char;
  }
  console.log("Result: " + result);
}
 
keepFirstOccurrence("apple");
8. Remove consecutive duplicate characters (e.g., “aaabb” → “ab”).
function removeConsecutiveDuplicates(str) {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    if (str[i] !== str[i + 1]) result += str[i];
  }
  console.log("Result: " + result);
}
 
removeConsecutiveDuplicates("aaabbccaa");
9. Swap case: uppercase → lowercase and lowercase → uppercase.
function swapCase(str) {
  let result = "";
  for (let char of str) {
    if (char >= 'A' && char <= 'Z') result += char.toLowerCase();
    else if (char >= 'a' && char <= 'z') result += char.toUpperCase();
    else result += char;
  }
  console.log("Result: " + result);
}
 
swapCase("Hello World");
10. Shift each character by 1 (e.g., “abc” → “bcd”).
function shiftChars(str) {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    const code = str.charCodeAt(i);
    result += String.fromCharCode(code + 1);
  }
  console.log("Result: " + result);
}
 
shiftChars("abc");

Category 5

1. Print each word of a sentence on a new line.
function printEachWord(str) {
  const words = str.split(/\s+/);
  for (let word of words) {
    if (word) console.log(word);
  }
}
 
printEachWord("Hello world from JavaScript");
2. Count how many words have even length.
function countEvenLengthWords(str) {
  const words = str.split(/\s+/);
  let count = 0;
  for (let word of words) {
    if (word && word.length % 2 === 0) count++;
  }
  console.log("Even Length Count: " + count);
}
 
countEvenLengthWords("This is an even word test");
3. Find the longest word in a sentence.
function findLongestWord(str) {
  const words = str.split(/\s+/);
  let longest = "";
  for (let word of words) {
    if (word.length > longest.length) longest = word;
  }
  console.log("Longest: " + longest);
}
 
findLongestWord("JavaScript is a powerful language");
4. Find the shortest word in a sentence.
function findShortestWord(str) {
  const words = str.split(/\s+/).filter(w => w.length > 0);
  if (words.length === 0) return;
  let shortest = words[0];
  for (let word of words) {
    if (word.length < shortest.length) shortest = word;
  }
  console.log("Shortest: " + shortest);
}
 
findShortestWord("JS is cool");
5. Swap first and last words in a sentence.
function swapFirstLastWords(str) {
  const words = str.split(/\s+/);
  if (words.length < 2) return;
  let temp = words[0];
  words[0] = words[words.length - 1];
  words[words.length - 1] = temp;
  console.log("Result: " + words.join(' '));
}
 
swapFirstLastWords("Hello world from JS");
6. Print all words that start and end with the same letter.
function wordsStartEndSameLetter(str) {
  const words = str.toLowerCase().split(/\s+/);
  for (let word of words) {
    if (word.length > 1 && word[0] === word[word.length - 1]) {
      console.log(word);
    }
  }
}
 
wordsStartEndSameLetter("Mom and dad went to a park with a pup");
7. Count how many words contain the letter ‘a’.
function countWordsWithA(str) {
  const words = str.toLowerCase().split(/\s+/);
  let count = 0;
  for (let word of words) {
    if (word.includes('a')) count++;
  }
  console.log("Count: " + count);
}
 
countWordsWithA("This is a simple apple test");
8. Capitalize the first letter of each word.
function capitalizeFirstLetters(str) {
  const words = str.split(/\s+/).map(word => {
    return word.charAt(0).toUpperCase() + word.slice(1);
  });
  console.log("Result: " + words.join(' '));
}
 
capitalizeFirstLetters("hello world from javascript");
9. Print the sentence in title case (first letter capital, rest lowercase).
function toTitleCase(str) {
  const result = str.split(/\s+/).map(word => {
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  }).join(' ');
  console.log("Result: " + result);
}
 
toTitleCase("hELLO wORLD fROM js");
10. Remove extra spaces between words (normalize spacing).
function normalizeSpacing(str) {
  const result = str.trim().split(/\s+/).join(' ');
  console.log("Result: '" + result + "'");
}
 
normalizeSpacing("  Hello    world   from   JS  ");

Phase 6

Category 1

1. Print all numbers between 1 and N that are divisible by both 3 and 5.
function printDiv3And5(n) {
  for (let i = 1; i <= n; i++) {
    if (i % 3 === 0 && i % 5 === 0) console.log(i);
  }
}
 
printDiv3And5(100);
2. Find the sum of digits of a number (use loop).
function sumOfDigits(n) {
  let sum = 0;
  let temp = Math.abs(n);
  while (temp > 0) {
    sum += temp % 10;
    temp = Math.floor(temp / 10);
  }
  console.log("Sum: " + sum);
}
 
sumOfDigits(12345);
3. Check if a number is an Armstrong number.
function isArmstrong(n) {
  const digits = n.toString().split('').map(Number);
  const p = digits.length;
  const sum = digits.reduce((acc, d) => acc + Math.pow(d, p), 0);
  console.log(n + " is Armstrong: " + (sum === n));
}
 
isArmstrong(153);
4. Print all Armstrong numbers between 1 and 1000.
function printArmstrongRange() {
  for (let i = 1; i <= 1000; i++) {
    let digits = i.toString().split('').map(Number);
    let p = digits.length;
    let sum = digits.reduce((acc, d) => acc + Math.pow(d, p), 0);
    if (sum === i) console.log(i);
  }
}
 
printArmstrongRange();
5. Find the factorial of a number using recursion.
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
 
console.log("Factorial (5): " + factorial(5));
6. Count how many even digits a number contains.
function countEvenDigits(n) {
  let count = 0;
  let temp = Math.abs(n);
  while (temp > 0) {
    if ((temp % 10) % 2 === 0) count++;
    temp = Math.floor(temp / 10);
  }
  console.log("Even Digits: " + count);
}
 
countEvenDigits(123456);
7. Print all prime numbers between 1 and N.
function printPrimes(n) {
  for (let i = 2; i <= n; i++) {
    let isPrime = true;
    for (let j = 2; j * j <= i; j++) {
      if (i % j === 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) console.log(i);
  }
}
 
printPrimes(50);
8. Print the reverse of a number (123 → 321).
function reverseNumber(n) {
  let rev = 0;
  let temp = Math.abs(n);
  while (temp > 0) {
    rev = rev * 10 + (temp % 10);
    temp = Math.floor(temp / 10);
  }
  console.log("Reverse: " + (n < 0 ? -rev : rev));
}
 
reverseNumber(123);
9. Check if a number is palindrome (121 → true).
function isPalindrome(n) {
  let rev = 0;
  let temp = Math.abs(n);
  while (temp > 0) {
    rev = rev * 10 + (temp % 10);
    temp = Math.floor(temp / 10);
  }
  console.log(n + " is palindrome: " + (rev === Math.abs(n)));
}
 
isPalindrome(121);
10. Check if a number is perfect (sum of factors equals number).
function isPerfect(n) {
  if (n <= 1) return false;
  let sum = 1;
  for (let i = 2; i * i <= n; i++) {
    if (n % i === 0) {
      sum += i;
      if (i * i !== n) sum += n / i;
    }
  }
  console.log(n + " is perfect: " + (sum === n));
}
 
isPerfect(28);

Category 2

1. Check if two strings are anagrams (without using collections).
function isAnagram(s1, s2) {
  if (s1.length !== s2.length) {
    console.log("Not Anagrams");
    return;
  }
  const sortStr = (s) => s.split('').sort().join('');
  if (sortStr(s1) === sortStr(s2)) {
    console.log("Anagrams");
  } else {
    console.log("Not Anagrams");
  }
}
 
isAnagram("listen", "silent");
2. Count vowels in each word of a sentence.
function countVowelsPerWord(str) {
  const words = str.split(/\s+/);
  for (let word of words) {
    const vowels = (word.match(/[aeiouAEIOU]/g) || []).length;
    console.log(word + ": " + vowels);
  }
}
 
countVowelsPerWord("JavaScript is awesome");
3. Reverse words in a string if their length is even.
function reverseEvenLenWords(str) {
  const result = str.split(/\s+/).map(word => {
    if (word.length % 2 === 0) return word.split('').reverse().join('');
    return word;
  }).join(' ');
  console.log("Result: " + result);
}
 
reverseEvenLenWords("Hello world from JS"); // Hello -> Hello, world -> world, from -> from, JS -> SJ
4. Replace every vowel in a string with its position (a=1, e=2, i=3, o=4, u=5).
function replaceVowelsPosition(str) {
  const map = { a: 1, e: 2, i: 3, o: 4, u: 5 };
  let result = "";
  for (let char of str) {
    const l = char.toLowerCase();
    if (map[l]) result += map[l];
    else result += char;
  }
  console.log("Result: " + result);
}
 
replaceVowelsPosition("apple"); // 1ppl2
5. Print characters that appear more than once (without map).
function charsMoreThanOnce(str) {
  const chars = str.split('').sort();
  let i = 0;
  let result = "";
  while (i < chars.length) {
    let count = 1;
    let char = chars[i];
    while (i + 1 < chars.length && chars[i + 1] === char) {
      count++;
      i++;
    }
    if (count > 1) result += char + " ";
    i++;
  }
  console.log("Result: " + result);
}
 
charsMoreThanOnce("banana");
6. Count words that start and end with the same letter.
function countStartEndSame(str) {
  const words = str.toLowerCase().split(/\s+/);
  let count = 0;
  for (let word of words) {
    if (word.length > 1 && word[0] === word[word.length - 1]) count++;
  }
  console.log("Count: " + count);
}
 
countStartEndSame("Mom and dad went to park with a pup");
7. Toggle case for every alternate word in a sentence.
function toggleAlternateWords(str) {
  const result = str.split(/\s+/).map((word, i) => {
    if (i % 2 === 1) {
      return word.split('').map(c => {
        if (c >= 'A' && c <= 'Z') return c.toLowerCase();
        if (c >= 'a' && c <= 'z') return c.toUpperCase();
        return c;
      }).join('');
    }
    return word;
  }).join(' ');
  console.log("Result: " + result);
}
 
toggleAlternateWords("Hello World from JavaScript");
8. Check if two strings are rotations of each other.
function isRotation(s1, s2) {
  if (s1.length !== s2.length) {
    console.log("Not Rotations");
    return;
  }
  const result = (s1 + s1).includes(s2);
  console.log("Is Rotation: " + result);
}
 
isRotation("abcd", "cdab");
9. Find the word with maximum vowels in a sentence.
function maxVowelsWord(str) {
  const words = str.split(/\s+/);
  let maxVowels = -1;
  let result = "";
  for (let word of words) {
    const count = (word.match(/[aeiouAEIOU]/g) || []).length;
    if (count > maxVowels) {
      maxVowels = count;
      result = word;
    }
  }
  console.log("Word with max vowels: " + result);
}
 
maxVowelsWord("JavaScript is amazing language");
10. Remove duplicate words from a sentence.
function removeDuplicateWords(str) {
  const words = str.split(/\s+/);
  const result = [];
  for (let word of words) {
    if (!result.includes(word)) result.push(word);
  }
  console.log("Result: " + result.join(' '));
}
 
removeDuplicateWords("hello world hello js");

Category 3

1. Implement Bubble Sort logic to sort an array.
function bubbleSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  console.log("Sorted:", arr);
}
 
bubbleSort([5, 1, 4, 2, 8]);
2. Implement Binary Search logic (array must be sorted).
function binarySearch(arr, x) {
  let start = 0, end = arr.length - 1;
  while (start <= end) {
    let mid = Math.floor((start + end) / 2);
    if (arr[mid] === x) return mid;
    if (arr[mid] < x) start = mid + 1;
    else end = mid - 1;
  }
  return -1;
}
 
const arr = [1, 2, 4, 8, 12];
console.log("Index of 8: " + binarySearch(arr, 8));
3. Find missing number in an array of 1 to N.
function findMissing(arr, n) {
  const expectedSum = (n * (n + 1)) / 2;
  const actualSum = arr.reduce((a, b) => a + b, 0);
  console.log("Missing Number: " + (expectedSum - actualSum));
}
 
findMissing([1, 2, 4, 5], 5); // 3
4. Generate Fibonacci series up to N terms using iteration.
function fibonacciIteration(n) {
  let a = 0, b = 1;
  const result = [];
  for (let i = 0; i < n; i++) {
    result.push(a);
    let next = a + b;
    a = b;
    b = next;
  }
  console.log("Fibonacci:", result);
}
 
fibonacciIteration(10);
5. Calculate sum of Fibonacci series up to N terms.
function sumFibonacci(n) {
  let a = 0, b = 1, sum = 0;
  for (let i = 0; i < n; i++) {
    sum += a;
    let next = a + b;
    a = b;
    b = next;
  }
  console.log("Sum: " + sum);
}
 
sumFibonacci(5); // 0+1+1+2+3 = 7
6. Calculate x^n using iteration.
function powerIteration(x, n) {
  let res = 1;
  for (let i = 0; i < n; i++) res *= x;
  console.log("Result: " + res);
}
 
powerIteration(2, 5);
7. Check if a number is a power of 2.
function isPowerOfTwo(n) {
  if (n <= 0) return false;
  const result = (n & (n - 1)) === 0;
  console.log(n + " is power of 2: " + result);
}
 
isPowerOfTwo(16);
isPowerOfTwo(18);
8. Find the sum of all elements in a 2x2 matrix.
function sumMatrix(matrix) {
  let sum = 0;
  for (let row of matrix) {
    for (let val of row) sum += val;
  }
  console.log("Matrix Sum: " + sum);
}
 
sumMatrix([[1, 2], [3, 4]]);
9. Find the sum of diagonal elements of a 3x3 matrix.
function diagonalSum(matrix) {
  let sum = 0;
  for (let i = 0; i < matrix.length; i++) {
    sum += matrix[i][i];
  }
  console.log("Diagonal Sum: " + sum);
}
 
diagonalSum([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
10. Implement Transpose of a 2x2 matrix.
function transposeMatrix(matrix) {
  const result = [[0, 0], [0, 0]];
  for (let i = 0; i < 2; i++) {
    for (let j = 0; j < 2; j++) {
      result[i][j] = matrix[j][i];
    }
  }
  console.log("Transpose:", result);
}
 
transposeMatrix([[1, 2], [3, 4]]);

Category 4

1. Merge two sorted arrays into one sorted array.
function mergeSorted(arr1, arr2) {
  let i = 0, j = 0;
  const result = [];
  while (i < arr1.length && j < arr2.length) {
    if (arr1[i] < arr2[j]) result.push(arr1[i++]);
    else result.push(arr2[j++]);
  }
  while (i < arr1.length) result.push(arr1[i++]);
  while (j < arr2.length) result.push(arr2[j++]);
  console.log("Merged:", result);
}
 
mergeSorted([1, 3, 5], [2, 4, 6]);
2. Find the second largest element in an array in a single pass.
function secondLargestOnePass(arr) {
  if (arr.length < 2) return;
  let max = -Infinity, secondMax = -Infinity;
  for (let x of arr) {
    if (x > max) {
      secondMax = max;
      max = x;
    } else if (x > secondMax && x !== max) {
      secondMax = x;
    }
  }
  console.log("Second Max:", secondMax);
}
 
secondLargestOnePass([10, 5, 20, 15, 20]);
3. Check if one array is a subset of another.
function isSubset(arr1, arr2) {
  let result = arr2.every(val => arr1.includes(val));
  console.log("Is Subset: " + result);
}
 
isSubset([1, 2, 3, 4, 5], [2, 4]); // true
4. Find the intersection of two arrays without using Map.
function intersectionNoMap(arr1, arr2) {
  const result = [];
  for (let x of arr1) {
    if (arr2.includes(x) && !result.includes(x)) result.push(x);
  }
  console.log("Intersection:", result);
}
 
intersectionNoMap([1, 2, 3], [2, 3, 4]);
5. Find the union of two arrays without using Map.
function unionNoMap(arr1, arr2) {
  const result = [...arr1];
  for (let x of arr2) {
    if (!result.includes(x)) result.push(x);
  }
  console.log("Union:", result);
}
 
unionNoMap([1, 2], [2, 3]);
6. Move all zeros in an array to the end while maintaining order.
function moveZeros(arr) {
  let j = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== 0) {
      [arr[i], arr[j]] = [arr[j], arr[i]];
      j++;
    }
  }
  console.log("Result:", arr);
}
 
moveZeros([0, 1, 0, 3, 12]);
7. Count triplets in an array whose sum is less than a given value K.
function countTripletsSum(arr, k) {
  arr.sort((a, b) => a - b);
  let count = 0;
  for (let i = 0; i < arr.length - 2; i++) {
    let j = i + 1, m = arr.length - 1;
    while (j < m) {
      if (arr[i] + arr[j] + arr[m] < k) {
        count += (m - j);
        j++;
      } else {
        m--;
      }
    }
  }
  console.log("Triplets Count: " + count);
}
 
countTripletsSum([5, 1, 3, 4, 7], 12);
8. Find the majority element (appears more than n/2 times).
function findMajority(arr) {
  let candidate = null, count = 0;
  for (let x of arr) {
    if (count === 0) {
      candidate = x;
      count = 1;
    } else if (x === candidate) {
      count++;
    } else {
      count--;
    }
  }
  // Verify candidate
  let actualCount = arr.filter(x => x === candidate).length;
  if (actualCount > arr.length / 2) {
    console.log("Majority Element: " + candidate);
  } else {
    console.log("No Majority Element");
  }
}
 
findMajority([3, 3, 4, 2, 3, 3, 1]);
9. Find the length of the longest consecutive subsequence.
function longestConsecutive(arr) {
  if (arr.length === 0) return 0;
  arr.sort((a, b) => a - b);
  let maxLen = 1, currentLen = 1;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] === arr[i - 1] + 1) {
      currentLen++;
    } else if (arr[i] !== arr[i - 1]) {
      maxLen = Math.max(maxLen, currentLen);
      currentLen = 1;
    }
  }
  console.log("Max Length: " + Math.max(maxLen, currentLen));
}
 
longestConsecutive([100, 4, 200, 1, 3, 2]); // 4 (1,2,3,4)
10. Find a peak element (greater than its neighbors).
function findPeak(arr) {
  const n = arr.length;
  if (n === 1) return 0;
  if (arr[0] >= arr[1]) return 0;
  if (arr[n - 1] >= arr[n - 2]) return n - 1;
  for (let i = 1; i < n - 1; i++) {
    if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i;
  }
  return -1;
}
 
const peakIdx = findPeak([1, 2, 3, 1]);
console.log("Peak at Index: " + peakIdx);

Category 5

1. Solve Tower of Hanoi for 3 discs recursively.
function towerOfHanoi(n, from, to, aux) {
  if (n === 1) {
    console.log("Move disc 1 from " + from + " to " + to);
    return;
  }
  towerOfHanoi(n - 1, from, aux, to);
  console.log("Move disc " + n + " from " + from + " to " + to);
  towerOfHanoi(n - 1, aux, to, from);
}
 
towerOfHanoi(3, 'A', 'C', 'B');
2. Generate Pascal’s Triangle up to N rows.
function generatePascal(n) {
  const triangle = [];
  for (let i = 0; i < n; i++) {
    triangle[i] = new Array(i + 1).fill(1);
    for (let j = 1; j < i; j++) {
      triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
    }
  }
  console.log("Pascal's Triangle:");
  triangle.forEach(row => console.log(row.join(' ')));
}
 
generatePascal(5);
3. Print elements of a 2x2 matrix in spiral order.
function printSpiral2x2(matrix) {
  if (!matrix || matrix.length === 0) return;
  console.log("Spiral Order: " + matrix[0][0] + " " + matrix[0][1] + " " + matrix[1][1] + " " + matrix[1][0]);
}
 
printSpiral2x2([[1, 2], [3, 4]]);
4. Find all unique triplets in an array that sum to zero.
function findTripletsSumZero(arr) {
  arr.sort((a, b) => a - b);
  const result = [];
  for (let i = 0; i < arr.length - 2; i++) {
    if (i > 0 && arr[i] === arr[i - 1]) continue;
    let j = i + 1, k = arr.length - 1;
    while (j < k) {
      const sum = arr[i] + arr[j] + arr[k];
      if (sum === 0) {
        result.push([arr[i], arr[j], arr[k]]);
        while (j < k && arr[j] === arr[j + 1]) j++;
        while (j < k && arr[k] === arr[k - 1]) k--;
        j++; k--;
      } else if (sum < 0) j++;
      else k--;
    }
  }
  console.log("Triplets:", result);
}
 
findTripletsSumZero([-1, 0, 1, 2, -1, -4]);
5. Best time to buy and sell stock (find max profit).
function maxProfit(prices) {
  let minPrice = Infinity, maxProfit = 0;
  for (let p of prices) {
    if (p < minPrice) minPrice = p;
    else if (p - minPrice > maxProfit) maxProfit = p - minPrice;
  }
  console.log("Max Profit: " + maxProfit);
}
 
maxProfit([7, 1, 5, 3, 6, 4]);
6. Find the number of ways to climb N stairs (1 or 2 steps).
function climbStairs(n) {
  if (n <= 2) return n;
  let a = 1, b = 2;
  for (let i = 3; i <= n; i++) {
    let next = a + b;
    a = b;
    b = next;
  }
  return b;
}
 
console.log("Ways to climb 5 stairs: " + climbStairs(5));
7. Check if a string has valid parentheses.
function isValidParenthesis(str) {
  const stack = [];
  const map = { ')': '(', '}': '{', ']': '[' };
  for (let char of str) {
    if (['(', '{', '['].includes(char)) {
      stack.push(char);
    } else if (map[char]) {
      if (stack.pop() !== map[char]) {
        console.log("Invalid");
        return;
      }
    }
  }
  console.log(stack.length === 0 ? "Valid" : "Invalid");
}
 
isValidParenthesis("({[]})");
8. Trapping rain water problem (simple logic using prefix/suffix max).
function trapRainWater(height) {
  const n = height.length;
  if (n === 0) return 0;
  const leftMax = new Array(n), rightMax = new Array(n);
  leftMax[0] = height[0];
  for (let i = 1; i < n; i++) leftMax[i] = Math.max(leftMax[i - 1], height[i]);
  rightMax[n - 1] = height[n - 1];
  for (let i = n - 2; i >= 0; i--) rightMax[i] = Math.max(rightMax[i + 1], height[i]);
  let result = 0;
  for (let i = 0; i < n; i++) result += Math.min(leftMax[i], rightMax[i]) - height[i];
  console.log("Trapped Water: " + result);
}
 
trapRainWater([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]);
9. Remove duplicates from a sorted array in-place and return new length.
function removeDupsSorted(arr) {
  if (arr.length === 0) return 0;
  let j = 0;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] !== arr[j]) {
      j++;
      arr[j] = arr[i];
    }
  }
  console.log("New Length: " + (j + 1) + ", Array:", arr.slice(0, j + 1));
}
 
removeDupsSorted([1, 1, 2, 2, 3, 4, 4]);
10. Reverse an integer and check for 32-bit signed integer overflow.
function reverseInt(n) {
  const limit = Math.pow(2, 31);
  let rev = 0;
  let temp = Math.abs(n);
  while (temp > 0) {
    rev = rev * 10 + (temp % 10);
    temp = Math.floor(temp / 10);
  }
  if (rev > limit - 1) {
    console.log("Overflow");
    return 0;
  }
  console.log("Result: " + (n < 0 ? -rev : rev));
}
 
reverseInt(123);
reverseInt(1534236469); // Overflow