0% found this document useful (0 votes)
21 views163 pages

JavaScript Coding Challenges Guide

The document contains a series of JavaScript coding challenges and projects, including tasks such as printing numbers, calculating sums, creating functions for various operations, and implementing games and converters. It covers a wide range of topics from basic loops and functions to more complex algorithms and data structures. Additionally, it includes console projects like a to-do list, quiz games, and temperature converters.

Uploaded by

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

JavaScript Coding Challenges Guide

The document contains a series of JavaScript coding challenges and projects, including tasks such as printing numbers, calculating sums, creating functions for various operations, and implementing games and converters. It covers a wide range of topics from basic loops and functions to more complex algorithms and data structures. Additionally, it includes console projects like a to-do list, quiz games, and temperature converters.

Uploaded by

Prabin Magar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JS Challenges from codeguppy.

com

Print numbers from 1 to 10

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


[Link](i);
}
Print the odd numbers less than 100

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


if(i % 2 !== 0){
[Link](i);
}
}
Print the multiplication table with 7

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


[Link](`7 * ${i} = ${7 * i}`)
}
Print all the multiplication tables with numbers from 1 to 10

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


for(let j = 1; j <= 10; j++){
[Link](`${i} * ${j} = ${i * j}`)
}
[Link]("************************");
}
Calculate the sum of numbers from 1 to 10

let sum = 0;
for(let i = 1; i <= 10; i++){
sum += i;
}
[Link](sum);
Calculate 10!

let fact = 1;
for(let i = 1; i <= 10; i++){
fact *= i;
}
[Link](fact);
Calculate the sum of odd numbers greater than 10 and less than 30

function sumOfOdd(){
let sum = 0;
for(let i = 11; i <= 30; i++){
if(i % 2 !== 0){
sum += i;
}
}
[Link](sum); // 200
}
sumOfOdd();
Calculate the sum of numbers in an array of numbers

function sumArray(arr){
let sum = 0;
for(let i = 0; i < [Link]; i++){
sum += arr[i];
}
return sum;
}
[Link](sumArray([2, 3, -1, 5, 7, 9, 10, 15, 95])); // 145
Calculate the average of the numbers in an array of numbers
function avgOfNums(arr){
let sum = 0;
for(let i = 0; i < [Link]; i++){
sum += arr[i];
}
return (sum/[Link]);
}

[Link](avgOfNums([1, 3, 9, 15, 90])); // 23.6


Create a function that receives an array of numbers as argument and returns an array containing
only the positive numbers

function onlyPositive(arr){
let posArr = [];
for(let i = 0; i < [Link]; i++){
if(arr[i] > 0){
[Link](arr[i]);
}
}
return posArr;
}
[Link](onlyPositive([-5, 10, -3, 12, -9, 5, 90, 0, 1])); // [10, 12, 5, 90, 1]
Find the maximum number in an array of numbers

Print the first 10 Fibonacci numbers without recursion

Create a function that will find the nth Fibonacci number using recursion

Create a function that will return a Boolean specifying if a number is prime

Calculate the sum of digits of a positive integer number

Print the first 100 prime numbers

Create a function that will return in an array the first “p” prime numbers greater than “n”

Rotate an array to the left 1 position

Rotate an array to the right 1 position

Reverse an array

Reverse a string

Create a function that will merger two arrays and return the result as a new array

Create a function that will receive two arrays of numbers as arguments and return an array
composed of all the numbers that are either in the first array or second array but not in both
Create a function that will receive two arrays and will return an array with elements that are in the
first array but not in the second

Create a function that will receive an array of numbers as argument and will return a new array
with distinct elements.

Calculate the sum of first 100 prime numbers and return them in an array

Print the distance between the first 100 prime numbers

Create a function that will add two positive numbers of indefinite size. The numbers are received as
strings and the result should be also provided as string.

Create a function that will return the number of words in a text

Create a function that will capitalize the first letter of each word in a text

Calculate the sum of numbers received in a comma delimited string

Create a function that returns an array with words inside a text.

Create a function to convert as CSV text to a “bi-dimensional” array

Create a function that converts a string to an array of characters

Create a function that will convert a string in an array containing the ASCII codes of each character

Create a function that will covert an array containing ASCII codes in a string

Implement the Caesar cypher

Implement the bubble sort algorithm for an array of numbers

Create a function to calculate the distance between two points defined by their x, y coordinates

Create a function that will return a Boolean value indicating if two circles defined by center
coordinates and radius are intersecting

Create a function that will receive a bi-dimensional array as argument and a number and will
extract as a unidimensional array the column specified by the number

Create a function that will convert a string containing a binary number into a number
Create a function to calculate the sum of all the numbers in a jagged array (contains numbers or
other arrays of numbers on an unlimited number of levels)

Find the maximum number in a jagged array of numbers or array of numbers

Deep copy a jagged array with numbers or other arrays in a new array

Shuffle an array of strings

Create a function that will receive n as argument and return an array of n random numbers from 1
to n. The numbers should be unique inside the array.

Find the frequency of letters inside a string. Return the result as an array of arrays. Each subarray
has 2 elements: letter and number of occurrences.

Calculate Fibonacci(500) with high precision (all digits)

Calculate 70! with high precision (all digits)

Console Projects

To Do List:

let toDoList = [];


let contd = true;

while(contd){
[Link]();
[Link]("1. Add an item to the list \n2. Remove an item from the list \n3. Show List \
n4. Exit");
let userChoice = prompt("Choose an option: ");
if(!isNaN(userChoice) && userChoice !== null){
switch(userChoice){
case "1":
addItem(toDoList);
break;
case "2":
removeItem(toDoList);
break;
case "3":
showItems(toDoList);
break;
case "4":
contd = false;
break;
default:
[Link]("Invalid choice!");
}
} else {
alert("Invalid choice");
}
}

function addItem(arr){
let answer = prompt("What would you like to do today?");
if(answer !== null){
let correct = [Link]().trim();
if(checkDuplicate(arr, correct)){
[Link](correct);
} else {
alert('Item already exists so it won\'t be added to the list');
}
} else {
alert("You didn't add anything!");
}
}

function checkDuplicate(arr, item){


let isUnqiue = false;
let index = [Link](item); // -1 if the item doesn't exists
if(index != -1){
isUnqiue = false;
} else {
isUnqiue = true;
}
return isUnqiue;
}

// remove item function

function removeItem(list){
let answer = prompt('Which item would you like to delete from the list');
let correct = [Link]().toLowerCase();

let index = [Link](correct);

if(!checkDuplicate(list, correct)){
let removedItem = [Link](index, 1);
alert(`You removed "${removedItem}" from your list`);
} else {
alert('No such value exists');
}
}

// show items
function showItems(list){
if([Link] > 0){
let listValues = 'Your list items are : ';
for(let i = 0; i < [Link]; i++){
listValues += `"List item no. ${i + 1} : ${list[i]}" `;
}
alert(listValues);
} else {
alert("Your to do list is empty!");
}
}
Displaying all the longest word of a sentence

function findTheLongestWord(words){
let result = [Link](" ");
let longestWord = "";
let wordArray = [];
for(let i = 0; i < [Link]; i++){
if(result[i].length > [Link]){
longestWord = result[i];
}
}
[Link](longestWord);

for(let i = [Link](longestWord) + 1; i < [Link]; i++){


if([Link] === result[i].length){
[Link](result[i]);
}
}
return wordArray;
}
[Link](findTheLongestWord("JS is an awesome language for learning for beginner")); //
["language", "learning", "beginner"]

Change Calculator

// quarters 25 cents
// dime 10 cents
// nickel 5 cents
// penny 1 cent

function returnChange(amount){
let quarters = [Link](amount / 25);
[Link](`There are ${quarters} quarters in your change.`);
amount = amount % 25;
[Link](`And your change is: ${amount} cents`);

let dime = [Link](amount / 10);


[Link](`There are ${dime} dime in your change.`);
amount = amount % 10;
[Link](`And your change is: ${amount} cents`);

let nickel = [Link](amount / 5);


[Link](`There are ${nickel} nickel in your
change.`);
amount = amount % 5;
[Link](`And your change is: ${amount} cents`);

let pennies = [Link](amount / 1);


[Link](`There are ${pennies} pennies in your change.`);
amount = amount % 1;
[Link](`And your change is: ${amount} cents`);
}

returnChange(118);

Quiz Game – 1

const quiz = [
['In which year did Twitter launch? (2008, 2004, 2010, 2006)', '2006'],
['How many hearts does an octopus have? (1, 2, 3, 4)', '3'],
['What is the longest river in the world? (amazon, nile, yangtze, congo)', 'nile']
];

let score = 0;
for(let i = 0; i < [Link]; i++){
let answer = prompt(quiz[i][0]);
if(answer !== null){
let answerCorrect = [Link]().trim();
if(answerCorrect === quiz[i][1]){
score++;
} else {
alert(`Wrong answer. The correct answer is ${quiz[i][1]}`);
}
} else alert("Invalid input");
}

let correctPercent = ((score / [Link]) * 100).toFixed(2);


alert(`You answered ${score} questions correctly
and your correct percent is ${correctPercent} %`);
Quiz Game – 2

(function(){
function Question(question, answers, correct){
[Link] = question;
[Link] = answers;
[Link] = correct;
}

[Link] = function(){
[Link]([Link]);

for(var i = 0; i < [Link]; i++){


[Link](i + ': ' + [Link][i]);
}
}

[Link] = function(ans, callback){


var sc;
if(ans === [Link]){
[Link]('Correct answer!');
sc = callback(true);
} else {
[Link]('Wrong answer. Try again!');
sc = callback(false);
}
[Link](sc);
}

[Link] = function(score){
[Link]('Your current score is: ' + score);

[Link]('-------------------------------------------------------------------');
}

var q1 = new Question('Is JavaScript the coolest programming language in the world?',
['Yes', 'No'], 0);
var q2 = new Question('What is the name of this course\' teacher?',
['John', 'Michael', 'Jonas'], 2);
var q3 = new Question('What does best describe coding?',
['Boring', 'Hard', 'Fun', 'Tedious'], 2);

var questions = [q1, q2, q3];

function score(){
var sc = 0;
return function(correct){
if(correct){
sc++;
}
return sc;
}
}

var keepScore = score();

function nextQuestion(){
var n = [Link]([Link]() * [Link]);
questions[n].displayQuestion();
var answer = prompt('Please select the correct answer. Type \'exit\' to end the
game');

if(answer !== 'exit'){


questions[n].checkAnswer(parseInt(answer), keepScore);
nextQuestion();
}
}
nextQuestion();
})();

Temperature Converter:

// Celsius = (Fahr-32)*5/9
// Fahreheit = Celsius*9/5+32

function toFahrenheit(temp){
let fahr = temp * 9 / 5 + 32;
[Link](`${temp} degrees in C is ${fahr} degrees in F`);
}
toFahrenheit(37);

function toCelsius(temp){
let cel = ((temp - 32) * 5 / 9).toFixed(2);
[Link](`${temp} degrees in F is ${cel} degrees in C`);
}
toCelsius(100);

Coversion to cm(centimeter):

// 1 inch === 2.54 cm


// 1 foot === 12 inches

function toCm(feet, inches){


if((feet < 0) || (inches < 0)) {
alert('invalid parameters');
return;
}
let centimeters = (feet * 12) * 2.54;
centimeters += inches * 2.54;
[Link](`${feet} feet and ${inches} inches is equal to ${[Link](2)} cm`);
}

toCm(12, 2); // 12 feet and 2 inches is equal to 370.84 cm


toCm(-1, 35); // this will show alert
JavaScript Basic

1. Write a JavaScript program to display the current day and time in the following format.

Sample Output : Today is : Tuesday.


Current time is : 10 PM : 30 : 38

var today = new Date();


var day = [Link]();

var daylist = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];


[Link](`Today is : ${daylist[day]}`);

var hour = [Link]();


var minute = [Link]();
var second = [Link]();
var prepand = (hour >= 12)? " PM " : " AM ";
hour = (hour >= 12)? hour - 12 : hour;

if(hour === 0 && prepand === 'PM'){


if(minute === 0 && second === 0){
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}
if(hour === 0 && prepand === 'AM'){
if(minute === 0 && second === 0){
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}

[Link](`Current Time: ${hour} ${prepand} : ${minute} : ${second}`);

Write a JavaScript program to print the contents of the current window.

<!DOCTYPE html>
<html>
<head>
<title>JS Course</title>
<meta charset = "utf-8" />
<script src = "[Link]"></script>
</head>

<body>
<p></p>
<p>Click the button to print the current page</p>
<button onclick = "print_current_page()">Print the age</button>
</body>
</html>

function print_current_page(){
[Link]();
}

Write a JavaScript program to get the current date.

var date = new Date();


var year = [Link]();
var month = [Link]() + 1;
var day = [Link]();

if(month < 10){


month = '0' + month;
}

if(day < 10){


day = '0' + day;
}
[Link](`${day}-${month}-${year}`); // dd-mm-yyyy
[Link](`${day}/${month}/${year}`);

Find the area of a triangle where lengths of the three of its sides are 5, 6, 7

let a = 5;
let b = 6;
let c = 7;
let s = (a + b + c)/2;

let areaOfTriangle = [Link](s*(s-a)*(s-b)*(s-c));


[Link](areaOfTriangle);

Write a JavaScript program to rotate the string 'w3resource' in right direction by periodically
removing one letter from the end of the string and attaching it to the front.

<!DOCTYPE html>
<html>
<head>
<title>JS Course</title>
<meta charset = "utf-8" />
<script src = "[Link]"></script>
</head>

<body onload = "animate_string('target')">


<h1 id = "target">w3resource</h1>
</body>
</html>

function animate_string(id){
var element = [Link](id);
var textNode = [Link][0]; // assuming no other children
var text = [Link];

setInterval(function(){
text = text[[Link] - 1] + [Link](0, [Link] - 1);
[Link] = text;
}, 1000);
}

ES6 Version:
function animate_string(id)
{
const element = [Link](id);
const textNode = [Link][0]; // assuming no other children
let text = [Link];

setInterval(() => {
text = text[[Link] - 1] + [Link](0, [Link] - 1);
[Link] = text;
}, 100);
}

Write a JavaScript program to determine whether a given year is a leap year in the Gregorian
calendar.

function leapYear(year){
if(year % 4 === 0){
if(year % 100 === 0){
if(year % 400 === 0){
[Link]("Leap Year");
} else {
[Link]("Not a leap year.");
}
} else {
[Link]("Leap Year");
}
} else {
[Link]("Not a leap year.");
}
}

leapYear(2016);
leapYear(2000);
leapYear(1700);
leapYear(1800);
leapYear(100);

*************************************************************
function leapYear(year){
return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}

[Link](leapYear(2016));
[Link](leapYear(2000));
[Link](leapYear(1700));
[Link](leapYear(1800));
[Link](leapYear(100));

Write a JavaScript program to find 1st January is being a Sunday between 2014 and 2050.

for(var year = 2014; year <= 2050; year++){


var d = new Date(year, 0, 1);
if([Link]() === 0){
[Link]("1st January is being a Sunday" + year);
}
}

Write a JavaScript program where the program takes a random integer between 1 to 10, the user is
then prompted to input a guess number. If the user input matches with guess number, the program
will display a message "Good Work" otherwise display a message "Not matched".

let randomNum = [Link]([Link]() * 10);


[Link](randomNum);
let guessedNum = prompt("Guess a number between 1 and 10: ");

if(Number(guessedNum) === randomNum){


[Link]("Good Work");
} else {1
[Link]("Not matched");5
}

Write a JavaScript program to calculate days left until next Christmas.

let today = new Date();


const cmas = new Date([Link](), 11, 25);
if([Link]() == 11 && [Link]() > 25){
[Link]([Link]() + 1);
}
const one_day = 1000 * 60 * 60 * 24;
[Link](`${[Link](([Link]() - [Link]())/(one_day))} days left until Christ
mas!`);

Write a JavaScript program to calculate multiplication and division of two numbers (input from
user).
<div class = "box">
<label for = "firstNum">1st Number</label>
<input type = "number" name = "firstNum" id = "firstNum">
<label for = "secondNum">2nd Number</label>
<input type = "number" name = "secondNum" id = "secondNum">

<button type = "button" onclick = "Multiply('firstNum', 'secondNum')">Multiply


</button>

<button type = "button" onclick = "Divide('firstNum', 'secondNum')">Divide</button>


<p id = "result"></p>
</div>

function Multiply(num1, num2){


let firstNum = [Link](num1).value;
let secondNum = [Link](num2).value;
[Link]('result').innerHTML = "<p> The result is " + (firstNum * secondNum
);
}

function Divide(num1, num2){


let firstNum = [Link](num1).value;
let secondNum = [Link](num2).value;
[Link]('result').innerHTML = "<p> The result is " + (firstNum / secondNum
);
}

Write a JavaScript program to convert temperatures to and from Celsius, Fahrenheit. [Formula : c/5
= (f-32)/9 [ where c = temperature in Celsius and f = temperature in
Fahrenheit ]

Expected Output:

60°C is 140 °F
45°F is 7.222222222222222°C

function CelsiusToFahren(c){
var convertedValue = (9*c+(32*5))/5;
return convertedValue;
}

function FahrenToCelsius(f){
var convertedValue = (5*(f-32))/9;
return convertedValue
}

[Link](`${CelsiusToFahren(60)} F`);
[Link](`${FahrenToCelsius(45)} C`);

Explanation:
For an exact conversion (Fahrenheit to Celsius / Celsius to Fahrenheit) the following formulas can be applied:

Fahrenheit to Celsius: (°F − 32) ÷ 1.8 = °C


Celsius to Fahrenheit: (°C × 1.8) + 32 = °F

An approximate conversion between degrees Celsius and degrees Fahrenheit is as follows:

Fahrenheit to Celsius: Subtract 30 and halve the resulting number.


Celsius to Fahrenheit: Double the number and add 30.

ES6 Version:
function cToF(celsius)
{
const cTemp = celsius;
const cToFahr = cTemp * 9 / 5 + 32;
const message = `${cTemp}\xB0C is ${cToFahr} \xB0F.`;
[Link](message);
}

function fToC(fahrenheit)
{
const fTemp = fahrenheit;
const fToCel = (fTemp - 32) * 5 / 9;
const message = `${fTemp}\xB0F is ${fToCel}\xB0C.`;
[Link](message);
}
cToF(60);
fToC(45);

Write a JavaScript program to get the website URL (loading page).

[Link]([Link]);

Write a JavaScript exercise to create a variable using a user-defined name.

const var_name = 'abcd';


const n = 120;
this[var_name] = n;
[Link](this[var_name]);

Write a JavaScript exercise to get the extension of a filename.

filename = "[Link]";
[Link]([Link](".").pop());
Write a JavaScript program to get the difference between a given number and 13, if the number is
greater than 13 return double the absolute difference.

function difference(n){
if(n <= 13){
return 13 - n;
} else {
return (n-13) * 2;
}
}
[Link](difference(32)); // 38
[Link](difference(11)); // 2

Write a JavaScript program to compute the sum of the two given integers. If the two values are
same, then returns triple their sum.

function Sum(num1, num2){


if(num1 === num2){
return (num1 + num2) * 3;
} else {
return (num1 + num2);
}
}
[Link](Sum(10, 20));
[Link](Sum(10, 10));

Write a JavaScript program to compute the absolute difference between a specified number and 19.
Returns triple their absolute difference if the specified number is greater than 19.

function TripleDiff(num){
let absValue = [Link](19 - num);
if(num > 19){
return absValue * 3;
} else {
return absValue;
}
}

[Link](TripleDiff(12));
[Link](TripleDiff(19));
[Link](TripleDiff(22));
Write a JavaScript program to check two given numbers and return true if one of the number is 50
or if their sum is 50.

function CheckForFifty(num1, num2){


if(num1 === 50 || num2 === 50 || (num1 + num2) === 50){
return true;
} else {
return false;
}
}

[Link](CheckForFifty(50, 50));
[Link](CheckForFifty(20, 50));
[Link](CheckForFifty(20, 20));
[Link](CheckForFifty(20, 30));
Write a JavaScript program to check whether a given integer is within 20 of 100 or 400.

function WithinTwenty(x){
if([Link](100 - x) <= 20 || [Link](400 - x) <= 20){
[Link]("true");
} else {
[Link]("false");
}
}

WithinTwenty(10); // false
WithinTwenty(90); // true
WithinTwenty(99); // true
WithinTwenty(199); // false
WithinTwenty(200); // false
Write a JavaScript program to check from two given integers, whether one is positive and another
one is negative.

function FindPositiveValue(num1, num2){


if((num1 < 0 & num2 > 0) || (num1 >0 && num2 < 0)){
return true;
} else {
return false;
}
}

[Link](FindPositiveValue(2, 2)); // false


[Link](FindPositiveValue(-2, 2)); // true
[Link](FindPositiveValue(2, -2)); // true
[Link](FindPositiveValue(-2, -2)); // false
21. Write a JavaScript program to create a new string adding "Py" in front of a given string. If the
given string begins with "Py" then return the
original string.

function stringCheck(text){
if(text === null || text === undefined || text === '' || [Link](0, 2) === "Py"){
return text;
} else {
return ('Py' + text);
}
}

let newText1 = stringCheck('Python'); // Python


let newText2 = stringCheck('thon'); // Python
let newText3 = stringCheck(''); //
[Link](newText1);
[Link](newText2);
[Link](newText3);

22. Write a JavaScript program to remove a character at the specified position of a given string and
return the new string.

function removeCharacter(string, index){


let part1 = [Link](0, index);
let part2 = [Link](index + 1, [Link]);
return part1 + part2;
}

[Link](removeCharacter('JavaScript', 4)); // Javacript

23. Write a JavaScript program to create a new string from a given string
changing the position of first and last characters. The string length must
be greater than or equal to 1.

function SwapCharacter(str){
if([Link] <= 1){
return str;
} else {
midChar = [Link](1, [Link] - 1);
return ([Link]([Link] - 1) + midChar + [Link](0));
}
}

[Link](SwapCharacter('Swift'));

***************************** Tedious
way*************************************
function SwapCharacter(str){
let strArray = [Link]("");
let firstChar = [Link]();
let lastChar = [Link]();
let swappedStr = "";
for(i=0; i<[Link]; i++){
swappedStr += strArray[i];
}
return (lastChar + swappedStr + firstChar);
}

[Link](SwapCharacter('Swift'));

24. Write a JavaScript program to create a new string from a given string with the first character of
the given string added at the front and back.

function findWord(str){
firstChar = [Link](0, 1);
return (firstChar + str + firstChar);
}

[Link](findWord('Swift')); // SSwiftS
25. Write a JavaScript program to check whether a given positive number is a multiple of 3 or a
multiple of 7.

function MultipleCheck(num){
if(num % 3 === 0){
[Link](`${num} is multiple of 3`);
} else if(num % 7 === 0){
[Link](`${num} is multiple of 7`);
} else {
[Link](`Multiple of none`);
}
}

MultipleCheck(12);
MultipleCheck(14);
MultipleCheck(10);
MultipleCheck(11);
26. Write a JavaScript program to create a new string from a given string taking the last 3
characters and added at both the front and back. The string length must be 3 or more.

function AppendChar(str){
if([Link] < 3){
return str;
}
//let tobeAppended = [Link](-3);
let tobeAppended = [Link]([Link]-3);
return (tobeAppended + str + tobeAppended);
}

[Link](AppendChar('Swift')); // iftSwiftift
27. Write a JavaScript program to check whether a string starts with 'Java' and false otherwise.

function findWord(str){
if([Link] < 4){
return false;
}

if([Link](0, 4) === 'Java'){


return true;
} else {
return false;
}
}

[Link](findWord('JavaScript')); // true
[Link](findWord('JAVASCRIPT')); // false;

28. Write a JavaScript program to check whether two given integer values are in the range 50..99
(inclusive). Return true if either of them are in the said range.

function RangeCheck(num1, num2){


if((num1 >= 50 && num1 <= 99) || (num2 >= 50 && num2 <= 99)){
return true;
} else {
return false;
}
}
[Link](RangeCheck(12, 101)); // false
[Link](RangeCheck(52, 80)); // true
[Link](RangeCheck(15, 99)); // true

30. Write a JavaScript program to check


whether a string "Script" presents at 5th (index
4) position in a given string, if "Script" presents
in the string return the string without "Script"
otherwise return the original one.

function CheckString(str){
let seekScript = [Link](4,
[Link]);
if(seekScript === 'script'){
let newStr = [Link]("Script",
"");
return newStr;
} else {
return str;
}
}

[Link](CheckString('JavaScript')); //
Java
[Link](CheckString('CoffeeScript')); //
CoffeeScript

*******************************************************
function CheckString(str){
if([Link] < 6){
return str;
}
let resultStr = str;
if([Link](10, 4) == 'Script'){
resultStr = [Link](0, 4) + [Link](10, [Link]);
}
return resultStr;
}

[Link](CheckString('JavaScript')); // Java
[Link](CheckString('CoffeeScript')); // CoffeeScript

31. Write a JavaScript program to find the largest of three given integers.

function LargestNum(num1, num2, num3){


let maxVal = 0;
if(num1 > num2){
if(num1 > num3){
maxVal = num1;
} else {
maxVal = num3;
}
} else {
if(num2 > num3){
maxVal = num2;
} else {
maxVal = num3;
}
}
return maxVal;
}

[Link](LargestNum(1, 0, 1));
[Link](LargestNum(0, -10, -20));
[Link](LargestNum(1000, 510, 440));

32. Write a JavaScript program to find a value which is nearest to 100 from two different given
integer values.

function NearestToHundred(num1, num2){


if(num1 != num2){
let diff1 = [Link](num1 - 100);
let diff2 = [Link](num2 - 100);
if(diff1 < diff2){
return num1;
}
if(diff2 < diff1){
return num2;
}
} else {
return false;
}

[Link](NearestToHundred(90, 89)); // 90
[Link](NearestToHundred(-90, -89)); // -89
[Link](NearestToHundred(90, 90)); // false

33. Write a JavaScript program to check whether two numbers are in range 40..60 or in the range
70..100 inclusive.
function numbersRange(num1, num2){
if((num1 >= 40 && num1 <= 60 && num2 >= 40 && num2 <= 60)
|| (num1 >= 70 && num1 <= 100 && num2 >= 70 && num2 <= 100)){
return true;
} else {
return false;
}
}

[Link](numbersRange(44, 56)); // true


[Link](numbersRange(70, 95)); // true
[Link](numbersRange(50, 89)); // false

34. Write a JavaScript program to find the larger number from the two given positive integers, the
two numbers are in the range 40..60 inclusive.

function numbersRange(num1, num2){


if((num1 >= 40 && num1 <= 60) && (num2 >= 40 && num2 <=60)){
if(num1 === num2){
[Link]("Numbers are equal");
} else if(num1 > num2){
[Link](`${num1} is larger.`)
} else {
[Link](`${num2} is larger.`);
}
} else {
[Link]("Numbers don't fit in range.");
}
}

numbersRange(45, 60); // 60 is larger.


numbersRange(25, 60); // Numbers don't fit in range.
numbersRange(45, 80); // Numbers don't fit in range.

35. Write a program to check whether a specified character exists within the 2nd to 4th position in
a given string.

function checkChar(str, char){


ctr = 0;
for(let i = 0; i < [Link]; i++){
if([Link](i) == char){
ctr++;
}
}
return (ctr >= 2 && ctr <= 4);
}

[Link](checkChar("Python", "y")); // false


[Link](checkChar("JavaScript", "a")); // true
[Link](checkChar("Console", "o")); // true
36. Write a JavaScript program to check whether the last digit of the three given positive integers
is same.

function checkInteger(num1, num2, num3){


if(num1 > 0 && num2 > 0 && num3 > 0){
return (num1 % 10 == num2 % 10 && num2 % 10 == num3 % 10 && num1 % 10 == num3 % 10);
} else {
return false;
}
}
[Link](checkInteger(20, 30, 400)); // true
[Link](checkInteger(-20, 30, 400)); // false
[Link](checkInteger(20, -30, 400)); // false
[Link](checkInteger(20, 30, -400)); // false
[Link](checkInteger(34, 54, 12)); // false
37. Write a JavaScript program to create new string with first 3 characters are in lower case from a
given string. If the string length is less than 3 convert all the characters in upper case.

function caseConversion(str){
if([Link] < 3){
return [Link]();
} else {
let lowCase = [Link](0, 3).toLowerCase();
let uppCase = [Link](3, [Link]);
return lowCase + uppCase;
}
}

[Link](caseConversion("Python")); //python
[Link](caseConversion("Py")); //PY
[Link](caseConversion("JAVAScript")); //javAScript

38. Write a JavaScript program to check the total marks of a student in various examinations. The
student will get A+ grade if the total marks are in the range 89..100 inclusive, if the examination is
"Final-exam." the student will get A+ grade and total marks must be greater than or equal to 90.
Return true if the student get A+ grade or false otherwise.

function examStatus(totmarks, isExam){


if(isExam){
return totmarks >= 90;
}
return (totmarks >= 89 && totmarks <= 100);
}

[Link](examStatus("78", " ")); // false


[Link](examStatus("89", "true")); // false
[Link](examStatus("99", "true")); // true

39. Write a JavaScript program to compute the sum of the two given integers, If the sum is in the
range 50..80 return 65 otherwise return 80.

function checkRange(num1, num2){


const sum = num1 + num2;
if(sum >= 50 && sum <= 80){
return 65;
} else {
return 80;
}
}

[Link](checkRange(30, 20)); // 65
[Link](checkRange(90, 80)); // 80

40. Write a JavaScript program to check from two given integers whether one of them is 8 or their
sum or difference is 8.

function checkForEight(num1, num2){


if(num1 === 8 || num2 === 8){
return true;
}
if((num1 + num2) === 8 || [Link](num1 - num2) === 8){
return true;
}
return false;
}

[Link](checkForEight(7, 8)); // true


[Link](checkForEight(16, 8)); // true
[Link](checkForEight(24, 32)); // true
[Link](checkForEight(17, 18)); // false

41. Write a JavaScript program to check three given numbers, if the three numbers are same return
30 otherwise return 20 and if two numbers are same return 40.

function checkNumber(num1, num2, num3){


if(num1 === num2 && num2 === num3){
return 30;
}
if(num1 === num2 || num2 === num3 || num1 === num3){
return 40;
}
return 20;
}
[Link](checkNumber(8, 8, 8)); // 30
[Link](checkNumber(8, 8, 18)); // 40
[Link](checkNumber(8, 7, 18)); // 20

42. Write a JavaScript program to check whether three given numbers are increasing in strict mode
or in soft mode.

Note: Strict mode -> 10, 15, 31 : Soft mode -> 24, 22, 31 or 22, 22, 31

function numberCheck(x, y, z){


if(y > x && z > y){
return "strict mode";
} else if(z > y){
return "soft mode";
} else {
return undefined;
}
}

[Link](numberCheck(10, 15, 31)); //strict mode


[Link](numberCheck(24, 22, 31)); //soft mode
[Link](numberCheck(50, 21, 15)); //undefined

43. Write a JavaScript program to check from three given numbers (non-negative integers) that two
or all of them have the same rightmost digit.

function checkNumber(num1, num2, num3){


return (num1 % 10 === num2 % 10) ||
(num1 % 10 === num3 % 10) ||
(num2 % 10 === num3 % 10);
}

[Link](checkNumber(22, 32, 42)); // true


[Link](checkNumber(102, 302, 2)); // true
[Link](checkNumber(20, 22, 45)); // false

44. Write a JavaScript program to check from three given integers that whether a number is greater
than or equal to 20 and less than one of the others.

function checkNumbers(x, y, z){


return (x >= 20 && (x < y || x < z)) ||
(y >= 20 && (y < x || y < z)) ||
(z >= 20 && (z < y || z < x));
}
[Link](checkNumbers(23, 45, 10)); // true
[Link](checkNumbers(23, 23, 10)); // false
[Link](checkNumbers(21, 66, 75)); // true

45. Write a JavaScript program to check two given integer values and return true if one of the
number is 15 or if their sum or difference is 15.

function checkNumbers(num1, num2){


if(num1 === 15 || num2 === 15 || num1 + num2 === 15 || [Link](num1 - num2) === 15){
return true;
} else {
return false;
}
}

[Link](checkNumbers(15, 9)); // true


[Link](checkNumbers(25, 15)); // true
[Link](checkNumbers(7, 8)); // true
[Link](checkNumbers(25, 10)); // true
[Link](checkNumbers(5, 9)); // false
[Link](checkNumbers(7, 9)); // false
[Link](checkNumbers(9, 25)); // false

46. Write a JavaScript program to check two given non-negative integers that whether one of the
number (not both) is multiple of 7 or 11.

function valCheck (a, b) {


if (!((a % 7 == 0 || a % 11 == 0) && (b % 7 == 0 || b % 11 == 0))) {
return ((a % 7 == 0 || a % 11 == 0) || (b % 7 == 0 || b % 11 == 0));
} else {
return false;
}
}
[Link](valCheck(14, 21)); // false
[Link](valCheck(14, 20)); // true
[Link](valCheck(16, 20)); // false

47. Write a JavaScript program to check whether a given number is presents in the range
40..10000. For example 40 presents in 40 and 4000

function checkNumber(x, y, n){


if(n < 40 || n > 10000){
return false;
} else if(n >= x && n <= y){
return true;
} else {
return false;
}
}

[Link](checkNumber(40, 4000, 45)); // true


[Link](checkNumber(80, 320, 79)); // false
[Link](checkNumber(89, 4000, 30)); // false

48. Write a JavaScript program to reverse a given string.


function reverseString(str){
return [Link]("").reverse().join("");
}

[Link](reverseString("www")); //www
[Link](reverseString("w3resource")); //ecruoser3w
[Link](reverseString("JavaScript")); //tpircSavaJ
*****************************************************************

function reverseString(str){
let strArray = [];
let strRevArray = [];
let finalArr = "";
for(let i = 0; i < [Link]; i++){
strArray[i] = [Link](i);
}
for(let i = 0, j = [Link] - 1; i < [Link]; i++, j--){
strRevArray[j] = strArray[i];
}
for(let i = 0; i < [Link]; i++){

finalArr += strRevArray[i];
}
return finalArr;
}

[Link](reverseString("www")); //www
[Link](reverseString("w3resource")); //ecruoser3w
[Link](reverseString("JavaScript")); //tpircSavaJ
49. Write a JavaScript program to replace every character in a given string with the character
following it in the alphabet.

function letterChanges(text){
let strArray = [Link]("");
for(let i = 0; i < [Link]; i++){
switch(strArray[i]){
case ' ':
break;
case 'z':
strArray[i] = 'a';
break;
case 'Z':
strArray[i] = 'A';
break;
default:
strArray[i] = [Link](1 + strArray[i].charCodeAt(0));
}
}
return [Link]("");
}

[Link](letterChanges("PYTHON")); //QZUIPO
[Link](letterChanges("W3R")); //X4S
[Link](letterChanges("pHp")); //qIq
[Link](letterChanges("FizzBuZZ")); //GjaaCvAA
50. Write a JavaScript program to capitalize the first letter of each word of a given string.

function CapitalizeFirst(str){
str = [Link](" ");
for(let i = 0, x = [Link]; i < x; i++){
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
return [Link](" ");
}

[Link](CapitalizeFirst("the quick brown fox")); // The Quick Brown Fox

51. Write a JavaScript program to convert a given number to hours and minutes.

function timeConversion(num){
const hours = [Link](num/60);
const minutes = num % 60;
return `${hours}:${minutes}`;
}

[Link](timeConversion(71)); //1:11
[Link](timeConversion(450)); //7:30
[Link](timeConversion(1441)); //24:1

52. Write a JavaScript program to convert the letters of a given string in alphabetical order.

function convertString(str){
return [Link]("").sort().join("");
}

[Link](convertString("Python")); //Phnoty
[Link](convertString("Exercises")); //Eceeirssx

53. Write a JavaScript program to check whether the characters a and b are separated by exactly 3
places anywhere (at least once) in a given string.

function checkString(str){
return (/a...b/).test(str) || (/b...a/).test(str);
}

[Link](checkString("Chainsbreak")); // true
[Link](checkString("pane borrowed")); // true
[Link](checkString("abCheck")); // false

**************************************************

function checkString(str){
if([Link]("a")){
let indexOfA = [Link]("a");
let indexOfB = [Link]("b");
return ((indexOfA + 4) === indexOfB || (indexOfA) === (indexOfB + 4))
} else {
return false;
}
}
[Link](checkString("Chainsbreak")); // true
[Link](checkString("pane borrowed")); // true
[Link](checkString("abCheck")); // false

54. Write a JavaScript program to count the number of vowels in a given string.

function countVowels(str){
return [Link](/[^aeiou]/g, "").length;
}
[Link](countVowels("Python"));
[Link](countVowels("[Link]"));
***********************************************************

function countVowels(str){
let stA = [Link]().split("");
let counter = 0;
for(let i = 0; i < [Link]; i++){
if(stA[i] === "a" || stA[i] === "e" || stA[i] === "i" || stA[i] === "o" || stA[i] ===
"u"){
counter++;
}
}
return counter;
}
[Link](countVowels("Python"));
[Link](countVowels("[Link]"));
55. Write a JavaScript program to check whether a given string contains equal number of p's and
t's.

function seekCharacters(str){
const noOfP = [Link](/[^p]/g, "").length;
const noOfT = [Link](/[^t]/g, "").length;
return (noOfP === noOfT);
}

[Link](seekCharacters("paatpss")); // false
[Link](seekCharacters("paatps")); // false
[Link](seekCharacters("peter")); // true
56. Write a JavaScript program to divide two positive numbers and return a string with properly
formatted commas.

function divisionString(){
n1 = 80;
n2 = 6;
var div = [Link](n1/n2).toString(), resultArray = [Link]("");
if(div >= 1000){
for(var i = [Link] - 3; i > 0; i -= 3){
[Link](i, 0, ",");
}
resultArray;
}
[Link](resultArray);
}

divisionString(); // ["1", "3"]

57. Write a JavaScript program to create a new string of specified copies (positive number) of a
given string.

function createCopies(str, num){


if(num < 0){
return false;
} else {
return [Link](num);
}
}

[Link](createCopies("abc", 5)); // abcabcabcabcabc


[Link](createCopies("abc", 0)); //
[Link](createCopies("abc", -2)); // false
*****************************************************8

function createCopies(str, num){


if(num < 0){
return false;
} else if (num === 0){
return "";
} else {
let tempStr = str;
str = "";
for(let i = 0; i < num; i++){
str += tempStr;
}
return str;
}
}

[Link](createCopies("abc", 5)); // abcabcabcabcabc


[Link](createCopies("abc", 0)); //
[Link](createCopies("abc", -2)); // false
58. Write a JavaScript program to create a new string of 4 copies of the last 3 characters of a given
original string. The length of the given string must be 3 and above.
function createCopies(str){
if([Link] >= 3){
let lastThree = [Link]([Link] - 3);
return [Link](4);
} else {
return false;
}
}

[Link](createCopies("Python 3.0")); //[Link].0


[Link](createCopies("JS")); //false
[Link](createCopies("JavaScript")); //iptiptiptipt

59. Write a JavaScript program to extract the first half of a string of even length.

function firstHalf(str){
if([Link] % 2 === 0){
//return ([Link](0, [Link]/2));
return [Link](0, [Link]/2);
} else {
return str;
}
}

[Link](firstHalf("Python")); //Pyt
[Link](firstHalf("JavaScript")); //JavaS
[Link](firstHalf("PHP")); //PHP

60. Write a JavaScript program to create a new string without the first and last character of a given
string.

function stringPlay(str){
return [Link](1, [Link] - 1);
}

[Link](stringPlay("JavaScript")); //avaScrip
[Link](stringPlay("JS")); //
[Link](stringPlay("PHP")); //H
61. Write a JavaScript program to concatenate two strings except their first character.
function stringConcatenate(str1, str2){
return ([Link](1, [Link])) + ([Link](1, [Link]));
}

[Link](stringConcatenate("PHP", "JS")); //HPS


[Link](stringConcatenate("A", "B"));
[Link](stringConcatenate("AA", "BB")); //AB

62. Write a JavaScript program to move last three character to the start of a given string. The
string length must be greater or equal to three.

function stringManipulation(str){
if([Link] >= 3){
let backStr = [Link]([Link] - 3);
let frontStr = [Link](0, [Link] - 3);
return backStr + frontStr;
} else {
return str;
}
}

[Link](stringManipulation("Python")); //honPyt
[Link](stringManipulation("JavaScript")); //iptJavaScr
[Link](stringManipulation("Hi")); //Hi
************************************************************************

function stringManipulation(str){
if([Link] >= 3){
return [Link](-3) + [Link](0, -3);
} else {
return str;
}
}

[Link](stringManipulation("Python")); //honPyt
[Link](stringManipulation("JavaScript")); //iptJavaScr
[Link](stringManipulation("Hi")); //Hi
63. Write a JavaScript program to create a string using the middle three characters of a given
string of odd length. The string length must be greater or equal to three.

function stringManipulation(str){
if([Link] >= 3 && [Link] % 2 !== 0){
let midVal = [Link]([Link]/2);
return ([Link](midVal - 1, midVal + 2));
} else {
return str;
}
}

[Link](stringManipulation("abcdefg")); //cde
[Link](stringManipulation("HTML5")); //TML
[Link](stringManipulation("Python")); //Python
[Link](stringManipulation("PHP")); //PHP
[Link](stringManipulation("Exercises")); //rci

64. Write a JavaScript program to concatenate two strings and return the result. If the length of the
strings are not same then remove the characters from the longer string.

function stringManipulation(str1, str2){


const m = [Link]([Link], [Link]);
return [Link]([Link] - m) + [Link]([Link] - m);
}

[Link](stringManipulation("Python", "JS")); //onJS


[Link](stringManipulation("ab", "cdef")); //abef
****************************************************************************

function stringManipulation(str1, str2){


if([Link] > [Link]){
return [Link]([Link] - [Link]) + str2;
} else if([Link] > [Link]){
return str1 + [Link]([Link] - [Link]);
}
}

[Link](stringManipulation("Python", "JS")); //onJS


[Link](stringManipulation("ab", "cdef")); //abef
65. Write a JavaScript program to test whether a string end with "Script". The string length must be
greater or equal to 6.

function stringManipulation(str){
if([Link] >= 6){
return ([Link]([Link] - 6) === "Script");
} else {
return false;
}
}

[Link](stringManipulation("JavaScript")); // true
[Link](stringManipulation("Java Script")); // true
[Link](stringManipulation("Java Scripts")); // false

66. Write a JavaScript program to display the city name if the string begins with "Los" or "New"
otherwise return blank.

function stringManipulation(str){
if([Link] >= 3 && (([Link](0, 3) === "Los") || ([Link](0, 3) ===
"New"))){
return str;
} else {
return "";
}
}

[Link](stringManipulation("New York")); //New York


[Link](stringManipulation("Los Angeles")); //Los Angeles
[Link](stringManipulation("London")); //

67. Write a JavaScript program to create a new string from a given string, removing the first and
last characters of the string if the first or last character are 'P'. Return the original string if the
condition is not satisfied.

function stringManipulation(str){
let startPos = 0;
let endPos = [Link];
if([Link] > 0 && [Link](0) == "P"){
startPos = 1;
}
if([Link] > 1 && [Link]([Link] - 1) == "P"){
endPos--;
}
return [Link](startPos, endPos);
}

[Link](stringManipulation("PythonP")); //ython
[Link](stringManipulation("Python")); //ython
[Link](stringManipulation("JavaScript")); //JavaScript
[Link](stringManipulation("P")); //
68. Write a JavaScript program to create a new string using the first and last n characters from a
given sting. The string length must be greater or equal to 2 * n.

function stringManipulation(str, n){


if([Link] >= 2 * n){
let firstPart = [Link](0, n);
let lastPart = [Link]([Link] - n);
return firstPart + lastPart;
} else {
return "";
}
}

[Link](stringManipulation("JavaScript", 2)); //Japt


[Link](stringManipulation("JavaScript", 3)); //Javipt
[Link](stringManipulation("Java", 4)); //

69. Write a JavaScript program to compute the sum of three elements of a given array of integers
of length 3.

function arrayFunc(nums){
return nums[0] + nums[1] + nums[2];
}

[Link](arrayFunc([10, 32, 20])); // 62


[Link](arrayFunc([5, 7, 9])); // 21
[Link](arrayFunc([0, 8, -11])); // -3

70. Write a JavaScript program to rotate the elements left of a given array of integers of length 3.

function arrayFunc(nums){
return [nums[1], nums[2], nums[0]];
}
[Link](arrayFunc([3, 4, 5]));
[Link](arrayFunc([0, -1, 2]));
[Link](arrayFunc([7, 6, 5]));
71. Write a JavaScript program to check whether 1 appears in first or last position of a given array
of integers. The array length must be greater or equal to 1.

function arrayFunc(nums){
var endPos = [Link] - 1;
return nums[0] == 1 || nums[endPos] == 1;
}

[Link](arrayFunc([1, 3, 5])); // true


[Link](arrayFunc([1, 3, 5, 1])); // true
[Link](arrayFunc([2, 4, 6])); // false

72. Write a JavaScript program to check whether the first and last elements are equal of a given
array of integers length 3.

function arrayFunc(nums){
if([Link] >= 1){
return (nums[0] === nums[[Link] - 1]);
}
}

[Link](arrayFunc([10, 20, 30])); // false


[Link](arrayFunc([10, 20, 30, 10])); // true
[Link](arrayFunc([20, 20, 20])); // true
73. Write a JavaScript program to reverse the elements of a given array of integers length 3.

function arrayFunc(nums){
return [Link]((element, idx, arr) => arr[([Link] - 1) - idx]);
}

[Link](arrayFunc([5, 4, 3])); // [3, 4, 5]


[Link](arrayFunc([1, 0, -1])); // [-1, 0, 1]
[Link](arrayFunc([2, 3, 1])); // [1, 3, 2]

74. Write a JavaScript program to find the larger value between the first or last and set all the other
elements with that value. Display the new array.

function arrayFunc(nums){
const large = [Link](nums[0], nums[[Link] - 1]);
for(let i = 0; i < [Link]; i++){
nums[i] = large;
}
return nums;
}

[Link](arrayFunc([20, 30, 40]));


[Link](arrayFunc([-7, -9, 0]));
[Link](arrayFunc([12, 10, 3]));

75. Write a JavaScript program to create a new array taking the middle elements of the two arrays
of integer and each length 3.

function arrayFunc(a, b){


var newArray = [];
[Link](a[1], b[1]);
return newArray;
}

[Link](arrayFunc([1, 2, 3], [1, 5, 6])); // [2,5]


[Link](arrayFunc([3, 3, 3], [2, 8, 0])); // [3,8]
[Link](arrayFunc([4, 2, 7], [2, 4, 5])); // [2,4]

76. Write a JavaScript program to create a new array taking the first and last elements from a given
array of integers and length must be greater or equal to 1.

function arrayFunc(arr){
let createArray = [];
if([Link] >= 1){
[Link](arr[0], arr[[Link] - 1]);
}
return createArray;
}

[Link](arrayFunc([20, 20, 30])); // [20,30]


[Link](arrayFunc([5, 2, 7, 8])); // [5,8]
[Link](arrayFunc([17, 12, 34, 78])); // [17,78]

77. Write a JavaScript program to test whether an array of integers of length 2 contains 1 or a 3.

function arrayFunc(arr){
if([Link](1) != -1 || [Link](3) != -1){
return true;
} else {
return false;
}
}

[Link](arrayFunc([1, 5])); // true


[Link](arrayFunc([2, 3])); // true
[Link](arrayFunc([7, 5])); // false

78. Write a JavaScript program to test whether an array of integers of length 2 does not contain 1
or a 3.

function arrayFunc(arr){
if([Link](1) == -1 && [Link](3) == -1){
return true;
} else {
return false;
}
}

[Link](arrayFunc([7, 8])); // true


[Link](arrayFunc([3, 2])); // false
[Link](arrayFunc([0, 1])); // false

79. Write a JavaScript program to test whether a given array of integers contains 30 and 40 twice.
The array length should be 0, 1, or 2.

function arrayFunc(arr){
let a = arr[0], b = arr[1];
return (a === 30 && b === 30) || (a === 40 && b === 40);
}

[Link](arrayFunc([30, 30])); // true


[Link](arrayFunc([40, 40])); // true
[Link](arrayFunc([20, 20])); // false
[Link](arrayFunc([30])); // false

80. Write a JavaScript program to swap the first and last elements of a given array of integers. The
array length should be at least 1.

function arrayFunc(arr){
[arr[0], arr[[Link] - 1]] = [arr[[Link] - 1], arr[0]];
return arr;
}

[Link](arrayFunc([1, 2, 3, 4]));
[Link](arrayFunc([0, 2, 1]));
[Link](arrayFunc([3]));

81. Write a JavaScript program to add two digits of a given positive integer of length two.

function addDigits(num){
return ([Link](num/10) + num % 10);
}

[Link](addDigits(25));
[Link](addDigits(50));
82. Write a JavaScript to add two positive integers without carry.

function addDigits(n1, n2){


let result = 0;
let x = 1;
while(n1 > 0 && n2 > 0){
result += x * ((n1 + n2) % 10);
n1 = [Link](n1 / 10);
n2 = [Link](n2 / 10);
x *= 10;
}
return result;
}

[Link](addDigits(222, 911)); // 133


[Link](addDigits(200, 900)); // 100

83. Write a JavaScript to find the longest string from a given array of strings.

function longestString(strArr){
let maxLen = strArr[0].length;
[Link](function(val){ // normal function
return (maxLen = [Link](maxLen, [Link]));
});
// Arrow function
let maxLenStr = [Link](val => [Link] == maxLen);
return maxLenStr; // ["aaaaa"]
}

[Link](longestString(['a', 'aa', 'aaa', 'aaaaa', 'aaaa'])); // aaaaa


***************************************************************

function longestString(strArr){
let maxLen = 0;
let maxLenStr = "";
for(let i = 0; i < [Link]; i++){
if(strArr[i].length >= maxLen){
maxLen = strArr[i].length;
maxLenStr = strArr[i];
}
}
return maxLenStr;
}

[Link](longestString(['a', 'aa', 'aaa', 'aaaaa', 'aaaa'])); // aaaaa


84. Write a JavaScript to replace each character of a given string by the next one in the English
alphabet.

Note: 'a' will be replace by 'b' or 'z' would be replaced by 'a'.

function alphaShift(str){
const strArr = [Link]("");
for(let i = 0; i < [Link]; i++){
let n = strArr[i].charCodeAt() - 'a'.charCodeAt();
n = (n + 1) % 26;
strArr[i] = [Link](n + 'a'.charCodeAt());
}
return [Link]("");
}

[Link](alphaShift("abcdxyz")); // bcdeyza
********************************************************

function alphaShift(str){
const strArr = [Link]("");
for(let i = 0; i < [Link]; i++){
switch(strArr[i]){
case " ":
break;
case "z":
strArr[i] = 'a';
break;
default:
strArr[i] = [Link]([Link](i) + 1);
}
}
return [Link]("");
}

[Link](alphaShift("abcdxyz")); // bcdeyza
85. Write a JavaScript code to divide a given array of positive integers into two parts. First element
goes to first part, second element goes to second part, and third element goes to first part and so
on. Now compute the sum of two parts and store into an array of size two.

function alternateSum(nums){
let arraySum = [0, 0];
[Link](function(val, idx, arr){
if((idx + 1) % 2 != 0){
arraySum[0] += val;
} else {
arraySum[1] += val;
}
});
return arraySum;

[Link](alternateSum([1, 3, 6, 2, 5, 10])); // [12,15]


86. Write a JavaScript program to find the types of a given angle.

Types of angles:

Acute angle: An angle between 0 and 90 degrees.


Right angle: An 90 degree angle.
Obtuse angle: An angle between 90 and 180 degrees.
Straight angle: A 180 degree angle.

function angleType(angleDeg){
if(angleDeg > 0 && angleDeg < 90){
return "Acute angle";
} else if(angleDeg == 90){
return "Right angle";
} else if(angleDeg > 90 && angleDeg < 180){
return "Obtuse angle";
} else if(angleDeg == 180){
return "Straight angle"
} else {
return "";
}
}

[Link](angleType(47));
[Link](angleType(90));
[Link](angleType(145));
[Link](angleType(180));
87. Write a JavaScript program to check whether two arrays of integers of same length are similar
or not. The arrays will be similar if one array can be obtained from another array by swapping at
most one pair of elements.

function checkArray(nums1, nums2){


for(let i = 0; i < [Link]; i++){
for(let j = i; j < [Link]; j++){
let result = true;
const temp = nums1[i];
nums1[i] = nums1[j];
nums1[j] = temp;
for(let k = 0; k < [Link]; k++){
if(nums1[k] !== nums2[k]){
result = false;
break;
}
}
if(result){
return true;
}
nums1[j] = nums1[i];
nums1[i] = temp;
}
}
return false;
}

[Link](checkArray([10, 20, 30], [10, 20, 30])); // true


[Link](checkArray([10, 20, 30], [30, 10, 20])); // false
[Link](checkArray([10, 20, 30, 40], [10, 30, 20, 40])); // true

88. Write a JavaScript program to check whether two given integers are similar or not, if a given
divisor divides both integers and it does not divide either.

function divisionCheck(x, y, divisor){


if(x % divisor === 0 && y % divisor === 0 || x % divisor !== 0 && y % divisor !== 0){
return true;
} else {
return false;
}
}

[Link](divisionCheck(10, 25, 5)); // true


[Link](divisionCheck(10, 20, 5)); // true
[Link](divisionCheck(10, 20, 4)); // false

89. Write a JavaScript program to check whether it is possible to replace $ in a given expression x $
y = z with one of the four signs +, -, * or / to obtain a correct expression.

For example x = 10, y = 30 and z = 300, we can replace $ with a multiple operator (*) to obtain x * y
=z

function arithmeticExp(x, y, op){


return ((x + y == op) || (x - y == op) || (x % y == op) || (x / y == op) || (x * y ==
op));
}

[Link](arithmeticExp(10, 25, 35)); // true


[Link](arithmeticExp(10, 25, 250)); // true
[Link](arithmeticExp(30, 25, 5)); // true
[Link](arithmeticExp(100, 25, 4.0)); // true
[Link](arithmeticExp(100, 25, 25)); // false

90. Write a JavaScript program to find the kth greatest element of a given array of integers

function greatestElement(arr, num){


for(let i = 0; i < [Link]; i++){
for(let j = 0; j < [Link] - i - 1; j++){
if(arr[j] < arr[j + 1]){
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr[num - 1];
}

[Link](greatestElement([1, 2, 6, 4, 5], 3)); // 4


[Link](greatestElement([-10, -25, -47, -36, 0], 1)); // 0

91. Write a JavaScript program to find the maximum possible sum of some of its k consecutive
numbers (numbers that follow each other in order.) of a given array of positive integers.

function consecutiveSum(nums, k) {
let result = 0;
let temp_sum = 0;
for (var i = 0; i < k - 1; i++) {
temp_sum += nums[i];
}
for (var i = k - 1; i < [Link]; i+
+) {
temp_sum += nums[i];
if (temp_sum > result) {
result = temp_sum;
}
temp_sum -= nums[i - k + 1];
}
return result;
}

[Link](consecutiveSum([1, 2, 3, 14,
5], 2)); // 19
[Link](consecutiveSum([2, 3, 5, 1, 6],
3)); // 12
[Link](consecutiveSum([9, 3, 5, 1, 7],
2)); // 12

*********************************************************************

function consecutiveSum(arr, n){


let num = ([Link]([Link] / n) + 1);
let newArr = Array(num).fill(0);
for(let i = 0; i < num; i++){
for(let j = i; j < n + i; j++){
newArr[i] += arr[j];
}
}
let larNum = 0;
for(let i = 0; i < [Link]; i++){
if(newArr[i] > larNum){
larNum = newArr[i];
}
}
return larNum;
}

[Link](consecutiveSum([1, 2, 3, 14, 5], 2)); // 19


[Link](consecutiveSum([2, 3, 5, 1, 6], 3)); // 12
[Link](consecutiveSum([9, 3, 5, 1, 7], 2)); // 12
92. Write a JavaScript program to find the maximal difference between any two adjacent elements
of a given array of integers.

function diffOfAdjacent(arr) {
var max = -1;
var temp;
for (var i = 0; i < [Link] - 1; i++)
{
temp = [Link](arr[i] - arr[i + 1]);
max = [Link](max, temp);
}
return max;
}

[Link](diffOfAdjacent([1, 2, 3, 8, 9])); // 5
[Link](diffOfAdjacent([1, 2, 3, 18, 9])); // 15
[Link](diffOfAdjacent([13, 2, 3, 8, 9])); // 11

*****************************************************************
function diffOfAdjacent(nums){
let smallDiff = -1;
for(let i = 0; i < [Link] - 1; i++){
for(let j = i; j < i + 2; j++){
if([Link](nums[j] - nums[j + 1]) > smallDiff){
smallDiff = [Link](nums[j] - nums[j + 1]);
}
}
}
return smallDiff;
}

[Link](diffOfAdjacent([1, 2, 3, 8, 9])); //
5
[Link](diffOfAdjacent([1, 2, 3, 18,
9])); // 15
[Link](diffOfAdjacent([13, 2, 3, 8,
9])); // 11

93. Write a JavaScript program to find the maximal difference among all possible pairs of a given
array of integers.

function maxDiff(nums){
let max = -1;
for(let i = 0; i < [Link]; i++){
for(let j = 0; j < [Link]; j++){
if(i != j){
if([Link](nums[i] - nums[j]) > max){
max = [Link](nums[i] - nums[j]);
}
}
}
}
return max;
}

[Link](maxDiff([1, 2, 3, 8, 9])); // 8
[Link](maxDiff([1, 2, 3, 18, 9])); // 17
[Link](maxDiff([13, 2, 3, 8, 9])); // 11
****************************************************************

function array_max_diff(arr) {

let max_result = 0;

for(let i=0;i<[Link];i++)
{
for(let k=0; k!=i && k<[Link]; k++)
{
const diff = [Link](arr[i]-arr[k]);
max_result = [Link](max_result, diff);
}
}
return max_result;
}
94. Write a JavaScript program to find the number which appears most in a given array of integers.

function array_element_mode(arr) {
const ctr = [];
let ans = 0;

for(var i = 0; i < 10; i++) {


[Link](0);
}
for(var i = 0; i < [Link]; i++) {
ctr[arr[i] - 1]++;
if(ctr[arr[i] - 1] > ctr[ans]) {
ans = arr[i] - 1;
}
}
return ans + 1;
}
[Link](array_element_mode([1, 2, 3, 2, 2, 8, 1, 9])); // 2

95. Write a JavaScript program to replace all the numbers with a specified number of a given array
of integers.

function arrayElementReplace(arr, oVal, nVal){


for(let i = 0; i < [Link]; i++){
if(arr[i] == 2){
arr[i] = 5;
}
}
return arr;
}

num = [1, 2, 3, 2, 2, 8, 1, 9];


[Link](`Original Array: ${num}`);
[Link](arrayElementReplace(num, 2, 5)); // [1, 5, 3, 5, 5, 8, 1, 9]

96. Write a JavaScript program to compute the sum of absolute differences of consecutive numbers
of a given array of integers.

function sumAdjacentdiff(arr){
let sum = 0;
for(let i = 0; i < [Link] - 1; i++){
for(let j = i + 1; j < i + 2; j++){
sum += [Link](arr[i] - arr[j]);
}
}
return sum;
}

[Link](sumAdjacentdiff([1, 2, 3, 2, -5])); // 10

97. Write a JavaScript program to find the shortest possible string which can create a string to
make it a palindrome by adding characters to the end of it.

function build_Palindrome(new_str) {
let flag;
for (let i = new_str.length;; i++) {
flag = true;
for (var j = 0; j < i - j - 1; j++) {
if (i - j - 1 < new_str.length && new_str[j] != new_str[i - j - 1]) {
flag = false;
break;
}
}
if (flag) {
for (var j = new_str.length; j < i; j++) {
new_str += new_str[i - j - 1];
}
return new_str;
}
}
}
[Link](build_Palindrome("abcddc"));
[Link](build_Palindrome("122"));
****************************************************************

function buildPalindrome(str){
for(let i = 0; i < [Link]; i++){
let tempArr = [Link]("");
for(let j = i; j >= 0; j--){
[Link]([Link](j));
}
let forStr = [Link]("");
let revStr = [Link]().join("");
if(forStr == revStr){
return forStr;
}
}
}

[Link](buildPalindrome("abcddc")); // abcddcba
[Link](buildPalindrome("122")); // 1221
[Link](buildPalindrome("prabin")); // prabinibarp
98. Write a JavaScript program to switch case of the minimum possible number of letters to make a
given string written in the upper case or in the lower case.

Fox example "Write" will be write and "PHp" will be "PHP"

function changeCase(str){
let x = 0, y = 0;
for(let i = 0; i < [Link]; i++){
if(/[A-Z]/.test(str[i])){
x++;
} else y++;
}
if(y > x) return [Link]();
return [Link]();
}

[Link](changeCase("Write")); // write
[Link](changeCase("PHp")); // PHP
***********************************************************************************************

function changeCase(word){
let str = [Link]("");
let upperNum = 0, lowerNum = 0;
for(let i = 0; i < [Link]; i++){
if(str[i].charCodeAt(0) >= 65 && str[i].charCodeAt(0) <= 90){
upperNum++;
} else if(str[i].charCodeAt(0) >= 97 && str[i].charCodeAt(0) <= 122){
lowerNum++;
}
}
return ((upperNum < lowerNum) ? [Link]() : [Link]());

[Link](changeCase("Write")); // write
[Link](changeCase("PHp")); // PHP
99. Write a JavaScript program to check whether it is possible to rearrange characters of a given
string in such way that it will become equal to another given string.

function rearrangingChars(str1, str2){


const firstSet = [Link]('');
const secondSet = [Link]('');
let result = true;
[Link]();
[Link]();
for(let i = 0; i < [Link]([Link], [Link]); i++){
if(firstSet[i] !== secondSet[i]){
result = false;
}
}
return result;
}

[Link](rearrangingChars("xyz", "zyx")); // true


[Link](rearrangingChars("xyz", "zyp")); // false

100. Write a JavaScript program to check whether there is at least one element which occurs in two
given sorted arrays of integers.

function checkCommonElement(arr1, arr2){


for(let i = 0; i < [Link]; i++){
if([Link](arr1[i])){
return true;
}
}
return false;
}

[Link](checkCommonElement([1, 2, 3], [3, 4, 5])); // true


[Link](checkCommonElement([1, 2, 3], [4, 5, 6])); // false
*******************************************************************************************

function checkCommonElement(arr1, arr2){


let result = false;
for(let i = 0; i < [Link]; i++){
for(let j = 0; j < [Link]; j++){
if(arr1[i] === arr2[j]){
result = true;
}
}
}
return result;
}

[Link](checkCommonElement([1, 2, 3], [3, 4, 5])); // true


[Link](checkCommonElement([1, 2, 3], [4, 5, 6])); // false
101. Write a JavaScript program to check whether a given string contains only Latin letters and no
two uppercase and no two lowercase letters are in adjacent positions.
function testString(str){
const isLowerCase = symbol =>{
if('a' <= symbol && symbol <= 'z'){
return true;
} return false;
}

const isUpperCase = symbol =>{


if('A' <= symbol && symbol <= 'Z'){
return true;
} return false;
}

const isFirstCharLower = isLowerCase(str[0]);


const isFirstCharUpper = isUpperCase(str[0]);

if(!(isFirstCharLower || isFirstCharUpper)){
return false;
}

for(let i = 1; i < [Link]; i++){


if(i % 2){
if(isLowerCase(str[i]) ===
isFirstCharLower
|| isUpperCase(str[i]) === isFirstCharUpper){
return false;
}
} else {
if(isLowerCase(str[i]) !== isFirstCharLower
|| isUpperCase(str[i]) !== isFirstCharUpper){
return false;
}
}
}
return true;
}

[Link](testString('xYr')); // true
[Link](testString('XXyx')); // false

********************************************************************
function testString(str){
if(str != ""){
let tempChar = "";
const isLowerCase = function(symbol){
if('a' <= symbol && 'z' >= symbol){
return true;
}
return false;
}

const isUpperCase = function(symbol){


if('A' <= symbol && 'Z' >= symbol){
return true;
}
return false;
}

for(let i = 0; i < [Link]; i++){


if((isLowerCase(str[i]) || isUpperCase(str[i]))){
if(tempChar == str[i]){
return false;
} else {
tempChar = str[i];
}
} else {
return false;
}
}
} else {
return "empty string";
}

return true;
}

[Link](testString('xYr')); // true
[Link](testString('XXyx')); // false
102. Write a JavaScript program to find the number of inversions of a given array of integers.

Note: Two elements of the array a stored at positions i and j form an inversion if a[i] > a[j] and i < j.

function numberOfInversionsNaive(arr){
let ctr = 0;
for(let i = 0; i < [Link]; i++){
for(let j = i + 1; j < [Link]; j++){
if(arr[i] > arr[j])
ctr++;
}
}
return ctr;
}

[Link](numberOfInversionsNaive([0, 3, 2, 5, 9])); // 1
[Link](numberOfInversionsNaive([1, 5, 4, 3])); /// 3
[Link](numberOfInversionsNaive([10, 30, 20, -10])); // 4

103. Write a JavaScript program to find the maximal number from a given positive integer by
deleting exactly one digit of the given number.

function digitDelete(num){
let result = 0;
const numdigits = [];
while(num){
[Link](num % 10);
num = [Link](num / 10);
}

for(let indexNum = 0; indexNum < [Link]; indexNum++){


let n = 0;
for(let i = [Link] - 1; i >= 0; i--){
if(i !== indexNum){
n = n * 10 + numdigits[i];
}
}
result = [Link](n, result);
}
return result;
}

[Link](digitDelete(100)); // 10
[Link](digitDelete(10)); // 1
[Link](digitDelete(1245)); // 245

***********************************************************************

function digitDelete(num){
let largeNum = 0;
let numArr = [];
while(num){
[Link](num % 10);
num = [Link](num / 10);
}
numArr = [Link]();
let tempArr = numArr;
for(let i = 0; i < [Link]; i++){
let n = [Link](i, 1);
if(Number([Link]("")) >= largeNum){
largeNum = Number([Link](""));
}
[Link](i, 0, n);
}
return largeNum;
}

[Link](digitDelete(100)); // 10
[Link](digitDelete(10)); // 1
[Link](digitDelete(1245)); // 245

104. Write a JavaScript program to find two elements of the array such that their absolute
difference is not greater than a given integer but is as close to the said integer.

function differentValues(ara, n){


let maxVal = -1;
for(let i = 0; i < [Link]; i++){
for(let j = i + 1; j < [Link]; j++){
const x = [Link](ara[i] - ara[j]);
if(x <=n){
maxVal = [Link](maxVal, x);
}
}
}
return maxVal;
}

[Link](differentValues([12, 10, 33, 34], 10));


[Link](differentValues([12, 10, 33, 34], 24));
[Link](differentValues([12, 10, 33, 44], 40));

105. Write a JavaScript program to find the number of times to replace a given number with the
sum of its digits until it convert to a single digit number.

function digitToOne(num){
const digitSum = num =>{
let sum = 0;
while(num){
sum += num % 10;
num = [Link](num/10);
}
return sum;
}
let result = 0;
while(num >= 10){
result += 1;
num = digitSum(num);
}

return result;
}

[Link](digitToOne(123)); // 1
[Link](digitToOne(156)); // 2

106. Write a JavaScript program to divide an integer by another integer as long as the result is an
integer and return the result.

function divideDigit(num, div){


if(div == 1){
return num;
} else {
while(num % div === 0){
num /= div;
}
return num;
}
}

[Link](divideDigit(-12, 2)); // -3
[Link](divideDigit(13, 2)); // 13
[Link](divideDigit(13, 1)); // 13

107. Write a JavaScript program to find the number of sorted pairs formed by its elements of a
given array of integers such that one element in the pair is divisible by the other one.

For example - The output of [1, 3, 2] ->2 - (1,3), (1,2).

The output of [2, 4, 6] -> 2 - (2,4), (2,6)

The output of [2, 4, 16] -> 3 - (2,4), (2,16), (4,16)

function arrPairs(nums){
let noOfParis = 0;
for(let i = 0; i < [Link]; i++){
for(let j = i + 1; j < [Link]; j++){
if(nums[j] % nums[i] == 0 || nums[i] % nums[j] === 0){
noOfParis++;
}
}
}
return noOfParis;
}

[Link](arrPairs([1, 2, 3])); // 2
[Link](arrPairs([2, 4, 6])); // 2
[Link](arrPairs([2, 4, 16])); // 3

108. Write a JavaScript program to create the dot products of two given 3D vectors.

Note: The dot product is the sum of the products of the corresponding entries of the two sequences
of numbers.

function dotProduct(arr1, arr2){


let sum = 0;
for(let i = 0; i < [Link]; i++){
sum += arr1[i] * arr2[i];
}
return sum;
}

[Link](dotProduct([1, 2, 3], [1, 2, 3])); // 14


[Link](dotProduct([2, 4, 6], [2, 4, 6])); // 56
[Link](dotProduct([1, 1, 1], [0, 1, -1])); // 0

/*

Note: The dot product is the sum of the products of the corresponding entries of the two
sequences of numbers.
1*1 + 2*2 + 3*3 = 14

*/

109. Write a JavaScript program to sort an array of all prime numbers between 1 and a given
integer.

function sortPrime(n){
let counter = 0;
let primeArr = [];
for(let i = 1; i <= n; i++){
counter = 0;
for(let j = 1; j <= i; j++){
if(i % j == 0){
counter++;
}
}
if(counter == 2){
[Link](i);
}
}
return primeArr;
}

[Link](sortPrime(5)); // [2,3,5]
[Link](sortPrime(11)); // [2,3,5,7,11]
[Link](sortPrime(19)); // [2,3,5,7,11,13,17,19]
*******************************************************************************

function sortPrime(num){
const primeNum1 = [];
const primeNum2 = [];
for(let i = 0; i <= num; i++){
[Link](true);
}
for(let i = 2; i <= num; i++){
if(primeNum2[i]){
[Link](i);
for(let j = 1; i * j <= num; j++){
primeNum2[i * j] = false;
}
}
}
return primeNum1;
}

[Link](sortPrime(5)); // [2,3,5]
[Link](sortPrime(11)); // [2,3,5,7,11]
[Link](sortPrime(19)); // [2,3,5,7,11,13,17,19]
110. Write a JavaScript program to find the number of even values in sequence before the first
occurrence of a given number.

function findNumbers(arr, num){


let count = 0;
for(let i = 0; i < [Link]; i++){
if(arr[i] % 2 == 0 && arr[i] < num){
count++;
}
}
return count;
}

[Link](findNumbers([1, 2, 3, 4, 5, 6, 7, 8], 5)); // 2


[Link](findNumbers([1, 3, 5, 6, 7, 8], 6)); // 0

111. Write a JavaScript program to check a number from three given numbers where two numbers
are equal, find the third one.

function findThirdNumber(x, y, z){


if((x !== y) && (x !== z) && (y !== z))
return "Three numbers are unequal.";
if(x == y) return z;
if(x == z) return y;
return x;
}

[Link](findThirdNumber(1, 2, 2)); //1


[Link](findThirdNumber(1, 1, 2)); //2
[Link](findThirdNumber(1, 2, 3)); //Three numbers are unequal.
112. Write a JavaScript program to find the number of trailing zeros in the decimal representation
of the factorial of a given number.

***********************************************************************

function trailingZeros(num){
let fact = 1;
let trailZeroCount = 0;
for(let i = 1; i <= num; i++){
fact *= i;
}
let rem = 0;
while(rem == 0){
rem = fact % 10;
if(rem == 0){
trailZeroCount++;
}
fact = [Link](fact / 10);
}
return trailZeroCount;
}

[Link](trailingZeros(8)); // 1
[Link](trailingZeros(9)); // 1
[Link](trailingZeros(10)); // 2
113. Write a JavaScript program to calculate the sum of n + n/2 + n/4 + n/8 + .... where n is a
positive integer and all divisions are integer.

function intSum(num){
let sum = 0;
while(num > 0){
sum += num;
num = [Link](num / 2);
}
return sum;
}
[Link](intSum(8)); // 15
[Link](intSum(9)); // 16
[Link](intSum(26)); // 49
114. Write a JavaScript program to check whether a given string represents a correct sentence or
not. A string is considered correct sentence if it starts with the capital letter and ends with a full
stop (.).

function isCorrectSentence(str){
const firstChar = str[0];
const lastChar = str[[Link] - 1];
return (/[A-Z]/.test(firstChar) && lastChar == ".");
}

[Link](isCorrectSentence("This tool will help you write better English and efficiently
corrects texts.")); // true
[Link](isCorrectSentence("This tool will help you write better English and efficiently
corrects texts")); // false
[Link](isCorrectSentence("this tool will help you write better English and efficiently
corrects texts.")); // false

115. Write a JavaScript program to check whether a matrix is a diagonal matrix or not. In linear
algebra, a diagonal matrix is a matrix in which the entries outside the main diagonal are all zero
(the diagonal from the upper left to the lower right).

Example:

[1, 0, 0], [0, 2, 0], [0, 0, 3] ]) = true

[1, 0, 0], [0, 2, 3], [0, 0, 3] ]) = false

function diagonalMatrix(arr){
for(let i = 0; i < [Link]; i++){
for(let j = 0; j < [Link]; j++){
if(i !== j && arr[i][j] !== 0){
return false;
}
}
}
return true;
}

[Link](diagonalMatrix([[1, 0, 0], [0, 2, 0], [0, 0, 3]])); // true


[Link](diagonalMatrix([[1, 0, 0], [0, 2, 3], [0, 0, 3]])); // false

116. Write a JavaScript program to find all the possible options to replace the hash in a string
(Consists of digits and one hash (#)) with a digit to produce an integer divisible by 3.

For a string "2*0", the output should be : ["210", "240", "270"]

function isDivisibleBy3(maskStr){
let digitSum = 0;
const left = '0'.charCodeAt();
const right = '9'.charCodeAt();
const result = [];
const maskData = [Link]('');
let hashPos = -1;
for(var i = 0; i < [Link]; i++){
if(left <= maskData[i].charCodeAt() && maskData[i].charCodeAt() <= right){
digitSum += maskData[i].charCodeAt() - left;
} else {
hashPos = i;
}
}
for(var i = 0; i < 10; i++){
if((digitSum + i) % 3 === 0){
maskData[hashPos] = [Link](left + i);
[Link]([Link](''));
}
}
return result;
}

[Link](isDivisibleBy3("2#0")); // [210, 240, 270]


[Link](isDivisibleBy3("4#2")); // [402, 432, 462, 492]

************************************************************
function isDivisibleBy3(str){
let newHashArr = [];
for(let i = 0; i < 10; i++){
let newStr = [Link](/#/, `${i}`);
if(Number(newStr) % 3 == 0){
[Link](Number(newStr));
}
}
return newHashArr;
}

[Link](isDivisibleBy3("2#0")); // [210, 240, 270]


[Link](isDivisibleBy3("4#2")); // [402, 432, 462, 492]

117. Write a JavaScript program to check whether a given matrix is an identity matrix.

Note: In linear algebra, the identity matrix, or sometimes ambiguously called a unit matrix, of size
n is the n ? n square matrix with ones on the main diagonal and zeros elsewhere.

[[1, 0, 0], [0, 1, 0], [0, 0, 1]] -> true

[[1, 0, 0], [0, 1, 0], [1, 0, 1]] -> false

function checkIndentityMatrix(matrixData){
for(let i = 0; i < [Link]; i++){
for(let j = 0; j < [Link]; j++){
if(matrixData[i][j] !== 1 && i === j || matrixData[i][j] && i !== j){
return false;
}
}
}
return true;
}

[Link](checkIndentityMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])); // true


[Link](checkIndentityMatrix([[1, 0, 1], [0, 1, 0], [0, 0, 1]])); // false

118. Write a JavaScript program to check whether a given number


is in a given range.

function isInRange(x, y, z){


return (x <= y && z >= y);
}

[Link](isInRange(1, 2, 3)); // true


[Link](isInRange(1, 2, -3)); // false
[Link](isInRange(1.1, 1.3, 1.3)); // true

119. Write a JavaScript program to check whether a given integer


has an increasing digits sequence.
function isIncreasingDigitsSequence(num){
let numsArray = [];
while(num > 0){
let rem = num % 10;
[Link](rem);
num = [Link](num / 10);
}
numsArray = [Link]();
for(let i = 0; i < [Link]; i++){
if(numsArray[i] >= numsArray[i + 1]){
return false;
}
}
return true;
}

[Link](isIncreasingDigitsSequence(123)); // true
[Link](isIncreasingDigitsSequence(1223)); // false
[Link](isIncreasingDigitsSequence(45677)); // false

120. Write a JavaScript program to check whether a point lies strictly inside a given circle.

Input:

Center of the circle (x, y)

Radius of circle: r

Point inside a circle (a, b)

function checkAPoint(a, b, x, y, r){


var distPoints = (a - x) * (a - x) + (b - y) * (b - y);
r *= r;
if(distPoints < r){
return true;
}
return false;
}

[Link](checkAPoint(0, 0, 2, 4, 6)); // true


[Link](checkAPoint(0, 0, 6, 8, 6)); // false

121. Write a JavaScript program to check whether a given matrix is lower triangular or not.

Note: A square matrix is called lower triangular if all the entries above the main diagonal are zero.

Note: A square matrix is called lower triangular if all the entries above the main diagonal are zero.

function lowerTriangularMatrix(arr){
for(let i = 0; i < [Link]; i++){
for(let j = 0; j < [Link]; j++){
if(i < j && arr[i][j] !== 0){
return false;
}
}
}
return true;
}

[Link](lowerTriangularMatrix([[1, 0, 0], [2, 0, 0], [0, 3, 3]])); // true


[Link](lowerTriangularMatrix([[1, 0, 1], [2, 0, 0], [0, 3, 3]])); // false

122. Write a JavaScript program to check whether a given array of integers represents either a
strictly increasing or a strictly decreasing sequence.
function isMonotonous(num){
if([Link] === 1){
return true;
}

const numDirection = num[1] - num[0];


for(let i = 0; i < [Link]; i++){
if(numDirection * (num[i + 1] - num[i]) <= 0){
return false;
}
}
return true;
}

[Link](isMonotonous([1, 2, 3])); // true


[Link](isMonotonous([1, 2, 2])); // false
[Link](isMonotonous([-3, -2, -1])); // true

123. Write a JavaScript program to find whether the members of a given array of integers is a
permutation of numbers from 1 to a given integer.

function isPermutation(arr, n){


for(let i = 0; i < n; i++){
if(![Link](i + 1)){
return false;
}
}
return true;
}

[Link](isPermutation([1, 2, 3, 4, 5], 5)); // true


[Link](isPermutation([1, 2, 3, 5], 5)); // false

124. Write a JavaScript program to create the value of NOR of two given booleans.

Note: In boolean logic, logical nor or joint denial is a truth-functional operator which produces a
result that is the negation of logical or. That is, a sentence of the form (p NOR q) is true precisely
when neither p nor q is true - i.e. when both of p and q are false

Sample Example:

For x = true and y = false, the output should be logical_Nor(x, y) = false; For x = false and y = false,
the output should be logical_Nor(x, y) = true.

function testLogicalNOR(a, b){


return (!a && !b);
}

[Link](testLogicalNOR(true, false)); // false


[Link](testLogicalNOR(false, false)); // true
[Link](testLogicalNOR(true, true)); // false

125. Write a JavaScript program to find the longest string from a given array.

function longestStr(arra){
let maxStr = arra[0].length;
let ans = arra[0];
for(let i = 1; i < [Link]; i++){
const maxi = arra[i].length;
if(maxi > maxStr){
ans = arra[i];
maxStr = maxi;
}
}
return ans;
}

[Link](longestStr(["ab", "a", "abcd"])); // abcd


[Link](longestStr(["ab", "ab", "ab"])); // ab
*********************************************************************************

function longestStr(strArr){
let longStrLen = "";
for(let i = 0; i < [Link]; i++){
if(strArr[i].length > [Link]){
longStrLen = strArr[i];
}
}
return longStrLen;
}

[Link](longestStr(["ab", "a", "abcd"]));


[Link](longestStr(["ab", "ab", "ab"]));

126. Write a JavaScript program to get the largest even number from an array of integers.

function maxEven(arr){
[Link]((x, y) => y - x); // descending order
for(let i = 0; i < [Link]; i++){
if(arr[i] % 2 == 0){
return arr[i];
}
}
}

[Link](maxEven([20, 40, 200])); // 200


[Link](maxEven([20, 40, 200, 301])); // 200
**************************************************************************

function maxEven(arr){
let largestEvenNum = 0;
for(let i = 0; i < [Link]; i++){
if(arr[i] % 2 == 0){
if(arr[i] > 0){
largestEvenNum = arr[i];
}
}
}
return largestEvenNum;
}

[Link](maxEven([20, 40, 200])); // 200


[Link](maxEven([20, 40, 200, 301])); // 200
127. Write a JavaScript program to reverse the order of the bits in a given integer.

56 -> 111000 after reverse 7 -> 111

234 -> 11101010 after reverse 87 -> 1010111


function mirrorBits(n){
return parseInt([Link](2).split("").reverse().join(""), 2);
}

[Link](mirrorBits(56)); // 7
[Link](mirrorBits(234)); // 87
128. Write a JavaScript program to find the smallest round number that is not less than a given
value.

Note: A round number is informally considered to be an integer that ends with one or more zeros.
[3] So, 590 is rounder than 592, but 590 is less round than 600.

function nearestRoundNumber(num){
while(num % 10){
num++;
}
return num;
}

[Link](nearestRoundNumber(56)); // 60
[Link](nearestRoundNumber(592)); // 600

129. Write a JavaScript program to find the smallest prime number strictly greater than a given
number.

function nextPrimeNum(num){
for(let i = num + 1;; i++){
let isPrime = true;
for(let d = 2; d * d <= i; d++){
if(i % d === 0){
isPrime = false;
break;
}
}
if(isPrime){
return i;
}
}
}

[Link](nextPrimeNum(3)); // 5
[Link](nextPrimeNum(17)); // 19
****************************************************************************************

function nextPrimeNum(num){
let primeNum = 0;
for(let i = num + 1;; i++){
let counter = 0;
for(let j = 1; j <= i; j++){
if(i % j == 0){
counter++;
}
}
if(counter == 2){
primeNum = i;
break;
}
}
return primeNum;
}

[Link](nextPrimeNum(3)); // 5
[Link](nextPrimeNum(17)); // 19
130. Write a JavaScript program to find the number of even digits in a given integer.

function evenDigits(num){
let count = 0;
while(num > 0){
let n = num % 10;
num = [Link](num / 10);
if(n % 2 == 0){
count++;
}
}
return count;
}

[Link](evenDigits(123));
[Link](evenDigits(1020));
[Link](evenDigits(102));

131. Write a JavaScript program to create an array of prefix sums of the given array.

In computer science, the prefix sum, cumulative sum, inclusive scan, or simply scan of a sequence
of numbers x0, x1, x2, ... is a second sequence of numbers y0, y1, y2, ..., the sums of prefixes of
the input sequence:

y0 = x0
y1 = x0 + x1
y2 = x0 + x1+ x2
...

function prefixSum(arr){
let prefixArr = [];
for(let i = 0; i < [Link]; i++){
let tempSum = 0;
for(let j = 0; j < i + 1; j++){
tempSum += arr[j];
}
[Link](tempSum);
}
return prefixArr;
}

[Link](prefixSum([1, 2, 3, 4, 5])); // [1, 3, 6, 10, 15]


[Link](prefixSum([1, 2, -3, 4, 5])); // [1, 3, 0, 4, 9]
132. Write a JavaScript program to find all distinct prime factors of a given integer.

function primeFactor(num){
function isPrime(num){
for(let i = 2; i <= [Link](num); i++){
if(num % i === 0) return false;
} return true;
return false;
}
const result = [];
for(let i = 2; i <= num; i++){
while(isPrime(i) && num % i === 0){
if(![Link](i)) [Link](i);
num /= i;
}
}
return result;
}

[Link](primeFactor(100)); // [2, 5]
[Link](primeFactor(101)); // [101]
[Link](primeFactor(103)); // [101]
[Link](primeFactor(104)); // [2, 13]
[Link](primeFactor(105)); // [3, 5, 7]

133. Write a JavaScript program to check whether a given fraction is proper or not.

Note: There are two types of common fractions, proper or improper. When the numerator and the
denominator are both positive, the fraction is called proper if the numerator is less than the
denominator, and improper otherwise.

function properImproperTest(num){
/*let msg = (arr[0] < arr[1] && (arr[0] > 0 && arr[1] > 0))
? "Proper fraction" : "Improper fraction";
return msg;*/
return [Link](num[0] / num[1]) < 1
? "Proper fraction" : "Improper fraction";
}

[Link](properImproperTest([12, 300])); // Proper fraction


[Link](properImproperTest([2, 4])); // Proper fraction
[Link](properImproperTest([103, 3])); // Improper fraction
[Link](properImproperTest([104, 2])); // Improper fraction
[Link](properImproperTest([5, 40])); // Proper fraction
134. Write a JavaScript program to change the characters (lower case) in a string where a turns
into z, b turns into y, c turns into x, ..., n turns into m, m turns into n, ..., z turns into a.

function changeChar(str){
const result = [];
for(let i = 0; i < [Link]; i++){
const charOrder = [Link](i) - 'a'.charCodeAt(0);
const changeChar = 25 - charOrder + 'a'.charCodeAt(0);
[Link]([Link](changeChar));
}
return [Link]("");
}

[Link](changeChar("abcxyz")); // zyxcba
[Link](changeChar("python")); // kbgslm

135. Write a JavaScript program to remove all characters from a given string that appear more than
once.

function removeDuplicateChars(str){
const arrChar = [Link]("");
const resultArr = [];
for(let i = 0; i < [Link]; i++){
if([Link](arrChar[i]) === [Link](arrChar[i])){
[Link](arrChar[i]);
}
}
return [Link]("");
}

[Link](removeDuplicateChars("abcdabc")); // d
[Link](removeDuplicateChars("python")); // python
[Link](removeDuplicateChars("abcabc")); //
[Link](removeDuplicateChars("1365451")); // 364

136. Write a JavaScript program to replace the first digit in a string (should contains at least digit)
with $ character.

function replaceFirstDigit(str){
return ([Link](/[1-9]/, "$"));
}
[Link](replaceFirstDigit("abc1dabc")); // abc$dabc
[Link](replaceFirstDigit("p3ython")); // p$ython
[Link](replaceFirstDigit("ab1abc")); // ab$abc

137. Write a JavaScript program to test whether a given integer is greater than 15 return the given
number, otherwise return 15.

function testFifteen(num){
while(num < 15){
num++;
}
return num;
}

[Link](testFifteen("123")); // 123
[Link](testFifteen("10")); // 15
[Link](testFifteen("5")); // 15
***********************************************************

function testFifteen(str){
return (Number(str) >= 15) ? str : "15";
}

[Link](testFifteen("123")); // 123
[Link](testFifteen("10")); // 15
[Link](testFifteen("5")); // 15
138. Write a JavaScript program to reverse the bits of a given 16 bits unsigned short integer.
function sixteenBitsReverse(num){
let result = 0;
for(let i = 0; i < 16; i++){
result = result * 2 + (num % 2);
num = [Link](num / 2);
}
return result;
}

[Link](sixteenBitsReverse(12345)); // 39948
[Link](sixteenBitsReverse(10)); // 20480
[Link](sixteenBitsReverse(5)); // 40960
139. Write a JavaScript program to find the position of a rightmost round number in an array of
integers. Returns 0 if there are no round number. Note: A round number is informally considered
to be an integer that ends with one or more zeros.

function rightmostRoundNum(arr){
for(let i = [Link]; i >= 0; i--){
if(arr[i] % 10 === 0){
return i;
}
}
return 0;
}
[Link](rightmostRoundNum([1, 22, 30, 54, 56]));
[Link](rightmostRoundNum([1, 22, 32, 54, 56]));
[Link](rightmostRoundNum([1, 22, 32, 54, 50]));

140. Write a JavaScript program to check whether all the digits in a given number are the same or
not.

function testSameDigit(num){
const first = num % 10;
while(num){
if(num % 10 !== first) return false;
num = [Link](num / 10);
}
return true;
}

[Link](testSameDigit(1234)); // false
[Link](testSameDigit(1111)); // true
[Link](testSameDigit(22222222)); // true
***********************************************************************

function testSameDigit(num){
let numArr = [];
while(num > 0){
let rem = num % 10;
[Link](rem);
num = [Link](num / 10);
}
for(let i = 0; i < [Link] - 1; i++){
if(numArr[i] !== numArr[i + 1]){
return false;
}
}
return true;
}

[Link](testSameDigit(1234)); // false
[Link](testSameDigit(1111)); // true
[Link](testSameDigit(22222222)); // true
141. Write a JavaScript program to find the number of elements which presents in both of the given
arrays.

function testSameElements(arr1, arr2){


let counter = 0;
for(let i = 0; i < [Link]; i++){
for(let j = 0; j <[Link]; j++){
if(arr1[i] === arr2[j]){
counter++;
}
}
}
return counter;
}

[Link](testSameElements([1, 2, 3, 4], [1, 2, 3, 4]));


[Link](testSameElements([1, 2, 3, 4], [1, 2, 3, 5]));
[Link](testSameElements([1, 2, 3, 4], [11, 22, 33, 44]));

142. Write a JavaScript program to simplify a given absolute path for a file in Unix-style.

function simplifyPath(mainPath){
const parts = [Link]('/');
const newPath = [];
let length = 0;
for(let i = 0; i < [Link]; i++){
const part = parts[i];
if(part === '.' || part === '' || part === '..'){
if(part === '..' && length > 0){
length--;
}
continue;
}
newPath[length++] = part;
}
if(length == 0){
return '/';
}
let result = '';
for(let i = 0; i < length; i++){
result += `/${newPath[i]}`;
}
return result;
}

[Link](simplifyPath("/home/var/./www/../html//sql/")); // /home/var/html/sql

143. Write a JavaScript program to sort the strings of a given array of strings in the order of
increasing lengths. Note: Do not change the order if the lengths of two string are same.

function sortByStringLength(arr){
let temp = "";
for(let i = 0; i < [Link]; i++){
for(let j = i + 1; j < [Link]; j++){
if(arr[i].length > arr[j].length){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}

var arra = ["xyz", "acd", "aa", "bb", "zzz", "", "a", "b"];
[Link]("Original array: " + arra + "\n");
[Link](sortByStringLength(["xyz", "acd", "aa", "bb", "zzz", "", "a", "b"]));
// Original array: xyz,acd,aa,bb,zzz,,a,b
// ["","a","b","bb","aa","xyz","acd","zzz"]
144. Write a JavaScript program to break an address of an url and put it's part into an array. Note:
url structure : ://.org[/] and there may be no part in the address.

function breakAddress(urlAdd){
let data = [Link]("://");
const protocol = data[0];
data = data[1].split(".com");
const domain = data[0];
data = data[1].split("/");
if(data[1]){
return [protocol, domain, data[1]];
}
return [protocol, domain];
}

let urlAdd = "[Link]


[Link](`Original address: ${urlAdd}`);
[Link](breakAddress(urlAdd)); // ["https", "www.w3resource", "javascript-exercises"]
145. Write a JavaScript program to find the maximum integer n such that 1 + 2 + ... + n <= a given
integer.

function sumn(val){
let sn = 0;
let i = 0;
while(sn <= val){
sn += i++;
}
return i - 2;
}
[Link](sumn(11)); // 4
[Link](sumn(15)); // 5
146. Write a JavaScript program to compute the sum of cubes of all integer from 1 to a given
integer.

function sumOfCubes(n){
let sum = 0;
for(let i = 1; i <= n; i++){
sum += [Link](i, 3);
}
return sum;
}
[Link](sumOfCubes(3));
[Link](sumOfCubes(4));
147. Write a JavaScript program to compute the sum of all digits that occur in a given string.
function sumDigitsFromString(str){
let sum = 0;
for(let i = 0; i <[Link]; i++){
if(/[0-9]/.test(str[i])) sum += parseInt(str[i]);
}
return sum;
}
[Link](sumDigitsFromString("abcd12efg9")); // 12
[Link](sumDigitsFromString("w3resource")); // 3

**********************************************************************************************
*********
function sumDigitsFromString(str){
let sum = 0;
for(let i = 0; i < [Link]; i++){
if(!isNaN(str[i])){
sum += Number(str[i]);
}
}
return sum;
}
[Link](sumDigitsFromString("abcd12efg9")); // 12
[Link](sumDigitsFromString("w3resource")); // 3
148. Write a JavaScript program to swap two halves of a given array of integers of even length.
function halvArraySwap(arr){
if((([Link]) % 2) != 0){
return false;
}
for(let i = 0; i < [Link] / 2; i++){
let temp = arr[i];
arr[i] = arr[i + [Link] / 2];
arr[i + [Link] / 2] = temp;
}
return arr;
}

[Link](halvArraySwap([1, 2, 3, 4, 5, 6])); // [4, 5, 6, 1, 2, 3]


[Link](halvArraySwap([1, 2, 3, 4, 5, 6, 7])); // false
************************************************************************************************************
****************

function halvArraySwap(arr){
let tempArr = [];
if([Link] % 2 == 0){
tempArr = [Link](0, [Link] / 2);
return ([Link](tempArr));
} else return false;
}
[Link](halvArraySwap([1, 2, 3, 4, 5, 6]));
[Link](halvArraySwap([1, 2, 3, 4, 5, 6, 7]));
149. Write a JavaScript program to change the capitalization of all letters in a given string.

function changeCase(str){
let tmpStr = "";
for(let i = 0; i < [Link]; i++){
if(/[A-Z]/.test(str[i])){
tmpStr += str[i].toLowerCase();
} else tmpStr += str[i].toUpperCase();
}
return tmpStr;
}
[Link](changeCase("w3resource")); // W3RESOURCE
[Link](changeCase("Germany")); // gERMANY
150. Write a JavaScript program to swap pairs of adjacent digits of a given integer of even length.

function swapAdjacentDigits(n){
if(n % 2 != 0) return false;
var result = 0, x = 1;
while(n != 0){
var dg1 = n % 10,
dg2 = ((n - dg1) / 10) % 10;
result += x * (10 * dg1 + dg2);
n = [Link](n / 100);
x *= 100;
}
return result;
}
[Link](swapAdjacentDigits(1234)); // 2143
[Link](swapAdjacentDigits(123456)); // 214365
[Link](swapAdjacentDigits(12345)); // false

**********************************************************************************************
*********

function swapAdjacentDigits(num){
let numArr = [];
while(num){
let temp = num % 10;
[Link](temp);
num = [Link](num / 10);
}
[Link]();
if([Link] % 2 == 0){
for(let i = 0; i < [Link]; i += 2){
for(let j = i + 1; j < i + 2; j++){
let temp = numArr[i];
numArr[i] = numArr[j];
numArr[j] = temp;
}
}
return [Link](“”);
} else return false;
}
[Link](swapAdjacentDigits(1234)); // 2143
[Link](swapAdjacentDigits(123456)); // 214365
[Link](swapAdjacentDigits(12345)); // false

JavaScript functions - Exercises, Practice, Solution

Last update on February 26 2020 08:09:06 (UTC/GMT +8 hours)

JavaScript functions

1. Write a JavaScript function that reverse a number.

Example x = 32243;

Expected Output : 34223

function reverseANumber(num){
num = num + "";
return [Link]("").reverse().join("");
}
[Link](reverseANumber(32243)); // 3

2. Write a JavaScript function that checks whether a passed string is palindrome or not?

A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam
or nurses run.
// Write a JavaScript function that checks whether a passed string is palindrome or not?

function check_Palindrome(str_entry){
// Change the string into lower case and remove all non-alphanumeric characters
var cstr = str_entry.toLowerCase().replace(/[^a-zA-Z0-9]+/g,'');
var ccount = 0;
// Check whether the string is empty or not
if(cstr==="") {
[Link]("Nothing found!");
return false;
}
// Check if the length of the string is even or odd
if (([Link]) % 2 === 0) {
ccount = ([Link]) / 2;
} else {
// If the length of the string is 1 then it becomes a palindrome
if ([Link] === 1) {
[Link]("Entry is a palindrome.");
return true;
} else {
// If the length of the string is odd ignore middle character
ccount = ([Link] - 1) / 2;
}
}
// Loop through to check the first character to the last character and then move next
for (var x = 0; x < ccount; x++) {
// Compare characters and drop them if they do not match
if (cstr[x] != [Link](-1-x)[0]) {
[Link]("Entry is not a palindrome.");
return false;
}
}
[Link]("The entry is a palindrome.");
return true;
}
check_Palindrome('madam'); // The entry is a palindrome.
check_Palindrome('nurses run'); // The entry is a palindrome.
check_Palindrome('fox'); // Entry is not a palindrome.
***************************************************** For normal string
*****************************************************

function checkPalindrome(str){
if(str == ""){ return "Empty string."};
let strArr = [Link]("");
for(let i = 0; i < [Link]; i++){
if(strArr[i] == " "){
[Link](i, 1);
}
}
if([Link]("") == [Link]().join("")){
return "The entry is a palindrome.";
} else return "Entry is not a palindrome.";
}

[Link](checkPalindrome('madam'));
[Link](checkPalindrome('nurses run'));
[Link](checkPalindrome('fox'));
3. Write a JavaScript function that generates all combinations of a string.

Example string : 'dog'

Expected Output : d,do,dog,o,og,g

function substrings(str1){
let array1 = [];
for(let x = 0, y = 1; x < [Link]; x++, y++){
array1[x] = [Link](x, y);
}
let combi = [];
var temp = "";
var slent = [Link](2, [Link]);
for(let i = 0; i < slent; i++){
temp = "";
for(let j = 0; j < [Link]; j++){
if((i & [Link](2, j))){
temp += array1[j];
}
}
if(temp !== ""){
[Link](temp);
}
}
[Link]([Link]("\n"));
}

substrings("dog"); // d o do g dg og dog

4. Write a JavaScript function that returns a passed string with letters in alphabetical order.

Example string : 'webmaster'

Expected Output : 'abeemrstw'

Assume punctuation and numbers symbols are not included in the passed string.

function alphabetOrder(str){
return ([Link]("").sort().join(""));
}
[Link](alphabetOrder("webmaster")); // abeemrstw
5. Write a JavaScript function that accepts a string as a parameter and converts the first letter of
each word of the string in upper case.

Example string : 'the quick brown fox'

Expected Output : 'The Quick Brown Fox '


Explanation:

Assume str = "the quick brown fox";

The split() method is used to split a String object into an array of strings by separating the string into substrings.
[Link]([Link](' '));
Output : ["the", "quick", "brown", "fox"]
First substrings -> "the"
Code to convert first character of the above sting to upper case-> array1[x].charAt(0).toUpperCase()
[Link](array1[x].charAt(0).toUpperCase()); [here x=0]
Output : "T"
Rest part of the string "the" -> array1[x].slice(1)
[Link](array1[0].slice(1));
Output : "he"
Final string :
[Link](array1[0].charAt(0).toUpperCase()+array1[0].slice(1));
Output : "The"
Now insert the above string into another array :
[Link](array1[x].charAt(0).toUpperCase()+array1[x].slice(1));

function uppercase(str){
let array1 = [Link](" ");
var newarray1 = [];
for(let x = 0; x < [Link]; x++){
[Link](array1[x].charAt(0).toUpperCase() + array1[x].slice(1));
}
return [Link](" ");
}

[Link](uppercase("the quick brown fox")); // The Quick Brown Fox

***********************************************************************************
function uppercase(str){
let arr = [Link]("");
arr[0] = arr[0].toUpperCase();
for(let i = 0; i < [Link]; i++){
if(arr[i] == " "){
arr[i + 1] = arr[i + 1].toUpperCase();
}
}
return [Link]("");
}

[Link](uppercase("the quick brown fox"));


6. Write a JavaScript function that accepts a string as a parameter and find the longest word within
the string.

Example string : 'Web Development Tutorial'

Expected Output : 'Development'

function findLongestWord(str){
let array1 = [Link](/\w[a-z]{0,}/gi);
let result = array1[0];
for(let x = 1; x <[Link]; x++){
if([Link] < array1[x].length)
result = array1[x];
}
return result;
}

[Link](findLongestWord('Web Development Tutorial')); // Development


//\w metacharacter is used to find a word character

7. Write a JavaScript function that accepts a string as a parameter and counts the number of
vowels within the string.
Note : As the letter 'y' can be regarded as both a vowel and a consonant, we do not count 'y' as
vowel here.

Example string : 'The quick brown fox'

Expected Output : 5

function vowelCount(str){
let vowelList = "aeiouAEIOU";
let vowelCount = 0;
for(let x = 0; x < [Link]; x++){
if([Link](str[x]) !== -1){
vowelCount++;
}
}
return vowelCount;
}
[Link](vowelCount("The quick brown fox")); // 5
8. Write a JavaScript function that accepts a number as a parameter and check the number is prime
or not.

Note : A prime number (or a prime) is a natural number greater than 1 that has no positive divisors
other than 1 and itself.

function testPrime(num){
let counter = 0;
if(num == 1) return false;
else if(num == 2) return true;
else{
for(let i = 1; i <= num; i++){
if(num % i == 0){
counter++;
}
}
}
return (counter == 2);
}
[Link](testPrime(37)); // true
10. Write a JavaScript function which returns the n rows by n columns identity matrix.

function matrixGen(n){
for(let i = 0; i < n; i++){
for(let j = 0; j < n; j++){
if(i == j){
[Link](' 1 ');
} else {
[Link](' 0 ');
}
}
[Link]("----------------");
}
}

matrixGen(4);

Output:
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
11. Write a JavaScript function which will take an array of numbers stored and find the second
lowest and second greatest numbers, respectively.
Sample array : [1,2,3,4,5]

Expected Output : 2,4

function secondGreatestLowest(arr){
[Link](function(a, b){
return a - b;
});

let uniqa = [arr[0]];


let result = [];
for(let j = 1; j < [Link]; j++){
if(arr[j - 1] !== arr[j]){
[Link](arr[j]);
}
}
[Link](uniqa[1], uniqa[[Link] - 2]);
return [Link](", ");
}
[Link](secondGreatestLowest([4, 2, 3, 1, 5])); // 2, 4

12. Write a JavaScript function which says whether a number is perfect.

According to Wikipedia : In number theory, a perfect number is a positive integer that is equal to
the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number
itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the
sum of all of its positive divisors (including itself).

Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 +
2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3
+ 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect
numbers 496 and 8128.

function isPerfect(num){
let temp = 0;
for(let i = 1; i <= num/2; i++){
if(num % i === 0){
temp += i;
}
}
if(temp === num && temp !== 0){
[Link]("It is a perfect number.");
} else {
[Link]("It is not a perfect number.");
}
}
isPerfect(28); // It is a perfect number.

13. Write a JavaScript function to compute the factors of a positive integer.

function factors(num){
let factorsArr = [];
for(let i = 1; i <= num; i++){
if(num % i === 0){
[Link](i);
}
}
return factorsArr;
}

[Link](factors(15));
[Link](factors(16));
[Link](factors(17));
**********************************************************
function factors(n){
let numFactors = [], i;
for(i = 1; i <= [Link]([Link](n)); i++){
if(n % i === 0){
[Link](i);
if(n / i !== i){
[Link](n / i);
}
}
}
[Link](function(x, y) { return x - y}); // numeric sort
return numFactors;
}

[Link](factors(15)); // [1, 3, 5, 15]


[Link](factors(16)); // [1, 2, 4, 8, 16]
[Link](factors(17)); // [1, 17]

14. Write a JavaScript function to convert an amount to coins.

Sample function : amountTocoins(46, [25, 10, 5, 2, 1])

Here 46 is the amount. and 25, 10, 5, 2, 1 are coins.

Output : 25, 10, 10, 1

function amountToCoins(amount, coins){


if(amount === 0) {
return [];
} else {
if(amount >= coins[0]){
left = (amount - coins[0]);
return [coins[0]].concat(amountToCoins(left, coins));
} else {
[Link]();
return amountToCoins(amount, coins);
}
}
}
[Link](amountToCoins(46, [25, 10, 5, 2, 1])); // [25, 10, 10, 1]
15. Write a JavaScript function to compute the value of b n where n is the exponent and b is the
bases. Accept b and n from the user and display the result.

function exp(b, n){


let ans = 1;
for(let i = 1; i <=n; i++){
ans *= b;
}
return ans;
}
[Link](exp(2, 3)); // 8
16. Write a JavaScript function to extract unique characters from a string.

Example string : "thequickbrownfoxjumpsoverthelazydog"

Expected Output : "thequickbrownfxjmpsvlazydg"

function uniqueChar(str){
let uChar = [];
for(let i = 0; i < [Link]; i++){
if(![Link](str[i])){
[Link](str[i]);
}
}
return [Link]("");
}
[Link](uniqueChar("thequickbrownfoxjumpsoverthelazydog")); // thequickbrownfxjmpsvlazydg
*********************************************************
function uniqueChar(str1){
var str = str1;
var uniq1 = "";
for(var x = 0; x < [Link]; x++){
if([Link]([Link](x)) == -1){
uniq1 += str[x];
}
}
return uniq1;
}
[Link](uniqueChar("thequickbrownfoxjumpsoverthelazydog")); // thequickbrownfxjmpsvlazydg
17. Write a JavaScript function to get the number of occurrences of each letter in specified string.

function uniqueChar(str1){
var uChars = {};
[Link](/\S/g, function(l){uChars[l] = (isNaN(uChars[l]) ? 1 : uChars[l] + 1);});
return uChars;
}
[Link](uniqueChar("The quick brown fox jumps over the lazy dog"));
//
{"T":1,"h":2,"e":3,"q":1,"u":2,"i":1,"c":1,"k":1,"b":1,"r":2,"o":4,"w":1,"n":1,"f":1,"x":1,"j"
:1,"m":1,"p":1,"s":1,"v":1,"t":1,"l":1,"a":1,"z":1,"y":1,"d":1,"g":1}
18. Write a function for searching JavaScript arrays with a binary search.

Note : A binary search searches by splitting an array into smaller and smaller chunks until it finds
the desired value.
function arrayBinarySearch(narray, delement){
var mposition = [Link]([Link] / 2);
if(narray[mposition] === delement){
return mposition;
} else if([Link] === 1){
return null;
} else if(narray[mposition] < delement){
var arr = [Link](mposition + 1);
var res = arrayBinarySearch(arr, delement);
if(res === null){
return null;
} else {
return mposition + 1 + res;
}
} else {
var arr1 = [Link](0, mposition);
return arrayBinarySearch(arr1, delement);
}
}
let myArray = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23];
[Link](arrayBinarySearch(myArray, 6)); // 4
19. Write a JavaScript function that returns array elements larger than a number.

function BiggerElements(val){
return function(evalue, index, array){
return (evalue >= val);
};
}
var result = [11, 45, 1, 31, 64, 10].filter(BiggerElements(10));
[Link](result); // [11, 45, 31, 64, 10]
20. Write a JavaScript function that generates a string id (specified length) of random characters.

Sample character list :


"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

function makeID(len){
var charList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var newID = "";
for(let i = 0; i < len; i++){
newID += [Link]([Link]([Link]() * [Link]));
}
return newID;
}
[Link](makeID(8));
// VOlKwxxA
// URflDCfa
// bHIgYCrE
21. Write a JavaScript function to get all possible subset with a fixed length (for example 2)
combinations in an array.

Sample array : [1, 2, 3] and subset length is 2

Expected output : [[2, 1], [3, 1], [3, 2], [3, 2, 1]]

function subset(arra, arraSize){


var resultSet = [], result;

for(var x = 0; x < [Link](2, [Link]); x++){


result = [];
i = [Link] - 1;
do{
if((x & (1 << i)) !== 0){
[Link](arra[i]);
}
} while(i--);
if([Link] >= arraSize){
[Link](result);
}
}
return resultSet;
}
[Link](subset([1, 2, 3], 2));

22. Write a JavaScript function that accepts two arguments, a string and a letter and the function
will count the number of occurrences of the specified letter within the string.

Sample arguments : '[Link]', 'o'

Expected output : 2

function charCount(str, letter){


let count = 0;
for(let i = 0; i < [Link]; i++){
if(str[i] === letter) count++;
}
return count;
}
[Link](charCount('[Link]', 'o')); // 2
23. Write a JavaScript function to find the first not repeated character.

Sample arguments : 'abacddbec'

Expected output : 'e'

function firstNonRepeatChar(str){
let tempArr = [Link]("");
for(let i = 0; i < [Link]; i++){
let count = 0;
for(let j = 0; j < [Link]; j++){
if(tempArr[i] === tempArr[j]){
count++;
}
}
if(count === 1){
return tempArr[i];
}
}
return false;
}
[Link](firstNonRepeatChar('abacddbec')); // e
[Link](firstNonRepeatChar('abcddbec')); // a
[Link](firstNonRepeatChar('abacddbeec')); // false
24. Write a JavaScript function that accept a list of country names as input and returns the longest
country name as output.

Sample function : Longest_Country_Name(["Australia", "Germany", "United States of America"])

Expected output : "United States of America"

function longestCountryName(countryName){
return [Link](function(lname, country){
return [Link] > [Link] ? lname : country;
}, "");
}
[Link](longestCountryName(["Australia", "Germany", "United States of America"]));
// United States of America
25. Write a JavaScript function to find longest substring in a given a string without repeating
characters.
function longest_substring_without_repeating_characters(input) {
var chars = [Link]('');
var curr_char;
var str = "";
var longest_string = "";
var hash = {};
for (var i = 0; i < [Link]; i++) {
curr_char = chars[i];
if (!hash[chars[i]])
{
str += curr_char;
hash[chars[i]] = {index:i};
}
else
{
if(longest_string.length <= [Link])
{
longest_string = str;
}
var prev_dupeIndex = hash[curr_char].index;
var str_FromPrevDupe = [Link](prev_dupeIndex + 1, i);
str = str_FromPrevDupe + curr_char;
hash = {};
for (var j = prev_dupeIndex + 1; j <= i; j++) {
hash[[Link](j)] = {index:j};
}
}
}
return longest_string.length > [Link] ? longest_string : str;
}
[Link](longest_substring_without_repeating_characters("[Link]")); // [Link]
[Link](longest_substring_without_repeating_characters("[Link]")); // [Link]

26. Write a JavaScript function that returns the longest palindrome in a given string.

Note: According to Wikipedia "In computer science, the longest palindromic substring or longest
symmetric factor problem is the problem of finding a maximum-length contiguous substring of a
given string that is also a palindrome. For example, the longest palindromic substring of "bananas"
is "anana". The longest palindromic substring is not guaranteed to be unique; for example, in the
string "abracadabra", there is no palindromic substring with length greater than three, but there
are two palindromic substrings with length three, namely, "aca" and "ada".

In some applications it may be necessary to return all maximal palindromic substrings (that is, all
substrings that are themselves palindromes and cannot be extended to larger palindromic
substrings) rather than returning only one substring or returning the maximum length of a
palindromic substring.

function is_Palindrome(str1) {
var rev = [Link]("").reverse().join("");
return str1 == rev;
}

function longest_palindrome(str1){
var max_length = 0,
maxp = '';

for(var i=0; i < [Link]; i++)


{
var subs = [Link](i, [Link]);

for(var j=[Link]; j>=0; j--)


{
var sub_subs_str = [Link](0, j);
if (sub_subs_str.length <= 1)
continue;

if (is_Palindrome(sub_subs_str))
{
if (sub_subs_str.length > max_length)
{
max_length = sub_subs_str.length;
maxp = sub_subs_str;
}
}
}
}

return maxp;
}
[Link](longest_palindrome("abracadabra")); // aca
[Link](longest_palindrome("HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE"));
// 12345678987654321

27. Write a JavaScript program to pass a 'JavaScript function' as parameter.

function addStudent(id, refreshCallback){


refreshCallback();
}
function refreshStudentList(){
[Link]('Hello');
}
addStudent(1, refreshStudentList); // Hello
28. Write a JavaScript function to get the function name.

function abc(){
[Link]([Link]);
}
abc(); // abc

JavaScript conditional statements and loops

1. Write a JavaScript program that accept two integers and display the larger.

let num1, num2;


num1 = prompt("Input the first integer", "0");
num2 = prompt("Input the second number", "0");
if(parseInt(num1, 10) > parseInt(num2, 10)){
[Link]("The larger between " + num1 + " and " + num2 + " is " + num1 + ".");
} else if (parseInt(num2, 10) > parseInt(num1, 10)){
[Link]("The larger between " + num1 + " and " + num2 + " is " + num2 + ".");
} else {
[Link]("The values " + num1 + " and " + num2 + " are equal.");
}
2. Write a JavaScript conditional statement to find the sign of product of three numbers. Display an
alert box with the specified sign.

Sample numbers : 3, -7, 2

Output : The sign is -

let x = 3, y = -7, z = 2;
if(x > 0 && y > 0 && z > 0){
alert("The sign is +");
} else if (x < 0 && y < 0 && z < 0){
alert("The sign is +");
} else if (x > 0 && y < 0 && z < 0){
alert("The sign is +");
} else if (x < 0 && y > 0 && z < 0){
alert("The sign is +");
} else {
alert("the sign is -");
}
3. Write a JavaScript conditional statement to sort three numbers. Display an alert box to show the
result.

Sample numbers : 3, -7, 2

Output : 3, 2, -7

let x = 3, y = -7, z = 2;
if(x > y && x > z){
if(y > z){
[Link](`${x}, ${y}, ${z}`);
} else {
[Link](`${x}, ${z}, ${y}`);
}
} else if(y > x && y > z){
if(x > z){
[Link](`${y}, ${x}, ${z}`);
} else {
[Link](`${y}, ${z}, ${x}`);
}
} else if(z > x && z > y){
if(x > y){
[Link](`${z}, ${x}, ${y}`);
} else {
[Link](`${z}, ${y}, ${x}`);
}
}
// 3, 2, -7
4. Write a JavaScript conditional statement to find the largest of five numbers. Display an alert box
to show the result.

Sample numbers : -5, -2, -6, 0, -1

Output : 0

let a = -5, b = -2, c = -6, d = 0, e = -1;


if(a > b && a > c && a > d && a > e) [Link](a);
else if(b > a && b > c && b > d && b > e) [Link](b);
else if(c > a && c > b && c > d && c > e) [Link](c)
else if(d > a && d > b && d > c && d > e) [Link](d);
else [Link](e); // 0
5. Write a JavaScript for loop that will iterate from 0 to 15. For each iteration, it will check if the
current number is odd or even, and display a message to the screen.

Sample Output :

"0 is even"

"1 is odd"

"2 is even"

----------

----------

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


if(i === 0) [Link](i + " is even");
else if(i % 2 === 0) [Link](i + " is even");
else [Link](i + " is odd");
}
6. Write a JavaScript program which compute, the average marks of the following students Then,
this average is used to determine the corresponding grade.

Student Name Marks


David 80
Vinoth 77
Divya 88
Ishitha 95
Thomas 68

The grades are computed as follows :

Range Grade
<60 F
<70 D
<80 C
<90 B
<100 A

let students = [['David', 80], ['Vinoth', 77], ['Divya', 88], ['Ishitha', 95], ['Thomas',
68]];
let avgMarks = 0;
let average = 0;
for(let i = 0; i < [Link]; i++){
avgMarks += students[i][1];
average = (avgMarks / [Link]);
}
[Link]("Average grade: " + average);
if(average < 60) [Link]("Grade: F");
else if(average < 70) [Link]("Grade: D");
else if(average < 80) [Link]("Grade: C");
else if(average < 90) [Link]("Grade: B");
else if(average < 100) [Link]("Grade: A");
// Average grade: 81.6
// Grade : B
7. Write a JavaScript program which iterates the integers from 1 to 100. But for multiples of three
print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are
multiples of both three and five print "FizzBuzz".

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


if(i % 3 === 0 && i % 5 === 0) [Link](i + " FizzBuzz");
else if(i % 3 === 0) [Link](i + " Fizz");
else if(i % 5 === 0) [Link](i + " Buzz");
else [Link](i);
}

/*
1
2
3 Fizz
4
5 Buzz
6 Fizz
7
8
9 Fizz
10 Buzz
-----
*/
8. According to Wikipedia a happy number is defined by the following process :

"Starting with any positive integer, replace the number by the sum of the squares of its digits, and
repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle
which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while
those that do not end in 1 are unhappy numbers (or sad numbers)".

Write a JavaScript program to find and print the first 5 happy numbers.
function happyNumber(num){
let numArr = [];
let i = 1;
while([Link] !== num){
let checkNum = digitSqSum(i);
if(checkNum === 1){
[Link](i);
}
i++;
}

function digitSqSum(n){
let sqSum = 0;
while(n){
let rem = n % 10;
sqSum += [Link](rem, 2);
n = [Link](n / 10);
}
if(sqSum < 10){
return sqSum;
} else {
return digitSqSum(sqSum);
}
}
return numArr;
}
[Link](happyNumber(5)); // [1, 7, 10, 13, 19]
9. Write a JavaScript program to find the armstrong numbers of 3 digits.

Note : An Armstrong number of three digits is an integer such that the sum of the cubes of its
digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 +
1**3 = 371.
function threeDigitArmstrong(){
let sum;
let armstrongArray = [];
for(let i = 100; i < 1000; i++){
sum = 0;
let temp = i;
while(temp > 0){
let rem = temp % 10;
sum = sum + [Link](rem, 3);
temp = [Link](temp / 10);
}
if(i === sum){
[Link](i);
}
}
return armstrongArray;
}
[Link](threeDigitArmstrong()); // [153, 370, 371, 407]

**************************************************************************8
function threeDigitArmstrong(){
for(let i = 1; i < 10; ++i){
for(let j = 0; j < 10; ++j){
for(let k = 0; k < 10; ++k){
let pow = ([Link](i, 3) + [Link](j, 3) + [Link](k, 3));
let plus = (i * 100 + j * 10 + k);
if(pow == plus){
[Link](pow);
}
}
}
}
}
threeDigitArmstrong(); // [153, 370, 371, 407]

10. Write a JavaScript program to construct the following pattern, using a nested for loop.

*
* *
* * *
* * * *
* * * * *

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


let temp = "";
for(let j = 1; j <= i; j++){
temp += "* ";
}
[Link](temp);
}
11. Write a JavaScript program to compute the greatest common divisor (GCD) of two positive
integers.
Also, for finding the HCF of two numbers, we can also proceed by long division method. We divide the larger
number by the smaller number (divisor). Now, we divide the divisor by the remainder obtained in the previous
stage. We repeat the same procedure until we get zero as the remainder. At that stage, the last divisor would be
the required HCF.

For example, we find the HCF of 30 and 42.

let a = 42; // first number


let b = 30; // second number
var gcd;
while(a != b){
if(a > b) a = a - b;
else b = b - a;
}
gcd = a;
[Link](gcd); // 6
12. Write a JavaScript program to sum the multiples of 3 and 5 under 1000.

let sum = 0;
for(let i = 1; i < 1000; i++){
if(i % 3 === 0 || i % 5 === 0){
sum += i;
}
}
[Link](sum); // 233168

JavaScript array

1. Write a JavaScript function to check whether an `input` is an array or not.

Test Data :

[Link](is_array('w3resource'));

[Link](is_array([1, 2, 4, 0]));

false

true

let isArray = function(input){


if([Link](input) === "[object Array]") return true;
return false;
}
[Link](isArray('text')); // false
[Link](isArray([1, 2, 4, 0])); // true

Note:

let isArray = function(input){


return [Link](input);
}
[Link](isArray('text')); // [object String]
[Link](isArray([1, 2, 4, 0])); // [object Array]
[Link](isArray(3435)); // [object Number]
2. Write a JavaScript function to clone an array.

Test Data :

[Link](array_Clone([1, 2, 4, 0]));

[Link](array_Clone([1, 2, [4, 0]]));

[1, 2, 4, 0]

[1, 2, [4, 0]]

function arrayClone(arr){
return [Link](0);
}
[Link](arrayClone([1, 2, 4, 0])); // [1,2,4,0]
[Link](arrayClone([1, 2, [4, 0]])); // [1, 2, Array(2)]

3. Write a JavaScript function to get the first element of an array. Passing a parameter 'n' will
return the first 'n' elements of the array.

Test Data :

[Link](first([7, 9, 0, -2]));

[Link](first([],3));

[Link](first([7, 9, 0, -2],3));

[Link](first([7, 9, 0, -2],6));

[Link](first([7, 9, 0, -2],-3));

Expected Output :

[]

[7, 9, 0]

[7, 9, 0, -2]

[]

function first(arr, n){


if(arr == null) return void 0;
if(n == null) return arr[0];
if(n < 0) return [];
return [Link](0, n);
}
[Link](first([7, 9, 0, -2])); // 7
[Link](first([], 3)); // []
[Link](first([7, 9, 0, -2], 3)); // [7, 9, 0]
[Link](first([7, 9, 0, -2], 6)); // [7, 9, 0, -2]
[Link](first([7, 9, 0, -2], -3)); // []

4. Write a JavaScript function to get the last element of an array. Passing a parameter 'n' will return
the last 'n' elements of the array.

Test Data :

[Link](last([7, 9, 0, -2]));

[Link](last([7, 9, 0, -2],3));

[Link](last([7, 9, 0, -2],6));
Expected Output :

-2

[9, 0, -2]

[7, 9, 0, -2]

function last(arr, n){


if(arr == null) return void 0;
if(n == null) return arr[[Link] - 1];
if(n < 0) return [];
return [Link](-n);
}
[Link](last([7, 9, 0, -2])); // -2
[Link](last([7, 9, 0, -2], 3)); // [9, 0, -2]
[Link](last([7, 9, 0, -2], 6)); // [7, 9, 0, -2]

5. Write a simple JavaScript program to join all elements of the following array into a string.

Sample array : myColor = ["Red", "Green", "White", "Black"];

Expected Output :

"Red,Green,White,Black"

"Red+Green+White+Black"

let myColor = ["Red", "Green", "White", "Black"];


[Link]([Link]()); // Red,Green,White,Black
[Link]([Link]("+")); // Red+Green+White+Black
6. Write a JavaScript program which accept a number as input and insert dashes (-) between each
two even numbers. For example if you accept 025468 the output should be 0-254-6-8.

const num = [Link]();


const str = [Link]();
const result = [str[0]];
for(let x = 1; x < [Link]; x++){
if((str[x - 1] % 2 === 0) && (str[x] % 2 === 0)){
[Link]('-', str[x]);
} else {
[Link](str[x]);
}
}
[Link]([Link]("")); // 0-254-6-8
7. Write a JavaScript program to sort the items of an array.

Sample array : var arr1 = [ 3, 8, 7, 6, 5, -4, 3, 2, 1 ];

Sample Output : -4,-3,1,2,3,5,6,7,8

const arr1=[-3,8,7,6,5,-4,3,2,1];
const arr2=[];
let min=arr1[0];
let pos;
var max=arr1[0];
for (i=0; i<[Link]; i++){
if (max<arr1[i]) max=arr1[i];
}

for (var i=0;i<[Link];i++){


for (let j=0;j<[Link];j++){
if (arr1[j]!="x"){
if (min>arr1[j]) {
min=arr1[j];
pos=j;
}
}
}
arr2[i]=min;
arr1[pos]="x";
min=max;
}
[Link](arr2); // [-4, -3, 1, 2, 3, 5, 6, 7, 8]
8. Write a JavaScript program to find the most frequent item of an array.

Sample array : var arr1=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];

Sample Output : a ( 5 times )

9. Write a JavaScript program which accept a string as input and swap the case of each character.
For example if you input 'The Quick Brown Fox' the output should be 'tHE qUICK bROWN fOX'.

let str = 'c';


let upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let lower = "abcdefghijklmnopqrstuvwxyz";
var result = [];
for(let x = 0; x < [Link]; x++){
if([Link](str[x]) !== -1){
[Link](str[x].toLowerCase());
} else if([Link](str[x]) !== -1){
[Link](str[x].toUpperCase());
} else {
[Link](str[x]);
}
}
[Link]([Link]("")); // C

10. Write a JavaScript program which prints the elements of the following array.

Note : Use nested for loops.

Sample array : var a = [[1, 2, 1, 24], [8, 11, 9, 4], [7, 0, 7, 27], [7, 4, 28, 14], [3, 10, 26, 7]];

Sample Output :

"row 0"

" 1"

" 2"

" 1"

" 24"

"row 1"

------

------

// a sample 2-D array


let a = [[1, 2, 1, 24], [8, 11, 9, 4], [7, 0, 7, 27], [7, 4, 28, 14], [3, 10, 26, 7]];
for(let i = 0; i < [Link]; i++){
[Link]("row " + i);
for(let j = 0; j < a[j].length; j++){
[Link](" " + a[i][j]);
}
}

Alternative method:

var a = [[1, 2, 1, 24], [8, 11, 9, 4], [7, 0, 7, 27], [7, 4, 28, 14], [3, 10, 26, 7]];
for(let i in a){
[Link]("row " + i);
for(let j in a[i]){
[Link](" " + a[i][j]);
}
}
11. Write a JavaScript program to find the sum of squares of a numeric vector.

function sumSquare(arr){
let sum = 0;
for(let i = 0; i < [Link]; i++){
sum += [Link](arr[i], 2);
}
return sum;
}
[Link](sumSquare([0, 1, 2, 3, 4])); // 30
12. Write a JavaScript program to compute the sum and product of an array of integers.

let array = [1, 2, 3, 4, 5, 6];


let sumArr = 0;
let productArr = 1;
for(let i = 0; i < [Link]; i++){
sumArr += array[i];
productArr *= array[i];
}
[Link](`Sum of an array integers: ${sumArr} and Product of an array integers: $
{productArr}`);
// Sum of an array integers: 21 and Product of an array integers: 720
13. Write a JavaScript program to add items in an blank array and display the items.

<input type = "text" id = "text1">


<input type = "button" id = "button1" value = "Add" onclick = "addElementToArray()">
<input type = "button" id = "button2" value = "Display" onclick = "displayArray()">
<div id = "Result"></div>

let x = 0;
let array = Array();
function addElementToArray(){
array[x] = [Link]("text1").value;
alert("Element: " + array[x] + " Added at index " + x);
x++;
[Link]("text1").value = "";
}

function displayArray(){
let e = "";
for(let i = 0; i < [Link]; i++){
e += "Element " + i + " = " + array[i] + "<br/>";
}
[Link]("Result").innerHTML = e;
}
14. Write a JavaScript program to remove duplicate items from an array (ignore case sensitivity).

function removeDuplicate(num){
let x;
let len = [Link];
let out = [];
let obj = {};
for(x = 0; x < len; x++){
obj[num[x]] = 0;
}
for(x in obj){
[Link](x);
}
return out;
}
let myNum = [1, 2, 2, 4, 5, 4, 7, 8, 7, 3, 6];
result = removeDuplicate(myNum);
[Link](myNum); // [1, 2, 2, 4, 5, 4, 7, 8, 7, 3, 6]
[Link](result); // ["1", "2", "3", "4", "5", "6", "7", "8"]

*****************************************************************
function removeDuplicate(orgArr){
let arr = [];
for(let i = 0; i < [Link]; i++){
arr[i] = orgArr[i];
}

let temp = 0;
for(let i = 0; i < [Link]; i++){
temp = arr[i];
for(let j = i + 1; j < [Link]; j++){
if(temp === arr[j]){
[Link](j, 1);
}
}
}
return [Link]((a, b) => a - b);
}

let myNum = [1, 2, 2, 4, 5, 4, 7, 8, 7, 3, 6];


result = removeDuplicate(myNum);
[Link](myNum); // [1, 2, 2, 4, 5, 4, 7, 8, 7, 3, 6]
[Link](result); // [1, 2, 3, 4, 5, 6, 7, 8]

15. We have the following arrays :

color = ["Blue ", "Green", "Red", "Orange", "Violet", "Indigo", "Yellow "];

o = ["th","st","nd","rd"]

Write a JavaScript program to display the colors in the following way :

"1st choice is Blue ."

"2nd choice is Green."

"3rd choice is Red."

-------------

Note : Use ordinal numbers to tell their position.

let color = ["Blue", "Green", "Red", "Orange", "Violet", "Indigo", "Yellow"];


function Ordinal(n){
var o = ["th", "st", "nd", "rd"];
x = n % 100;
return x + (o[(x - 20) % 10] || o[x] || o[0]);
}

for(n = 0; n < [Link]; n++){


let ordinal = n + 1;
let output = (Ordinal(ordinal) + " choice is " + color[n] + ".");
[Link](output);
}
16. Find the leap years in a given range of years.

function leapYearRange(lowRange, upRange){


let yearRange = [];
for(let i = lowRange; i <= upRange; i++){
[Link](i);
}
let leapYearArr = [];
[Link](functio
n(year){
if(leapYear(year)){
[Link](year);
}
});
return leapYearArr;
}

function leapYear(year){
if((year % 4 === 0 && year % 100 !== 0) || (year % 100 === 0 && year % 400 === 0)) return
true;
else return false;
}

[Link](leapYearRange(2000, 2012)); // [2000, 2004, 2008, 2012]


17. Write a JavaScript program to shuffle an array.

function shuffle(arr){
let ctr = [Link], temp, index;
// while there are elements in the array
while(ctr > 0){
// Pick a random index
index = [Link]([Link]() * ctr);
// Decrease ctr by 1
ctr--;
// And swap the last element with it
temp = arr[ctr];
arr[ctr] = arr[index];
arr[index] = temp;
}
return arr;
}
let myArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
[Link](shuffle(myArr)); // [4, 6, 1, 2, 8, 5, 9, 0, 3, 7]
18. Write a JavaScript program to perform a binary search.

Note : A binary search or half-interval search algorithm finds the position of a specified input value
within an array sorted by key value.

Sample array :
var items = [1, 2, 3, 4, 5, 7, 8, 9];
Expected Output :
[Link](binary_Search(items, 1)); //0
[Link](binary_Search(items, 5)); //4

function binarySearch(items, value){


let firstIndex = 0,
lastIndex = [Link] - 1;
middleIndex = [Link]((lastIndex + firstIndex) / 2);
while(items[middleIndex] != value && firstIndex < lastIndex){
if(value < items[middleIndex]){
lastIndex = middleIndex - 1;
} else if(value > items[middleIndex]){
firstIndex = middleIndex + 1;
}
middleIndex = [Link]((lastIndex + firstIndex) / 2);
}
return (items[middleIndex] != value) ? -1 : middleIndex;
}
let items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
[Link](binarySearch(items, 1)); // 0
[Link](binarySearch(items, 5)); // 4
19. There are two arrays with individual values, write a JavaScript program to compute the sum of
each individual index value from the given arrays.

Sample array :
array1 = [1,0,2,3,4];
array2 = [3,5,6,7,8,13];
Expected Output :
[4, 5, 8, 10, 12, 13]

function ArraysSum(arr1, arr2){


let result = [];
let ctr = 0;
if([Link] === 0) return "arr1 is empty";
if([Link] === 0) return "arr2 is empty";

while(ctr < [Link] && ctr < [Link]){


[Link](arr1[ctr] + arr2[ctr]);
ctr++;
}
if(ctr === [Link]){
for(let i = ctr; i < [Link]; i++){
[Link](arr2[i]);
}
} else {
for(let i = ctr; i < [Link]; i++){
[Link](arr1[i]);
}
}
return result;
}
[Link](ArraysSum([1, 0, 2, 3, 4], [3, 5, 6, 7, 8, 13]));
// [4, 5, 8, 10, 12, 13]

*********************************************************************

function ArraysSum(arr1, arr2){


let a = [Link];
let b = [Link];
let tempArr = [];
if(a !== b){
let diff = [Link](a - b);
if(a > b){
for(let i = 0; i < diff; i++){
[Link](b + i, 0, 0);
}
} else {
for(let i = 0; i < diff; i++){
[Link](b + i, 0, 0);
}
}
}
for(let i = 0; i < [Link]; i++){
[Link](arr1[i] + arr2[i]);
}
return tempArr;
}
[Link](ArraysSum([1, 0, 2, 3, 4], [3, 5, 6, 7, 8, 13]));
20. Write a JavaScript program to find duplicate values in a JavaScript array.

function find_duplicate_in_array(arra1) {
const object = {};
const result = [];

[Link](item => {
if(!object[item])
object[item] = 0;
object[item] += 1;
})

for (const prop in object) {


if(object[prop] >= 2) {
[Link](prop);
}
}
return result;
}
[Link](find_duplicate_in_array([1, 2, -2, 4, 5, 4, 7, 8, 7, 7, 71, 3, 6])); // ["4", "7"]
21. Write a JavaScript program to flatten a nested (any depth) array. If you pass shallow, the array
will only be flattened a single level.

Sample Data :
[Link](flatten([1, [2], [3, [[4]]],[5,6]]));
[1, 2, 3, 4, 5, 6]
[Link](flatten([1, [2], [3, [[4]]],[5,6]], true));
[1, 2, 3, [[4]], 5, 6]

let flatten = function(a, shallow, r){


if(!r){r = []}

if(shallow){
return [Link](r, a);
}
for(let i = 0; i < [Link]; i++){
if(a[i].constructor == Array){
flatten(a[i], shallow, r);
} else {
[Link](a[i]);
}
}
return r;
}
[Link](flatten([1, [2], [3, [[4]]], [5, 6]])); // [1,2,3,4,5,6]
[Link](flatten([1, [2], [3, [[4]]], [5, 6]], true)); // [1,2,3,[[4]],5,6]
22. Write a JavaScript program to compute the union of two arrays.

Sample Data :
[Link](union([1, 2, 3], [100, 2, 1, 10]));
[1, 2, 3, 10, 100]

JavaScript | hasOwnProperty() Method

The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its
own property. This is useful for checking if the object has inherited the property rather than being it’s own.

Syntax: [Link]( prop )

Parameters: This method accepts single parameter prop which holds the name in the form of a String or a
Symbol of the property to test.

Return Value: It returns a boolean value indicating whether the object has the given property as its own
property.

function union(arr1, arr2){


if((arr1 == null) || (arr2 == null)){
return void 0;
}
const obj = {};
for(let i = [Link] - 1; i >= 0; --i){
obj[arr1[i]] = arr1[i];
}
for(let i = [Link] - 1; i >= 0; --i){
obj[arr2[i]] = arr2[i];
}
const res = [];
for(const n in obj){
if([Link](n)){
[Link](obj[n]);
}
}
return res;
}
[Link](union([1, 2, 3], [100, 2, 1, 10])); // [1, 2, 3, 10, 100]
23. Write a JavaScript function to find the difference of two arrays.

Test Data :
[Link](difference([1, 2, 3], [100, 2, 1, 10]));
["3", "10", "100"]
[Link](difference([1, 2, 3, 4, 5], [1, [2], [3, [[4]]],[5,6]]));
["6"]
[Link](difference([1, 2, 3], [100, 2, 1, 10]));
["3", "10", "100"]

function differenceOf2Arrays(arr1, arr2){


const temp = [];
arr1 = [Link]().split(",").map(Number);
arr2 = [Link]().split(",").map(Number);
for(let i in arr1){
if(![Link](arr1[i])){
[Link](arr1[i]);
}
}
for(let i in arr2){
if(![Link](arr2[i])){
[Link](arr2[i]);
}
}
return [Link]((a, b) => a - b);
}
[Link](differenceOf2Arrays([1, 2, 3], [100, 2, 1, 10])); // [3, 10, 100]
[Link](differenceOf2Arrays([1, 2, 3, 4, 5], [1, [2], [3, [[4]]], [5, 6]])); // [6]
24. Write a JavaScript function to remove. 'null', '0', '""', 'false', 'undefined' and 'NaN' values from
an array.

Sample array : [NaN, 0, 15, false, -22, '',undefined, 47, null]


Expected result : [15, -22, 47]

function filterArray(testArray){
let index = -1;
const arrLength = testArray ? [Link] : 0;
let resIndex = -1;
const result = [];

while(++index < arrLength){


const value = testArray[index];
if(value){
result[++resIndex] = value;
}
}
return result;
}
[Link](filterArray([NaN, 0, 15, false, -22, '', undefined, 47, null])); // [15, -22, 47]
25. Write a JavaScript function to sort the following array of objects by title value.

Sample object :
var library = [
{ author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254},
{ author: 'Steve Jobs', title: 'Walter Isaacson', libraryID: 4264},
{ author: 'Suzanne Collins', title: 'Mockingjay: The Final Book of The Hunger Games', libraryID:
3245}
];

const library = [
{author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254},
{author: 'Steve Jobs', title: 'Walter Isaacson', libraryID: 4264},
{author: 'Suzanne Collins', title: 'Mockingjay: The Final Book of the Hunger Games',
libraryID: 3245}
];

function compareToSort(x, y){


if([Link] < [Link]) return -1;
if([Link] > [Link]) return 1;
return 0;
}

[Link]([Link](compareToSort));
Expected result :

[[object Object] {
author: "Suzanne Collins",
libraryID: 3245,
title:"Mockingjay:The Final Book of The Hunger Games"
}, [object Object] {
author: "Bill Gates",
libraryID: 1254,
title: "The Road Ahead"
}, [object Object] {
author: "Steve Jobs",
libraryID: 4264,
title: "Walter Isaacson"
}]

26. Write a JavaScript program to find a pair of elements (indices of the two numbers) from an
given array whose sum equals a specific target number.

Input: numbers= [10,20,10,40,50,60,70], target=50


Output: 2, 3

function twoSum(arr, num){


const map = [];
const indexnum = [];

for(let x = 0; x < [Link]; x++){


if(map[arr[x]] != null){
let index = map[arr[x]];
indexnum[0] = index;
indexnum[1] = x;
break;
} else {
map[num - arr[x]] = x;
}
}
return indexnum;
}
[Link](twoSum([10, 20, 10, 40, 50, 60, 70], 50)); // [2, 3]

***********************************************
function twoSum(arr, num){
let indices = [];
for(let i = 0; i < [Link] - 1; i++){
if(arr[i] + arr[i + 1] === num){
[Link](i, i + 1);
}
}
return indices;
}
[Link](twoSum([10, 20, 10, 40, 50, 60, 70], 50));

27. Write a JavaScript function to retrieve the value of a given property from all elements in an
array.

Sample array : [NaN, 0, 15, false, -22, '',undefined, 47, null]


Expected result : [15, -22, 47]

function filterArray(testArr){
let index = -1, resIndex = -1, result = [];
let arrLength = testArr ? [Link] : 0;
while(++index < arrLength){
let value = testArr[index];
if(value){
result[++resIndex] = value;
}
}
return result;
}
[Link](filterArray([NaN, 0, 15, false, -22, '', undefined, 47, null])); // [15, -22, 47]
28. Write a JavaScript function to find the longest common starting substring in a set of strings.

Sample array : [Link](longest_common_starting_substring(['go', 'google']));


Expected result : "go"

function longestCommonStartingSubstring(arr1){
const arr = [Link]().sort();
const a1 = arr[0];
const a2 = arr[[Link] - 1];
const L = [Link];
let i = 0;
while(i < L && [Link](i) === [Link](i)){
i++;
}
return [Link](0, i);
}
[Link](longestCommonStartingSubstring(['go', 'google'])); // go
[Link](longestCommonStartingSubstring(['SQLInjection', 'SQLTutorial'])); // SQL
[Link](longestCommonStartingSubstring(['abcd', '1234']));
29. Write a JavaScript function to fill an array with values (numeric, string with one character) on
supplied bounds.

Test Data :
[Link](num_string_range('a', "z", 2));
["a", "c", "e", "g", "i", "k", "m", "o", "q", "s", "u", "w", "y"]

function numStringRange(start, end, step){


let range = [];
if((step === 0) || (typeof start == "undefined" || typeof end == "undefined") || (typeof
start != typeof end)){
return false;
}

if(end < start){


step = -step;
}
if(typeof start == "number"){
while(step > 0 ? end >= start : end <= start){
[Link](start);
start += step;
}
} else if(typeof start == "string"){
if([Link] != 1 || [Link] != 1){
throw TypeError("Strings with one character are supported.");
}
start = [Link](0);
end = [Link](0);

while(step > 0 ? end >= start : end <= start){


[Link]([Link](start));
start += step;
}
} else {
throw TypeError("Only string and number are supported");
}
return range;
}

[Link](numStringRange('a', 'z', 2)); // ["a", "c", "e", "g", "i", "k", "m", "o", "q",
"s", "u", "w", "y"]
[Link](numStringRange('Z', 'A', 2)); // ["Z", "X", "V", "T", "R", "P", "N", "L", "J",
"H", "F", "D", "B"]
[Link](numStringRange(0, -5, 1)); // ["Z", "X", "V", "T", "R", "P", "N", "L", "J", "H",
"F", "D", "B"]
[Link](numStringRange(0, 25, 5)); // ["Z", "X", "V", "T", "R", "P", "N", "L", "J", "H",
"F", "D", "B"]
[Link](numStringRange(20, 5, 5)); // ["Z", "X", "V", "T", "R", "P", "N", "L", "J", "H",
"F", "D", "B"]
30. Write a JavaScript function to merge two arrays and removes all duplicates elements.

Test data :
var array1 = [1, 2, 3];
var array2 = [2, 30, 1];
[Link](merge_array(array1, array2));
[3, 2, 30, 1]

function mergeArray(arr1, arr2){


let resultArr = [];
let arr = [Link](arr2);
let len = [Link];
let assoc = {};

while(len--){
let item = arr[len];
if(!assoc[item]){
[Link](item);
assoc[item] = true;
}
}
return resultArr;
}

let array1 = [1, 2, 3];


let array2 = [2, 30, 1];
[Link](mergeArray(array1, array2)); // [3, 2, 30, 1]
************************************************************************************************

function mergeArray(arr1, arr2){


let tempArr = [];
tempArr = arr1;
for(let i = 0; i < [Link]; i++){
[Link](arr2[i]);
}

let uq = [];
for(let i = 0; i < [Link]; i++){
if(![Link](tempArr[i])){
[Link](tempArr[i]);
}
}
return uq;
}

let array1 = [1, 2, 3];


let array2 = [2, 30, 1];
[Link](mergeArray(array1, array2)); // [1, 2, 3, 30]
31. Write a JavaScript function to remove a specific element from an array.

Test data :
[Link](remove_array_element([2, 5, 9, 6], 5));
[2, 9, 6]

function removeArrayElement(arr, num){


/* removes only the first matching value
let index = [Link](num);
if(index > -1){
[Link](index, 1);
}
return arr;
*/
return [Link]((value) => value !== num);
}
[Link](removeArrayElement([2, 5, 9, 6, 5, 5], 5)); // [2, 9, 6]
32. Write a JavaScript function to find an array contains a specific element.

Test data :
arr = [2, 5, 9, 6];
[Link](contains(arr, 5));
[True]

function Contains(arr, element){


for(let i = 0; i < [Link]; i++){
if(arr[i] === element){
return true;
}
}
return false;
}
[Link](Contains([2, 5, 9, 6], 5)); // true
33. Write a JavaScript script to empty an array keeping the original.

let arr = [1, 3, 6, 3, -5];


[Link](arr); // [1, 3, 6, 3, -5]
[Link] = 0;
[Link](arr); // []
34. Write a JavaScript function to get nth largest element from an unsorted array.

Test Data :
[Link](nthlargest([ 43, 56, 23, 89, 88, 90, 99, 652], 4));
89

function nthlargest(arra,highest){
var x = 0, y = 0, z = 0, temp = 0, tnum = [Link], flag = false, result = false;

while(x < tnum){


y = x + 1;
if(y < tnum){
for(z = y; z < tnum; z++){
if(arra[x] < arra[z]){
temp = arra[z];
arra[z] = arra[x];
arra[x] = temp;
flag = true;
} else continue;
}
}

if(flag){
flag = false;
} else {
x++;
if(x === highest) result = true;
}
if(result) break;
}
return (arra[(highest - 1)]);
}

[Link](nthlargest([ 43, 56, 23, 89, 88, 90, 99, 652], 4));
**********************************************************************************

function nthLargest(arr, n){


let tempArr = BubbleSort(arr);
return tempArr[n];
}

function BubbleSort(arr){
for(let i = 0; i < [Link]; i++)
{
let flag = false;
for(let j = 0; j < [Link] - i; j++){
if(arr[j] > arr[j + 1]){
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = true;
}
}
if(!flag) break;
}
return arr;
}

[Link](nthLargest([43, 56, 23, 89, 88, 90, 99, 652], 4)); // 89

35. Write a JavaScript function to get a random item from an array.

function randomItem(items){
return items[[Link]([Link]() * [Link])];
}

let items = [254, 45, 212, 365, 2543];


[Link](randomItem(items));
36. Write a JavaScript function to create a specified number of elements with pre-filled numeric
value array.

Test Data :
[Link](array_filled(6, 0));
[0, 0, 0, 0, 0, 0]
[Link](array_filled(4, 11));
[11, 11, 11, 11]

function arrayFill(eleNum, prefillVal){


return Array(...Array(eleNum)).map([Link], prefillVal);
}

[Link](arrayFill(3, 0)); // [0,0,0,0,0,0]


[Link](arrayFill(4, 11)); // [11,11,11,11]
37. Write a JavaScript function to create a specified number of elements with pre-filled string value
array.

Test Data :

[Link](array_filled(3, 'default value'));

["default value", "default value", "default value"]

[Link](array_filled(4, 'password'));

["password", "password", "password", "password"]

function arrayFill(eleNum, prefillVal){


return [Link](null, Array(eleNum)).map([Link], prefillVal);
}

[Link](arrayFill(3, 'default value')); // ["default value","default value","default


value"]
[Link](arrayFill(4,'password')); // ["password","password","password","password"]

38. Write a JavaScript function to move an array element from one position to another.

Test Data :

[Link](move([10, 20, 30, 40, 50], 0, 2));

[20, 30, 10, 40, 50]

[Link](move([10, 20, 30, 40, 50], -1, -2));

[10, 20, 30, 50, 40]

39. Write a JavaScript function to filter false, null, 0 and blank values from an array.

Test Data :

[Link](filter_array_values([58, '', 'abcd', true, null, false, 0]));

[58, "abcd", true]

40. Write a JavaScript function to generate an array of specified length, filled with integer numbers,
increase by one from starting position.

Test Data :

[Link](array_range(1, 4));
[1, 2, 3, 4]

[Link](array_range(-6, 4));

[-6, -5, -4, -3]

41. Write a JavaScript function to generate an array between two integers of 1 step length.

Test Data :

[Link](rangeBetwee(4, 7));

[4, 5, 6, 7]

[Link](rangeBetwee(-4, 7));

[-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]

42. Write a JavaScript function to find the unique elements from two arrays.

Test Data :

[Link](difference([1, 2, 3], [100, 2, 1, 10]));

["1", "2", "3", "10", "100"]

[Link](difference([1, 2, 3, 4, 5], [1, [2], [3, [[4]]],[5,6]]));

["1", "2", "3", "4", "5", "6"]

[Link](difference([1, 2, 3], [100, 2, 1, 10]));

["1", "2", "3", "10", "100"]


Algorithms and Problem Solving Patterns

What is an Algorithm?

A process or set of steps to accomplish a certain task.

Why do I need to know this ?

Almost everything that you do in programming involves some kind of algorithm!

It’s the foundation for being a successful problem solving and developer

How to you improve?

1. Devise a plan for solving problems

2. Master common problem solving patterns

Problem Solving Strategies

1. Understand the Problem

 Can I restate the problem in my own words?

 What are the inputs that go into the problem?

 What are the outputs that should come from the solution to the problem?

 Can the outputs be determined from the inputs? In other words, do I have enough information to solve the
problem? (You may not be able to answer this question until you set about solving the problem. That’s okay;
it’s still worth considering the question at this early stage.)

 How should I label the important pieces of data that are a part of the problem?

Simple example: Write a function which takes two numbers and returns their num.

 “implement addition”

 - ints? floats? What about string for large numbers?

 - int? float? string?

2. Explore Concrete Examples

Coming up with examples can help you understand the problem better

Examples also provide sanity checks that your eventual solution works how it should

User Stories!

Unit Tests!

Steps to be taken for this point:

 Start with Simple Examples

 Progress to More Complex Examples

 Explore Examples with Empty Inputs

 Explore Examples with Invalid Inputs

3. Break It Down

Explicitly write out the steps you need to take – This forces you to think about the code you’ll write before you
write it, and helps you catch any lingering conceptual issues or misunderstandings before you dive in and have
to worry about details (e.g. language syntax) as well.

4. Solve/Simplify

Sovle the problem … if you can’t … solve a simpler problem!

Simplify

 Find the core difficulty in what you’re trying to do


 Temporarily ignore that difficulty

 Write a simplified solution

 Then incorporate that difficulty back in

5. Look Back and Refactor

Congrats on solving it, but you’re not done!

 Can you check the result?

 Can you derive the result differently?

 Can you understand it at a glance?

 Can you use the result or method for some other problem?

 Can you improve the performance of your solution?

 Can you think of other ways to refactor?

 How have other people solved this problem?

How Do You Improve?

1. Devise a plan for solving problems


2. Master common problem solving patterns

Problem Solving Patterns

Frequency Counters

This pattern uses objects or sets to collect values/frequencies of values

This can often avoid the need for nested loops or O(N^2) operations with arrays / strings

Example: Write a function called same, which accepts two arrays. The function should return true if every value
in the array has it’s corresponding value squared in the second array. The frequency of values must be the
same.

function same(arr1, arr2){


if([Link] !== [Link]){
return false;
}
for(let i = 0; i < [Link]; i++){
let correctIndex = [Link](arr1[i] ** 2);
if(correctIndex === -1){
return false;
}
[Link](correctIndex, 1);
}
return true;
}
[Link](same([5, 2, 4, 3, 1], [1, 4, 9, 16, 25])); // true

Refactored

function same(arr1, arr2){


if([Link] !== [Link]){
return false;
}
let frequencyCounter1 = {};
let frequencyCounter2 = {};
for(let val of arr1){
frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1;
}
for(let val of arr2){
frequencyCounter2[val] = (frequencyCounter2[val] || 0) + 1;
}
for(let key in frequencyCounter1){
if(!(key ** 2 in frequencyCounter2)){
return false;
}
if(frequencyCounter2[key ** 2] !== frequencyCounter1[key]){
return false;
}
}
return true;
}
[Link](same([1, 4, 3, 2, 5], [1, 4, 9, 16, 25])); // true

Anagrams

Given two strings, write a function to determine if the second string is an anagram of the first. An anagram is a
word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.

function validAnagram(first, second){


if([Link] !== [Link]){
return false;
}
const lookup = {};
for(let i = 0; i < [Link]; i++){
let letter = first[i];
//if letter exists, increment, otherwise set to 1
lookup[letter] ? lookup[letter] += 1 : lookup[letter] = 1;
}
[Link](lookup);
// {a: 3, n: 1, g: 1, r: 1, m: 1}
// {q: 1, u: 1, e: 2, r: 1}
for(let i = 0; i < [Link]; i++){
let letter = second[i];
// can't find letter or letter is zero then it's not an anagram
if(!lookup[letter]){
return false;
} else {
lookup[letter] -= 1;
}
}
return true;
}

[Link](validAnagram("anagram", "nagaram")); // true


[Link](validAnagram("queer", "queen")); // false
Multiple Pointers

Creating pointers or values that correspond to an index or position and move towards the beginning, end or
middle based on a certain condition

Very efficient for solving problems with minimal space complexity as well

An example:

Write a function called sumZero which accepts a sorted array of integers. The function should find the first pair
where the sum is 0. Return an array that includes both values that sum to zero or undefined if a pair does not
exist

function sumZero(arr){
for(let i = 0; i < [Link]; i++){
for(let j = i + 1; j < [Link]; j++){
if(arr[i] + arr[j] === 0){
return [arr[i], arr[j]];
}
}
}
}
[Link](sumZero([-4, -3, -2, -1, 0, 1, 2, 5])); // [-2, 2]
Refactored

function sumZero(arr){
let left = 0;
let right = [Link] - 1;
while(left < right){
let sum = arr[left] + arr[right];
if(sum === 0){
return [arr[left], arr[right]];
} else if(sum > 0){
right--;
} else {
left++;
}
}
}
[Link](sumZero([-4, -3, -2, -1, 0, 1, 2, 3, 10])); // [-3, 3]

countUniqueValues

Implement a function called countUniqueValues, which accepts a sorted array, and counts the unqiue values in
the array. There can be negative numbers in the array, but it will always be sorted.

function countUnqiueValues(arr){
var i = 0;
for(var j = 1; j < [Link]; j++){
if(arr[i] !== arr[j]){
i++;
arr[i] = arr[j];
}
}
return i + 1;
}
[Link](countUnqiueValues([1, 1, 1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 7])); // 7
DATA STRUCTURE AND ALGORITHM IN JS

Recursion

Tip: A process (a function in our case) that calls itself

Simple Example: Our first recursive function

function countDown(num){
if(num <= 0){
[Link]("All done!");
return;
}
[Link](num);
num--;
countDown(num);
}

countDown(5);

/*
5
4
3
2
1
All done!
*/

*************************************************************
Simple Example: Our second recursive function (Sum upto n)

function sumRange(num){
if(num === 1) return 1;
return num + sumRange(num - 1);
}
[Link](sumRange(4)); // 10

*************************************************************
Factorial Example using Recursion

function factorial(x){
if(x < 0) return 0;
if(x <= 1) return 1;
return x * factorial(x - 1);
}

[Link](factorial(5)); // 120

*************************************************************
// Collecting Odd Values

function collectOddsValues(arr){
let result = [];
function helper(helperInput){
if([Link] == 0){
return;
}
if(helperInput[0] % 2 !== 0){
[Link](helperInput[0])
}
helper([Link](1))
}
helper(arr);
return result;
}

[Link](collectOddsValues([1, 2, 3, 4, 5, 6, 7, 8, 9])); // // [1, 3, 5, 7, 9]

**********************************************************
// Previous problem using pure recursion

function collectOddsValues(arr){
let newArr = [];
if([Link] === 0){
return newArr;
}
if(arr[0] % 2 !== 0){
[Link](arr[0]);
}
newArr = [Link](collectOddsValues([Link](1)));
return newArr;
}

[Link](collectOddsValues([1, 2, 3, 4, 5, 6, 7, 8, 9])); // [1, 3, 5, 7, 9]

Power
function power(base, exponent){
if(exponent === 0) return 1;
return base * power(base, exponent - 1);
}

[Link](power(3, 3)); // 27

Factorial
function factorial(x){
if(x < 0) return 0;
if(x <= 1) return 1;
return x * factorial(x - 1);
}

[Link](factorial(5)); // 120

Product of Array
function productOfArray(arr){
if([Link] === 0){
return 1;
}
return arr[0] * productOfArray([Link](1));
}
[Link](productOfArray([2, 3, 4, 1]));

Fibonacci
function fib(n){
if(n <= 2) return 1;
return fib(n - 1) + fib(n - 2);
}
[Link](fib(10)); // 55

Reverse
function reverse(str){
if([Link] <= 1) return str;
return reverse([Link](1)) + str[0];
}
[Link](reverse("javascript")); // tpircsavaj

isPalindrome
function isPalindrome(str){
if([Link] === 1) return true;
if([Link] === 2) return str[0] === str[1];
if(str[0] === [Link](-1)) return isPalindrome([Link](1, -1));
return false;
}

[Link](isPalindrome("peep")); // true
[Link](isPalindrome("peer")); // false

capitalizeWords
function capitalizedWords(array){
if([Link] === 1){
return [array[0].toUpperCase()];
}
let res = capitalizedWords([Link](0, -1));
[Link]([Link]([Link] - 1)[0].toUpperCase());
return res;
}

[Link](capitalizedWords("JavaScript")); // ["J", "A", "V", "A", "S", "C", "R", "I", "P",
"T"]
[Link](capitalizedWords("This is cool")); // ["T", "H", "I", "S", " ", "I", "S", " ",
"C", "O", "O", "L"]

Searching

Linear Search – There are many different search methods on arrays in JavaScript: indexOf, includes,
find, findIndex

Pseudocode

- This function accepts an array and a value


- Loop through the array and check if the current array element is equal to the value
- If it is, return the index at which the element is found
- If the value is never found, return -1

function searchLinear(arr, val){


for(var i = 0; i < [Link]; i++){
if(arr[i] === val) return i;
}
return -1;
}
[Link](searchLinear([34, 56, 1, 76, 7, 9, 21], 1)); // 2 (Located at index = 2)
[Link](searchLinear([34, 56, 1, 76, 7, 9, 21], 77)); // -1 (Not found)

Binary Search

- Binary search is a much faster form of search


- Rather than eliminating one element at a time, you can eliminate half of the remaining elements at a time
- Binary search only works on sorted arrays!

Pseudocode

- This function accepts a sorted array and a value


- Create a left pointer at the start of the array, and a right pointer at the end of the array
- While the left pointer comes before the right pointer:
 Create a pointer in the middle
 If you find the value you want, return the index
 If the value is too small, move the left pointer up
 If the value is too large, move the right pointer down
- If you never find the value, return -1

function binarySearch(arr, elem){


arr = [Link]((a, b) => a - b);
[Link](`Sorted Array: ${arr}`);
var start = 0;
var end = [Link] - 1;
var middle = [Link]((start + end) / 2);
[Link](`start = ${start}, middle = ${middle}, end = ${end}`);
while(arr[middle] !== elem && start <= end){
if(elem < arr[middle]) end = middle - 1;
else start = middle + 1;
middle = [Link]((start + end) / 2);
}
if(arr[middle] == elem) return middle;
return -1;
// Or return arr[middle] === elem ? middle : -1;
}

[Link](binarySearch([9, 15, 6, 2, 13, 5, 30, 28], 15));


[Link](binarySearch([9, 15, 6, 2, 13, 5, 30, 28], 50));
/*
Sorted Array: 2,5,6,9,13,15,28,30
start = 0, middle = 3, end = 7
5
Sorted Array: 2,5,6,9,13,15,28,30
start = 0, middle = 3, end = 7
-1
*/
Naive String Search

- Suppose you want to count the number of times a smaller string appears in a longer string
- A straightforward approach involves checking pairs of characters individually

Pseudocode

- Loop over the longer string


- Loop over the shorter string
- If the characters don’t match, break out of the inner loop
- If the characters do match, keep going
- If you complete the inner loop and find a match, increment the count of matches
- Return the count

Practice Code:
function stringSearch(str, shortStr){
let tempStr = "";
let counter = 0, k = 0;
for(let i = 0; i < [Link]; i++){
k = i;
tempStr = "";
for(let j = 0; j < [Link]; j++){
if(str[k] !== shortStr[j]){
break;
} else {
tempStr += str[k];
str[k++];
}
}
if(tempStr === shortStr) counter++;
}
return counter;
}
[Link](stringSearch("wowomgzomg", "omg")); // 2

Tutor’s Code:

function naiveSearch(long, short){


let count = 0;
for(let i = 0; i < [Link]; i++){
for(let j = 0; j < [Link]; j++){
if(short[j] !== long[i + j]) break;
if(j === [Link] - 1) count++;
}
}
[Link](count);
}
naiveSearch("lorie loled", "lol"); // 1
naiveSearch("lorie loled", "lo"); // 2

Elementary Sorting Algorithms

What is sorting?

Sorting is the process of rearranging the items in a collection (e.g. an array) so that the items are in some kind
of order.

Examples:

- Sorting numbers from smallest to largest


- Sorting names alphabetically
- Sorting movies based on release year
- Sorting movies based on revenue

Why do we need to learn this?

- Sorting is an incredibly common task, so it’s good to know how it works


- There are many different ways to sort things, and different techniques have their own advantages and
disadvantages.

JS has a sort method

… but it doesn’t always work the way you expect.


[“Steele”, “Colt”, “Data Structures”, “Algorithms”].sort();
// [“Algorithms”, “Colt”, “Data Structures”, “Steele”]
[6, 4, 15, 10].sort();
// [10, 15, 4, 6]

// The default sort order is according to string Unicode code points.

Telling JS how to sort


- The built-in sort method accepts an optional comparator function
- You can use this comparator function to tell JavaScript how you want it to sort
- The comparator looks at pars of elements (a and b), determines their sort order based on the return value

 If it returns a negative number, a should come before b


 If it returns a positive number, a should come after b,
 If it returns 0, a and b are the same as far as the sort is concerned

function numberCompare(num1, num2){


return num1 - num2;
}
[Link]([6, 4, 15, 10].sort(numberCompare)); // [4, 6, 10, 15]

******************************************************************

function numberCompare(num1, num2){


return num2 - num1;
}
[Link]([6, 4, 15, 10].sort(numberCompare)); // [15, 10, 6, 4]

**************** Sorting as per the string length ****************

function compareByLen(str1, str2){


return [Link] - [Link];
}
[Link](["Steele", "Colt", "Data Structures", "Algorithms"].sort(compareByLen));
// ["Colt", "Steele", "Algorithms", "Data Structures"]
Bubble Sort

A sorting algorithm where the largest values bubble up to the top!

Before we sort, we must swap!

Many sorting algorithms involve some type of swapping functionality (e.g. swapping to numbers to put them in
order)

// Img here

BubbleSort Pseudocode

- Start looping from with a variable called i the end of the array towards the beginning
- Start an inner loop with a variable called j from the beginning until i – 1
- If arr[j] is greater than arr[j + 1], swap those two values!
- Return the sorted array

Implementation:

function bubbleSort(arr){
for(var i = [Link]; i > 0; i--){
for(var j = 0; j < i - 1; j++){
[Link](arr, arr[j], arr[j + 1]);
if(arr[j] > arr[j + 1]){
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
[Link](bubbleSort([37, 45, 29, 8]));
Optimized Code: (if no swap is occurring or the data is nearly sorted)

function bubbleSort(arr){
var noSwaps;
for(var i = [Link]; i > 0; i--){
noSwaps = true;
for(var j = 0; j < i - 1; j++){
[Link](arr, arr[j], arr[j + 1]);
if(arr[j] > arr[j + 1]){
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
noSwaps = false;
}
}
if(noSwaps) break;
}
return arr;
}
[Link](bubbleSort([8, 1, 2, 3, 4, 5, 6, 7]));

Selection Sort

Similar to bubble sort, but instead of first placing large values into sorted position, it places small values into
sorted position

- Store the first element as the smallest value you’ve seen so far.
- Compare this item to the next item in the array until you find a smaller number.
- If a smaller number is found, designate that smaller number to be the new “minimum” and continue until
the end of the array.
- If the ‘minimum’ is not the value (index) you initially began with, swap the two values.
- Repeat this with the next element until the array is sorted.

function selectionSort(arr){
for(i = 0; i <[Link]; i++){
var lowest = i;
for(var j = i + 1; j < [Link]; j++){
if(arr[j] < arr[lowest]){
lowest = j;
}
}
if(i !== lowest){
var temp = arr[i];
arr[i] = arr[lowest];
arr[lowest] = temp;
}
[Link](arr);
}
return arr;
}
[Link](selectionSort([0, 2, 34, 22, 10, 19, 17]));
ES2015:

function selectionSort(arr){
const swap = (arr, idx1, idx2) => ([arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]]);
for(let i = 0; i < [Link]; i++){
let lowest = i;
for(let j = i + 1; j < [Link]; j++){
if(arr[lowest] > arr[j]){
lowest = j;
}
}
if(i !== lowest) swap(arr, i, lowest);
}
return arr;
}
[Link](selectionSort([0, 2, 34, 22, 10, 19, 17]));

Insertion Sort

Builds up the sort by gradually creating a larger left half which is always sorted

Insertion Sort Pseudocode

- Start by picking the second element in the array


- Now compare the second element with the one before it and swap if necessary.
- Continue to the next element and if it is in the incorrect order, iterate through the sorted portion (i.e. the left
side) to place the element in the correct place.
- Repeat until the array is sorted.

function insertionSort(arr){
for(var i = 1; i < [Link]; i++){
var currentVal = arr[i];
for(var j = i - 1; j >= 0 && arr[j] > currentVal; j--){
arr[j + 1] = arr[j];
}
arr[j + 1] = currentVal;
[Link](arr);
}
return arr;
}
[Link](insertionSort([2, 1, 30, 9, 76, 4]));

Intermediate Sorting Algorithms


Why learn this?

- The sorting algorithms we’ve learned so far don’t scale well


- Try out bubble sort on an array of 100000 elements, it will take quite some time!

Faster Sorts

- There is a family of sorting algorithms that can improve time complexity from O(n 2) to O(nlogn)
- There’s a tradeoff between efficiency and simplicity
- The more efficient algorithms are much less simple, and generally take longer to understand

Merge Sort

- It’s a combination of two things – merging and sorting!


- Exploits the fact that arrays of 0 or 1 element are always sorted
- Works by decomposing an array into smaller arrays of 0 or 1 elements, then building up a newly sorted
array

Merging Arrays

- In order to implement merge sort, it’s useful to first implement a function responsible for merging two
sorted arrays

- Given two arrays which are sorted, this helper function should create a new array which is also sorted, and
consist of all of the elements in the two input arrays

- This function should run in O(n + m) time and O(n + m) space and should not modify the parameters passed
to it.

Merging Arrays Pseudocode

- Create an empty array, take a look at the smallest values in each input array

- While there are still values we havent’ looked at …

 If the value in the first array is smaller than the value in the second array, push the value in the first
array into our results and move on to the next value in the first array

 If the value in the first array is larger than the value in the second array, push the value in the
second array into our results and move on to the next value in the second array

 Once we exhaust one array, push in all remaining values from the other array

function merge(arr1, arr2){


let results = [];
let i = 0;
let j = 0;
while(i < [Link] && j < [Link]){
if(arr2[j] > arr1[i]){
[Link](arr1[i]);
i++;
} else {
[Link](arr2[j]);
j++;
}
}
while(i < [Link]){
[Link](arr1[i]);
i++;
}
while(j < [Link]){
[Link](arr2[j]);
j++;
}
return results;
}
[Link](merge([1, 10, 50], [2, 14, 99, 100]));
// [1, 2, 10, 14, 50, 99, 100]
[Link](merge([], [5, 8, 10]));
// [5, 8, 10]
mergeSort Pseudocode

- Break up the array into halves until you have arrays that are empty or have one element
- Once you have smaller sorted arrays, merge those arrays with other sorted arrys until you are back at the
full length of the array
- Once the array has been merged back together, return the merged (and sorted!) array

function merge(arr1, arr2){


let results = [];
let i = 0;
let j = 0;
while(i < [Link] && j < [Link]){
if(arr2[j] > arr1[i]){
[Link](arr1[i]);
i++;
} else {
[Link](arr2[j]);
j++;
}
}
while(i < [Link]){
[Link](arr1[i]);
i++;
}
while(j < [Link]){
[Link](arr2[j]);
j++;
}
return results;
}

function mergeSort(arr){
if([Link] <= 1) return arr;
let mid = [Link]([Link] / 2);
let left = mergeSort([Link](0, mid));
let right = mergeSort([Link](mid));
return merge(left, right);
}
[Link](mergeSort([10, 24, 76, 73, 72, 1, 9]));
// [1, 9, 10, 24, 72, 73, 76]
Quick Sort

Pivot Helper

- In order to implement merger sort, it’s useful to first implement a function responsible arranging elements in
an array on either side of a pivot
- Given an array, this helper function should designate an element as the pivot
- It should then rearrange elements in the array so that all values less than the pivot are moved to the left of
the pivot, and all values greater than the pivot are moved to the right of the pivot.
- The order of elements on either side of the pivot doesn’t matter!
- The helper should do this in place, that is, it should not create a new array
- When complete, the helper should return the index of the pivot.

Picking a pivot

- The runtime of quick sort depends in part on how one selects the pivot
- Ideally, the pivot should be chosen so that it’s roughly the median value in the data set you’re sorting
- For simplicity, we’ll always choose the pivot to be the first element

Pivot Pseudocode

- It wil help to accept three arguments: an array, a start index, and an end index (these can default to 0 and
the array length minus 1, respectively)

- Grab the pivot from the start of the array

- Store the current pivot index in a variable (this will keep track of where the pivot should end up)
- Loop through the array from the start until the end

 If the pivot is greater than the current element, increment the pivot index variable and then swap
the current element with the element at the pivot index

- Swap the starting element (i.e. the pivot) with the pivot index

- Return the pivot index

function pivot(arr, start = 0, end = [Link] - 1){


var pivot = arr[start];
var swapIdx = start; // it starts at 0
for(var i = start + 1; i < [Link]; i++){
if(pivot > arr[i]){
swapIdx++;
swap(arr, swapIdx, i);
}
}
swap(arr, start, swapIdx);
[Link](arr); // [3, 2, 1, 4, 5, 7, 6, 8]
return swapIdx;

function swap(array, i, j){


var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
[Link](pivot([4, 8, 2, 1, 5, 7, 6, 3])); // 3
/*

[4, 8, 2, 1, 5, 7, 6, 3]
[4, 2, 8, 1, 5, 7, 6, 3]
[4, 2, 1, 8, 5, 7, 6, 3]
[4, 2, 1, 3, 5, 7, 6, 8]
[3, 2, 1, 4, 5, 7, 6, 8]

*/

ES6 version:

function pivot(arr, start = 0, end = [Link] - 1){


const swap = (arr, idx1, idx2) =>{
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
};
// We are assuming the pivot is always the first element
let pivot = arr[start];
let swapIdx = start;

for(let i = start + 1; i <= end; i++){


if(pivot > arr[i]){
swapIdx++;
swap(arr, swapIdx, i);
}
}

// Swap the pivot from the start the swapPoint


swap(arr, start, swapIdx);
[Link](arr); // [3, 2, 1, 4, 5, 7, 6, 8]
return swapIdx;
}
[Link](pivot([4, 8, 2, 1, 5, 7, 6, 3])); // 3
Quicksort Pseudocode

- Call the pivot helper on the array


- When the helper returns to you the updated pivot index, recursively call the pivot helper on the subarray to
the left of that index, and the subarray to the right of that index
- Your base case occurs when you consider a subarray with less than 2 elements

function pivot(arr, start = 0, end = [Link] - 1){


var pivot = arr[start];
var swapIdx = start;
for(var i = start + 1; i < [Link]; i++){
if(pivot > arr[i]){
swapIdx++;
swap(arr, swapIdx, i);
}
}
swap(arr, start, swapIdx);
return swapIdx;

function swap(array, i, j){


var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}

function quickSort(arr, left = 0, right = [Link] - 1){


if(left < right){
let pivotIndex = pivot(arr, left, right);
// left
quickSort(arr, left, pivotIndex - 1);
// right
quickSort(arr, pivotIndex + 1, right);
}
return arr;
}
[Link](quickSort([100, -3, 2, 4, 6, 9, 1, 2, 5, 3, 23]));
// [-3, 1, 2, 2, 3, 4, 5, 6, 9, 23, 100]

Radix Sort

Radix sort is a special sorting algorithm that works on lists of numbers

It never makes comparisons between elements!

It exploits the fact that information about the size of a number is encoded in the number of digits.

More digits means a bigger number!

Radix Sort Helpers

In order to implement radix sort, it’s helpful to build a few helper functions first:

getDigit(num, place) - returns the digit in num at the given place value

Just for fun!

function returnPlaceNum(num, place){


let counter = -1;
let temp = num;
let rem;
while(counter !== place){
rem = temp % 10;
counter++;
temp = [Link](temp / 10);
}
return rem;
}
[Link](returnPlaceNum(28374, 3)); // 8
[Link](returnPlaceNum(28374, 0)); // 4
[Link](returnPlaceNum(28374, 5)); // 0
Shortcut code:

function getDigit(num, i){


return [Link]([Link](num) / [Link](10, i)) % 10;
}
[Link](getDigit(7323, 2)); // 3
[Link](getDigit(7323, 5)); // 0
// This code will work with negative number also (because of [Link]()).

digitCount(num) – returns the number of digits in num

Just for fun!

function digitCount(num){
if(num === 0) return 1;
return [Link](Math.log10([Link](num))) + 1;
}
[Link](digitCount(84)); // 2
[Link](digitCount(93847)); // 5

/*
> let temp = Math.log10(84);
undefined
> temp;
1.9242792860618816
> [Link](temp);
1
So, we add 1 finally and it becomes 2.
*/

mostDigits(nums) – Given an array of numbers, returns the number of digits in the largest numbers in the list

Just for fun!

function digitCount(num){
if(num === 0) return 1;
return [Link](Math.log10([Link](num))) + 1;
}

function mostDigits(arr){
let n = 0;
if(arr !== null){
for(let i = 0; i < [Link]; i++){
if(n < digitCount(arr[i])){
n = digitCount(arr[i]);
}
}
} else {
return "";
}
return n;
}
[Link](mostDigits([1, 1, 11111, 1])); // 5
Tutor’s code:

function digitCount(num){
if(num === 0) return 1;
return [Link](Math.log10([Link](num))) + 1;
}

function mostDigits(nums){
let maxDigits = 0;
for(let i = 0; i < [Link]; i++){
maxDigits = [Link](maxDigits, digitCount(nums[i]));
}
return maxDigits;
}
[Link](mostDigits([1, 1, 11111, 1])); // 5

Radix Sort Pseudocode

- Define a function that accepts list of numbers


- Figure out how many digits the largest number has
- Loop from k = 0 up to this largest number of digits
- For each iteration of the loop:
 Create buckets for each digit (0 to 9)
 Place each number in the correspoinding bucket based on its kth digit
- Replace our existing array with values in our buckets, starting with 0 and going up to 9
- Return list at the end!

function getDigit(num, i){


return [Link]([Link](num) / [Link](10, i)) % 10;
}

function digitCount(num){
if(num === 0) return 1;
return [Link](Math.log10([Link](num))) + 1;
}

function mostDigits(nums){
let maxDigits = 0;
for(let i = 0; i < [Link]; i++){
maxDigits = [Link](maxDigits, digitCount(nums[i]));
}
return maxDigits;
}
function radixSort(nums){
let maxDigitCount = mostDigits(nums);
for(let k = 0; k < maxDigitCount; k++){
let digitBuckets = [Link]({length: 10}, () => []); // creating 10 buckets or 10
empty arrays inside digitBuckets
for(let i = 0; i < [Link]; i++){
let digit = getDigit(nums[i], k);
digitBuckets[digit].push(nums[i]);
}
nums = [].concat(...digitBuckets);
}
return nums;
}

[Link](radixSort([23, 345, 5467, 12, 2345, 9852]));


// [12, 23, 345, 2345, 5467, 9852]
Data Structures

What do they do? Data structures are collections of values, the relationships among them, and the functions
or operations that can be applied to the data.

Why so many?? Different data structures excel at different things. Some are highly specialized, while others
(like arrays) are more generally used.

Why care? The more time you spend as a developer, the more likely you’ll need to use one of these data
structures. You’ve already worked with many of them unknowingly! (E.g. Tree used in DOM manipulation)

Note: They all excel in different situations. So no any particular data structures suits best in every situation.
Working with map/location data? Use a graph!
Need an ordered list with fast inserts/removals at the beginning and end? Use a linked list!
Web scraping nested HTML? Use a tree!
Need to write a scheduler? Use a binary heap!

Singly Linked Lists

What is a linked list? A data structure that contains a head, tail and length property. Linked lists consist of
nodes, and each node has a value and a pointer to another node or null (no indexing for random jump to any
particular element).

Comparisons with Arrays

Lists

- Do not have indexes!


- Connected via nodes with a next pointer
- Random access is not allowed

Arrays

- Indexed in order!
- Insertion and deletion can be expensive
- Can quickly be accessed at a specific index

Pushing – Adding a new node to the end of the Linked List!

Pseudocode

- This function should accept a value


- Create a new node using the value passed to the function
- If there is no head property on the list, set the head and tail to be the newly created node
- Otherwise set the next property on the tail to be the new node and set the tail property on the list to be the
newly created node
- Increment the length by one

- Return the linked list

// piece of data - val


// reference to next node - node
class Node{
constructor(val){
[Link] = val;
[Link] = null;
}
}

class SinglyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = [Link];
} else {
[Link] = newNode;
[Link] = newNode;
}
[Link]++;
return this;
}
}

var list = new SinglyLinkedList();


//[Link]("Hello");
//[Link]("You");
/*
var first = new Node("Hi");
[Link] = new Node("there");
[Link] = new Node("how");
[Link] = new Node("are");
[Link] = new Node("you");
// Bad way of creating linked list
*/

Popping – Removing a node from the end of the Linked List!

Note: First of all, let’s learn to traverse by adding this method:

traverse(){
var current = [Link];
while(current){
[Link]([Link]);
current = [Link];
}
}
Popping Pseudocode

- If there are no nodes in the list, return undefined


- Loop through the list until you reach the tail
- Set the next property of the 2nd to last node to be null
- Set the tail to be the 2nd to last node
- Decrement the length of the list by 1
- Return the value of the node removed

class Node{
constructor(val){
[Link] = val;
[Link] = null;
}
}
class SinglyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}

push(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = [Link];
} else {
[Link] = newNode;
[Link] = newNode;
}
[Link]++;
return this;
}

pop(){
if(![Link]) return undefined;

var current = [Link];


var newTail = current;
while([Link]){
newTail = current;
current = [Link];
}
[Link] = newTail;
[Link] = null;
[Link]--;
// after poping the last item, we make everything empty or null
if([Link] === 0){
[Link] = null;
[Link] = null;
}
return current;
}
}

var list = new SinglyLinkedList();


[Link]("Hello");
[Link]("Goodbye");
[Link]("!");

Shifting – Removing a new node from the beginning of the Linked List!

Shifting Pseudocode

- If there are no nodes, return undefined


- Store the current head property in a variable
- Set the head property to be the current head’s next property
- Decrement the length by 1
- Return the value of the node removed

class Node{
constructor(val){
[Link] = val;
[Link] = null;
}
}
class SinglyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = [Link];
} else {
[Link] = newNode;
[Link] = newNode;
}
[Link]++;
return this;
}
pop(){
if(![Link]) return undefined;
var current = [Link];
var newTail = current;
while([Link]){
newTail = current;
current = [Link];
}
[Link] = newTail;
[Link] = null;
[Link]--;
if([Link] === 0){
[Link] = null;
[Link]= null;
}
return current;
}
shift(){
if(![Link]) return undefined;
var currentHead = [Link];
[Link] = [Link];
[Link]--;
if([Link] === 0){
[Link] = null;
[Link] = null;
}
return currentHead;
}
}

var list = new SinglyLinkedList();


[Link]("Hello");
[Link]("Goodbye");
[Link]("!");

Unshifting – Adding a new node to the beginning of the Linked List!

Unshifting Pseudocode

- This function should accept a value


- Create a new node using the value passed to the function
- If there is no head property on the list, set the head and tail to be the newly created node
- Otherwise set the newly created node’s next property to be the current head property on the list
- Set the head property on the list to be the newly created node
- Increment the length of the list by 1
- Return the linked list

class Node{
constructor(val){
[Link] = val;
[Link] = null;
}
}
class SinglyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = [Link];
} else {
[Link] = newNode;
[Link] = newNode;
}
[Link]++;
return this;
}

unshift(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = [Link];
} else {
[Link] = [Link];
[Link] = newNode;
}
[Link]++;
return this;
}
}

var list = new SinglyLinkedList();


[Link]("Hello");
[Link]("Goodbye");
[Link]("!");

Get – Retrieving a node by its position in the Linked List!

Get Pseudocode

- This function should accept an index


- If the index is less than zero or greater than or equal to the length of the list, return null
- Loop through the list until you reach the index and return the node at the specific index

class Node{
constructor(val){
[Link] = val;
[Link] = null;
}
}
class SinglyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = [Link];
} else {
[Link] = newNode;
[Link] = newNode;
}
[Link]++;
return this;
}
get(index){
if(index < 0 || index >= [Link]) return null;
var counter = 0;
var current = [Link];
while(counter !== index){
current = [Link];
counter++;
}
return current;
}

var list = new SinglyLinkedList();


[Link]("Hello");
[Link]("Dude");
[Link]("Goodbye");
[Link]("!");

Set – Changing the value of a node based on its position in the Linked List

Set Pseudocode

- This function should accept a value and an index


- Use your get function to find the specific node.
- If the node is not found, return false
- If the node is found, set the value of that node to be the value passed to the function and return true
class Node{
constructor(val){
[Link] = val;
[Link] = null;
}
}
class SinglyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = [Link];
} else {
[Link] = newNode;
[Link] = newNode;
}
[Link]++;
return this;
}
get(index){
if(index < 0 || index >= [Link]) return null;
var counter = 0;
var current = [Link];
while(counter !== index){
current = [Link];
counter++;
}
return current;
}

set(index, val){
var foundNode = [Link](index);
if(foundNode){
[Link] = val;
return true;
}
return false;
}
}

var list = new SinglyLinkedList();


[Link]("Hello");
[Link]("Dude");
[Link]("Goodbye");
[Link]("!");

Insert – Adding a node to the Linked List at a specific position

Insert Pseudocode

- If the index is less than zero or greater than the length, return false
- If the index is the same as the length, push a new node to the end of the list
- If the index is 0, unshift a new node to the start of the list
- Otherwise, using the get method, access the node at the index -1
- Set the next property on that node to be the new node
- Set the next property on the new node to be the previous next
- Increment the length
- Return true

class Node{
constructor(val){
[Link] = val;
[Link] = null;
}
}
class SinglyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = [Link];
} else {
[Link] = newNode;
[Link] = newNode;
}
[Link]++;
return this;
}
unshift(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = [Link];
} else {
[Link] = [Link];
[Link] = newNode;
}
[Link]++;
return this;
}
get(index){
if(index < 0 || index >= [Link]) return null;
var counter = 0;
var current = [Link];
while(counter !== index){
current = [Link];
counter++;
}
return current;
}

set(index, val){
var foundNode = [Link](index);
if(foundNode){
[Link] = val;
return true;
}
return false;
}

insert(index, val){
if(index < 0 || index > [Link]) return false;
if(index === [Link]) return [Link](val);
if(index === 0) return [Link](val);
var newNode = new Node(val);
var prev = [Link](index - 1); // it gives the item right before the place where we
are going to insert a new item
var temp = [Link];
[Link] = newNode;
[Link] = temp;
[Link]++;
return true;
}
}

var list = new SinglyLinkedList();


[Link]("Hello");
[Link]("Dude");
[Link]("Goodbye");
[Link]("!");

/*
if(index === [Link]) return !![Link](val);
if(index === 0) return !![Link](val);

*/

Remove – Removing a node from the Linked List at a specific position

Remove Pseudocode

- If the index is less than zero or greater than or equal to the length, return undefined
- If the index is the same as the length – 1, pop
- If the index is 0, shift
- Otherwise, using the get method, access the node at the index – 1
- Set the next property on that node to be the next of the next node
- Decrement the length
- Return the value of the node removed

class Node{
constructor(val){
[Link] = val;
[Link] = null;
}
}
class SinglyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
pop(){
if(![Link]) return undefined;
var current = [Link];
var newTail = current;
while([Link]){
newTail = current;
current = [Link];
}
[Link] = newTail;
[Link] = null;
[Link]--;
if([Link] === 0){
[Link] = null;
[Link] = null;
}
return current;
}
shift(){
if(![Link]) return undefined;
var currentHead = [Link];
[Link] = [Link];
[Link]--;
if([Link] === 0){
[Link] = null;
[Link] = null;
}
return currentHead;
}
get(index){
if(index < 0 || index >= [Link]) return null;
var counter = 0;
var current = [Link];
while(counter !== index){
current = [Link];
counter++;
}
return current;
}
insert(index, val){
if(index < 0 || index > [Link]) return false;
if(index === [Link]) return !![Link](val);
if(index === 0) return !![Link](val);
var newNode = new Node(val);
var prev = [Link](index - 1);
var temp = [Link];
[Link] = newNode;
[Link] = temp;
[Link]++;
return true;
}
remove(index){
if(index < 0 || index >= [Link]) return undefined;
if(index === 0) return [Link]();
if(index === [Link] - 1) return [Link]();
var previousNode = [Link](index - 1);
var removed = [Link];
[Link] = [Link];
[Link]--;
return removed;
}

var list = new SinglyLinkedList();


[Link](100);
[Link](201);
[Link](250);
[Link](350);
Reverse – Reversing the Linked List in place!

Reverse Pseudocode

- Swap the head and tail


- Create a variable called next
- Create a variable called prev
- Create a variable called node and initialize it to the head property
- Loop through the list
- Set next to be the next property on whatever node is
- Set the next property on the node to be whatever prev is
- Set prev to be the value of the node variable
- Set the node variable to be the value of the next variable

class Node{
constructor(val){
[Link] = val;
[Link] = null;
}
}
class SinglyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = [Link];
} else {
[Link] = newNode;
[Link] = newNode;
}
[Link]++;
return this;
}
reverse(){
var node = [Link];
[Link] = [Link];
[Link] = node;

var prev = null;


var next;
for(var i = 0; i < [Link]; i++){
next = [Link];
[Link] = prev;
prev = node;
node = next;
}
return this;
}
print(){
var arr = [];
var current = [Link];
while(current){
[Link]([Link]);
current = [Link];
}
[Link](arr);
}

var list = new SinglyLinkedList();


[Link](100);
[Link](201);
[Link](250);
[Link](350);
[Link](999);

Doubly Linked List

We know what lists are … but doubly? Almost identical to Singly Linked Lists, except every node has another
pointer, to the previous node!

Comparisons with Singly Linked Lists

More memory === More Flexibility

It’s almost always a tradeoff!

class Node{
constructor(val){
[Link] = val;
[Link] = null;
[Link] = null;
}
}

class DoublyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
}

Pushing – Adding a node to the end of the Doubly Linked List

Pushing Pseudocode

- Create a new node with the value passed to the function


- If the head property is null set the head and tail to be the newly created node
- If not, set the next property on the tail to be that node
- Set the previous property on the newly created node to be the tail
- Set the tail to be the newly created node
- Increment the length
- Return the Doubly Linked List
Popping – Removing a node from the end of the Doubly Linked List

Popping Pseudocode

- If there is no head, return undefined


- Store the current tail in a variable to return later
- If the length is 1, set the head and tail to be null
- Update the tail to be the previous Node.
- Set the newTail’s next to null
- Decrement the length
- Return the value removed

class Node{
constructor(val){
[Link] = val;
[Link] = null;
[Link] = null;
}
}
class DoublyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if([Link] === 0){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = [Link];
[Link] = newNode;
}
[Link]++;
return this;
}
pop(){
if(![Link]) return undefined;
var poppedNode = [Link];
// if([Link] === [Link])
if([Link] === 1){
[Link] = null;
[Link] = null;
} else {
[Link] = [Link];
[Link] = null;
[Link] = null;
}
[Link]--;
return poppedNode;
}
}

Shifting – Removing a node from the beginning of the Doubly Linked List

Shifting Pseudocode

- If length is 0, return undefined


- Store the current head property in a variable (we’ll call it old head)
- If the length is one
 set the head to be null
 set the tail to be null
- Update the head to be the next of the old head
- Set the head’s prev property to null
- Set the old head’s next to null
- Decrement the length
- Return old head

class Node{
constructor(val){
[Link] = val;
[Link] = null;
[Link] = null;
}
}
class DoublyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if([Link] === 0){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = [Link];
[Link] = newNode;
}
[Link]++;
return this;
}
shift(){
if([Link] === 0) return
undefined;
var oldHead = [Link];
if([Link] === 1){
[Link] = null;
[Link] = null;
} else {
[Link] = [Link];
[Link] = null;
[Link] = null;
}
[Link]--;
return oldHead;
}
}

var list = new DoublyLinkedList();


[Link]("Harry");
[Link]("Ron");
[Link]("Hermione");

Unshifting – Adding a node to the beginning of the Doubly Linked List

Unshifting Pseudocode

- Create a new node with the value passed to the function


- If the length is 0
 Set the head to be the new node
 Set the tail to be the new node
- Otherwise
 Set the prev property on the head of the list to be the new node
 Set the next property on the new node to be the head property
 Update the head to be the new node
- Increment the length
- Return the list
class Node{
constructor(val){
[Link] = val;
[Link] = null;
[Link] = null;
}
}
class DoublyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if([Link] === 0){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = [Link];
[Link] = newNode;
}
[Link]++;
return this;
}
pop(){
if(![Link]) return undefined;
var poppedNode = [Link];
if([Link] === 1){
[Link] = null;
[Link] = null;
} else {
[Link] = [Link];
[Link] = null;
[Link] = null;
}
[Link]--;
return poppedNode;
}
unshift(val){
var newNode = new Node(val);
if([Link] === 0){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = [Link];
[Link] = newNode;
}
[Link]++;
return this;
}
}

var list = new DoublyLinkedList();


[Link]("Harry");
[Link]("Ron");
[Link]("Hermione");

Get – Accessing a node in a Doubly Linked List by its position

Get Pseudocode

- If the index is less than 0 or greater or equal to the length, return null
- If the index is less than or equal to half the length of the list
 Loop through the list starting from the head and loop towards the middle
 Return the node once it is found
- If the index is greater than half the length of the list
 Loop through the list starting from the tail and loop towards the middle
 Return the node once it is found

class Node{
constructor(val){
[Link] = val;
[Link] = null;
[Link] = null;
}
}
class DoublyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if([Link] === 0){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = [Link];
[Link] = newNode;
}
[Link]++;
return this;
}
get(index){
if(index < 0 || index >= [Link]) return null;
var count, current;
if(index <= [Link] / 2){
[Link]("Working from
start");
count = 0;
current = [Link];
while(count != index){
current = [Link];
count++;
}
} else {
[Link]("Working from
end");
count = [Link] - 1;
current = [Link];
while(count != index){
current = [Link];
count--;
}

}
return current;
}
}

var list = new DoublyLinkedList();


[Link]("Harry");
[Link]("Ron");
[Link]("Hermione");
Set – Replacing the value of a node in a Doubly Linked List

Set Pseudocode

- Create a variable which is the result of the get method at the index passed to the function

 If the get method returns a valid node, set the value of that node to be the value passed to the function

 Return true

- Otherwise, return false

class Node{
constructor(val){
[Link] = val;
[Link] = null;
[Link] = null;
}
}
class DoublyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if([Link] === 0){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = [Link];
[Link] = newNode;
}
[Link]++;
return this;
}
get(index){
if(index < 0 || index >= [Link]) return null;
var count, current;
if(index <= [Link] / 2){
count = 0;
current = [Link];
while(count != index){
current = [Link];
count++;
}
} else {
count = [Link] - 1;
current = [Link];
while(count != index){
current = [Link];
count--;
}

}
return current;
}
set(index, val){
var foundNode = [Link](index);
if(foundNode){
[Link] = val;
return true;
}
return false;
}
}
var list = new DoublyLinkedList();
[Link]("Harry");
[Link]("Ron");
[Link]("Hermione");

Insert – Adding a node in a Doubly Linked List by a certain position

Insert Pseudocode

- If the index is less than zero or greater than or equal to the length return false

- If the index is 0, unshift

- If the index is the same as the length, push

- Use the get method to access the index – 1

- Set the next and prev properties on the correct nodes to link everything together

- Incrment the length

- Return true

class Node{
constructor(val){
[Link] = val;
[Link] = null;
[Link] = null;
}
}
class DoublyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if([Link] === 0){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = [Link];
[Link] = newNode;
}
[Link]++;
return this;
}
pop(){
if(![Link]) return undefined;
var poppedNode = [Link];
if([Link] === 1){
[Link] = null;
[Link] = null;
} else {
[Link] = [Link];
[Link] = null;
[Link] = null;
}
[Link]--;
return poppedNode;
}
unshift(val){
var newNode = new Node(val);
if([Link] === 0){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = [Link];
[Link] = newNode;
} [Link]++;
return this;
}
shift(){
if([Link] === 0) return undefined;
var oldHead = [Link];
if([Link] === 1){
[Link] = null;
[Link] = null;
} else {
[Link] = [Link];
[Link] = null;
[Link] = null;
}
[Link]--;
return oldHead;
}
get(index){
if(index < 0 || index >= [Link]) return null;
var count, current;
if(index <= [Link] / 2){
count = 0;
current = [Link];
while(count != index){
current = [Link];
count++;
}
} else {
count = [Link] - 1;
current = [Link];
while(count != index){
current = [Link];
count--;
}

}
return current;
}
set(index, val){
var foundNode =
[Link](index);
if(foundNode){
[Link] = val;
return true;
}
return false;
}
insert(index, val){
if(index < 0 || index > [Link]) return false;
if(index === 0) return [Link](val);
if(index === [Link]) return [Link](val);

var newNode = new Node(val);


var beforeNode = [Link](index - 1);
var afterNode = [Link];
[Link] = newNode;
[Link] = beforeNode;
[Link] = afterNode;
[Link] = newNode;
[Link]++;
return true;
}
}

var list = new DoublyLinkedList();


[Link]("Harry");
[Link]("Ron");
[Link]("Hermione");

Remove – Removing a node in a Doubly Linked List by a certain position

- If the index is less than zero or greater than or equal to the length return undefined

- If the index is 0, shift

- If the index is the same as the length – 1, pop

- Use the get method to retrieve the item to be removed

- Update the next and prev properties to remove the found node from the list

- Set next and prev to null on the found node

- Decrement the length

- Return the removed node.

class Node{
constructor(val){
[Link] = val;
[Link] = null;
[Link] = null;
}
}
class DoublyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if([Link] === 0){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = [Link];
[Link] = newNode;
}
[Link]++;
return this;
}
pop(){
if(![Link]) return undefined;
var poppedNode = [Link];
if([Link] === 1){
[Link] = null;
[Link] = null;
} else {
[Link] = [Link];
[Link] = null;
[Link] = null;
}
[Link]--;
return poppedNode;
}
unshift(val){
var newNode = new Node(val);
if([Link] === 0){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = [Link];
[Link] = newNode;
} [Link]++;
return this;
}
shift(){
if([Link] === 0) return undefined;
var oldHead = [Link];
if([Link] === 1){
[Link] = null;
[Link] = null;
} else {
[Link] = [Link];
[Link] = null;
[Link] = null;
}
[Link]--;
return oldHead;
}
get(index){
if(index < 0 || index >= [Link]) return null;
var count, current;
if(index <= [Link] / 2){
count = 0;
current = [Link];
while(count != index){
current = [Link];
count++;
}
} else {
count = [Link] - 1;
current = [Link];
while(count != index){
current = [Link];
count--;
}

}
return current;
}
set(index, val){
var foundNode = [Link](index);
if(foundNode){
[Link] = val;
return true;
}
return false;
}
insert(index, val){
if(index < 0 || index > [Link]) return false;
if(index === 0) return [Link](val);
if(index === [Link]) return [Link](val);

var newNode = new Node(val);


var beforeNode = [Link](index - 1);
var afterNode = [Link];
[Link] = newNode;
[Link] = beforeNode;
[Link] = afterNode;
[Link] = newNode;
[Link]++;
return true;
}
remove(index){
if(index < 0 || index >= [Link]) return false;
if(index === 0) return [Link]();
if(index === [Link] - 1) return [Link]();
var removedNode = [Link](index);
[Link] = [Link];
[Link] = [Link];
[Link] = null;
[Link] = null;
[Link]--;
return removedNode;
}
}

var list = new DoublyLinkedList();


[Link]("Harry");
[Link]("Ron");
[Link]("Hermione");

Recap!

- Doubly Linked Lists are almost identical to Singly Linked Lists except there is an additional pointer to
previous nodes

- Better than Singly Linked Lists for finding nodes and can be done in half the time!

- However, they do take up more memory considering the extra pointer

STACKS

What is a stack?

A LIFO data structure! The last element added to the stack will be the first element removed from the stack

How is it used?

Think about a stack of plates, or a stack of markers, or a stack of … anything. As you pile it up the last thing (or
the topmost thing) is what gets removed first.

Where stacks are used?

- Managing function invocations


- Undo / Redo
- Routing (the history object) is treated like a stack!

Array Implementation
There is more than one way of implementing a stack

Linked List Implementation

Pushing – Add a value to the top of the stack!

Pushing Pseudocode

- The function should accept a value

- Create a new node with that value


- If there are no nodes in the stack, set the first and last property to be the newly created node

- If there is at least one node, create a variable that stores the current first property on the stack

- Reset the first property to be the newly created node

- Set the next property on the node to be the previously created variable

- Increment the size of the stack by 1

Note: shift() and unshift() are going to be named as pop() and push().

Pop Pseudocode

- If there are no ndoes in the stack, return null


- Create a temporary variable to store the first property on the stack
- If there is only 1 node, set the first and last property to be null
- If there is more than one node, set the first property to be the next property on the current first
- Decrement the size by 1
- Return the value of the node removed

class Node{
constructor(value){
[Link] = value;
[Link] = null;
}
}
class Stack{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
push(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = newNode;
} else {
var temp = [Link];
[Link] = newNode;
[Link] = temp;
}
return ++[Link];
}
pop(){
if(![Link]) return null;
var temp = [Link];
if([Link] === [Link]){
[Link] = null;
}
[Link] = [Link];
[Link]--;
return [Link];
}
}

Recap:

- Stacks are a LIFO data structure where the last value in is always the first one out.

- Stacks are used to handle function invocations (the call stack), for oeprations like undo/redo, and for
routing(remember pages you have visited and go back/forward) and much more!

- They are not a built in data structure in JavaScript, but are realtively simple to implement.
Queues

What is a Queue?

A FIFO data structure! First In First Out

We’ve seen this before

Queues exist everywhere! Think about the last time you waited in line …

How do we use them in programming?

- Background tasks
- Uploading resources
- Printing / Task processing

Building a Queue with an Array

Combination of push() and shift()

Combination of unshift() and pop()


Note: The main problem with these above approaches is that reindexing takes places either adding or removing
data from the array which is not a good thing in terms of performance if we have large amount of data as it.

Queue Implementation using Linked List

Enqueue Pseudocode

- This function accepts some value


- Create a new node using that value passed to the function
- If there are no nodes in the queue, set this node to be the first and last property of the queue
- Otherwise, set the next property on the current last to be that node, and then set the last property of the
queue to be that node

Dequeue Pseudocode

- If there is no first property, just return null


- Store the first property in a variable
- See if the first is the same as the last (check if there is only 1 node). If so, set the first and last to be null
- If there is more than 1 node, set the first property to be the next property of first
- Decrement the size by 1
- Return the value of the node dequeued

class Node{
constructor(value){
[Link] = value;
[Link] = null;
}
}
class Queue{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
enqueue(val){
var newNode = new Node(val);
if(![Link]){
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = newNode;
}
return ++[Link];
}
dequeue(){
if(![Link]) return null;
var temp = [Link];
if([Link] === [Link]){
[Link] = null;
}
[Link] = [Link];
[Link]--;
return [Link];
}
}

Trees

What is a Tree?

A data structure that consist of nodes in a parent/chid relationship.


Lists – linear

Trees = nonlinear

Tree Terminology

 Root – The top node in a tree.


 Child – A node directly connected to another node when moving away from the Root.
 Parent – The converse notion of a child.
 Siblings – A group of nodes with the same parent.
 Leaf – A node with no children.
 Edge – The connection between one node and another.

Lots of different applications!

 HTML DOM
 Network Routing
 Abstract Syntax Tree
 Artificial Intelligence
 Folders in Operating Systems
 Computer File Systems

KINDS OF TREES

 Trees
 Binary Trees
 Binary Search Trees

How BSTS work

- Every parent node has at most two children


- Every node to the left of a parent node is always less than the parent.
- Every node to the right of a parent node is always greater than the parent.

The BinarySearchTree Class

class Node{
constructor(value){
[Link] = value;
[Link] = null;
[Link] = null;
}
}
class BinarySearchTree{
constructor(){
[Link] = null;
}
}

var tree = new BinarySearchTree();


[Link] = new Node(10);
[Link] = new Node(15);
[Link] = new Node(7);
[Link] = new Node(9);

INSERTING A NODE

Steps – Iteratively or Recursively

- Create a new node


- Starting at the root
 Check if there is a root if not – the root now becomes that new node!
 If there is a root, check if the value of the new node is greater than or less than the value of the root
 If it is greater
 Check to see if there is a node to the right
If there is, move to that node and repeat these steps
If there is not, add that node as the right property
 If it is less
 Check to see if there is a node to the left
If there is, move to that node and repeat these steps
If there is not, add that node as the left property

class Node{
constructor(value){
[Link] = value;
[Link] = null;
[Link] = null;
}
}
class BinarySearchTree{
constructor(){
[Link] = null;
}

insert(value){
var newNode = new Node(value);
if([Link] === null){
[Link] = newNode;
return this;
} else {
var current = [Link];
while(true)
if(value === [Link]) return undefined;
if(value < [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
} else if(value > [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
}
}
}
}
}

// 10
// 5 13
// 2 7 11 16

var tree = new BinarySearchTree();


[Link](10);
[Link](5);
[Link](13);
[Link](11);
[Link](2);
[Link](16);
[Link](7);

FINDING A NODE IN A BST

Steps – Iteratively or recursively

- Starting at the root


 Check if there is a root, if not – we’re done searching!
 If there is a root, check if the value of the new node is the value we are looking for. If we foud it, we’re done!
 If not, check to see if the value is greater than or less than the value of the root
 If it is greater
 Check to see if there is a node to the right
If there is, move to that node and repeat these steps
If there is not, we’are done searching!
 If it is less
 Check to see if there is a node to the left
If there is, move to that node and repeat these steps
If there is not, we’re done searching!

class Node{
constructor(value){
[Link] = value;
[Link] = null;
[Link] = null;
}
}
class BinarySearchTree{
constructor(){
[Link] = null;
}

insert(value){
var newNode = new Node(value);
if([Link] === null){
[Link] = newNode;
return this;
} else {
var current = [Link];
while(true){
if(value === [Link]) return undefined;
if(value < [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
} else if(value > [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
}
}
}
}

find(value){
if([Link] === null) return false;
var current = [Link];
var found = false;
while(current && !found){
if(value < [Link]){
current = [Link];
} else if(value > [Link]){
current = [Link];
} else {
found = true;
}
}
if(!found) return undefined;
return current;
}

contains(value){
if([Link] === null) return false;
var current = [Link];
var found = false;
while(current && !found){
if(value < [Link]){
current = [Link];
} else if(value > [Link]){
current = [Link];
} else {
return true;
}
}
return false;
}
}

// 10
// 5 13
// 2 7 11 16

var tree = new BinarySearchTree();


[Link](10);
[Link](5);
[Link](13);
[Link](11);
[Link](2);
[Link](16);
[Link](7);

Tree Travsersal

Two ways:

Breadth First Search

Steps – Iteratively

- Create a queue (this can be an array) and a variable to store the values of nodes visited
- Place the root node in the queue
- Loop as long as there is anything in the queue
 Dequeue a node from the queue and push the value of the node into the variable that stores the nodes
 If there is a left property on the node dequeued – add it to the queue
 If there is a right property on the node dequeued – add it to the queue
- Return the variable that stores the values

// 10
// 6 15
// 3 8 20

queue: []
visited: []
queue: [10]
visited: []
queue: [6, 15]
visited: [10]
queue: [15, 3, 8]
visited: [10, 6]
queue: [3, 8, 20]
visited: [10, 6, 15]
queue: [8, 20]
visited: [10, 6, 15, 3]
queue: [20]
visited: [10, 6, 15, 3, 8]
queue: []
visited: [10, 6, 15, 3, 8, 20]

Implementation:

class Node{
constructor(value){
[Link] = value;
[Link] = null;
[Link] = null;
}
}
class BinarySearchTree{
constructor(){
[Link] = null;
}
insert(value){
var newNode = new Node(value);
if([Link] === null){
[Link] = newNode;
return this;
} else {
var current = [Link];
while(true){
if(value === [Link]) return undefined;
if(value < [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
} else if(value > [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
}
}
}
}
find(value){
if([Link] === null) return false;
var current = [Link];
var found = false;
while(current && !found){
if(value < [Link]){
current = [Link];
} else if(value > [Link]){
current = [Link];
} else {
found = true;
}
}
if(!found) return undefined;
return current;
}

contains(value){
if([Link] === null) return false;
var current = [Link];
var found = false;
while(current && !found){
if(value < [Link]){
current = [Link];
} else if(value > [Link]){
current = [Link];
} else {
return true;
}
}
return false;
}
BFS(){
var data = [],
queue = [],
node = [Link];

[Link](node);
while([Link]){
node = [Link]();
[Link]([Link]);
if([Link]) [Link]([Link]);
if([Link]) [Link]([Link]);
}
return data;
}
}

var tree = new BinarySearchTree();


[Link](10);
[Link](6);
[Link](15);
[Link](3);
[Link](8);
[Link](20);
Depth First Search

DFS – PreOrder

Steps – Recursively

- Create a variable to store the values of nodes visited


- Store the root of the BST in a variable called current
- Write a helper function which accepts a node
 Push the value of the node to the variable that stores the values
 If the node has a left property, call the helper function with the left property on the node
 If the node has a right property, call the helper function with the right property on the node
- Invoke the helper function with the current variable
- Return the array of values

class Node{
constructor(value){
[Link] = value;
[Link] = null;
[Link] = null;
}
}
class BinarySearchTree{
constructor(){
[Link] = null;
}
insert(value){
var newNode = new Node(value);
if([Link] === null){
[Link] = newNode;
return this;
} else {
var current = [Link];
while(true){
if(value === [Link]) return undefined;
if(value < [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
} else if(value > [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
}
}
}
}

DFSPreOrder(){
var data = [];
var current = [Link];
function traverse(node){
[Link]([Link]);
if([Link]) traverse([Link]);
if([Link]) traverse([Link]);
}
traverse([Link]);
return data;
}
}

var tree = new BinarySearchTree();


[Link](10);
[Link](6);
[Link](15);
[Link](3);
[Link](8);
[Link](20);
[Link]([Link]()); // [10, 6, 3, 8, 15, 20]
DFS – PostOrder

Steps – Recursively

- Create a variable to store the values of nodes visited


- Store the root of the BST in a variable called current
- Write a helper function which accepts a node
 If the node has a left property, call the helper function with the left property on the node
 If the node has a right property, call the helper function with the right property on the node
 Push the value of the node to the variable that stores the values
 Invoke the helper function with the current variable
- Return the array of values

class Node{
constructor(value){
[Link] = value;
[Link] = null;
[Link] = null;
}
}
class BinarySearchTree{
constructor(){
[Link] = null;
}
insert(value){
var newNode = new Node(value);
if([Link] === null){
[Link] = newNode;
return this;
} else {
var current = [Link];
while(true){
if(value === [Link]) return undefined;
if(value < [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
} else if(value > [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
}
}
}
}

DFSPostOrder(){
var data = [];
var current = [Link];
function traverse(node){
if([Link]) traverse([Link]);
if([Link]) traverse([Link]);
[Link]([Link]);
}
traverse([Link]);
return data;
}
}

var tree = new BinarySearchTree();


[Link](10);
[Link](6);
[Link](15);
[Link](3);
[Link](8);
[Link](20);
[Link]([Link]()); // [3, 8, 6, 20, 15, 10]
DFS - InOrder

Steps – Recursively

- Create a variable to store the values of nodes visited


- Store the root of the BST in a variable called current
- Write a helper function which accepts a node
 If the node has a left property, call the helper function with the left property on the node
 Push the value of the node to the variable that stores the values
 If the node has a right property, call the helper function with the right property on the node
- Invoke the helper function with the current variable
- Return the array of values

class Node{
constructor(value){
[Link] = value;
[Link] = null;
[Link] = null;
}
}
class BinarySearchTree{
constructor(){
[Link] = null;
}
insert(value){
var newNode = new Node(value);
if([Link] === null){
[Link] = newNode;
return this;
} else {
var current = [Link];
while(true){
if(value === [Link]) return undefined;
if(value < [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
} else if(value > [Link]){
if([Link] === null){
[Link] = newNode;
return this;
}
current = [Link];
}
}
}
}

DFSInOrder(){
var data = [];
var current = [Link];
function traverse(node){
if([Link]) traverse([Link]);
[Link]([Link]);
if([Link]) traverse([Link]);
}
traverse([Link]);
return data;
}
}

var tree = new BinarySearchTree();


[Link](10);
[Link](6);
[Link](15);
[Link](3);
[Link](8);
[Link](20);
[Link]([Link]()); // [3, 6, 8, 10, 15, 20]

BINARY HEAPS

What is a Binary Tree?

Very similar to a binary search tree, but with some different rules!

In a MaxBinaryHeap, parent nodes are always larger than child nodes. In a MinBinaryHeap, parent nodes are
always smaller than child nodes

Max Binary Heap

- Each parent has at most two child nodes

- The value of each parent node is always greater than its child nodes

- In a max Binary Heap the parent is greater than the children, there are no guarantees between sibling
nodes.

- A binary heap is as compact as possible. All the children of each node are as full as they can be and left
children are filled out first

Why do we need to know this?

Binary Heaps are used to implement Priority Queues, which are very commonly used data structures

They are also used quite a bit, with graph traversal algorithms

There’s an easy way of storing a binary heap … A LIST/ARRAY

Defining Our Class

…..

Insert Pseudocode
- Push the value into the values property on the heap
- Bubble Up:
 Create a variable called index which is the length of the values property – 1
 Create a variable called parentIndex which is the floor of (index -1) / 2
 Keep looping as long as the values element at the parentIndex is less than the values element at the child
index
 Swap the value of the values element at the parentIndex with the value of the element property at
the child index
 Set the index to be the parentIndex, and start over!

class MaxBinaryHeap{
constructor(){
[Link] = [];
}
insert(element){
[Link](element);
[Link]();
}
bubbleUp(){
let idx = [Link] - 1;
const element = [Link][idx];
while(idx > 0){
let parentIdx = [Link]((idx - 1) / 2);
let parent = [Link][parentIdx];
if(element <= parent) break;
[Link][parentIdx] = element;
[Link][idx] = parent;
idx = parentIdx;
}
}
}
let heap = new MaxBinaryHeap();
[Link](41);
[Link](39);
[Link](33);
[Link](18);
[Link](27);
[Link](12);
[Link](55);

/*
[41, 39, 33, 18, 27, 12, 55]
0 1 2 3 4 5 6

idx = 7 - 1 = 6
element = 55 (values[6])
parentIdx = [Link]((6 - 1) / 2) = 2
parent = 33 (values[2])

Swapping (as element is greater than


parent):
values[2] = 55
values[6] = 33

[41, 39, 33, 18, 27, 12, 55]


[41, 39, 55, 18, 27, 12, 33]
[55, 39, 41, 18, 27, 12, 33]
[55, 39, 41, 18, 27, 12, 33]

*/

Removing From A Heap

Sink Down?
The procedure for deleting the root from the heap (effectively extracting the maximum element in a max-heap
or the minimum element in a min-heap) and restoring the properties is called down-heap (also known as bubble-
down, percolate-down, sift-down, trickle down, heapify-down, cascade-down, and extract-min/max).

Removing (also called extractMax)

- Swap the first value in the values property with the last one
- Pop from the values property, so you can return the value at the end.
- Have the new root “sink down” to the correct spot …
 Your parent index starts at 0 (the root)
 Find the index of the left child: 2 * index + 1 (make sure its not out of bounds)
 Find the index of the right child: 2 * index + 2 (make sure its not out of bounds)
 If the left or right child is greater than the element … swap. If both left and right children are larger, swap
with the largest child.
 The child index you swapped to now becomes the new parent index.
 Keep looping and swapping until neither child is larger than the element.
 Return the old root!

class MaxBinaryHeap{
constructor(){
[Link] = [];
}
insert(element){
[Link](element);
[Link]();
}
bubbleUp(){
let idx = [Link] - 1;
const element = [Link][idx];
while(idx > 0){
let parentIdx = [Link]((idx - 1) / 2);
let parent = [Link][parentIdx];
if(element <= parent) break;
[Link][parentIdx] = element;
[Link][idx] = parent;
idx = parentIdx;
}
}
extractMax(){
const max = [Link][0];
const end = [Link]();
if([Link] > 0){
[Link][0] = end;
[Link]();
}
return max;
}
sinkDown(){
let idx = 0;
const length = [Link];
const element = [Link][0];
while(true){
let leftChildIdx = 2 * idx + 1;
let rightChildIdx = 2 * idx + 2;
let leftChild, rightChild;
let swap = null;
if(leftChildIdx < length){
leftChild = [Link][leftChildIdx];
if(leftChild > element){
swap = leftChildIdx;
}
}
if(rightChildIdx < length){
rightChild = [Link][rightChildIdx];
if((swap === null && rightChild > element) ||
(swap !== null && rightChild > leftChild)){
swap = rightChildIdx;
}
}
if(swap === null) break;
[Link][idx] = [Link][swap];
[Link][swap] = element;
idx = swap;
}
}
}

let heap = new MaxBinaryHeap();


[Link](41);
[Link](39);
[Link](33);
[Link](18);
[Link](27);
[Link](12);
[Link](55);

/*
> heap
MaxBinaryHeap {values: Array(7)}values: (7) [55, 39, 41, 18, 27, 12, 33]
> [Link]();
55
> [Link];
(6) [41, 39, 33, 18, 27, 12]
> [Link]();
41
> [Link];
(5) [39, 27, 33, 18, 12]
> [Link]();
39
> [Link];
(4) [33, 27, 12, 18]
> [Link]();
33
> [Link];
(3) [27, 18, 12]
> [Link]();
27
> [Link];
(2) [18, 12]
> [Link]();
18
> [Link];
[12]
> [Link]();
12
> [Link];
[]
> [Link](20);
undefined
> [Link];
[20]
*/
Building A Priority Queue

What is a Priority Queue?

A data structure where each element has a priority. Elements with higher priorities are served before elements
with lower priorities.

Our Priority Queue

- Write a Min Binary Heap – lower number means higher priority.


- Each Node has a val and a priority. Use the priority to build the heap.
- Enqueue method accepts a value and priority, makes a new node, and puts it in the right spot based off of
its priority.
- Dequeue method removes root element, returns it, and rearranges heap using priority.

……………………………………….

Graphs

What are Graphs?

A graph data structure consists of a finite (and possibly mutable) set of vertices or nodes or points, together
with a set of unordered paris of these vertices for an undirected graph or a set of ordered pairs for a directed
graph.

Uses for Graph

- Social Networks
- Location / Mapping
- Routing Algorithms
- Visual Hierarchy
- File System Optimizations
- Everywhere!

Recommendations

 ‘People also watched’


 ‘You might also like …’
 ‘People you might know’
 ‘Frequently bought with’

Types of Graphs

Essential Graph Terms

 Vertex – a node
 Edge – connection between nodes
 Weighted/Unweighted – values assigned to distances between vertices
 Directed/Undirected – directions assigned to distanced between vertices

Representing A Graph

How do we store graph?

Adjacency Matrix

Adjacency List

Adjacency List Adjancency Matrix


Can take up less space (in sparse graphs) Takes up more space (in sparse graphs)
Faster to iterate over all edges Slower to iterate over all edges
Can be slower to lookup specific edge Faster to lookup specific edge

What will we use? An Adjacency List Why? Most data in the real-world tends to be lend itself to sparser and/or
larger graphs

Adding a Vertex

- Write a method called addVertex, which accepts a name of the vertex

- It should add a key to the adjacency list with the name of the vertex and set its value to be an empty array

[Link](“Tokyo”);
{
“Tokyo”: []
}

class Graph{
constructor(){
[Link] = {};
}
addVertex(vertex){
if(![Link][vertex]){
[Link][vertex] = [];
}
}
}

Adding an Edge

- This function should accept two vertices, we can call them vertex1 and vertex2
- The function should find in the adjacency list the key of vertex1 and push vertex2 to the array.
- The function should find in the adjacency list the key of vertex2 and push vertex1 to the array.
- Don’t worry about handling errors/invalid vertices

class Graph{
constructor(){
[Link] = {};
}
addVertex(vertex){
if(![Link][vertex]){
[Link][vertex] = [];
}
}
addEdge(v1, v2){
[Link][v1].push(v2); // we would do this only in the case of directed
graph but here we are working with non-directed one
[Link][v2].push(v1);
}
}
let g = new Graph();
[Link]("Dallas");
[Link]("Tokyo");
[Link]("Aspen");

Removing an Edge

- This function should accept two vertices, we’ll call them vertex1
and vertex2
- The function should reassign the key of vertex1 to be an array
that does not contain vertex2
- The function should reassign the key of vertex2 to be an array
that does not contain vertex1
- Don’t worry about handling errors/invalid vertices

class Graph{
constructor(){
[Link] = {};
}
addVertex(vertex){
if(![Link][vertex]){
[Link][vertex] = [];
}
}
addEdge(v1, v2){
[Link][v1].push(v2);
[Link][v2].push(v1);
}

removeEdge(vertex1, vertex2){
[Link][vertex1] =
[Link][vertex1].filter(
v => v !== vertex2
);
[Link][vertex2] =
[Link][vertex2].filter(
v => v !== vertex1
);
}
}

let g = new Graph();


[Link]("Dallas");
[Link]("Tokyo");
[Link]("Aspen");
[Link]("Dallas", "Aspen");
[Link]("Tokyo", "Dallas");

Removing a Vertex

- The function should accept a vertex to remove

- The function should loop as long as there are any other vertices in the adjacency list for that vertex

- Inside of the loop, call our removeEdge function with the vertex we are removing and any values in the
adjacency list for that vertex

- Delete the key in the adjacency list for that vertex

You might also like