0% found this document useful (0 votes)
14 views

_Day 1 Problem Statements & Systematic Approaches

The document outlines a series of coding sessions focused on problem-solving and systematic approaches using JavaScript. It includes various practice questions and functions for tasks such as determining the positivity of numbers, calculating sums, and manipulating strings. Additionally, it covers mathematical problems, pattern creation, and string operations, providing a comprehensive overview of fundamental programming concepts.

Uploaded by

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

_Day 1 Problem Statements & Systematic Approaches

The document outlines a series of coding sessions focused on problem-solving and systematic approaches using JavaScript. It includes various practice questions and functions for tasks such as determining the positivity of numbers, calculating sums, and manipulating strings. Additionally, it covers mathematical problems, pattern creation, and string operations, providing a comprehensive overview of fundamental programming concepts.

Uploaded by

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

Session 1

//? Day 1: Problem Statements & Systematic Approaches

//* Session Focus: Interpreting problem statements, breaking down problems systematically.

//? Session Practice Questions:

//! Determine if a number is positive or negative.

function isPositive(num) {

if (num > 0) {

return "Positive";

} else if (num == 0) {

return "Zero";

} else {

return "Negative";

//! Find the sum of two integers.

function sumOfTwoNumbers(num1, num2) {

return num1 + num2;

//! Identify the maximum, middle and minimum of three numbers.

function max(num1, num2) {

return num1 < num2 ? num2 : num1;

function min(num1, num2) {

return num1 < num2 ? num1 : num2;


}

function maxMiddleMin(num1, num2, num3) {

let maximum = max(max(num1, num2), num3);

let minimum = min(min(num1, num2), num3);

let middle = num1 + num2 + num3 - maximum - minimum;

return [maximum, middle, minimum];

// console.log(maxMiddleMin(1, 2, 3));

// console.log(maxMiddleMin(3, 2, 1));

// console.log(maxMiddleMin(2, 3, 1));

// console.log(maxMiddleMin(2, 1, 3));

// console.log(maxMiddleMin(1, 3, 2));

// console.log(maxMiddleMin(3, 1, 2));

//! Count the number of digits in a number.

function countDigits(num) {

if (num == 0) return 1;

if (num < 0) return countDigits(-num);

let count = 0;

while (num > 0) {

num = Math.floor(num / 10);

count++;

return count;

//! Check if a string contains only alphabets.


// function isAlphabetOnly(str) {

// let regex = /^[a-zA-Z]+$/;

// return regex.test(str);

// }

function isAlphabetOnly(str) {

if(str.length == 0) return false

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

let charCode = str.charCodeAt(i);

if (

!(charCode >= 65 && charCode <= 90) &&

!(charCode >= 97 && charCode <= 122)

){

return false;

return true;

// console.log("a".charCodeAt(0));

// console.log("z".charCodeAt(0));

// console.log("A".charCodeAt(0));

// console.log("Z".charCodeAt(0));

//! Calculate the area of a circle with a given radius.

function areaOfCircle(rad) {

return ((22 / 7) * rad * rad).toFixed(2);

//! Check if a character is a vowel.

function isVowel(char) {
// return char == 'a' || char == 'e' || char == 'i' || char == 'o' || char == 'u' || char == 'A' || char == 'E' || char == 'I' ||
char == 'O' || char == 'U'

return "aeiouAEIOU".indexOf(char) !== -1;

module.exports = {

isPositive,

sumOfTwoNumbers,

maxMiddleMin,

countDigits,

isAlphabetOnly,

areaOfCircle,

isVowel,

};

// todo Post-Session Practice Questions:

// todo Calculate the difference between two integers.

function difference1(a, b) {

return a > b ? a - b : b - a;

function difference2(a, b) {

return Math.abs(a - b);

// todo Check if a number is even or odd.

function isEvenOrOdd(num) {

return num % 2 === 0 ? "Even" : "Odd";

// todo Calculate the perimeter of a rectangle.


function perimeterOfRectangle(length, width) {

return 2 * (length + width);

// todo Find the largest of four numbers.

function findLargest(a, b, c, d) {

return Math.max(a, b, c, d);

// todo Calculate the average of three numbers.

function averageOfThree(a, b, c) {

return (a + b + c) / 3;

// todo Count the number of vowels in a string.

function countVowels(str) {

const vowels = "aeiouAEIOU"; // Include uppercase vowels

let count = 0;

for (let char of str) {

if (vowels.includes(char)) {

count++;

return count;

// todo Determine if a character is uppercase.

function isUpperCase(char) {

return /^[A-Z]$/.test(char);
}

// todo Print the reverse of a string.

function reverseString(str) {

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

// todo Find the square of a number.

function square(num) {

return num ** 2;

module.exports = {

isPositive,

sumOfTwoNumbers,

maxMiddleMin,

countDigits,

isAlphabetOnly,

areaOfCircle,

isVowel,

difference1,

difference2,

};

Session 2

// function swap(num1, num2) {

// console.log(num1, num2);

// let temp = num1;


// num1 = num2;

// num2 = temp;

// console.log(num1, num2);

// }

// function swap(num1, num2) {

// num1 = num1 + num2;

// num2 = num1 - num2;

// num1 = num1 - num2;

// console.log(num1, num2);

// }

// function swap(num1, num2) {

// num1 = num1 ^ num2;

// num2 = num1 ^ num2;

// num1 = num1 ^ num2;

// console.log(num1, num2);

// }

// function swap(num1, num2) {

// [num1, num2] = [num2, num1];

// console.log(num1, num2)

// }

// function swap(num1, num2) {

// console.log(num1, num2)

// num1 = num1 + num2 - (num2 = num1);

// console.log(num1, num2)

// }
// swap(10, 15);

// swapWithoutTemp(10, 15)

//? Day 2: Maths & Pattern Creation

//* Session Focus: Solving fundamental math problems and creating patterns.

//? Session Practice Questions:

//! Sum of digits in a number.

function sumOfDigits(num) {

let sum = 0;

let temp = num;

while (num > 0) {

sum += num % 10;

num = Math.floor(num / 10);

return [temp, sum];

// console.log(sumOfDigits(1372))

//! Calculate the factorial of a number.

function fact(num) {

// 5 => 5 * 4 * 3 * 2 * 1 = 120

if (num == 0) return 1;

let factorial = 1;

for (let val = num; val > 0; val--) {

factorial = val * factorial;

return factorial;

}
// console.log(fact(5));

//! Generate the Fibonacci sequence up to N terms.(Space Complexity)

// 0 1 1 2 3 5 8 13 21 34 55 89

function fibonacci(n) {

// let sequence = [0, 1];

let x = 0;

let y = 1;

if (n < 1) return;

if (n < 2) {

console.log(0);

return;

if (n < 3) {

console.log(0);

console.log(1);

return;

for (let ind = 0; ind < n; ind++) {

console.log(x);

x = x + y;

y = x - y;

// for (let i = 0; i < 100; i++)

// console.log(...fibonacci(10));

//! Check if a number is prime. (Time Complexity)

function isPrime(num) {
if (num < 2) return false;

if (num == 2) return true;

if (num % 2 == 0) return false;

// let x = num / 2;

// for (let factor = 2; factor < num; factor++) {

// for (let factor = 2; factor < num/2; factor++) {

// for (let factor = 2; factor * factor <= num; factor++) {

for (let factor = 3; factor * factor <= num; factor += 2) {

if (num % factor == 0) return [factor, false];

return true;

// console.time("isPrime");

// const x = isPrime(1057438801);

// console.timeEnd("isPrime");

// console.log(x);

//! Print a hollow square pattern.

// 5

// * * * * *

// * *

// * *

// * *

// * * * * *

function hallowSquare(n) {

for (let row = 0; row < n; row++) {

const line = [];


for (let col = 0; col < n; col++) {

if (

row == 0 ||

col == 0 ||

row == col ||

row == n - col - 1 ||

row == Math.floor(n / 2) ||

col == Math.floor(n / 2) ||

row == n - 1 ||

col == n - 1

line.push("*");

else line.push(" ");

console.log(line.join(" "));

// hallowSquare(15);

//! Print a right-angled triangle pattern of asterisks.

function patterns(n) {

for (let row = 0; row < n; row++) {

const line = [];

for (let col = 0; col < n; col++) {

if ((row < n / 2 && col < n / 2) || (row >= n / 2 && col >= n / 2)) {

if ((row+col) % 2 == 0) line.push("*");

else line.push("#");

} else line.push(" ");


}

console.log(line.join(" "));

patterns(10);

module.exports = { sumOfDigits };

// todo Post-Session Practice Questions:

// todo Find the LCM of two numbers.

function findLCM_GCD(a, b) {

function gcd(x, y) {

return y === 0 ? x : gcd(y, x % y);

return (a * b) / gcd(a, b);

console.log(findLCM_GCD(12, 18)); // Output: 36

// todo Generate a pyramid pattern of numbers.

function numberPyramid_Iterative(n) {

for (let i = 1; i <= n; i++) {

let str = " ".repeat(n - i);

for (let j = 1; j <= i; j++) {

str += j + " ";

console.log(str);

}
numberPyramid_Iterative(5);

// todo Calculate the GCD of two numbers.

function findGCD_Iterative(a, b) {

while (b !== 0) {

let temp = b;

b = a % b;

a = temp;

return a;

console.log(findGCD_Iterative(12, 18)); // Output: 6

// todo Check if a number is a palindrome.

//with string conversion

function isPalindrome_String(num) {

let str = num.toString();

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

console.log(isPalindrome_String(121)); // Output: true

console.log(isPalindrome_String(123)); // Output: false

//without string conversion

function isPalindrome_Numeric(num) {

let reversed = 0, temp = num;

while (temp > 0) {


reversed = reversed * 10 + (temp % 10);

temp = Math.floor(temp / 10);

return reversed === num;

console.log(isPalindrome_Numeric(121)); // Output: true

console.log(isPalindrome_Numeric(123)); // Output: false

// todo Print an inverted triangle pattern of stars.

function invertedTriangle_Iterative(n) {

for (let i = n; i >= 1; i--) {

console.log("*".repeat(i));

invertedTriangle_Iterative(5);

// todo Check if two numbers are coprime.

function areCoprime_GCD(a, b) {

function gcd(x, y) {

return y === 0 ? x : gcd(y, x % y);

return gcd(a, b) === 1;

console.log(areCoprime_GCD(8, 9)); // Output: true

console.log(areCoprime_GCD(12, 18)); // Output: false

// todo Print a diamond pattern of stars.


function diamondPattern_TwoLoops(n) {

// Top half (including the middle row)

for (let i = 1; i <= n; i += 2) {

console.log(" ".repeat((n - i) / 2) + "*".repeat(i));

// Bottom half

for (let i = n - 2; i >= 1; i -= 2) {

console.log(" ".repeat((n - i) / 2) + "*".repeat(i));

diamondPattern_TwoLoops(5);

// todo Print Pascal’s triangle up to N rows.

function pascalTriangle_Iterative(n) {

let triangle = [[1]];

for (let i = 1; i < n; i++) {

let row = [1];

for (let j = 1; j < i; j++) {

row.push(triangle[i - 1][j - 1] + triangle[i - 1][j]);

row.push(1);

triangle.push(row);

triangle.forEach(row => console.log(" ".repeat(n - row.length) + row.join(" ")));

}
pascalTriangle_Iterative(5);

// todo Find all divisors of a number.

function findDivisors_Loop(n) {

let divisors = [];

for (let i = 1; i <= Math.sqrt(n); i++) {

if (n % i === 0) {

divisors.push(i);

if (i !== n / i) divisors.push(n / i);

return divisors.sort((a, b) => a - b);

console.log(findDivisors_Loop(28)); // Output: [1, 2, 4, 7, 14, 28]

// todo Print a checkerboard pattern.

function checkerboardPattern_Nested(n) {

for (let i = 0; i < n; i++) {

let row = "";

for (let j = 0; j < n; j++) {

row += (i + j) % 2 === 0 ? "* " : "# ";

console.log(row);

checkerboardPattern_Nested(5);
Session 3

//? Day 3: Strings & String Manipulation

//* Session Focus: Basic string operations, string traversal, and manipulation techniques.

//? Session Practice Questions:

//! Reverse a string.

function reverseStr(str = "") {

// return str.split("").reverse().join("")

let revStr = "";

for (let ind = str.length; ind >= 0; ind--) {

revStr += str.charAt(ind);

return revStr;

// console.log(reverseStr("Hello World!"));

//! Count vowels and consonants in a string.

function countVowAndCons(str) {

const obj = { vowels: 0, consonants: 0 };

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

if ("aeiou".indexOf(str.charAt(ind)) != -1) {

obj.vowels++;

} else if (str.charCodeAt(ind) >= 97 && str.charCodeAt(ind) <= 122) {

obj.consonants++;

}
return obj;

// console.log(countVowAndCons("Convert a string to lowercase/uppercase."));

//! Convert a string to lowercase/uppercase.

function toLowerCase(str) {

let res = "";

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

if (str.charCodeAt(ind) >= 65 && str.charCodeAt(ind) <= 90) {

res += String.fromCharCode(str.charCodeAt(ind) + 32);

} else {

res += str.charAt(ind);

return res;

function toUpperCase(str) {

let res = "";

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

if (str.charCodeAt(ind) >= 97 && str.charCodeAt(ind) <= 122) {

res += String.fromCharCode(str.charCodeAt(ind) - 32);

} else {

res += str.charAt(ind);

return res;

}
function convertTo(str, toUpper = true) {

let convertedStr = "";

if (toUpper) {

convertedStr = toUpperCase(str);

} else {

convertedStr = toLowerCase(str);

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

// const char = str[ind];

// if (char.charCodeAt(0) >= 65 && char.charCodeAt(0) <= 90) {

// // checking char whether it is uppercase

// if (toUpper) {

// // needs to be changed uppercase?

// convertedStr += char;

// } else {

// // needs to be changed to lowercase?

// convertedStr += String.fromCharCode(char.charCodeAt(0) + 32);

// }

// } else if (char.charCodeAt(0) >= 97 && char.charCodeAt(0) <= 122) {

// // checking char whether it is lowercase

// if (toUpper) {

// // needs to change to uppercase?

// convertedStr += String.fromCharCode(char.charCodeAt(0) - 32);

// } else {

// // to lowercase?

// convertedStr += char;
// }

// } else {

// // it is not an alphabet?

// convertedStr += char;

// }

// }

return convertedStr;

// console.log(convertTo("Find the longest word in a sentence."));

// console.log(convertTo("Find the longest word in a sentence.", false));

//! Find the longest word in a sentence.

function findLongestWord(str) {

let longest = "";

for (let word of str.split(" ")) {

if (word.length > longest.length) longest = word;

return longest;

// console.log(findLongestWord("Remove duplicates from a string"));

//! Check if a string is a palindrome.

function isPalindrome(str) {

// return str === reverseStr(str);

// two pointers approach

let left = 0,

right = str.length - 1;
while (left < right) {

if (str[left] != str[right]) {

return false;

left++;

right--;

return true;

// console.log(isPalindrome("madam"));

// console.log(isPalindrome("racecar"));

// console.log(isPalindrome("javascript"));

//! Remove duplicates from a string.

function removeDuplicates(str) {

let uniqueStr = "";

for (let char of str) {

if (!uniqueStr.includes(char)) {

uniqueStr += char;

return uniqueStr;

// console.log(removeDuplicates("Find all substrings of a given string."));

//! Find all substrings of a given string.

function allSubstrings(str) {

const substrings = [""];


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

let substring = "";

for (let ind = itr; ind < str.length; ind++) {

// nested loop for substring

substring += str[ind];

substrings.push(substring);

return substrings;

// console.log(allSubstrings("string"));

// todo Post-Session Practice Questions:

// todo Concatenate two strings.

function concatenateStrings(str1, str2) {

let result = "";

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

result += str1[i];

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

result += str2[i];

return result;

console.log(concatenateStrings("Hello", "World"));

// todo Find the frequency of each character in a string.

function frequencyCounter(str) {
let freq = {};

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

let char = str[i];

if (freq[char]) {

freq[char]++;

} else {

freq[char] = 1;

return freq;

console.log(frequencyCounter("banana"));

// todo Replace spaces in a string with %20.

function replaceSpaces(str) {

let result = "";

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

if (str[i] === " ") {

result += "%20";

} else {

result += str[i];

return result;

console.log(replaceSpaces("hello world"));

// todo Check if a string is an anagram and panagram of another.


function isAnagram(str1, str2) {

let freq1 = {}, freq2 = {};

if (str1.length !== str2.length) return false;

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

freq1[str1[i]] = (freq1[str1[i]] || 0) + 1;

freq2[str2[i]] = (freq2[str2[i]] || 0) + 1;

for (let key in freq1) {

if (freq1[key] !== freq2[key]) return false;

return true;

console.log(isAnagram("listen", "silent"));

function isPangram(str) {

let letters = {};

let count = 0;

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

let ch = str[i].toLowerCase();

if (ch >= 'a' && ch <= 'z' && !letters[ch]) {

letters[ch] = true;

count++;

}
}

return count === 26;

console.log(isPangram("The quick brown fox jumps over the lazy dog"));

// todo Count the number of words in a sentence.

function countWords(sentence) {

let count = 0, inWord = false;

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

if (sentence[i] !== " " && !inWord) {

count++;

inWord = true;

} else if (sentence[i] === " ") {

inWord = false;

return count;

console.log(countWords("Count the number of words in a sentence"));

// todo Find the first non-repeating character in a string.

function firstNonRepeatingChar(str) {

let freq = {};

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

freq[str[i]] = (freq[str[i]] || 0) + 1;

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

if (freq[str[i]] === 1) return str[i];

return null;

console.log(firstNonRepeatingChar("swiss"));

// todo Remove all vowels from a string.

function removeVowels(str) {

let result = "";

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

let ch = str[i].toLowerCase();

if (ch !== "a" && ch !== "e" && ch !== "i" && ch !== "o" && ch !== "u") {

result += str[i];

return result;

console.log(removeVowels("Remove vowels from this string"));

// todo Find the shortest word in a sentence.

function shortestWord(sentence) {

let minLen = Infinity, minWord = "", word = "";

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

if (i === sentence.length || sentence[i] === ' ') {

if (word.length > 0 && word.length < minLen) {

minLen = word.length;
minWord = word;

word = "";

} else {

word += sentence[i];

return minWord;

console.log(shortestWord("Find the shortest word in a sentence"));

// todo Count occurrences of a substring within a string.

function countSubstring(str, sub) {

let count = 0;

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

let match = true;

for (let j = 0; j < sub.length; j++) {

if (str[i + j] !== sub[j]) {

match = false;

break;

if (match) count++;

return count;

}
console.log(countSubstring("ababababa", "aba"));

Session 4

// ? Day 4: Arrays & Array Manipulations

// * Session Focus: Array creation, traversal, and manipulation techniques.

// ? Session Practice Questions:

// ! Calculate the sum of elements in an array.

function sumOfArr(arr = []) {

let sum = 0;

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

sum += arr[ind];

return sum;

// ! Find the maximum and minimum elements in an array.

function maxAndMin(arr = []) {

let min = arr[0];

let max = arr[0];

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

if (min > arr[ind]) {

min = arr[ind];

if (max < arr[ind]) {

max = arr[ind];

}
return [min, max];

// ! Find the second-largest element in an array.

function secondLargest(arr = []) {

// console.log(arr);

let max = arr[0];

let secLargest = -Infinity;

for (let ind = 1; ind < arr.length; ind++) {

if (max < arr[ind]) {

secLargest = max;

max = arr[ind];

if (arr[ind] < max && secLargest < arr[ind]) {

secLargest = arr[ind];

return secLargest;

// console.log(secondLargest([1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5]));

// ! Rotate an array to the left by one position.

function rotate(arr = []) {

// O(n)

let temp = arr[0];

for (let ind = 1; ind < arr.length; ind++) {

arr[ind - 1] = arr[ind];

}
arr[arr.length - 1] = temp;

return arr;

// rotate([1,2,3,4,5])

// ! Rotate an array to the left by K positions.

// function rotateByK(arr = [], k = 0) { // O(nk)

// console.log(k);

// k = k % arr.length;

// console.log(k);

// while (k > 0) {

// rotate(arr);

// k--;

// }

// console.log(arr);

// }

function reverse(arr = [], start = 0, end = arr.length - 1) {

while (start < end) {

[arr[start], arr[end]] = [arr[end], arr[start]];

start++;

end--;

function rotateByK(arr = [], k = 0) {

// O(n)

k = k % arr.length;

reverse(arr, 0, k - 1);

reverse(arr, k);
reverse(arr);

console.log(arr);

// rotateByK([1, 2, 3, 4, 5, 6, 7], 2);

// [2, 1, 3, 4, 5, 6, 7];

// [2, 1, 7, 6, 5, 4, 3];

// [3, 4, 5, 6, 7, 1, 2];

// ! Sort an array of integers.

function sort(arr = []) {

// ASC => first <= second => start => end

// DESC => first >= second => start => end

// console.log(...arr);

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

for (let ind1 = ind + 1; ind1 < arr.length; ind1++) {

if (arr[ind] > arr[ind1]) {

let temp = arr[ind];

arr[ind] = arr[ind1];

arr[ind1] = temp;

// console.log(...arr);

return arr;

// console.log(...sort(

// Array.from({ length: 10 }, () => Math.floor(Math.random() * 100))

// ));
// ! Remove duplicates from a sorted array.

function removeDuplicates(arr = []) {

console.log(arr);

for (let ind = 0, slowInd = 0; ind < arr.length; ind++) {

if (arr[ind] !== arr[slowInd]) {

slowInd++;

arr[slowInd] = arr[ind];

if (arr.length - 1 == ind) {

slowInd++;

arr.length = slowInd;

return arr;

// console.log(

// removeDuplicates(

// sort(Array.from({ length: 25 }, () => Math.floor(Math.random() * 10)))

// )

// );

module.exports = { sumOfArr, maxAndMin, rotateByK };

// todo Post-Session Practice Questions:

// todo Find the number of occurrences of an element in an array.

function countOccurrences(arr = [], target) {

let count = 0;

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


if (arr[i] === target) {

count++;

return count;

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

// todo Merge two sorted arrays.

function mergeSortedArrays(arr1 = [], arr2 = []) {

let merged = [];

let i = 0, j = 0;

while (i < arr1.length && j < arr2.length) {

if (arr1[i] < arr2[j]) {

merged.push(arr1[i]);

i++;

} else {

merged.push(arr2[j]);

j++;

while (i < arr1.length) {

merged.push(arr1[i]);

i++;

while (j < arr2.length) {


merged.push(arr2[j]);

j++;

return merged;

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

// todo Reverse the elements in an array.

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--;

return arr;

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

// todo Search for an element in a sorted array.

function binarySearch(arr = [], target) {

let left = 0, right = arr.length - 1;

while (left <= right) {

let mid = Math.floor((left + right) / 2);


if (arr[mid] === target) return mid;

if (arr[mid] < target) left = mid + 1;

else right = mid - 1;

return -1;

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

// todo Find the cumulative sum of an array.

function cumulativeSum(arr = []) {

let sum = 0, result = [];

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

sum += arr[i];

result.push(sum);

return result;

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

// todo Calculate the product of all elements in an array.

function productOfArray(arr = []) {

let product = 1;

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

product *= arr[i];

}
return product;

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

// todo Check if an array is a palindrome.

function isPalindromeArray(arr = []) {

let start = 0, end = arr.length - 1;

while (start < end) {

if (arr[start] !== arr[end]) return false;

start++;

end--;

return true;

console.log(isPalindromeArray([1, 2, 3, 2, 1])); // Output: true

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

// todo Find the intersection of two arrays.

function arrayIntersection(arr1 = [], arr2 = []) {

let result = [];

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

for (let j = 0; j < arr2.length; j++) {

if (arr1[i] === arr2[j]) {

result.push(arr1[i]);

break;
}

return result;

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

Session 5

const { rotateByK } = require("./Session - 4.js");

// ? Day 5: Searching Algorithms

// * Session Focus: Linear search and binary search techniques.

// ? Session Practice Questions:

// ! Implement a linear search to find an element in an array.

// * Algorithm

// * 0. You're having a function with 2 args, arr and target.

// * 1. Start from the first element of the array.

// * 2. Compare the target element with each element in the array.

// * 3. If the target element is found, return its index.

// * 4. If the target element is not found, return -1.

function linearSearch(arr = [], target = 0, start = 0) {

for (let ind = start; ind < arr.length; ind++) {

if (arr[ind] == target) {

return ind;

}
}

return -1;

// array with duplicate values

// console.log(

// linearSearch([3, 4, 3, 3, 5, 23, 6, 8, 75, 76, 33, 6, 4, 89, 3], 3)

// );

// console.log(linearSearch([3, 4, 3, 3, 5, 23, 6, 8, 75, 76, 33, 6, 4, 89, 3], 3, 4))

// ! Implement a binary search on a sorted array.

// * Algorithm

// * 0. You're having a function with 2 args, arr and target.

// * 1. Start from the middle element of the array.

// * 2. Compare the target element with the middle element.

// * 3. If the target element is found, return its index of middle element.

// * 4. If the target element is greater than the middle element, search the right half of the array.

// * 5. If the target element is less than the middle element, search the left half of the array.

// * 6. Repeat the process until the target element is found or the array is empty.

// * 7. If the target element is not found, return -1.

function binarySearch(arr = [], target = 0) {

let start = 0;

let end = arr.length - 1;

while (start <= end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] == target) return mid;

else if (arr[mid] > target) end = mid - 1;

else start = mid + 1;

}
return -1;

// console.log(

// binarySearch(

// Array.from({ length: 25 }, () => Math.floor(Math.random() * 100)).sort(

// (a, b) => a - b

// ),

// Math.floor(Math.random() * 100)

// )

// );

// ! Find the first and last occurrence of a target in an array.

function firstAndLastOccurrenceArr(arr = [], target = 0) {

let first = -1;

let last = -1;

let count = 0;

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

if (arr[ind] == target) {

last = ind;

count++;

if (first == -1) {

first = ind;

return { count, first, last };

}
function firstAndLastOccurrenceSortedArr(arr = [], target = 0) {

function findOccurrence(arr, target, isFirst = true) {

let start = 0;

let end = arr.length - 1;

let foundInd = -1;

while (start <= end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] == target) {

foundInd = mid;

if (isFirst) end = mid - 1;

else start = mid + 1;

} else if (arr[mid] > target) end = mid - 1;

else start = mid + 1;

return foundInd;

console.log(...arr);

console.log(target);

let first = findOccurrence(arr, target);

let last = findOccurrence(arr, target, false);

return { first, last };

// console.log(

// firstAndLastOccurrenceSortedArr(

// Array.from({ length: 25 }, () => Math.floor(Math.random() * 10)).sort(


// (a, b) => a - b

// ),

// Math.floor(Math.random() * 10)

// )

// );

// ! Count occurrences of a target using binary search.

function countOccurrences(arr, target) {

const { first, last } = firstAndLastOccurrenceSortedArr(arr, target);

return first == -1 ? 0 : last - first + 1;

// console.log(

// countOccurrences(

// Array.from({ length: 25 }, () => Math.floor(Math.random() * 10)).sort(

// (a, b) => a - b

// ),

// Math.floor(Math.random() * 10)

// )

// );

// ! Find the index where an element should be inserted in a sorted array.

function findInsertionIndex(arr, target) {

let start = 0;

let end = arr.length - 1;

while (start <= end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] == target) return mid;

else if (arr[mid] > target) end = mid - 1;

else start = mid + 1;


}

return start;

// ! Find the peak element in a mountain array.

function peakElement(arr = []) {

if (arr.length < 2) return -1;

let start = 0;

let end = arr.length - 1;

while (start <= end) {

let mid = Math.floor((start + end) / 2);

if (

(mid == arr.length - 1 || arr[mid] > arr[mid + 1]) &&

(mid == 0 || arr[mid] > arr[mid - 1])

return mid;

else if (arr[mid] > arr[mid + 1]) end--;

else start++;

return -1;

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

// console.log(peakElement([1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1]));

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

// ! Search for a target in a rotated sorted array.

function searchRotated(arr = [], target = 0) {

console.log(...arr);
console.log(target);

let start = 0;

let end = arr.length - 1;

while (start <= end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] == target)

return mid; // if target is equals with mid, return mid

else if (arr[start] <= arr[mid]) {

// if left side us sorted

if (arr[start] <= target && target < arr[mid])

end = mid - 1; // is taget within the range?

else start = mid + 1; // if target is not in the sorted range

} else {

// if right side is sorted

if (arr[mid] < target && target <= arr[end])

start = mid + 1; // if target is in the right side ?

else end = mid - 1; // what if it is not there?

return -1;

console.log(

searchRotated(

rotateByK(

Array.from({ length: 15 }, () => Math.floor(Math.random() * 10)).sort(

(a, b) => a - b

),
Math.floor(Math.random() * 10)

),

Math.floor(Math.random() * 10)

);

// todo Post-Session Practice Questions:

// todo Find the floor and ceiling of a target in a sorted array.

function findFloorCeiling(arr, target) {

let floor = -1, ceiling = -1;

let start = 0, end = arr.length - 1;

while (start <= end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] === target) {

return { floor: arr[mid], ceiling: arr[mid] };

if (arr[mid] < target) {

floor = arr[mid];

start = mid + 1;

} else {

ceiling = arr[mid];

end = mid - 1;

return { floor, ceiling };

}
// console.log(findFloorCeiling([1, 2, 8, 10, 10, 12, 19], 5)); // { floor: 2, ceiling: 8 }

// todo Find the smallest missing element in a sorted array.

function findSmallestMissing(arr) {

let start = 0, end = arr.length - 1;

while (start <= end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] !== mid) {

end = mid - 1;

} else {

start = mid + 1;

return start;

// console.log(findSmallestMissing([0, 1, 2, 3, 5, 6, 7, 8])); // 4

// todo Perform ternary search on a sorted array.

function ternarySearch(arr, target) {

let start = 0, end = arr.length - 1;

while (start <= end) {

let mid1 = start + Math.floor((end - start) / 3);

let mid2 = end - Math.floor((end - start) / 3);

if (arr[mid1] === target) return mid1;


if (arr[mid2] === target) return mid2;

if (target < arr[mid1]) {

end = mid1 - 1;

} else if (target > arr[mid2]) {

start = mid2 + 1;

} else {

start = mid1 + 1;

end = mid2 - 1;

return -1;

// console.log(ternarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9], 5)); // 4

// todo Find the index of a target in an infinite array.

function searchInfiniteArray(arr, target) {

let start = 0, end = 1;

while (arr[end] < target) {

start = end;

end *= 2;

while (start <= end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] === target) return mid;

else if (arr[mid] < target) start = mid + 1;


else end = mid - 1;

return -1;

// console.log(searchInfiniteArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 7)); // 6

// todo Find the minimum element in a rotated sorted array.

function findMinInRotated(arr) {

let start = 0, end = arr.length - 1;

while (start < end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] > arr[end]) start = mid + 1;

else end = mid;

return arr[start];

// console.log(findMinInRotated([4, 5, 6, 7, 0, 1, 2])); // 0

// todo Count the frequency of elements using binary search.

function countFrequency(arr, target) {

function findOccurrence(isFirst) {

let start = 0, end = arr.length - 1, index = -1;

while (start <= end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] === target) {


index = mid;

if (isFirst) end = mid - 1;

else start = mid + 1;

} else if (arr[mid] < target) start = mid + 1;

else end = mid - 1;

return index;

let first = findOccurrence(true);

let last = findOccurrence(false);

return first === -1 ? 0 : last - first + 1;

// console.log(countFrequency([1, 2, 2, 2, 3, 4, 5], 2)); // 3

// todo Find the closest element to a target in a sorted array.

function findClosest(arr, target) {

let start = 0, end = arr.length - 1;

while (start < end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] === target) return arr[mid];

if (arr[mid] < target) start = mid + 1;

else end = mid;

}
if (start === 0) return arr[0];

if (Math.abs(arr[start] - target) < Math.abs(arr[start - 1] - target)) {

return arr[start];

return arr[start - 1];

// console.log(findClosest([1, 3, 5, 8, 10], 6)); // 5

// todo Implement an exponential search.

function exponentialSearch(arr, target) {

if (arr[0] === target) return 0;

let index = 1;

while (index < arr.length && arr[index] <= target) {

index *= 2;

function binarySearch(start, end) {

while (start <= end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] === target) return mid;

else if (arr[mid] < target) start = mid + 1;

else end = mid - 1;

return -1;

}
return binarySearch(index / 2, Math.min(index, arr.length - 1));

// console.log(exponentialSearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 7)); // 6

// todo Find the peak index in a bitonic array.

function findPeakBitonic(arr) {

let start = 0, end = arr.length - 1;

while (start < end) {

let mid = Math.floor((start + end) / 2);

if (arr[mid] > arr[mid + 1]) {

end = mid;

} else {

start = mid + 1;

return start;

// console.log(findPeakBitonic([1, 3, 8, 12, 4, 2])); // 3 (index of 12)

You might also like