Programming
Programming
console.log(output);
Above code will output 0 as output. delete operator is used to delete a property
from an object. Here x is not an object it's local variable. delete operator doesn't
affect local variable.
2.
var Employee = {
company: 'xyz'
}
delete emp1.company
console.log('After', emp1.company);
o Above code will output xyz as output. Here emp1 object got company as
prototype property. delete operator doesn't delete prototype property.
o emp1 object doesn't have company as its own property.
o console.log(emp1.hasOwnProperty('company')); //false
3.
(function(){
var a = b = 3;
})();
o Since both a and b are defined within the enclosing scope of the function,
and since the line they are on begins with the var keyword,
o But in fact, var a = b = 3;
4. Consider the two functions below. Will they both return the same thing?
Why or why not?
function foo1(){
return {
bar: "hello"
};
}
function foo2(){
return
{
bar: "hello"
};
}
console.log("foo1 returns:",foo1());
console.log("foo2 returns:",foo2());
As a result, when the line containing the return statement (with nothing else on the
line) is encountered in foo2(), a semicolon is automatically inserted immediately
after the return statement.
5. Write a sum method which will work properly when invoked using either
syntax below.
function sum(x, y) {
if (y !== undefined) {
return x + y;
} else {
return function(y) { return x + y; };
}
}
console.log(sum(2,3));
console.log(sum(2)(3));
6. The following recursive code will cause a stack overflow if the array list is
too large. How can you fix this and still retain the recursive pattern?
var list = readHugeList();
var nextListItem = function() {
var item = list.pop();
if (item) {
// process the list item...
nextListItem();
}
};
The stack overflow is eliminated because the event loop handles the recursion, not
the call stack. When nextListItem runs, if item is not null, the timeout function
(nextListItem) is pushed to the event queue and the function exits, thereby leaving
the call stack clear. When the event queue runs its timed-out event, the next item is
processed and a timer is set to again invoke nextListItem. Accordingly, the method
is processed from start to finish without a direct recursive call, so the call stack
remains clear, regardless of the number of iterations.
7.
//1
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
//2
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
Each function executed within the loop will be executed after the entire loop has
completed and so reference the last value stored in i.
Closures can be used to prevent this problem by creating a unique scope for each
iteration, storing each unique value of the variable within its scope, as follows:
var a={},
b={key:'b'},
c={key:'c'};
a[b]=123;
a[c]=456;
console.log(a[b]);
JavaScript will implicitly stringify the parameter value. In this case, since b and c
are both objects, they will both be converted to "[object object]". As a result, a[b]
and a[c] are both equivalent to a["[object object]"] and can be used
interchangeably. Therefore, referencing a[c] is same as referencing a[b].
a closure is a function, along with all variables or functions that were in-scope at
the time that the closure was created. In JavaScript, a closure is implemented as an
“inner function”; An important feature of closures is that an inner function still has
access to the outer function’s variables.
foo();
console.log(typeof a);
console.log(typeof b);
let a = b = 0; //declares a
is local variable and b is global variable.
console.log(clothes[0]);
//undefined
console.log(numbers);
12. Clousers
let i;
for (i = 0; i < 3; i++) {
const log = () => {
console.log(i);
}
setTimeout(log, 100);
}
13. What happens if you access myVar and myConst before declaration
const variables are in a temporal dead zone until the declaration line const
myConst = 3.14.
console.log(myVar);
console.log(myConst);
14.
o In the outer function, both this and self refer to myObject and therefore
both can properly reference and access foo.
o In the inner function, this no longer refers to myObject. As a result,
this.foo is undefined in the inner function, whereas the reference to the
local variable self remains in scope and is accessible there.
var myObject = {
foo: "bar",
func: function () {
var self = this;
console.log("outer func" + this.foo);
console.log("outer func" + self.foo);
(function () {
console.log("inner func" + this.foo);
console.log("inner func" + self.foo);
}());
}
};
myObject.func();
15. How to check if an object is an array or not
console.log(Array.isArray(v1));
// false
console.log(Array.isArray(v2));
// true
arr.forEach(el => {
count[el] = count[el] ? (count[el] += 1) : 1
})
console.log(count)
The hasOwnProperty() is used to check whether the object has the specified
property as its own property. It returns a boolean value indicating whether the
object has the given property as its own property.
function unique(arr) {
var count = {};
return arr.filter((item) => {
return count.hasOwnProperty(item) ? false :
(count[item] = true);
});
}
console.log(unique([2, 3, 4, 3, 2, 5]));
console.log(arr)
console.log(arr)
delete obj.name;
console.log(obj);
arr.splice(2, 0, 7);
console.log(arr.join());
23. Checking if a key exists in a JavaScript object
const car = {
color: 'blue'
}
obj = car.hasOwnProperty('color')
console.log(obj)
24.
console.log(1 + "2" + "2");
console.log(1 + +"2" + "2");
console.log(1 + -"1" + "2");
console.log(+"1" + "1" + "2");
console.log("A" - "B" + "2");
console.log("A" - "B" + 2);
25.
console.log("0 || 1 = "+(0 || 1));
console.log("1 || 2 = "+(1 || 2));
console.log("0 && 1 = "+(0 && 1));
console.log("1 && 2 = "+(1 && 2));
26.
var x = 21;
var girl = function () {
console.log(x);
var x = 20;
};
girl();
27.
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
29.
typeof 1 will return "number" and typeof "number" will return string.
console.log(typeof typeof 1);
//string
console.log(typeof NaN);
//number
30. Which operator returns true if the two compared values are not equal?
console.log("~", ~3,~2+ "<>", 1<2>3 ,"==!", 3==!2 ,"!==",
3!==2) //!==
console.log([] == [])
//false
console.log([...arr1, ...arr2]);
//[2, 4, 6, 3, 5, 7]
44.
const fun = ({ a, b, c }) => {
console.log(a, b, c);
};
fun(0, 1, 2);
//undefined undefined undefined
//
x = 3;
console.log(x);
var x;
45.
var x = 0;
var y = 23;
//2
console.log(typeof typeof 12)
console.log(typeof NaN)
47.
let arr=[{id:1, name:'Krishana'},{id:2, name:'Ram'}]
function add(obj,index){
obj[index].name = obj[index].name
console.log('obj[index] ', obj[index].name)
console.log('obj', obj)
}
add(arr, 1)
console.log('arr', arr)
o Using backticks
o Using + operator
o Using \ (backslash)
const string = “line1” +
“line2” +
“line3”;
//
const string = “line1 line2 line3”;
52.
const courses = ["JavaScript","Java","C","C++","Python"];
delete courses[2];
console.log(courses);
console.log(courses.length);
The delete operator does not really affect the entire length of the array as the
operates removes only the value which is there at the position.
53.
function test1(name) {
var a = name;
function test2() {
console.log(this.a);
}
test2();
}
test1("John");
54.
console.log(1);
Promise.resolve().then(
console.log(2)
);
setTimeout(function () {
console.log(3)
}, 10);
Promise.resolve().then(
console.log(4)
);
Promise.resolve().then(
setTimeout(function () {
console.log(5)
}, 10)
);
console.log(6);
// 1,6,2,4,5,3
55. Star
Time Complexity:
o The inner loop runs 1 time for the first iteration of the outer loop, 2
times for the second iteration, and 3 times for the third iteration.
o The function would be O(n^2) if the inner for loop iterated n+1 times,
and the outer for loop iterated n times. In this case, the total number of
iterations would be n * (n+1) = n^2 + n. This is also a quadratic time
complexity.
o So, the function is similar to O(n^2), but it is not strictly O(n^2). The
difference is that the function's runtime is dependent on the constant 3,
instead of the input size n. However, for most practical purposes, the
difference is negligible.
Space Complexity:
o For each iteration of the inner loop, we add one star character to the
start variable.
o For each iteration of the outer loop, we add a newline character to the
start variable.
o Therefore, the space complexity is directly proportional to the number
of stars and newlines produced, which is 3 lines with 1, 2, and 3 stars,
respectively. So the space complexity of the star() function can be
considered as O(1) or constant space complexity.
newLine =
// *
// **
// ***
function star(){
var start="";
for(let i=0; i<3; i++){
for(let j=1; j<=(i+1); j++){
start += "*"
}
start +="newLine";
}
console.log(start);
}
star();
// *
// **
// ***
function star(){
let n = 3;
let str = "";
for (let i = 1; i <= n; i++){
for (let j=0; j<(n-i); j++){
str += " ";
}
for (let k=0; k<i; k++){
str += "*";
}
str += "newLine";
}
console.log(str);
}
star();
// ***
// **
// *
function star(){
var start="";
for(let i=3; i>0; i--){
for(let j=(i+1); j>1; j--){
start += "*"
}
start +="newLine";
}
console.log(start);
}
star();
// ***
// **
// *
function star(){
let n = 3;
let str = "";
for (let i = n; i >= 1; i--){
for (let j=0; j<(n-i); j++){
str += " ";
}
for (let k=0; k<i; k++){
str += "*";
}
str += "newLine";
}
console.log(str);
}
star();
56. Pyramind
// Upside pyramid.
function pyraminds() {
let i, j, k, str = "";
str += 'newLine';
}
console.log(str)
}
pyraminds();
// downside pyramid.
for (i=1; i<5; i++) {
for (j=0; j<i; j++) {
str += " ";
}
for (k=(5 - i)*2; k>1; k--) {
str += "*";
}
str += 'newLine';
}
console.log(str)
57. Pattern
let i,j, str="";
//Square pattern.
for(i=1; i<=5; i++){
for(j=0; j<5; j++){
str += "*";
}
str += "newLine";
}
console.log(str);
console.log(str);
o In simple words, the arm() function takes a linear amount of time to run,
and it uses a constant amount of space.
o The time complexity is O(n) because the while loop iterates n times.
This is the worst-case scenario, where the input number is a three-digit
number with all the digits equal to 9.
function arm() {
const num = prompt('Enter a three-digit positive
integer: ');
let sum=0, remainder=0;
let temp=num;
while(temp>0){
remainder = temp%10;
sum += remainder*remainder*remainder;
temp = parseInt(temp/10)
}
if(sum == num){
console.log('Armstrong', num);
}
else{
console.log('Not an Armstrong', num);
}
}
arm()
59. Permutations
o In simple words, the arm() function takes a cubic amount of time to run,
and it uses a quadratic amount of space.
o The space complexity is O(n^2) because the result array can contain up
to n^2 elements. However, the actual space complexity is likely to be
lower, because the result array will only contain unique strings.
function arm(str){
let currentChar = [];
let remaingChar = [];
let result = [];
console.log(arm('abc'));
60. Given an amount of money, return the minimum number of coins needed
to make that change.
o The time complexity of the minCoin() function is O(ks), where k is the
amount of money and s is the number of coins. This is because the
while loop iterates at most k times, and each iteration takes constant
time.
o The time complexity of the arr.sort() method in JavaScript is O(n log n),
where n is the length of the array. This is because the arr.sort() method
uses the Timsort algorithm, which is a hybrid of merge sort and
insertion sort. Merge sort has a time complexity of O(n log n), and
insertion sort has a time complexity of O(n^2). The Timsort algorithm
uses merge sort for large arrays, and insertion sort for small arrays.
62:
//2
Time complexity: O(n^2)
Space complexity: O(n)
function minCoin() {
const arr = [3, 5, 1, 9, 6, 2, 1, -1];
const result = [];
minCoin();
while(left.length) result.push(left.shift());
while(right.length) result.push(right.shift());
console.log(result)
return result;
}
mergeSort([3,2,1])
temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
console.log(arr)
return arr;
}
selectionSort([7,5,2,4,3,9]);
66. Write a function which loops through an array and checks if n of the
elements of the array satisfy the condition function that is passed
function isEven(num) {
return num % 2 === 0;
}
function isPrime(num) {
if (num < 2) {
return false;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
// Function to loop through an array and check if n
elements satisfy the condition function
function some(array, n, isCheck) {
let count = 0;
for (let i = 0; i < array.length; i++) {
if (isCheck(array[i])) {
count++;
}
if (count === n) {
return true;
}
}
return false;
}
return function() {
const result = a;
const next = a + b;
a = b;
b = next;
return result;
};
}
o Time complexity: O(n), where n is the length of the string str. This is
because the split() method iterates over the string str once, and the
reverse() method iterates over the array of characters once.
o Space complexity: O(n), where n is the length of the string str. This is
because the split() method creates a new array of characters, and the
reverse() method stores the reversed array of characters.
o In simple words, the code takes a linear amount of time to run, and it
uses a linear amount of space.
console.log(reverseWords)
// Linked List
function reverse() {
let prev = null;
let current = head;
let next = null;
while (current) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
return { append, reverse };
}
console.log(list.reverse());
o Time complexity: O(n), where n is the length of the string str. This is
because the split() method iterates over the string str once, and the new
Set() method iterates over the array of words once.
o Space complexity: O(n), where n is the length of the string str. This is
because the new Set() method creates a new set that can store up to n
elements.
for(let i=0;i<arr.length;i++){
if(result.includes(arr[i])){
result.pop()
}else{
result.push(arr[i])
}
}
console.log(result.join(''))
}
fun() // O(n^2)
//2
function unique(){
let str="Java is great Grails is also great";
let uniqueStr = str.split(' ');
unique();
//3
function fun(){
let str="Reverse Words in a String Reverse Words
in".split(' ');
let hash={};
fun()
// Linked list
function unique() {
let current = head;
let uniqeChar = '';
while (current) {
let isUnique = true;
let runner = head;
current = current.next;
}
return uniqeChar;
}
console.log(list.unique());
Duplicate Character
function fun(){
const arr='apple'.split('')
let result=[]
for(let i=0;i<arr.length;i++){
let count=0;
for(let j=i+1;j<arr.length;j++){
if(arr[i]==arr[j]){
count +=1;
}
}
if(count >=1){
result.push(arr[i])
}
}
console.log(result.join(''))
}
fun()
// Linked list
function duplicatesCh() {
let current = head;
let duplicates = '';
const result = {};
while (current) {
if (result[current.value]) {
if (!duplicates.includes(current.value)) {
duplicates += current.value;
}
} else {
result[current.value] = true;
}
current = current.next;
}
return duplicates;
}
console.log(list.duplicatesCh());
o Time: O(n), where n is the length of the string str. This is because the
split() method iterates over the string str once, and the for loop iterates
over the array newStr once.
o Space: O(n), where n is the length of the string str. This is because the
result array can store up to n elements.
2:
o Time: O(n^2), where n is the length of the string str. This is because the
for loop iterates over the string str twice, and each iteration of the inner
for loop takes constant time.
o Space: O(n), where n is the length of the string str. This is because the
result variable can store up to n characters.
function unique(){
let str="Java is great Grails is also great Grails is
also great";
let newStr = str.split(' ');
const result = [];
unique();
o Time: O(n), where n is the length of the string str. This is because the
for loop iterates over the string str once, and the indexOf() method
takes constant time.
o Space: O(1), where n is the length of the string str. This is because the
vowelList variable is a constant, and the vowels variable can store up to
5 characters.
function fun(){
const str='apple';
const vowel='aeiou';
let result='';
for(let i=0;i<str.length;i++){
if(vowel.includes(str.charAt(i))){
result += str.charAt(i)
}
}
console.log(result)
}
fun()
// Linked List
function vowels() {
let str = head;
const vowel = 'aeiouAEIOU';
let result = '';
while (str) {
if (vowel.includes(str.value)) {
result += str.value;
}
str = str.next;
}
console.log(result);
}
list.vowels();
Input: 121
function palindromNum(){
let num=121, result=0;
let temp=num;
while(temp>0){
result = result*10 + temp%10;
temp=Math.floor(temp/10);
}
if(result==num) console.log('Palindrom', result)
else{console.log('Not a Palindrom', result)}
}
palindromNum();
Note:
o The same word in the dictionary may be reused multiple times in the
segmentation.
o You may assume the dictionary does not contain duplicate words.
return console.log(result);
}
fun()
removeDup();
o Time: O(n), where n is the length of the string str. This is because the
for loop iterates over the string str once, and the stack.push() and
stack.pop() methods take constant time.
o Space: complexity: O(n), where n is the length of the string str. This is
because the stack variable can store up to n characters.
fun()
// Linked List
function fun() {
let str = head;
let result = '';
while (str) {
if (!result.includes(str.value)) {
result += str.value;
}
str = str.next;
}
console.log(result);
}
list.fun();
console.log(result);
}
lonStr();
console.log(currentStr);
}
longStr();
function fun() {
const str1 = 'egg';
const str2 = 'add';
return true;
}
console.log(fun());
Break
79. Word Ladder.
Given two words (beginWord and endWord), and a dictionary's word list, find
the length of shortest transformation sequence from beginWord to endWord,
such that:
Note:
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
let count = 1
while (current.length > 0) {
const next = []
for (const word of current) {
if (word === endWord) {
return count
}
if (!visited[word]) {
next.push(...wordList.filter(word2 =>
distance(word, word2) && !visited[word2]))
}
visited[word] = true
}
count += 1
current = next
}
return 0
}
console.log(ladderLength("hit", "cog",
["hot","dot","dog","lot","log","cog"]))
Output: [
["aa","b"],
["a","a","b"] ]
function partition(s = ''){
function isPalindrome(left, right){
if (left === right) return true;
const result = []
function aux(index = 0, current = []){
if (index === s.length) {
result.push(current)
}
for (let i = index; i < s.length; i++) {
if (isPalindrome(index, i)) {
aux(i + 1, [...current, s.substring(index, i +
1)])
}
}
}
aux()
return result
}
console.log(partition("aab"))
memo[left] = memo[left] || {}
if (memo[left][right] !== undefined) {
return memo[left][right]
}
if (isPalindrome(left, right)) {
return s.substring(left, right + 1)
}
memo[left][right] = aux(left + 1, right).length >
aux(left, right - 1).length
? aux(left + 1, right) : aux(left, right - 1)
return memo[left][right]
}
return aux(0, s.length - 1)
}
console.log(longestPalindrome("babad"))
for(let i=0;i<arr.length;i++){
if(arr2.includes(arr[i]) && (arr3.includes(arr[i]))){
result.push(arr[i])
}
}
console.log(result);
}
fun()
// Linked List
function fun(list1, list2, list3) {
let currentNode1 = list1.head;
console.log("Common Digit:", list1.head);
while (currentNode1) {
const digit = currentNode1.value;
currentNode1 = currentNode1.next;
}
}
list.print();
list2.print();
list3.print();
fun(list, list2, list3);
83. Sort
let i, j, arr=[0,9,8,7,6];
var max=0;
console.log(arr);
//Greatest Product Of 3
max = arr[arr.length-1] * arr[arr.length-2] *
arr[arr.length-3]
console.log(max);
//optimsed
const arr = [0, 9, 8, 7, 6];
arr.sort((a, b) => a - b);
console.log(arr);
// 2. Linked List
function sorts(){
let current=head;
let temp;
while(current.next){
if(current.value>current.next.value){
temp=current.value;
current.value=current.next.value;
current.next.value=temp;
}
current=current.next;
}
}
o Time: O(n^2), where n is the length of the array arr. This is because the
for loop iterates over the array arr twice, and the inner for loop iterates
over the array arr once.
o Space: O(1), where n is the length of the array arr. This is because the
algorithm only uses the variables i, j, temp, and arr.
o In simple words, the code takes a quadratic amount of time to run, and
it uses a constant amount of space.
console.log(result)
}
removeDup();
// 2. Linked List
function unique(){
let current=head;
console.log(containsDuplicate([1,2,3,1]))
o Time: O(n), where n is the length of the array nums. This is because the
for loop iterates over the array nums once, and the map[num] lookup
takes constant time.
o Space: O(n), where n is the length of the array nums. This is because the
map object can store up to n keys.
compare();
//Unique name
function getUnique(){
var names = ["John", "Peter", "Clark", "Harry", "John",
"Alice"];
var newName = [];
getUnique();
for(let i=0;i<arr.length;i++){
result.push(arr[i]*arr[i])
}
console.log(result)
}
fun()
console.log(hash);
}
fun();
o Time: O(n), where n is the length of the array arr. This is because the for
loop iterates over the array arr once, and the hash[arr[i]] lookup takes
constant time.
o Space: O(n), where n is the length of the array arr. This is because the
hash object can store up to n keys.
o In simple words, the function fun() takes a linear amount of time to run,
and it uses a linear amount of space.
hash[num] = num;
}
return console.log(result);
}
fun();
console.log(result);
console.log(num);
console.log(str);
pattern123();
combinationSum();
// 2 Linked List
function fun() {
let current1 = head;
while (current1) {
let current2 = current1.next;
while (current2) {
if (current1.value + current2.value === 7) {
console.log('('$'{current1.value},'$'{current2.value})');
}
current2 = current2.next;
}
current1 = current1.next;
}
}
list.fun();
fun();
// 2 Linked List
function fun(target) {
while (head !== null && head.value === target) {
head = head.next;
}
list.print();
list.fun(2);
list.print();
const index=arr.indexOf(num)
arr.splice(index,1,newnum)
console.log(arr)
}
fun();
for(let i=0;i<arr.length;i++){
const j = Math.floor(Math.random() * (i + 1));
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
console.log(arr);
}
fun();
if (result.length % 2){
arrMedian=result[half];
}
else{
arrMedian=((result[half] + result[half-1])/2);
}
return console.log(arrMedian);
}
median()
result.pop();
result.push(result2);
console.log(result)
}
plusOne();
result -= exactsum;
console.log('Missing Number', result)
}
missNum();
console.log(missing);
function fun(){
for(let i=0;i<objs.length;i++){
for(let j=i;j<objs.length;j++){
if(objs[i].first>objs[j].first){
let temp=objs[i];
objs[i]=objs[j];
objs[j]=temp;
}
}
console.log(objs[i])
}
}
fun()
//2
function compare(a, b) {
if (a.first < b.first){
return -1;
}
if (a.first > b.first){
return 1;
}
return 0;
}
function fun(){
const result = arr1[0].name.concat(arr2[1].age);
console.log(result)
}
fun();
function fun() {
const nums = [5, 7, 7, 8, 8, 10];
const target = 8;
const result = [];
return result;
}
console.log(fun());
for(let i=0;i<arr.length;i++){
maxReach = Math.max(maxReach, arr[i])
if(i>maxReach){
console.log('false')
}
else if(maxReach>arr.length-1){
console.log('true')
}
}
}
fun()
fun();
fun();
function fun(){
const arr = [5,2,6,1];
const result = arr.map(() => 0);
for(let i=0;i<arr.length;i++){
for(let j=(i+1);j<arr.length;j++){
if(arr[i]>arr[j]){
result[i] +=1;
}
}
}
console.log(result)
}
fun()
for(let i=0;i<arr.length;i++){
if(arr[i]<=0){
sum=0
}else{
sum +=arr[i];
result=Math.max(result,sum)
}
}
console.log(result)
}
fun()
for(let i=0;i<arr.length;i++){
if(arr[i]<=0){
sum=1
}else{
sum *=arr[i];
result=Math.max(result,sum)
}
}
console.log(result)
}
fun()
let count = 0;
for (const bulb of result) {
if (bulb) {
count++;
}
}
return count;
}
console.log(fun());
return arr;
}
return count;
}
113. UnluckyNo 13
"Unlucky 13" typically refers to a problem where you need to count the
number of elements in an array that are not equal to 13.
function fun() {
const n = 1000;
const arr = [];
// Fill the arr array with random numbers between 0 and
99
for (let i = 0; i < n; i++) {
arr.push(Math.floor(Math.random() * 100));
}
let count = 0;
console.log(count);
}
fun();
if (isNice) {
count++;
}
}
return count;
}
if (!Array.isArray(nestedArr)) {
maxDepth = Math.max(maxDepth, depth);
// If it's not an array, it's the end of a branch
} else {
for (const element of nestedArr) {
//push its elements to the stack with increased depth
stack.push({ nestedArr: element, depth: depth + 1
});
}
}
}
console.log(maxDepth);
}
fun([[3]]);
fun([[[[[[[9]]]]]]]);
fun([]);
return result
}
console.log(summaryRanges([1,2,3,4,6,7,9]))
for(let i=0;i<=num;i++){
count +=i.toString().split('2').length-1
}
console.log(count);
}
fun();
// 2 Linked List
function fun() {
const num=19;
let count=0;
for(let i=0;i<=num;i++){
count +=i.toString().split('1').length-1
}
console.log(count);
}
118. Factorial
function factorial(n){
if(n === 1) return 1;
return n * factorial(n-1)
}
console.log(factorial(4));
119. Prime
function primes(){
const num=100;
const result=[];
let i,j;
if(count==0){
result.push(i);
}
}
console.log(result);
}
primes()
// 2 Linked List
function fun(){
const num=100;
const result=[];
let i,j;
if(count==0){
result.push(i);
}
}
console.log(result);
}
let newnum=num.toString().split('');
for(let i=0;i<newnum.length;i++){
sum += parseInt(newnum[i])
}
console.log(sum)
}
fun();
let newnum=num.toString().split('');
const index=newnum.indexOf(target)
newnum.splice(index,1)
console.log(newnum.join(''))
}
fun()
//Remove all 5.
function fun() {
let num = 915765;
const target = 5;
console.log(newnum.join(''));
}
fun();
remove();
function main(){
const result = Math.random(0, magicNum);
console.log(result);
}
main();
console.log(isInt(0));
console.log(numbers(12, 4));
console.log(numbers(9, 3));
result = Number(result)
console.log(result);
}
reverse(123)
num=Number(num)
num2=Number(num2)
product = num*num2;
console.log(product)
}
multiply();
fun();
fun()
console.log(myPow(2.00000, 10))
while(Y>X){
if(Y%2 === 0) {
Y /=2
}
else {
Y +=1
}
result +=1
}
console.log(result + X - Y);
}
brokenCalc()
function aux(n){
if (memo[n] !== undefined) return memo[n];
if (n===1 || n===2 || n===3 || n===5 || n===4) return
true;
if (n<5) return false;
isUgly();
while (b !== 0) {
carry = a & b
a ^= b
b = carry << 1
}
return a
}
console.log(getSum(5, 1))
arr.sort((a,b)=>a-b)
for (let i=0; i<arr.length-2; i++) {
result = arr[i] + arr[i+1] + arr[i+2];
}
return console.log(result)
}
fun()
1
11
121
1331
14641
function star(){
const numRows=5;
let result=[]
for (let i = 0; i < numRows; i++) {
const currentRow = [];
let num = 1; // The
first element in each row is always 1
result.push(currentRow);
}
console.log(result);
}
star();
return console.log(maxArea);
}
fun()
137. Combinations
Given two integers n and k, return all possible combinations of k numbers out
of 1 ... n.
You may return the answer in any order.
Example 1: Input: a = 2, b = 4
Output: [
[1,2],
[1,3],
[1,4],
[2,1],
[2,3],
[2,4],
]
function fun(){
let a=2,b=4;
const result=[];
for(let i=1;i<=a;i++){
for(let j=1;j<=b;j++){
if(i !==j){
result.push([i,j])
}
}
}
console.log(result)
}
fun()
nput: I[7,1,5,3,6,4]
Output: I5
Explanation: IBuy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1
= 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
function fun(){
const arr = [7,1,5,3,6,4];
let minVal=Math.min(...arr);
let maxVal=0;
let maxProfit=0;
let index=arr.indexOf(minVal)
for(let i=0;i<arr.length;i++){
if(i>index && maxVal< arr[i]){
maxVal=arr[i]
}
}
console.log(maxProfit)
}
fun()
return console.log(result);
}
fun();
console.log(max);
}
fun();
console.log(matrix);
}
fun();
let j = 0;
while (j < prevWord.length && j < currentWord.length)
{
const prevCharIndex = order.indexOf(prevWord[j]);
const currentCharIndex =
order.indexOf(currentWord[j]);
if (prevCharIndex < currentCharIndex) {
break; // Correct order, move
to the next pair of words
} else if (prevCharIndex > currentCharIndex) {
console.log('False'); // Incorrect order
return;
} else {
j++; // Characters are
equal, move to the next character
}
}
fun();
if (seen.has(rowKey) || seen.has(colKey) ||
seen.has(subgridKey)) {
return false; // Duplicate number found
}
seen.add(rowKey);
seen.add(colKey);
seen.add(subgridKey);
}
}
}
return true;
}
const sudokuBoard = [
['5','3','.','.','7','.','.','.','.'],
['6','.','.','1','9','5','.','.','.'],
['.','9','8','.','.','.','.','6','.'],
['8','.','.','.','6','.','.','.','3'],
['4','.','.','8','.','3','.','.','1'],
['7','.','.','.','2','.','.','.','6'],
['.','6','.','.','.','.','2','8','.'],
['.','.','.','4','1','9','.','.','5'],
['.','.','.','.','8','.','.','7','9']
];
const result = isValidSudoku(sudokuBoard);
console.log(result); // Output: true
return perimeter;
}
const grid = [
[0, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 0]
];
const result = islandPerimeter(grid);
console.log(result); // Output: 16
if (anagramGroups[sortedWord]) {
anagramGroups[sortedWord].push(word);
} else {
anagramGroups[sortedWord] = [word];
}
}
console.log(anagramGroups)
}
fun()
1.Adjacent cells C_i and C_i+1 are connected 8-directionally (ie., they
are different and share an edge or corner)
2.C_1 is at location (0, 0) (ie. has value grid[0][0])
3.C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1])
4.If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0).
o Return the length of the shortest such clear path from top-left to
bottom-right. If such a path does not exist, return -1.
grid[0][0] = 1
while (q.length) {
let curr = q.shift();
let i = curr & (1 << 7) - 1;
let j = curr >> 7;
console.log(shorPath([[0,0,0],[1,1,0],[1,1,0]]));
Output: [1,2,3,6,9,8,7,4,5]
function spiralOrder(matrix) {
let result = []
if(!matrix.length) return result;
let rowMin = 0
let rowMax = matrix.length -1
let columnMin = 0
let columnMax = matrix[0].length - 1
let i = 0
let j = 0
let direction = "right"
return result
};
console.log(spiralOrder([
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]))
Input: m = 7, n = 3
Output: 28
function uniquePaths(m, n){
const memo = {}
memo[rowIndex] = memo[rowIndex] || {}
memo[rowIndex][columnIndex] = aux(rowIndex + 1,
columnIndex) + aux(rowIndex, columnIndex + 1)
return memo[rowIndex][columnIndex]
}
return aux(0, 0)
}
console.log(uniquePaths(7,3))
let reminder = 0
const digits = longer.map((num1, index) => {
let res = parseInt(num1, 10) + reminder +
(parseInt(shorter[index], 10) ? parseInt(shorter[index],
10) : 0)
if (res >= 2) {
res -= 2
reminder = 1
} else {
reminder = 0
}
return res
})
if (reminder === 1) {
digits.push(reminder)
}
return digits.reverse().join('')
}
console.log(addBinary("1010", "1011"))
console.log(currMax)
}
fun()
fun()
152. Climbing Stairs.
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can
you climb to the top?
Example 1: Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2: Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
function fun(n) {
if (n <= 2) {
return n;
}
console.log(fun(3));
153. 24 Game.
You have 4 cards each containing a number from 1 to 9. You need to judge
whether they could operated through *, /, +, -, (, ) to get the value of 24.
Input: [4, 1, 8, 7]
Output: True
Explanation: (8-4) * (7-1) = 24
function fun() {
const arr=[4, 1, 8, 7];
let result=0;
const sum=24;
const operator = "+";
for(let i=0;i<arr.length;i++){
while(result<sum){
switch(operator){
case "+":
result += arr[i];
break;
case "-":
result -= arr[i];
break;
case "*":
result *= arr[i];
break;
case "/":
result /= arr[i];
break;
default:
console.log("Invalid operator");
return;
}
}
}
console.log(result)
}
fun()
console.log(destCity([["London","New York"],["New
York","Lima"],["Lima","Sao Paulo"]]))
155. Bulls and Cows.
You are playing the following Bulls and Cows game with your friend: You write
down a number and ask your friend to guess what the number is. Each time
your friend makes a guess, you provide a hint that indicates how many digits in
said guess match your secret number exactly in both digit and position (called
"bulls") and how many digits match the secret number but locate in the wrong
position (called "cows"). Your friend will use successive guesses and hints to
eventually derive the secret number.
Write a function to return a hint according to the secret number and friend's
guess, use A to indicate the bulls and B to indicate the cows.
Please note that both secret number and friend's guess may contain duplicate
digits.
nput: Isecret = "1807", guess = "7810"
Output: I"1A3B"
Explanation: I1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.
function getHint(secret, guess) {
const secretMap = {};
for(let c of secret) {
secretMap[c] = secretMap[c] || 0
secretMap[c] += 1
}
let bulls = 0;
let cows = 0;
let used = {};
console.log(getHint("1123", "0111"))
156. Iterative:
Iterative algorithms are algorithms that use loops to repeatedly execute a set
of instructions until a specific condition is met.
Advantages:
Disadvantages:
2. Recursion
Is a programming technique where a function calls itself to solve a problem.
Advantages:
3. Stack
Advantages:
Disadvantages:
o Limited Data Access: Stacks have limited access patterns; you can only
access the top element. This limitation can be a drawback for problems
that require random access to data.
o Additional Memory Overhead: Stacks consume memory for each
element pushed onto the stack. In situations with a large number of
stack operations, this can result in additional memory overhead.
4. Queue
Advantages:
Disadvantages:
5. Linked list
Advantages:
Disadvantages:
6. Hash table
Store key-value pairs.
Advantages:
Disadvantages:
o Collisions: Hash collisions occur when two different keys hash to the
same location in the table.
157. Find the longest common prefix string amongst an array of strings.
//Iterative
function fun(){
const arr=["flower","flow","flight"];
let result = arr[0];
for(let i=0;i<arr.length;i++){
while(arr[i].indexOf(result) !==0){
result = result.substring(0, result.length-1)
}
}
return console.log(result)
}
fun()
//Recursion
function fun(arr, index=0, result=arr[0]) {
if (index === arr.length) {
console.log(result);
return;
}
//Stack
function fun(arr) {
if (arr.length === 0) {
return "";
}
console.log(stack.join(""));
}
for(let i=0;i<arr.length;i++){
sum +=arr[i];
}
console.log(sum)
}
fun()
//Recursion
function fun(arr, index = 0) {
if (arr.length==index) return 0;
return arr[index] + fun(arr, index + 1);
}
console.log(fun([-1, 2, 1, -4]));
//Stack
function fun(arr) {
let stack = 0;
console.log(stack);
}
fun([-1, 2, 1, -4]);
//Queue
function fun(arr) {
let stack = 0;
console.log(stack);
}
fun([-1, 2, 1, -4]);
160. Close 3 sum equal to 1.
function fun() {
const nums = [-1, 3, 2, 5, 10, 4, -2];
const target = 1;
let closestSum = 0;
let closestTriplet = [];
nums.sort((a,b)=>a-b)
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
for (let k = j + 1; k < nums.length; k++) {
const currentSum = nums[i] + nums[j] + nums[k];
console.log(closestTriplet);
}
fun();
console.log(result);
}
fun();
//Hash table
function fun(digits) {
const arr = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z'],
};
const result = [];
fun('23');
console.log(result.join(''));
}
fun();
if (current.length === 2 * n) {
result.push(current);
} else {
if (open < n) {
stack.push([current + '(', open + 1, close]);
}
return console.log(result);
}
fun(3);