JavaScript Coding Challenges Guide
JavaScript Coding Challenges Guide
com
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]);
}
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
Create a function that will find the nth Fibonacci number using recursion
Create a function that will return in an array the first “p” prime numbers greater than “n”
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
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 capitalize the first letter of each word in a text
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
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)
Deep copy a jagged array with numbers or other arrays in a new array
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.
Console Projects
To Do List:
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 removeItem(list){
let answer = prompt('Which item would you like to delete from the list');
let correct = [Link]().toLowerCase();
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);
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`);
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");
}
(function(){
function Question(question, answers, correct){
[Link] = question;
[Link] = answers;
[Link] = correct;
}
[Link] = function(){
[Link]([Link]);
[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);
function score(){
var sc = 0;
return function(correct){
if(correct){
sc++;
}
return sc;
}
}
function nextQuestion(){
var n = [Link]([Link]() * [Link]);
questions[n].displayQuestion();
var answer = prompt('Please select the correct answer. Type \'exit\' to end the
game');
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. Write a JavaScript program to display the current day and time in the following format.
<!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]();
}
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;
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>
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.
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".
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">
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:
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);
[Link]([Link]);
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.
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.
[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 stringCheck(text){
if(text === null || text === undefined || text === '' || [Link](0, 2) === "Py"){
return text;
} else {
return ('Py' + text);
}
}
22. Write a JavaScript program to remove a character at the specified position of a given string and
return the new string.
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;
}
[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 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.
[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.
[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;
}
}
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.
35. Write a program to check whether a specified character exists within the 2nd to 4th position in
a given string.
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.
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.
[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.
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.
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
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.
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.
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.
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.
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
[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](" ");
}
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);
}
57. Write a JavaScript program to create a new string of specified copies (positive number) of a
given string.
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]));
}
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(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 "";
}
}
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.
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];
}
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;
}
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]);
}
}
function arrayFunc(nums){
return [Link]((element, idx, arr) => arr[([Link] - 1) - idx]);
}
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;
}
75. Write a JavaScript program to create a new array taking the middle elements of the two arrays
of integer and each length 3.
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;
}
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;
}
}
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;
}
}
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);
}
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.
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"]
}
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;
}
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;
Types of angles:
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.
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.
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
90. Write a JavaScript program to find the kth greatest element of a given array of integers
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 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;
95. Write a JavaScript program to replace all the numbers with a specified number of a given array
of integers.
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.
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.
100. Write a JavaScript program to check whether there is at least one element which occurs in two
given sorted arrays of integers.
if(!(isFirstCharLower || isFirstCharUpper)){
return false;
}
[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;
}
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);
}
[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.
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.
[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.
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.
/*
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.
111. Write a JavaScript program to check a number from three given numbers where two numbers
are equal, find the third one.
***********************************************************************
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:
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;
}
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.
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;
}
************************************************************
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;
}
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.
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](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:
Radius of circle: r
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;
}
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;
}
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.
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.
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;
}
function longestStr(strArr){
let longStrLen = "";
for(let i = 0; i < [Link]; i++){
if(strArr[i].length > [Link]){
longStrLen = strArr[i];
}
}
return longStrLen;
}
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];
}
}
}
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](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;
}
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);
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";
}
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.
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];
}
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;
}
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
Example x = 32243;
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.
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.
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.
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](" ");
}
***********************************************************************************
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]("");
}
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;
}
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.
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]
function secondGreatestLowest(arr){
[Link](function(a, b){
return a - b;
});
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.
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;
}
function uniqueChar(str){
let uChar = [];
for(let i = 0; i < [Link]; i++){
if(){
[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.
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.
Expected output : [[2, 1], [3, 1], [3, 2], [3, 2, 1]]
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.
Expected output : 2
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.
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 = '';
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
function abc(){
[Link]([Link]);
}
abc(); // abc
1. Write a JavaScript program that accept two integers and display the larger.
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.
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.
Output : 0
Sample Output :
"0 is even"
"1 is odd"
"2 is even"
----------
----------
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".
/*
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.
*
* *
* * *
* * * *
* * * * *
let sum = 0;
for(let i = 1; i < 1000; i++){
if(i % 3 === 0 || i % 5 === 0){
sum += i;
}
}
[Link](sum); // 233168
JavaScript array
Test Data :
[Link](is_array('w3resource'));
[Link](is_array([1, 2, 4, 0]));
false
true
Note:
Test Data :
[Link](array_Clone([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]
[]
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]
5. Write a simple JavaScript program to join all elements of the following array into a string.
Expected Output :
"Red,Green,White,Black"
"Red+Green+White+Black"
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];
}
Sample array : var arr1=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
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'.
10. Write a JavaScript program which prints the elements of the following array.
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"
------
------
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 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);
}
color = ["Blue ", "Green", "Red", "Orange", "Violet", "Indigo", "Yellow "];
o = ["th","st","nd","rd"]
-------------
function leapYear(year){
if((year % 4 === 0 && year % 100 !== 0) || (year % 100 === 0 && year % 400 === 0)) return
true;
else return false;
}
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
Sample array :
array1 = [1,0,2,3,4];
array2 = [3,5,6,7,8,13];
Expected Output :
[4, 5, 8, 10, 12, 13]
*********************************************************************
function find_duplicate_in_array(arra1) {
const object = {};
const result = [];
[Link](item => {
if(!object[item])
object[item] = 0;
object[item] += 1;
})
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]
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]
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.
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.
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 filterArray(testArray){
let index = -1;
const arrLength = testArray ? [Link] : 0;
let resIndex = -1;
const result = [];
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}
];
[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.
***********************************************
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.
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.
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"]
[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]
while(len--){
let item = arr[len];
if(!assoc[item]){
[Link](item);
assoc[item] = true;
}
}
return resultArr;
}
let uq = [];
for(let i = 0; i < [Link]; i++){
if(){
[Link](tempArr[i]);
}
}
return uq;
}
Test data :
[Link](remove_array_element([2, 5, 9, 6], 5));
[2, 9, 6]
Test data :
arr = [2, 5, 9, 6];
[Link](contains(arr, 5));
[True]
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;
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 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;
}
function randomItem(items){
return items[[Link]([Link]() * [Link])];
}
Test Data :
[Link](array_filled(6, 0));
[0, 0, 0, 0, 0, 0]
[Link](array_filled(4, 11));
[11, 11, 11, 11]
Test Data :
[Link](array_filled(4, 'password'));
38. Write a JavaScript function to move an array element from one position to another.
Test Data :
39. Write a JavaScript function to filter false, null, 0 and blank values from an array.
Test Data :
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));
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));
42. Write a JavaScript function to find the unique elements from two arrays.
Test Data :
What is an Algorithm?
It’s the foundation for being a successful problem solving and developer
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”
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!
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
Simplify
Can you use the result or method for some other problem?
Frequency Counters
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.
Refactored
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.
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
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;
}
**********************************************************
// 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;
}
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
Binary Search
Pseudocode
- 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
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:
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:
******************************************************************
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
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]));
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
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.
- Create an empty array, take a look at the smallest values in each input array
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
- 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 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)
- 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
[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:
Radix Sort
It exploits the fact that information about the size of a number is encoded in the number of digits.
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
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
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
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;
}
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!
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).
Lists
Arrays
- Indexed in order!
- Insertion and deletion can be expensive
- Can quickly be accessed at a specific index
Pseudocode
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;
}
}
traverse(){
var current = [Link];
while(current){
[Link]([Link]);
current = [Link];
}
}
Popping Pseudocode
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;
Shifting – Removing a new node from the beginning of the Linked List!
Shifting Pseudocode
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;
}
}
Unshifting Pseudocode
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 Pseudocode
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 – Changing the value of a node based on its position in the Linked List
Set Pseudocode
set(index, val){
var foundNode = [Link](index);
if(foundNode){
[Link] = val;
return true;
}
return false;
}
}
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;
}
}
/*
if(index === [Link]) return !;
if(index === 0) return !;
*/
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 !;
if(index === 0) return !;
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;
}
Reverse Pseudocode
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;
We know what lists are … but doubly? Almost identical to Singly Linked Lists, except every node has another
pointer, to the previous node!
class Node{
constructor(val){
[Link] = val;
[Link] = null;
[Link] = null;
}
}
class DoublyLinkedList{
constructor(){
[Link] = null;
[Link] = null;
[Link] = 0;
}
}
Pushing Pseudocode
Popping Pseudocode
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
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;
}
}
Unshifting Pseudocode
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;
}
}
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
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 Pseudocode
- If the index is less than zero or greater than or equal to the length return false
- Set the next and prev properties on the correct nodes to link everything together
- 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);
- If the index is less than zero or greater than or equal to the length return undefined
- Update the next and prev properties to remove the found node from 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;
}
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);
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!
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.
Array Implementation
There is more than one way of implementing a stack
Pushing Pseudocode
- If there is at least one node, create a variable that stores the current first property on the stack
- Set the next property on the node to be the previously created variable
Note: shift() and unshift() are going to be named as pop() and push().
Pop Pseudocode
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?
Queues exist everywhere! Think about the last time you waited in line …
- Background tasks
- Uploading resources
- Printing / Task processing
Enqueue Pseudocode
Dequeue Pseudocode
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?
Trees = nonlinear
Tree Terminology
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
class Node{
constructor(value){
[Link] = value;
[Link] = null;
[Link] = null;
}
}
class BinarySearchTree{
constructor(){
[Link] = null;
}
}
INSERTING A NODE
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
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
Tree Travsersal
Two ways:
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;
}
}
DFS – PreOrder
Steps – Recursively
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;
}
}
Steps – Recursively
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;
}
}
Steps – Recursively
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;
}
}
BINARY HEAPS
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
- 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
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
…..
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])
*/
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).
- 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;
}
}
}
/*
> 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
A data structure where each element has a priority. Elements with higher priorities are served before elements
with lower priorities.
……………………………………….
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.
- Social Networks
- Location / Mapping
- Routing Algorithms
- Visual Hierarchy
- File System Optimizations
- Everywhere!
Recommendations
Types of Graphs
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
Adjacency Matrix
Adjacency List
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
- 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
);
}
}
Removing a Vertex
- 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