JS, DS & Algo
JS, DS & Algo
// function minimumBribes(arr) {
// let n = arr.length;
// let check = true;
// let count = 0;
// while(check) {
// check=false;
// for(let i=0; i<n-1; i++) {
// let init = arr[i];
// if(init !== i+1) {
// let index = init-1;
// let temp = init;
// arr[i] = arr[index];
// arr[index] = temp;
// count++;
// check=true;
// }
// }
// }
// console.log(“-------“, count);
// return count;
// }
// minimumBribes([1,3,5,2,4,6,7]);
//minimumBribes([10,9,2,7,4,5,1,3,8,6]);
//minimumBribes([2,1,3,4,5,6,7,8]);
//minimumBribes([8,4,1,3,2,7,6,5]);
//minimumBribes([7,1,3,2,4,5,6]);
//arrayManipulation(4, [[2,3,603],[1,1,286],[4,4,882]]);
//arrayManipulation(10, [[1,5,3],[4,8,7],[7,9,1]]);
// ------------------------------------------------------------------------------------------------------------------
/* 1. Anagram */
// Function to create anagrams
// 1 ≤ n ≤ 105
// s consists of digits only.
// The length of s is a multiple of 2.
// getAnagram(“123456");
//getAnagram(“12346392”);
/* 2. Find Vowels */
// strArr = [‘aba’,‘bcb’,‘ece’,‘aa’,‘e’]
// queries = [‘1-3’,‘2-5’,‘2-2’]
// result [2, 3, 0]
// 1 ≤ n, q ≤ 105
// 1 ≤ l ≤ r ≤ n
// 1 ≤ size of strArr[i] ≤ 10
// Determine how many strings starting from index l and ending at index r have vowels as the
first and last character
// hasVowels([‘aba’,‘bcb’,‘ece’,‘aa’,‘e’], [‘1-3’,‘2-5’,‘2-2’]);
// hasVowels([ “aab”, “a”, “bcd”, “awe”, “bbbbbu” ], [ “2-3", “4-5” ]);
/*hasVowels([‘iti’, ‘muspubz’, ‘st’, ‘o’, ‘xlt’, ‘ezymvlfie’, ‘iwljxna’, ‘azdfb’, ‘esifhidtfu’, ‘kckaa’, ‘aksy’,
‘zxcbugpopu’,
‘aper’, ‘esgfudro’, ‘vjiug’, ‘crlqi’, ‘io’, ‘as’, ‘opljvcfloa’, ‘edjshci’, ‘eovyrii’, ‘oahslcvqpi’, ‘oqrukywi’,
‘omfffogte’, ‘rg’, ‘i’, ‘orzxj’, ‘epe’, ‘bvcgahwhc’, ‘iyabe’, ‘urto’, ‘bl’, ‘ie’, ‘umnkvlo’, ‘utsqxou’,
‘nsggxktwcx’,
‘etwqee’, ‘swl’, ‘okcylznu’, ‘ispawolji’, ‘klzo’, ‘mufay’, ‘odgu’, ‘oa’, ‘qgp’, ‘jjxuw’, ‘usxai’, ‘ao’, ‘m’,
‘avo’],
[‘33-43’, ‘38-41’, ‘21-44’, ‘11-22’, ‘43-50’, ‘16-23’, ‘5-24’, ‘30-32’, ‘28-38’, ‘19-29’, ‘32-43’, ‘19-33’,
‘9-13’, ‘15-46’, ‘39-43’,‘21-31’, ‘10-25’, ‘24-47’, ‘4-36’, ‘21-48’, ‘35-36’, ‘10-21’, ‘2-42’, ‘19-42’, ‘20-
41’, ‘33-40’, ‘1-8’, ‘16-16’, ‘17-30’, ‘7-11’, ‘24-33’, ‘40-49’, ‘15-42’, ‘45-45’, ‘17-50’, ‘34-45’, ‘5-15’,
‘43-46’, ‘18-34’, ‘8-15’, ‘6-6’, ‘8-41’, ‘6-15’, ‘23-33’, ‘35-37’, ‘11-40’, ‘17-29’, ‘9-11’, ‘7-43’, ‘5-44’])*/
// ---------------------------------------------------------------------------------------------------------------------
/* 3. Rods cutting */
// Given an array with the lengths of various metal rods, repeatedly perform the following:
// Count the number of rods.
// Find the rod(s) with the shortest length.
// Discard any rod of that length.
// Cut that shortest length from each of the longer rods. These are offcuts.
// Discard all offcuts.
// Repeat until there are no more rods.
// function rodOffcut(arr) {
// const result = [];
// let smallest = 0;
// let len = 0;
// arr.sort((a,b) => a-b);
// while(arr && arr.length) {
// len = arr.length;
// result.push(len);
// smallest = arr[0];
// for (let i=0; i<len; i++) {
// arr[i] = arr[i] - smallest;
// }
// arr = arr.filter(item => {
// if(item > 0) {
// return item;
// }
// });
// }
// console.log(result);
// return result;
// }
// rodOffcut([1,1,3,4]);
// rodOffcut([5, 4, 4, 2, 2, 8]);
// ---------------------------------------------------------------------------------------------
// 4. Painting Graph
/* Digital graphics tools often make available a “bucket fill” tool that will only paint adjacent cells .
In one fill, a modified bucket tool recolors adjacent cells (connected horizontally or vertically but
not diagonally) that have the same color. Given a picture represented as a 2-dimensional array
of letters representing colors, find the minimum number of fills to completely repaint the picture.
*/
// picture= [“aabba”, “aabba”, “aaacb”]
// Each string represents a row of the picture and each letter represents a cell’s color.
// function strokesRequired(picture) {
// const obj = {};
// //const color1, color2, color3, color4, color5;
// const orgArr = picture.slice(0);
// while (picture.length) {
// const prev = (orgArr.length - (picture.length+1));
// const prevRow = prev ? orgArr[prev] : orgArr[0];
// const row = picture.shift();
// console.log()
// let len = row.length;
// for (let i = 0; i < len; i++) {
// // console.log(“----“, obj[row[i]], row[i], obj);
// let c = “color”;
// obj[c] = 0;
// if(!prev) {
// if (obj[c] && row[i] === row[i+1]) {
// obj[c] += 1;
// } else if(!obj[c]) {
// obj[c] = 1;
// } else {
// obj[c+1] = 1;
// }
// }
// else if() {
// }
// }
// }
// console.log(obj);
// return obj;
// }
// function strokesRequired(picture) {
// const orgArr = picture.slice(0);
// const obj = {};
// while(picture.length) {
// const prev = (orgArr.length - (picture.length+1));
// const prevRow = prev ? orgArr[prev] : orgArr[0];
// let row = picture.shift();
// let len = row.length;
// for (let i = 0; i < len; i++) {
// if(!prev) {
// while(row[i] === row[i+1]) {
// obj[row.substr(i, i+2)] = 1
// }
// }
// }
// }
// }
//strokesRequired([“aabba”, “aabba”, “aaacb”]);
////////////////////////////////////////////////////
/* String Question 1 */
// First Solution
// function makeAnagram (a, b) {
// const len = a.length >= b.length ? a.length : b.length;
// const alen = a.slice(0).length;
// const blen = b.slice(0).length;
// let c1 = ‘’;
// let count = 0;
// Second Solution
// function makeAnagram(a, b) {
// let counter = {};
// let total = 0;
// Array.from(a).forEach(char => {
// counter[char] = counter[char] || 0;
// counter[char]++;
// })
// // console.log(‘first’, counter);
// Array.from(b).forEach(char => {
// counter[char] = counter[char] || 0;
// counter[char]--;
// })
// // console.log(‘second’, counter);
// Object.keys(counter).forEach(k => {
// if (counter[k] !== 0) {
// total += Math.abs(counter[k]);
// }
// })
// return total;
// }
//makeAnagram(‘jxwtrhvujlmrpdoqbisbwhmgpmeoke’, ‘fcrxzwscanmligyxyvym’);
//makeAnagram(‘fcrxzwscanmligyxyvym’, ‘jxwtrhvujlmrpdoqbisbwhmgpmeoke’);
//makeAnagram(‘showman’, ‘woman’);
//makeAnagram(‘cde’, ‘abc’);
// -----------------------------------------------------------------------------------------------
// Maximum occuring element in an array
// function maxOccur (arr) {
// const obj = {};
// let max = 0;
// let key = [];
// arr.forEach(ele => {
// if(obj[ele]) {
// obj[ele] += 1;
// } else {
// obj[ele] = 1;
// }
// });
// Object.keys(obj).forEach(item => {
// if(obj[item] > max) {
// max=obj[item];
// }
// });
// Object.keys(obj).forEach(item => {
// if(obj[item] === max) {
// key.push(item);
// }
// })
// console.log(‘-----’, obj, max, key);
// return key;
// }
//maxOccur([1,1,1,2,2,2,2,3,4,5,5,5]);
//maxOccur([‘a’,‘a’,‘f’,‘r’,‘e’,‘e’,‘e’,‘e’,‘w’,‘w’,‘w’]);
/* String Question 2 */
// Delete matching adjcent characters
// SOLUTION 1
// function alternatingCharacters(s) {
// let str = s.slice(0).split(‘’);
// let len = s.length;
// let extra = [];
//SOLUTION 2
// function alternatingCharacters (s) {
// let c=0;
// const len = s.length;
/* String Question 3 */
// Remove only one char to make letters of equal frequency
//aabbccddeefghi
//{‘a’: 2, ‘b’: 2, ‘c’: 2, ‘d’: 2, ‘e’: 2, ‘f’: 1, ‘g’: 1, ‘h’: 1, ‘i’: 1}
// Return YES if it is valid and NO if it is not valid
// function isValid(s) {
// const freq = {};
// let len = s.length;
// for(let i=0; i<len; i++) {
// if(freq[s[i]]) {
// freq[s[i]] += 1;
// } else {
// freq[s[i]] = 1;
// }
// }
//isValid(‘aabbccddeefghi’); //NO
//isValid(‘aaabbcc’); //YES
//isValid(‘abcdefghhgfedecba’); //YES
//isValid(‘xxxaabbccrry’);//NO
//
isValid(‘ibfdgaeadiaefgbhbdghhhbgdfgeiccbiehhfcggchgghadhdhagfbahhddgghbdehidbibaeaag
aeeigffcebfbaieggabcfbiiedcabfihchdfabifahcbhagccbdfifhghcadfiadeeaheeddddiecaicbgigccage
icehfdhdgafaddhffadigfhhcaedcedecafeacbdacgfgfeeibgaiffdehigebhhehiaahfidibccdcdagifgaiha
cihadecgifihbebffebdfbchbgigeccahgihbcbcaggebaaafgfedbfgagfediddghdgbgehhhifhgcedechah
idcbchebheihaadbbbiaiccededchdagfhccfdefigfibifabeiaccghcegfbcghaefifbachebaacbhbfgfddec
eababbacgffbagidebeadfihaefefegbghgddbbgddeehgfbhafbccidebgehifafgbghafacgfdccgifdcbbb
idfifhdaibgigebigaedeaaiadegfefbhacgddhchgcbgcaeaieiegiffchbgbebgbehbbfcebciiagacaiechdi
gbgbghefcahgbhfibhedaeeiffebdiabcifgccdefabccdghehfibfiifdaicfedagahhdcbhbicdgibgcedieihci
chadgchgbdcdagaihebbabhibcihicadgadfcihdheefbhffiageddhgahaidfdhhdbgciiaciegchiiebfbcbh
aeagccfhbfhaddagnfieihghfbaggiffbbfbecgaiiidccdceadbbdfgigibgcgchafccdchgifdeieicbaididhfcf
dedbhaadedfageigfdehgcdaecaebebebfcieaecfagfdieaefdiedbcadchabhebgehiidfcgahcdhcdhgc
hhiiheffiifeegcfdgbdeffhgeghdfhbfbifgidcafbfcd’);
/* String Question 4 */
// Getting all substrings
// Given string s=‘mnonopoo’
// All posible substrings {m,n,o,n,o,p,o,o,non,ono,opo,oo}
// S1=‘aaaa’
// substrings = {a,a,a,a,aa,aa,aa,aaa,aaa,aaaa}
// s2=‘abcbaba’
// substrings = {a,b,c,b,a,b,a,bcb,bab,aba}
// substrings are accepted only if all chars are same or only middle char is different
// function substrCount(n, s) {
// let arr = [];
// let i=2;
// while(i <= n) {
// for(let j=0; j<=n-i; j++) {
// console.log(“1st”, i, j);
// if(i <= 3 && s[j] === s[j+(i-1)]) {
// arr.push(s.substr(j, i));
// }
// if(i > 3) {
// let len = parseInt(i/2);
// let chlen = [...new Set(s.substr(j, len))].join().length;
// if(chlen === 1 && [...new Set(s.substr(j, len))].join() === [...new Set(s.substr(len+1,
len))].join()) {
// arr.push(s.substr(j, i))
// }
// }
// }
// i++;
// }
// console.log(“result”, arr, n+arr.length);
// return n+arr.length;
// }
/* PYTHON SOLUTION
def substrCount(n, s):
count = len(s)
for i, char in enumerate(s):
diff_char_idx = None
for j in range(i+1, n):
if char == s[j]:
if diff_char_idx is None:
count +=1
elif j - diff_char_idx == diff_char_idx - i:
count += 1
break
else:
if diff_char_idx is None:
diff_char_idx = j
else:
break
return count
*/
//substrCount(7, ‘abcbaba’);
//substrCount(4, ‘aaaa’);
//substrCount(8, ‘mnonopoo’);
// --------------------------------------------------------------------
/* String question 5 */
// Find the common substring which is a child of both s1 and s2 string
// you can’t rearrange the characters
// Return the length of the string
// Both string is of equal lenght
// s1=“HARRY”, s2=“SALLY” common=“AY”
//s1=“ABCD”, s2=“ABDC” common=“ABC” or “ABD”
//commonChild(“ABCD”, “ABDC”);
//commonChild(“HARRY”, “SALLY”);
//commonChild(“SHINCHAN”, “NOHARAAA”);
//commonChild(“NOHARAAA”, “SHINCHAN”);
// ------------------------------------------------------
// Counting valleys
// UDDDUDUU only count consecutive down (i.e. valleys)
// A mountain is a sequence of consecutive steps above sea level, starting with a step up from
sea level and ending with a step down to sea level.
// A valley is a sequence of consecutive steps below sea level, starting with a step down from
sea level and ending with a step up to sea level.
// function countingValleys(steps, path) {
// let sum = 0;
// let count = 0;
// for(let i=0; i<steps; i++){
// if(path[i]==‘U’){
// if(++sum==0) count++;
// }
// else sum--;
// console.log(“--sum”, sum, count);
// }
// return count;
// }
//countingValleys(8, ‘UDDDUDUU’) //1
//countingValleys(8, ‘DDUUUUDD’) //1
//countingValleys(12, ‘DDUUDDUDUUUD’) //2
// --------------------------------------------------------------
// function loadDoc() {
// var x
// xhttp.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200) {
// console.log(this.responseText);
// }
// };
// xhttp.open(“GET”, “https://restcountries.eu/rest/v2/all”, true);
// xhttp.send();
// }
// axios.get(‘https://jsonmock.hackerrank.com/api/football_matches?
year=2011&team2=Barcelona&page=1’, { httpsAgent: agent })
// .then(res => console.log(res));
// }
// function callback1(data) {
// console.log(JSON.parse(“1”, data));
// }
// function callback2(data) {
// console.log(JSON.parse(“2", data));
// }
//totalGoals();
//
// Observe the following:
// Each letter is printed on a new line.
// Then the vowels are printed in the same order as they appeared in .
// Then the consonants are printed in the same order as they appeared in .
//javascriptloops
// function vowelsAndConsonants(s) {
// const str = s.split(‘’);
// const vowel = {a:1, e:1, i:1, o:1, u:1};
// const len = str.length;
// let v=[];
// let c=[];
// let finalStr=[];
// for(let i=0; i<len; i++) {
// if(vowel[str[i]]) {
// v.push(str[i]);
// }
// else {
// c.push(str[i]);
// }
// }
// finalStr = v.concat(c);
// for(let i=0; i<len; i++) {
// console.log(finalStr[i]);
// }
// }
// vowelsAndConsonants(‘javascriptloops’)
/*
* Declare a RegExp object variable named ‘re’
* It must match a string that starts and ends with the same vowel (i.e., {a, e, i, o, u})
*/
//const re = new RegExp(/^([aeiou]).*\1$/);
// function area() {
// return this.w*this.h;
// }
// console.log(lime.getInformation());
// lime.color = ‘yellow’;
// console.log(lime.getInformation());
// console.log(lime.getInformation());
// lime.color = ‘yellow’;
// console.log(lime.getInformation());
We define a class’ static methods using the static keyword. We typically use these methods to
create utility functions for applications, as they can’t be called on class objects.*/
// ‘use strict’;
// class Point {
// constructor(x, y) {
// this.x = x;
// this.y = y;
// }
// static distance(a, b) {
// const dx = a.x - b.x;
// const dy = a.y - b.y;
// return Math.sqrt(dx * dx + dy * dy);
// }
// }
// const p1 = new Point(5, 5);
// const p2 = new Point(10, 10);
/------------HOISTING---------------/
//salary();
//var amount=‘$30000’;
// function salary(){
// console.log(“My first salary: “, amount);
// var amount = ‘$50000’;
// console.log(“My second salary: “, amount);
// }
/------------------Closures-----------------------/
// function currying(a) {
// return function(b) {
// return function(c) {
// return function(d) {
// return a+b+c+d;
// }
// }
// }
// }
// console.log(currying(1)(2)(3)(4));
// Memoization
// function sum() {
// const obj = {};
// return function(a,b){
// key=${a}${b};
// if(obj[key]) {
// console.log(“Not calculating”);
// return obj[key];
// } else {
// obj[key] = a+b;
// console.log(“Calculating”);
// return a+b;
// }
// }
// }
// Includes both case same order and rev order of parameter, it will not do the calculation
// function sum() {
// const obj = {};
// return function(a,b){
// key=${a}${b};
// keyR=${b}${a};
// if(obj[key] && obj[keyR]) {
// console.log(“Not calculating”);
// return obj[key];
// } else {
// obj[key] = a+b;
// obj[keyR] = a+b;
// console.log(“Calculating”);
// return a+b;
// }
// }
// }
// const s = sum();
// console.log(s(1,2));
// console.log(s(3,4));
// console.log(s(1,2));
// console.log(s(2,1));
// console.log(s(4,3));
// console.log(s(4,4));
/*--
Print from 10 to 1 without any loops only using setTimeout with 1 second delay each
--*/
// Recursive function
// function delay(count) {
// setTimeout(()=>{
// if(count>0) {
// console.log(count);
// count -= 1;
// delay(count);
// }
// return;
// },1000);
// }
// delay(10);
//delay(5);
/*-----
Print from 10 to 1 with for loop with 1 second delay each
-----*/
// function forLoopDelay(count) {
// let c=1;
// for(let i=count; i>=1; i--) {
// setTimeout(()=>{
// console.log(i)
// }, c*1000);
// c++;
// }
// }
//forLoopDelay(5);
//forLoopDelay(10);
/*-----
Given an array of numbers ranging from -1000 to 1000 and array size can be in millions, find
first 3 numbers which will sum up to 0
-----*/
// function firstThree(arr) {
// const len = arr.length;
// const result = [];
// for (let i=0; i<3; i++){
// result.push(${arr[i]},${arr[len-i-1]});
// }
// return result.join(‘/’);
// }
//console.log(firstThree([-5,-4,-3,-2,-1,0,1,2,3,4,5]));
/*------
Given string A has length of million characters and string B has length of 256 and characters of
string B are non repetitive, find out if the substring B is present in any kind of order in string A,
but it has to be consecutive.
-------*/
// For eg:
// A = ‘awesomethingsarethereintheworld’ B = ‘lord’;
// At the end of the A string we can see ‘orld’ which can be a form of string B ‘lord
// function matchSubStr(strA, strB) {
// const len = strA.slice(0).length;
// let a = ‘’;
// let result = ‘’;
// for (let i=0; i<len; i++) {
// if(strB.includes(strA[i])) {
// a = a.concat(strA[i]);
// }
// }
// result = [...new Set(a.split(‘’).sort())].join(‘’);
// if (result === strB.split(‘’).sort().join(‘’)) {
// return ‘YES’
// }
// return ‘NO’;
// }
//console.log(matchSubStr(‘lloorrdd’, ‘lord’));
//console.log(matchSubStr(‘awesomethingsarethereintheworld’, ‘lord’));
//console.log(matchSubStr(‘abcdefgh’, ‘xyz’));
/*------
Finding factorial of a number
-------*/
// function factorial(n) {
// if(n==0) {
// return 1;
// }
// return n*factorial(n-1);
// }
//console.log(factorial(5));
//console.log(factorial(0));
//console.log(factorial(1));
/*-----
Fibonacci series (i.e. 0,1,1,2,3,5,8,13,21)
------*/
// function fibonacci(count) {
// let next = 1;
// let arr = [0,1];
// for(let i=2; i<count; i++){
// next = arr[i-2]+arr[i-1];
// arr.push(next);
// }
// console.log(arr.join(‘,’));
// }
// fibonacci(9);