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

Programming

The document discusses JavaScript concepts like delete operator, prototype inheritance, scope, closures, recursion, event loop, implicit type coercion, operator precedence and more. Examples are provided to explain these concepts in detail.

Uploaded by

Mukesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Programming

The document discusses JavaScript concepts like delete operator, prototype inheritance, scope, closures, recursion, event loop, implicit type coercion, operator precedence and more. Examples are provided to explain these concepts in detail.

Uploaded by

Mukesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

1.

var output = (function(x) {


delete x;
return x;
})(0);

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'
}

var emp1 = Object.create(Employee);


console.log(emp1.company);

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;
})();

console.log("a defined? " + (typeof a !== 'undefined'));


//False
console.log("b defined? " + (typeof b !== 'undefined'));
//True

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].

console.log((function f(n){return ((n > 1) ? n * f(n-1) :


n)})(10));
8.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
console.log(fruits)

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.

9. Accidental global variable


function foo() {
let a = b = 0;
a++;
return a;
}

foo();
console.log(typeof a);
console.log(typeof b);

let a = b = 0; //declares a
is local variable and b is global variable.

o No variable b is declared neither in the foo() scope/ global scope. So


JavaScript interprets b = 0 expression aswindow.b = 0.
o So, b is a global variable created accidentally.

10. Array length property


Reducing the value of the length property has the side-effect of deleting own
array elements whose array index is between the old and new length values.
const clothes = ['jacket', 't-shirt'];
clothes.length = 0;

console.log(clothes[0]);
//undefined

o undefined, because clothes array has been emptied.

11. What is the content of numbers array


for() iterates 4 times over the null statement, ignoring the block that actually
pushes items to array.
const length = 4;
const numbers = [];
for (var i = 0; i < length; i++); {
numbers.push(i + 1);
}

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

var myVar = 'value';


const myConst = 3.14;

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

o isArray() method is used to check if an object is an array.


o Array.isArray() method returns true if an object is an array, otherwise
returns false.

var v1 = { name: "John", age: 18 };


var v2 = ["red", "green", "blue", "yellow"];

console.log(Array.isArray(v1));
// false
console.log(Array.isArray(v2));
// true

16. Occurence elements in the array


const arr = [1, 2, 3, 3, 2];
const count = {};

arr.forEach(el => {
count[el] = count[el] ? (count[el] += 1) : 1
})

console.log(count)

17. Find unque element in array (hasOwnProperty)

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

18. Group Elements


var people = [
{ sex: "Male", name: "Jeff" },
{ sex: "Female", name: "Megan" },
{ sex: "Male", name: "Taylor" },
{ sex: "Female", name: "Madison" }
];

function groupBy(list, key) {


return list.reduce((data, val) => {
(data[val[key]] = data[val[key]] || []).push(val);
return data;
}, {});
};

var groupedPeople = groupBy(people, "sex");


console.log(groupedPeople.Male);
console.log(groupedPeople.Female);

19. Make duplicate elements in an array


var arr = [1, 2, 3];
arr = arr.concat(arr);

console.log(arr)

20. Remove a specific item from an array


var arr = [1, 2, 3, 4, 5, 3]
var value = 2

arr = arr.filter((item) => {


return item !== value
})

console.log(arr)

21. Delete a property from an object


var obj = {
name: "Mukesh",
Address: "India",
pincode: 201306
};

delete obj.name;

console.log(obj);

22. Insert an element at specific place in Array


var arr = [1, 2, 3, 4, 5];

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.

o It’s because JavaScript initialization is not hoisted.


o Why doesn’t it show the global value of 21? The reason is that when
the function is executed, it checks that there’s a local x variable present
but doesn’t yet declare it, so it won’t look for global one.

var x = 21;
var girl = function () {
console.log(x);
var x = 20;
};
girl();

27.
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);

The second returns false because of how the engine works


regarding operator associativity for < and >. It compares
left to right, so 3 > 2 > 1 JavaScript translates to true
> 1. true has value 1, so it then compares 1 > 1, which
is false.
28.
var a = [1, 2, 3];
a[10] = 99;
console.log(a[6]);

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

31. How is a forEach statement different from a for statement?


A for statement is generic, but a forEach statement can be used only with an
array.
32. How does a function create a closure?
It returns a reference to a variable in its parent scope.
33. Which Object method returns an iterable that can be used to iterate over
the properties of an object?
Object.keys()
34. What will be logged to the console?
var a = ['dog', 'cat', 'hen'];
a[100] = 'fox';
console.log(a.length);
//101

35. Add operator.


console.log(0 && hi)
//0

36. Which variable is an implicit parameter for every function in JavaScript?


Arguments
37. What will the value of y be in this code:
const x = 6 % 2;
const y = x ? 'One' : 'Two';
console.log(y)
//Two

38. Which keyword is used to create an error?


throw
39. What is the result in the console of running this code?
function logThis() {
console.log(this);
//window
}
logThis();

40. What will this code log to the console?


const foo = [1, 2, 3];
const [n] = foo;
console.log(n);
//1s

41. What does this code do?


const arr1 = [2, 4, 6];
const arr2 = [3, 5, 7];

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

42. Upon encountering empty statements, what does the Javascript


Interpreter do?
Ignores the statements.
43. What will be the output of the following code snippet?
var a = Math.max() < Math.min();
var b = Math.max() > Math.min();
console.log(a)
//true
console.log(b)
//false

console.log(NaN === NaN)


//false
console.log(typeof(NaN))
//number
console.log(parseInt("123Hello"))
//123
console.log(parseInt("Hello123"))
//NaN

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;

//since the initialization of "x" is not hoisted.


var x;
console.log(x);
//undefined
x = 23;

45.
var x = 0;
var y = 23;

if(x) { console.log(x) } // The code inside this block


will not run since the value of x is 0(Falsy)
if(y) { console.log(y) } // The code inside this block
will run since the value of y is 23 (Truthy)
46.
function add(...args){
console.log(args)
}
add(12)

//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)

48. Is JavaScript a pass-by-reference or pass-by-value language?


It’s always pass by value, but for objects the value of the variable is a
reference. Because of this, when you pass an object and change its members,
those changes persist outside of the function. This makes it look like pass by
reference. But if you actually change the value of the object variable you will
see that the change does not persist, proving it’s really pass by value.
50. How to “deep-freeze” object in JavaScript?
If you want make sure the object is deep frozen you have to create a recursive
function to freeze each property which is of type object.
let person = {
name: "Leonardo",
profession: {
name: "developer"
}
};
Object.freeze(person); // make object immutable
person.profession.name = "doctor";
console.log(person);

//With deep freeze


function deepFreeze(object) {
let propNames = Object.getOwnPropertyNames(object);
for (let name of propNames) {
let value = object[name];
object[name] = value && typeof value === "object" ?
deepFreeze(value) : value;
}
return Object.freeze(object);
}
let person = {
name: "Leonardo",
profession: {
name: "developer"
}
};
deepFreeze(person);
person.profession.name = "doctor";

51. Is it possible to write a multi-line string in JavaScript?

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 number of iterations in the inner loop is 1 + 2 + 3 = 6.

o Therefore, the total number of iterations in the nested loops is 3 (outer


loop) * 6 (inner loop) = 18.

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 The number of characters stored in the start variable is equal to the


number of stars and newlines produced by the nested loops.

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

for (i=0; i<5; i++) {


for (j=1; j<(5 - i); j++) {
str += " ";
}
for (k=1; k<=(2 * i +1); 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);

let i, j, str = "";


//Right pascal star pattern.
for (i=1; i<=5; i++) {
for (j=0; j<i; j++) {
str += "*";
}
str += "newLine";
}

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


for (j=0; j<(5-i); j++) {
str += "*";
}
str += "newLine";
}

console.log(str);

58. Armstrong Number

o The time complexity of the arm() function is O(n), where n is the


number of digits in the input number. This is because the while loop
iterates n times, and each iteration takes constant time.
o The space complexity of the arm() function is O(1), because it only uses
a constant amount of memory to store the variables num, sum,
remainder, and temp.

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 The time complexity of the arm() function is O(n^3), where n is the


length of the input string. This is because the for loop iterates n times,
and the arm() function is called recursively n times. The recursive call of
the arm() function takes O(n^2) time, so the total time complexity is
O(n^3).
o The space complexity of the arm() function is O(n^2), because the result
array can contain up to n^2 elements.

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.

o The function could be made more efficient by using a memoization


technique to store the results of the recursive calls. This would reduce
the time complexity to O(n^2).

Time complexity: O(n^3)


Space complexity: O(n^2)

function arm(str){
let currentChar = [];
let remaingChar = [];
let result = [];

if(str.length === 0) return "";


if(str.length === 1) return str;

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


currentChar = str[i];
remaingChar = str.slice(0,i) + str.slice(i+1);
for(let j=0; j<remaingChar.length; j++){
result.push(currentChar + arm(remaingChar)[j]);
}
}
return 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 space complexity of the minCoin() function is O(s), because it only


uses a constant amount of memory to store the variables amount, coins,
and count.

o In simple words, the minCoin() function takes a linear amount of time to


run, and it uses a constant amount of space.

Time complexity: O(ks)


Space complexity: O(s)

function minCoin(amount, coins) {


let count = 0;
for (let i = 0; i < coins.length; i++) {
while (coins[i] <= amount) {
amount -= coins[i];
count++;
}
}
return console.log(count);
}

minCoin(87, [25, 10, 5, 1]);

61. Sort an Array


1:

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.

o The space complexity of the arr.sort() method is O(n), where n is the


length of the array. This is because the arr.sort() method sorts the array
in place, which means that it does not create a new array.
o In simple words, the arr.sort() method takes a logarithmic amount of
time to run, and it uses a linear amount of space.

62:

o The time complexity of the minCoin() function is O(n^2), where n is the


length of the array. This is because the for loop iterates n times, and the
inner for loop iterates n times. The total number of iterations is
therefore n * n = n^2.

o The space complexity of the minCoin() function is O(n), because it only


uses a linear amount of memory to store the variables arr, result, temp,
and i, and j.

o In simple words, the minCoin() function takes a quadratic amount of


time to run, and it uses a linear amount of space.

const arr = [3, 5, 1, 9, 6, 2, 1];


arr.sort();
console.log(arr);

//2
Time complexity: O(n^2)
Space complexity: O(n)

function minCoin() {
const arr = [3, 5, 1, 9, 6, 2, 1, -1];
const result = [];

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


for (let j = i; j < arr.length; j++) {
if (arr[i] > arr[j]) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
result.push(arr[i]);
}
console.log(result);
}

minCoin();

63. Merg Sort


function mergeSort(arr){
if(arr.length < 2) return arr;
var middle = Math.floor(arr.length/2);
var left = arr.slice(0, middle);
var right = arr.slice(middle, arr.length);
return merge(mergeSort(left), mergeSort(right));
}

function merge(left, right){


var result = [];
while(left.length && right.length){
if(left[0] == right[0]){
result.push(left.shift());
}
else{
result.push(right.shift());}
}

while(left.length) result.push(left.shift());
while(right.length) result.push(right.shift());
console.log(result)
return result;
}
mergeSort([3,2,1])

64. Quick Sort


function QuickSort(arr){
if(arr.length <= 1) return arr;
var pivot = arr[arr.length -1];
var left = [];
var right = [];
for(var i=0;i<arr.length-1;i++){
if(arr[i] < pivot){
left.push(arr[i])
}
else right.push(arr[i])
}
return [...QuickSort(left), pivot,
...QuickSort(right)]
}
console.log(QuickSort([5,4,2,7,9]))
65. Selection Sort
function selectionSort(arr){
var minIdx, temp,
len = arr.length;
for(var i = 0; i < len; i++){
minIdx = i;
for(var j = i+1; j<len; j++){
if(arr[j]<arr[minIdx]){
minIdx = j;
}
}

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

Write the some function and isEven and isPrime functions

o console.log(some([2,4,6], 3, isEven)) // should print true


o console.log(some([2,3,4], 3, isEven)) // should print false
o console.log(some([2,3,11], 4, isPrime)) // should print false
o console.log(some([2,3,5,9], 3, isPrime)) // should print true

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

console.log(some([2, 4, 6], 3, isEven)); // true


console.log(some([2, 3, 4], 3, isEven)); // false
console.log(some([2, 3, 11], 4, isPrime)); // false
console.log(some([2, 3, 5, 9], 3, isPrime)); // true

67. Write a function whch returns a function that generates fibonacci


numbers. Don't use generators.
function fibbo() {
let a = 0;
let b = 1;

return function() {
const result = a;
const next = a + b;
a = b;
b = next;
return result;
};
}

let obj = fibbo();


console.log(obj()); // 0
console.log(obj()); // 1
console.log(obj()); // 1
console.log(obj()); // 2
console.log(obj()); // 3
console.log(obj()); // 5
console.log(obj()); // 8
68. Reverse Words in a String.
Note:

o A word is defined as a sequence of non-space characters.


o Input string may contain leading or trailing spaces. However, your
reversed string should not contain leading or trailing spaces.
o You need to reduce multiple spaces between two words to a single
space in the reversed string.

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.

const str = "the sky is blue";


const reverseWords = str.split("").reverse().join("");

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

const list = lists('a');


list.append('p');
list.append('p');
list.append('l');
list.append('e');

console.log(list.reverse());

69. Words that appear only once in the string.

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.

o In simple words, the unique() function takes a linear amount of time to


run, and it uses a linear amount of space.

Set(): Reduce time complexity of O(n).


function fun(){
const arr='apple'.split('')
let result=[]

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(' ');

let result=new Set(uniqueStr);


console.log(result);
console.log(result.size);
}

unique();

//3
function fun(){
let str="Reverse Words in a String Reverse Words
in".split(' ');
let hash={};

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


if(hash[str[i]]){
hash[str[i]]++;
}else{
hash[str[i]]=1
}
}

for (let word in hash) {


if (hash[word] === 1) {
console.log(word);
}
}
}

fun()

// Linked list
function unique() {
let current = head;
let uniqeChar = '';

while (current) {
let isUnique = true;
let runner = head;

while (runner !== current) {


if (runner.value === current.value) {
isUnique = false;
break;
}
runner = runner.next;
}
if (isUnique) {
uniqeChar += current.value;
}

current = current.next;
}

return uniqeChar;
}

return { append, print, unique };


}

const list = createList('a');


list.append('p');
list.append('p');
list.append('l');
list.append('e');
list.print();

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

return { append, print, duplicatesCh };


}

const list = createList('a');


list.append('p');
list.append('p');
list.append('l');
list.append('e');
list.print();

console.log(list.duplicatesCh());

70. Unique Char.

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.

o In simple words, the unique() function takes a linear amount of time to


run, and it uses a linear amount of space.

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.

o In simple words, the unique() function takes a quadratic amount of time


to run, and it uses a linear amount of space.

function unique(){
let str="Java is great Grails is also great Grails is
also great";
let newStr = str.split(' ');
const result = [];

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


if(!result.includes(newStr[i])){
result.push(newStr[i])
}
}
console.log(result);
}

unique();

71. Find vowel

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.

o In simple words, the vowel() function takes a linear amount of time to


run, and it uses a constant amount of space.

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

return { append, print, vowels };


}

const list = createList('a');


list.append('p')
list.append('p')
list.append('l')
list.append('e')
list.print();

list.vowels();

72. Palindrome Number.


Determine whether an integer is a palindrome. An integer is a palindrome
when it reads the same backward as forward.

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

73. Word Break.


Given a non-empty string s and a dictionary wordDict containing a list of non-
empty words, determine if s can be segmented into a space-separated
sequence of one or more dictionary words.

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.

Input: s = "leetcode", wordDict = ["leet", "code"]


Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
function fun() {
let str="leetcode"
let wordDict = ["leet", "code"];
let result=[]

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


for (let j = 0; j < i; j++) {
if (wordDict.includes(str.substring(j, i))) {
result.push(str.substring(j, i))
break;
}
}
}

return console.log(result);
}

fun()

74. Remove All Adjacent Duplicates In String.


Input: "abbaca"
Output: "ca"
Explanation: For example, in "abbaca" we could remove "bb" since the letters
are adjacent and equal, and this is the only possible move. The result of this
move is that the string is "aaca", of which only "aa" is possible, so the final
string is "ca".
function removeDup() {
const str = "wwelcom";
let stack = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === stack[stack.length - 1]) {
stack.pop();
} else {
stack.push(str[i]);
}
}
return console.log(stack.join(""));
}

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.

o In simple words, the removeDup() function takes a linear amount of


time to run, and it uses a linear amount of space.

75. Destroy Those Pairs.


"Destroy Those Pairs" is a problem where you need to find and remove pairs
of elements from an array such that each pair consists of two identical
elements. The task is to count how many such pairs can be formed and
removed from the array.
function fun(){
let str='abccd'
let newstr=[];

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


if(!newstr.includes(str.charAt(i))){
newstr.push(str.charAt(i))
}else{
newstr.pop()
}
}
console.log(newstr.join(''))
}

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

return { append, print, fun };


}

const list = createList('a');


list.append('p')
list.append('p')
list.append('l')
list.append('e')
list.print();

list.fun();

76. Longest Substring from a String.


function lonStr(){
const str = 'second itemlonger is longer than the third
one';
const arr=str.split(' ');
let result='';

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


if (arr[i].length > result.length) {
result = arr[i]
}
}

console.log(result);
}
lonStr();

77. Longest Substring Without Repeating Characters.


function longStr() {
const str = 'applaaops';
let currentStr = '';

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


if (currentStr.includes(str.charAt(i))) {
// Remove characters from the beginning of
currentStr until the repeated character
currentStr =
currentStr.slice(currentStr.indexOf(str.charAt(i)) + 1) +
str.charAt(i);
} else {
currentStr += str.charAt(i);
}
}

console.log(currentStr);
}

longStr();

78. Isomorphic Strings.


Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while
preserving the order of characters. No two characters may map to the same
character but a character may map to itself.

Input: s = "egg", t = "add"


Output: true

function fun() {
const str1 = 'egg';
const str2 = 'add';

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


const a = str1.indexOf(str1[i]);
const b = str2.indexOf(str2[i]);
if (str2[a] !== str2[b] || str1[b] !== str1[a]) {
return false;
}
}

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:

o Only one letter can be changed at a time.


o Each transformed word must exist in the word list.

Note:

o Return 0 if there is no such transformation sequence.


o All words have the same length.
o All words contain only lowercase alphabetic characters.
o You may assume no duplicates in the word list.
o You may assume beginWord and endWord are non-empty and are not
the same.

Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5

Explanation: As one shortest transformation is "hit" - "hot" - "dot" - "dog" -


"cog", return its length 5.
function ladderLength(beginWord, endWord = '', wordList =
[]){
function distance(a = '', b = ''){
let count = 0
for (let index = 0; index < b.length; index++) {
if (a[index] !== b[index]) {
count += 1
}
}
return count === 1
}

let current = [beginWord]


const visited = {
}

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"]))

80. Palindrome Partitioning.


Input: "aab"

Output: [
["aa","b"],
["a","a","b"] ]
function partition(s = ''){
function isPalindrome(left, right){
if (left === right) return true;

for (let i = left; i <= right; i++) {


if (s[i] !== s[right - i + left]) {
return false
}
}
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"))

81. Longest Palindromic Substring.


Given a string s, find the longest palindromic substring in s. You may assume
that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

function longestPalindrome(s = ''){


const memo = {}

function isPalindrome(left, right){


if (left === right) return true;

for (let i = left; i <= Math.floor((left + right) /


2); i++) {
if (s[i] !== s[right - i + left]) {
return false
}
}
return true
}

function aux(left, right){


if (left > right) return '';

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"))

82. Intersection of 3 Sorted Arrays


function fun() {
const arr = [1, 5, 10, 20, 40, 80];
const arr2 = [6, 7, 20, 80, 100];
const arr3 = [3, 4, 15, 20, 30, 70, 80, 120];
let result = [];

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;

if (list2.includes(digit) && list3.includes(digit)) {


console.log("Common Digit:", digit);
}

currentNode1 = currentNode1.next;
}
}

const list = createList(1);


list.append(6);
list.append(2);

const list2 = createList(2);


list2.append(7);
list2.append(6);

const list3 = createList(3);


list3.append(2);
list3.append(8);

list.print();
list2.print();
list3.print();
fun(list, list2, list3);

83. Sort
let i, j, arr=[0,9,8,7,6];
var max=0;

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


for(j=i; j<arr.length; j++){
if(arr[i]>arr[j]){
var temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}

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

return {append, traversing, sorts}


}

const obj=new createList(3);


obj.append(1)
obj.append(2)
obj.append(6)
obj.append(4)
obj.traversing()
obj.sorts()
obj.traversing()

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.

84. Remove Duplicates


function removeDup(){
const arr = [1,2,3,4,3,0,9,0,1];
const result=[];

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


let count=0;
// for(let j=0;j<result.length;j++){
for(let j=0;j<arr.length;j++){
//Remove Duplicates
// if(arr[i]==result[j]) count +=1;
//Unique Character
if(arr[i]==arr[j]) count +=1;
}
if(count==1){
//RD
// if(count==0){
//UC
result.push(arr[i]);
}
}

console.log(result)
}

removeDup();

// 2. Linked List
function unique(){
let current=head;

while(current.next !== null){


if(current.value === current.next.value){
current.next = current.next.next;
}else{
current=current.next;
}
}
}

return {append, traversing, unique}


}

const obj=new createList(3);


obj.append(1)
obj.append(2)
obj.append(2)
obj.append(6)
obj.append(4)
obj.traversing()
obj.unique()
obj.traversing()

85. Contains Duplicate.


Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the
array, and it should return false if every element is distinct.
function containsDuplicate(nums){
const map = {}

for (num of nums) {


if (map[num]) {
return true
}
map[num] = 1
}
return false
}

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.

o In simple words, the containsDuplicate() function takes a linear amount


of time to run, and it uses a linear amount of space.

86. Compare Array


function compare(){
const arr=[1,2,3,4,5,6];
const arr2=[5,6,7,8,9,0];
const result=[];

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


if(arr2.indexOf(arr[i]) !== -1){
result.push(arr[i]);
}
}
console.log(result)
}

compare();

//Unique name
function getUnique(){
var names = ["John", "Peter", "Clark", "Harry", "John",
"Alice"];
var newName = [];

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


if(newName.indexOf(names[i]) === -1) {
newName.push(names[i]);
}
}
console.log(newName);
}

getUnique();

87. Sort Those Squares.


"Sort Those Squares" is a problem where you're given an array of integers,
some of which could be negative, and you're asked to sort the squares of
those integers in ascending order.
function fun() {
const arr = [-7, -3, 2, 3, 11];
const result=[];

for(let i=0;i<arr.length;i++){
result.push(arr[i]*arr[i])
}

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


for(let j=i; j<result.length;j++){
if(result[i]>result[j]){
let temp=result[i];
result[i]=result[j];
result[j]=temp;
}
}
}

console.log(result)
}

fun()

88. Occurence of Elements.


function fun() {
const arr = [1, 2, 3, 4, 5, 6, 1, 2, 1, 3];
const hash = {};

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


if (hash[arr[i]]) {
hash[arr[i]] += 1;
} else {
hash[arr[i]] = 1;
}
}

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.

89. Target Elements.


function fun() {
const arr = [1, 2, 3, 4, 5, 6];
const target = 6;
const hash = {};
const result = [];

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


const num = arr[i];
if (hash[target - num] !== undefined) {
result.push(hash[target - num], num);
}

hash[num] = num;
}

return console.log(result);
}

fun();

90. Flat Arr.


// arr =
[10,'h',2,'k',['e','z','y','g'],[44,67,'b','c','a'],[25,1
00,101,'m','l'],'f',60,55,'x']
// output [a,b,c,..., 1,2,3....]

const newArr = [];


for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
newArr.push(...arr[i]);
} else {
newArr.push(arr[i]);
}
}

const result = [];


for (let i = 0; i < newArr.length; i++) {
for (let j = i; j < newArr.length; j++) {
if (newArr[i] > newArr[j]) {
let temp = newArr[i];
newArr[i] = newArr[j];
newArr[j] = temp;
}
}
result.push(newArr[i]);
}

console.log(result);

// 2. Separate number and string.


const arr=[
2, 'a', 10, 'b', 'c', 'e',
'f', 'g', 25, 44, 'h', 'k',
'l', 55, 60, 67, 'm', 'x',
'y', 100, 101, 'z'
]
const str=[], num=[];

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


if(typeof arr[i]==='number'){
num.push(arr[i])
}else if(typeof arr[i]==='string'){
str.push(arr[i])
}
}

console.log(num);
console.log(str);

91. 132 Pattern.


Input: nums = [1,2,3,4]
Output: false
Explanation: There is no 132 pattern in the sequence.
function pattern123() {
const arr=[1,2,3,4];
const number = 132;
const result=[];

const target = number.toString();


[target]

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


if(target.indexOf(arr[i]) !== -1){
result.push(arr[i]);
}
}
console.log(result)
}

pattern123();

92. Combination Sum


Input: candidates = [2,3,6,7], target = 7,
A solution set is: [ [7],
[2,2,3]
]
function combinationSum(){
const arr=[1,2,3,6,4,5];
const target = 7;
let result=[];

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


for(let j=i; j<arr.length; j++){
if(arr[i]+arr[j]==target){
result.push(arr[i],arr[j])
}
}
}
console.log(result);
}

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

return { append, print, fun };


}

const list = createList(6);


list.append(-7);
list.append(-3);
list.append(2);
list.append(3);
list.append(1);
list.append(3);
list.print();

list.fun();

93. Remove Element


function fun(){
const arr=[1,2,3,5,4];
const num=5;

const index = arr.indexOf(num);


arr.splice(index,1)
console.log(arr)
}

fun();

// 2 Linked List
function fun(target) {
while (head !== null && head.value === target) {
head = head.next;
}

let current = head;


let prev = null;

while (current !== null) {


if (current.value === target) {
prev.next = current.next;
} else {
prev = current;
}
current = current.next;
}
}
return { append, print, fun };
}

const list = createList(6);


list.append(-7);
list.append(2);
list.append(1);
list.append(3);

list.print();

list.fun(2);
list.print();

94. Replace Element


function fun(){
const arr=[1,2,3,5,4];
const num=5;
const newnum=6;

const index=arr.indexOf(num)
arr.splice(index,1,newnum)

console.log(arr)
}

fun();

95. Shuffle the Array.


function fun(){
const arr = [7,8,9,10];

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

96. Median of Two Sorted Arrays.


Given two sorted arrays nums1 and nums2 of size m and n respectively, return
the median of the two sorted arrays.
Follow up: The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.

const median = () => {


const arr = [1,12,15,26,38];
const arr2 = [4,3,1];
let arrMedian=[];

const result = [...arr, ...arr2].sort((a, b) => a - b);


const half = result.length / 2 | 0;

if (result.length % 2){
arrMedian=result[half];
}
else{
arrMedian=((result[half] + result[half-1])/2);
}
return console.log(arrMedian);
}

median()

97. Plus One.


Input: digits = [1,2,3]
Output: [1,2,4]
function plusOne(){
const arr=[1,2,3];
let result=[], result2=[];

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


result.push(arr[i]);
result2 = arr[arr.length-1]+1
}

result.pop();
result.push(result2);
console.log(result)
}

plusOne();

98. Missing Number


function missNum() {
let i, arr=[0,1,2,4,5], exactsum=0, result=0;
exactsum = arr.reduce((a, b) => a + b);
for (i=0; i<=arr.length; i++) {
result += i
}

result -= exactsum;
console.log('Missing Number', result)
}

missNum();

99. Missing Ranges.


const arr = [1,2,4,8];
const missing = [];
var count = 1;

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


if (arr[i] !== count) {
missing.push(count);
i--;
}
count++;
}

console.log(missing);

100. Sort name.


var objs = [
{ first: 'Mukesh', last: 'Jamf' },
{ first: 'Rakesh', last: 'Bodine' },
{ first: 'Bicky', last: 'Prentice' }
];

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

const obj = objs.sort(compare);


console.log(obj)

101. Concat 2 array on the basis of id


const arr1 =[{id:1,name:"sai"}, {id:2,name: "King"}];
const arr2 = [{id:1,age:23},{id:2,age:24}];

function fun(){
const result = arr1[0].name.concat(arr2[1].age);
console.log(result)
}

fun();

102. Find First and Last Position of Element in Sorted Array


Given an array of integers nums sorted in ascending order, find the starting
and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example 1:Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

function fun() {
const nums = [5, 7, 7, 8, 8, 10];
const target = 8;
const result = [];

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


// Find the first occurrence
if (nums[i] === target) {
result[0] = i;
break;
}
}

for (let i = nums.length - 1; i >= 0; i--) {


// Find the last occurrence
if (nums[i] === target) {
result[1] = i;
break;
}
}

return result;
}

console.log(fun());

103. Jump Game.


Given an array of non-negative integers representing the maximum jump
length from each position. The goal is to determine if you can reach the last
index of the array starting from the first position.
function fun() {
const arr = [2, 3, 1, 4];
let maxReach=0;

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()

104. Number of Good Pairs.


Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
function fun(){
const arr=[1,2,3,1,1,3];
const result=[];
let count=0;

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


for(let j=i+1; j<arr.length; j++){
if(arr[i]==arr[j]){
result.push([arr[i], arr[j]]);
count++;
}
}
}
console.log(result)
console.log(count)
}

fun();

105. Product of Array Except Self.


function fun() {
const arr = [1, 2, 3, 4];
const result = [];

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


let prod = 1;
for (let j = 0; j < arr.length; j++) {
if (arr[i]!==arr[j]) {
prod *= arr[j];
}
}
result.push(prod);
console.log(prod);
}
}

fun();

106. Count of Smaller Numbers After Self.


You are given an integer array nums and you have to return a new counts
array. The counts array has the property where counts[i] is the number of
smaller elements to the right of nums[i].
Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:

o To the right of 5 there are 2 smaller elements (2 and 1).


o To the right of 2 there is only 1 smaller element (1).
o To the right of 6 there is 1 smaller element (1).
o To the right of 1 there is 0 smaller element.

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()

107. Subarray max sum


function fun(){
const arr = [1,3,-1,6,2,2,0,3,2,1];
let result=0;
let sum=0;

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()

108. Maximum Product Subarray.


function fun(){
const arr = [1,3,-1,6,2,2,0,3,2,1];
let result=1;
let sum=1;

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()

109. Bulb swicher


Involves toggling the states of light bulbs based on a specific pattern. You start
with a row of n bulbs, and you toggle every i-th bulb (i=1 to n) during the i-th
round. The goal is to find how many bulbs are on after n rounds.
function fun() {
let n = 4;
let result = [];

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


let roundOnCount = 0;

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


if (i % j === 0) {
roundOnCount++;
}
}

result[i] = roundOnCount % 2 === 1;


}

let count = 0;
for (const bulb of result) {
if (bulb) {
count++;
}
}

return count;
}

console.log(fun());

110. involves rotating elements in an array by a given number of positions.


function rotateArray(arr, k) {
const n = arr.length;
k %= n;

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


if (i >= k) {
const temp = arr[i - k];
arr[i - k] = arr[i];
arr[i] = temp;
}
}

return arr;
}

const arr = [1, 2, 3, 4, 5];


const k = 2;
rotateArray(arr, k);
console.log(arr);
// Output: [4, 5, 1, 2, 3]
111. Count Inversions
involves counting the number of inversions in an array. An inversion occurs
when two elements at
function countInversions(arr) {
const n = arr.length;
let count = 0;

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


for (let j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
count++;
}
}
}

return count;
}

const arr = [4, 3, 1, 2];


const result = countInversions(arr);
console.log(result);
// Output: 5

112. Cyclic ShiftLeft


"Cyclic Shift" typically refers to rotating the elements of an array to the left or
right by a certain number of positions while maintaining the order of the
elements.
function cyclicShiftLeft(arr, k) {
const n = arr.length;
k %= n;
// In case k is larger than array length

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


const newIndex = (i + n - k) % n;
console.log(arr[newIndex]);
}
}

cyclicShiftLeft([1, 2, 3, 4, 5], 2);

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;

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


if (arr[i] !== 13) {
count++;
}
}

console.log(count);
}

fun();

114. Count Nice Strings


involves counting the number of strings that are "nice" among a given list of
strings. A string is considered "nice" if it is lexicographically smaller than all the
strings appearing after it in the list.
function countNiceStrings(strings) {
const n = strings.length;
let count = 0;

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


let isNice = true;

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


if (strings[i] >= strings[j]) {
isNice = false;
break;
}
}

if (isNice) {
count++;
}
}

return count;
}

const strings = ["a", "b", "ab", "ba"];


console.log(countNiceStrings(strings));
// Output: 3
115. Array Counter
function fun(arr) {
let maxDepth = 0;
let stack = arr.map(element => ({ nestedArr: element,
depth: 1 }));

while (stack.length > 0) {


const { nestedArr, depth } = stack.pop();

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([]);

1161. Summary Ranges.


Given a sorted integer array without duplicates, return the summary of its
ranges.
function summaryRanges(nums) {
let start = null
const result = []

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


if (start === null) {
start = nums[i]
}
if (nums[i] === nums[i + 1] - 1) continue;

if (nums[i] === start) {


result.push(nums[i].toString())
start = null
}
else {
result.push('$'{start}->'$'{nums[i]}')
start = null
}
}

return result
}

console.log(summaryRanges([1,2,3,4,6,7,9]))

117. Print number 1.


function fun() {
const num=19;
let count=0;

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

return { append, print, fun };


}

const list = createList(16);


list.fun(16)

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;

for(i=0; i<num; i++){


let count=0;
for(j=2; j<i; j++){
if(i%j==0) count +=1;
}

if(count==0){
result.push(i);
}
}
console.log(result);
}

primes()

// 2 Linked List
function fun(){
const num=100;
const result=[];
let i,j;

for(i=0; i<num; i++){


let count=0;
for(j=2; j<i; j++){
if(i%j==0) count +=1;
}

if(count==0){
result.push(i);
}
}
console.log(result);
}

return { append, fun };


}

const list = createList();


list.fun(100)
120. Add Digits.
function fun(){
let num = 2568;
let sum=0;

let newnum=num.toString().split('');
for(let i=0;i<newnum.length;i++){
sum += parseInt(newnum[i])
}
console.log(sum)
}

fun();

121. Remove number from number.


function fun(){
let num = 915765;
const target=5;

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;

let newnum = num.toString().split('');

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


if (newnum[i] === target.toString()) {
newnum.splice(i, 1);
}
}

console.log(newnum.join(''));
}

fun();

122. Remove last 3 characters of string or number in javascript.


function remove(){
let str=1437000;
str=str.toString();
str = str.slice(0, -3);
console.log(str)
}

remove();

123. Given a function magicNumber() that returns a random integer 1 or 0,


write a new function that will generate a random number that uses this
magicNumber() function.
function magicNum(){
const random = Math.random(0,1)
return random;
}

function main(){
const result = Math.random(0, magicNum);
console.log(result);
}

main();

124. Discuss possible ways to write a function isInteger(x) that determines if


x is an integer.
function isInt(value) {
var x;
if (isNaN(value)) {
return false;
}
x = parseFloat(value);
return (x | 0) === x;
}

console.log(isInt(0));

125. Common Divisor


function numbers(x, y) {
if ((typeof x !== 'number') || (typeof y !==
'number'))
return false;
x = Math.abs(x);
y = Math.abs(y);
while(y) {
var i = y;
y = x % y;
x = i;
}
return x;
}

console.log(numbers(12, 4));
console.log(numbers(9, 3));

126. Reverse Integer.


function reverse(num){
let result='';
const target = num.toString();

for(let i=target.length; i>=0; i--){


result += target.charAt(i);
}

result = Number(result)
console.log(result);
}

reverse(123)

127. Multiply Strings


Input: num1 = "2", num2 = "3"
Output: "6"
function multiply() {
let num="2";
let num2="3";
let product =0;

num=Number(num)
num2=Number(num2)

product = num*num2;
console.log(product)
}

multiply();

128. Perfect Squares.


Given a positive integer n, find the least number of perfect square numbers
(for example, 1, 4, 9, 16, ...) which sum to n.
function fun() {
var nums=64;

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


if(i*i === nums){
nums =i;
break;
}
}
console.log(nums);
}

fun();

129. Power of Two.


Given an integer, write a function to determine if it is a power of two.
function fun() {
const num=16;

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


if(2**i===num){
console.log(i)
break;
}
}
}

fun()

130. Pow(x, n).


Input: x = 2.00000, n = 10
Output: 1024.00000
function myPow(x, n){
if (n === 0) return 1;

const temp = myPow(x, Math.floor(Math.abs(n /2)))


const result = n%2 ===0 ?temp *temp :x *temp *temp;
return n<0 ? 1/ result :result;
}

console.log(myPow(2.00000, 10))

131. Broken Calculator.


On a broken calculator that has a number showing on its display, we can
perform two operations:

o Double: Multiply the number on the display by 2, or;


o Decrement: Subtract 1 from the number on the display.

Initially, the calculator is displaying the number X.


Return the minimum number of operations needed to display the number Y.
function brokenCalc(){
let X=5, Y=8;
let result = 0;

while(Y>X){
if(Y%2 === 0) {
Y /=2
}
else {
Y +=1
}
result +=1
}
console.log(result + X - Y);
}

brokenCalc()

132. Ugly Number.


Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
function isUgly(){
const num=15;
const memo = [];

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;

memo[n] = aux(n/ 2) || aux(n/ 3) || aux(n/ 5);


return memo[n]
}
console.log(aux(num));
}

isUgly();

133. Sum of Two Integers.


Calculate the sum of two integers a and b, but you are not allowed to use the
operator + and -.
function getSum(a, b) {
let carry = 0;

while (b !== 0) {
carry = a & b
a ^= b
b = carry << 1
}
return a
}

console.log(getSum(5, 1))

134. Largest Perimeter Triangle.


We need to find a set of three side lengths that satisfy the triangle inequality
theorem and have the largest possible perimeter.
7,8,9
function fun() {
const arr = [2,1,2,5,6,7,8,9,3]
let result=0;

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()

135. Pascal's Triangle


Pascal's Triangle is a pattern of numbers that starts with a "1" at the top. Each
row begins and ends with a "1", and the numbers inside each row are obtained
by adding the two numbers directly above them. Here's how it works:

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

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


currentRow.push(num);
num = num * (i - j) / (j + 1); //
Calculate the next number based on the previous number
}

result.push(currentRow);
}

console.log(result);
}
star();

136. Rectangle Area.


Area = length × width.
Each rectangle is defined by its bottom left corner and top right corner.
function fun() {
const arr = [-3, 0, 3, 4, 0, -1, 9, 2];
let maxArea = 0;

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


for (let j = i + 1; j < arr.length; j++) {
const length = Math.abs(arr[i]);
const width = Math.abs(arr[j]);
const area = length * width;

if (area > maxArea) {


maxArea = area;
}
}
}

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()

138. Best Time to Buy and Sell Stock.


Say you have an array for which the ith element is the price of a given stock on
day i.
If you were only permitted to complete at most one transaction (i.e., buy one
and sell one share of the stock), design an algorithm to find the maximum
profit.
Note that you cannot sell a stock before you buy one.

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]
}
}

maxProfit = (maxVal - minVal)

console.log(maxProfit)
}

fun()

139. Stuff Them Candies


Distribute candies to a list of children such that each child receives a specific
number of candies, and you have a limited number of candies available.
function fun() {
let candies = 10;
const child = 3;
let result = [];

const candiesPerChild = Math.floor(candies / child);


const remainingCandies = candies % child;

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


result.push(candiesPerChild + (i < remainingCandies ?
1 : 0));
}

return console.log(result);
}

fun();

140. Max Points On a Line


Finding the maximum number of points that lie on the same line in a given set
of points on a 2D plane.
function fun() {
const points = [[1,1],[2,2],[3,3],[4,2]];
let max = 0;

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


if(points[i][0] == points[i][1]){
max +=1;
}
}

console.log(max);
}
fun();

141. Rotate Image.


You are given an n x n 2D matrix representing an image, rotate the image by
90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the
input 2D matrix directly. DO NOT allocate another 2D matrix and do the
rotation.

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]


Output: [[7,4,1],[8,5,2],[9,6,3]]
function fun() {
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

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


for (let j =i+1; j<matrix.length; j++) {
const temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}

console.log(matrix);
}

fun();

142. Verify the Alien Dictionary


Given a list of words in an alien language and the order of characters in that
language. You need to determine if the given list of words is sorted
lexicographically according to the given alien dictionary.
function fun() {
const words = ["hello", "leetcode"];
const order = "hlabcdefgijkmnopqrstuvwxyz";

for (let i = 1; i < words.length; i++) {


const prevWord = words[i - 1];
const currentWord = words[i];

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

if (j === currentWord.length && j < prevWord.length)


{
console.log('False'); // Incorrect order
return;
}
}

console.log('True'); // All pairs are in correct order


}

fun();

143. Valid Sudoku


given a 9x9 Sudoku board, and you need to determine if the board is valid
according to Sudoku rules. The rules state that each row, each column, and
each of the nine 3x3 sub-grids that compose the board must contain distinct
digits from 1 to 9.
function isValidSudoku(board) {
const seen = new Set();

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


for (let j = 0; j < 9; j++) {
const num = board[i][j];

if (num !== '.') {


const rowKey = row'$'{i}-'$'{num};
const colKey = col'$'{j}-'$'{num};
const subgridKey = subgrid'$'{Math.floor(i
/ 3)}-'$'{Math.floor(j / 3)}-'$'{num};

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

144. Island Perimeter


finding the perimeter of an island represented as a grid, where '1's represent
land and '0's represent water. The goal is to determine the total perimeter of
the island.
function islandPerimeter(grid) {
let perimeter = 0;

for (let row = 0; row < grid.length; row++) {


for (let col = 0; col < grid[0].length; col++) {
if (grid[row][col] === 1) {
perimeter += 4;

if (row > 0 && grid[row - 1][col] === 1) {


perimeter -= 2; //
Subtract for adjacent land on top
}

if (col > 0 && grid[row][col - 1] === 1) {


perimeter -= 2; //
Subtract for adjacent land on left
}
}
}
}

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

145. Group Anagrams.


Given an array of strings strs, group the anagrams together. You can return the
answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a
different word or phrase, typically using all the original letters exactly once.

Input: strs = ["eat","tea","tan","ate","nat","bat"]


Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
function fun() {
const words = ["eat","tea","tan","ate","nat","bat"];
const anagramGroups = {};

for (const word of words) {


const sortedWord = word.split('').sort().join('');

if (anagramGroups[sortedWord]) {
anagramGroups[sortedWord].push(word);
} else {
anagramGroups[sortedWord] = [word];
}
}
console.log(anagramGroups)
}

fun()

146. Shortest Path in Binary Matrix

o In an N by N square grid, each cell is either empty (0) or blocked (1).


o A clear path from top-left to bottom-right has length k if and only if it is
composed of cells C_1, C_2, ..., C_k such that:

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.

Input: [[0,1],[1,0]], [[0,0,0],[1,1,0],[1,1,0]]


Output: 2, 4
function shorPath(grid) {
let n = grid.length - 1;
let q = [0]

if (grid[0][0] || grid[n][n]) return -1

grid[0][0] = 1
while (q.length) {
let curr = q.shift();
let i = curr & (1 << 7) - 1;
let j = curr >> 7;

if (i === n && j === n) return grid[n][n]


for (let a = Math.max(i-1,0); a <= Math.min(i+1,n);
a++){
for (let b = Math.max(j-1,0); b <=
Math.min(j+1,n); b++){
if (grid[a][b] === 0){
grid[a][b] = grid[i][j] + 1, q.push(a +
(b << 7))
}
}
}
}
return -1
};

console.log(shorPath([[0,0,0],[1,1,0],[1,1,0]]));

147. Spiral Matrix.


Input: [ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ] ]

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"

while(result.length < matrix.length * matrix[0].length)


{
result.push(matrix[i][j])
if(direction === "right") {
if(j === columnMax) {
rowMin += 1
i = rowMin
direction = "down"
} else {
j++
}
} else if(direction === "down") {
if(i === rowMax) {
direction = "left"
columnMax -= 1
j = columnMax
} else {
i++
}
} else if(direction === "left") {

if(j === columnMin) {


direction = "up"
rowMax -= 1
i = rowMax
} else {
j--
}
} else {
if(i === rowMin) {
direction = "right"
columnMin += 1
j = columnMin
} else {
i--
}
}
}

return result
};
console.log(spiralOrder([
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]))

148. Unique Paths.


A robot is located at the top-left corner of a m x n grid (marked 'Start' in the
diagram below).
The robot can only move either down or right at any point in time. The robot is
trying to reach the bottom-right corner of the grid (marked 'Finish' in the
diagram below).
How many possible unique paths are there?

Input: m = 7, n = 3
Output: 28
function uniquePaths(m, n){
const memo = {}

function aux(rowIndex, columnIndex){


if (memo[rowIndex] !== undefined &&
memo[rowIndex][columnIndex] !== undefined) {
return memo[rowIndex][columnIndex]
}

if (rowIndex >= m || columnIndex >= n) return 0


if (rowIndex === m - 1 && columnIndex === n - 1)
return 1

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

149. Add Binary


Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Input: a = "1010", b = "1011"
Output: "10101"
function addBinary(a, b) {
const reverse = x => x.split('').reverse()

const { shorter, longer } = a.length > b.length


? { shorter: reverse(b),
longer: reverse(a) }
: { shorter: reverse(a),
longer: reverse(b) }

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"))

150. House Robber.


You are a professional robber planning to rob houses along a street. Each
house has a certain amount of money stashed, the only constraint stopping
you from robbing each of them is that adjacent houses have security system
connected and it will automatically contact the police if two adjacent houses
were broken into on the same night.

Given a list of non-negative integers representing the amount of money of


each house, determine the maximum amount of money you can rob tonight
without alerting the police.

Input: nums = [1,2,3,1]


Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
function fun() {
const nums = [1, 2, 3, 1];
let prevMax = 0;
let currMax = 0;

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


const temp = currMax;
currMax = Math.max(prevMax + i, currMax);
prevMax = temp;
}

console.log(currMax)
}

fun()

151. Container With Most Water


Given n non-negative integers a1, a2, ..., an , where each represents a point at
coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i
is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a
container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

Example: Input: [1,8,6,2,5,4,8,3,7]


Output: 49
function fun(){
const height=[1,8,6,2,5,4,8,3,7]
let max = 0;
let left = 0;
let right = height.length - 1;

while (left < right) {


max = Math.max(max, Math.min(height[left],
height[right]) * (right - left));

if (height[left] <= height[right]) {


left += 1;
} else {
right -= 1;
}
}
console.log(max)
}

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

return fun(n - 1) + fun(n - 2);


}

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()

154. Destination City.


You are given the array paths, where paths[i] = [cityAi, cityBi] means there
exists a direct path going from cityAi to cityBi. Return the destination city, that
is, the city without any path outgoing to another city.
It is guaranteed that the graph of paths forms a line without any loop,
therefore, there will be exactly one destination city.
Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao
Paulo"]]Output: "Sao Paulo"Explanation: Starting at "London" city you will
reach "Sao Paulo" city which is the destination city. Your trip consist of:
"London" - "New York" - "Lima" - "Sao Paulo".
function destCity(paths) {
let result = '';

const map = paths.reduce((acc, [a, b]) => {


acc[a] = 1;
acc[b] = (acc[b] || 0)
if (acc[b] === 0) {
result = b;
}
return acc;
}, {})
return Object.keys(map).filter(x => map[x] === 0)[0];
}

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 = {};

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


if(guess[i] === secret[i] && secretMap[guess[i]] >
0) {
bulls += 1;
secretMap[guess[i]]--;
}
}

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


if(guess[i] !== secret[i] && secretMap[guess[i]] >
0) {
cows += 1;
secretMap[guess[i]]--;
}
}
return bulls + "A" + cows + "B";
};

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:

o Efficiency: Iterative algorithms can be more efficient than recursive


algorithms in terms of both time and space complexity. They often
require less memory because they don't create a new function call stack
for each iteration.
o Predictable Memory Usage: Iterative algorithms usually have a fixed
memory footprint, making them more predictable and less prone to
stack overflow errors compared to recursion.
o Faster Execution: In many cases, iterative algorithms can execute faster
than their recursive counterparts.

Disadvantages:

o State Management: In iterative algorithms, you often need to manage


and update the state explicitly.
o Inefficient Loops: Inefficient loop structures or suboptimal loop
conditions can lead to performance issues.

2. Recursion
Is a programming technique where a function calls itself to solve a problem.
Advantages:

o Simplicity and Clarity:


o Divide and Conquer: Recursive algorithms naturally follow the "divide
and conquer" strategy, breaking a problem into smaller, more
manageable parts. This can lead to efficient solutions for problems like
sorting and searching.
o Natural Fit for Certain Problems: Include tree traversal, backtracking,
and problems involving nested structures.
o Dynamic Programming: Recursion is often used in dynamic
programming, a technique for solving complex problems by breaking
them into smaller overlapping subproblems. Recursive functions can
help memoize (store and reuse) the results of subproblems, leading to
optimized solutions.
Disadvantages:

o Performance Overhead: Recursive function calls come with a


performance overhead. Each function call requires additional memory
on the call stack, and excessive recursion can lead to stack overflow
errors or slow performance.
o Memory Consumption: Recursive algorithms can consume a significant
amount of memory because each function call adds a new stack frame
to the call stack. This can be a problem for deep or unoptimized
recursion.

3. Stack
Advantages:

o Memory Efficiency: Stacks typically use a small, fixed amount of


memory for each item pushed onto the stack, making them memory-
efficient.
o Predictable Behavior: Stack-based algorithms are often more
predictable and easier to reason about than more complex data
structures.
o Undo/Redo Functionality: Stacks are useful for implementing undo and
redo functionality in applications where users can perform a series of
actions and then reverse or redo them one at a time.

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:

o Synchronization: In multithreading and multiprocessing environments,


queues are often used to safely synchronize and exchange data
between threads or processes. They help avoid race conditions and
ensure orderly communication.
o Buffering: Queues can be used as buffers to manage the flow of data
between producers and consumers.

Disadvantages:

o Limited Random Access:

5. Linked list
Advantages:

o Dynamic Memory Allocation:


o Insertion and Deletion: Linked lists excel at inserting and deleting
elements in constant time (O(1)) if you have a reference to the node
where the operation should take place. This is in contrast to arrays,
where inserting or deleting elements in the middle can be costly (O(n)).
o Memory Management: Linked lists allocate memory for each node
individually. This can lead to more efficient memory usage compared to
arrays.

Disadvantages:

o Not Random Access:


o Memory Overhead: Each node in a linked list requires extra memory to
store the data and a reference (pointer) to the next node.
o Reversing Order: Reversing a linked list or iterating in reverse order is
not as straightforward as with arrays, especially in singly linked lists. It
may require additional data structures or modifications to the list.

6. Hash table
Store key-value pairs.
Advantages:

o Fast Retrieval: Hash tables provide fast retrieval of values based on


their keys. The hashing function allows for constant-time (O(1))
average-case access, making them ideal for scenarios where quick data
retrieval is required.
o Efficient Insertions and Deletions:
o Flexible Key Types: Hash tables can be used with a wide range of key
types, including numbers, strings, objects, and more.
o Data Caching: Hash tables are commonly used for caching data to
speed up access to frequently used information. They can quickly
determine whether a value is cached or not.
o Implementation in Standard Libraries:

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

while (arr[index].indexOf(result) !== 0) {


result = result.substring(0, result.length - 1);
}

fun(arr, index + 1, result);


}

fun(["flower", "flow", "flight"]);

//Stack
function fun(arr) {
if (arr.length === 0) {
return "";
}

const stack = [...arr[0]];

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


while (arr[i].indexOf(stack.join("")) !== 0) {
stack.pop();
}
}

console.log(stack.join(""));
}

fun(["flower", "flow", "flight"]);

158. Evaluate Reverse Polish Notation


Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
function policeNotation(tokens) {
const stack = [];
for (const tok of tokens) {
if (!isNaN(tok)) {
stack.push(parseInt(tok));
} else {
const b = stack.pop();
const a = stack.pop();
switch (tok) {
case "+":
stack.push(a + b);
break;
case "*":
stack.push(a * b);
break;
case "-":
stack.push(a - b);
break;
case "/":
stack.push(a / b);
break;
}
}
}
return stack.pop();
}

console.log(policeNotation(["2", "1", "+", "3", "*"]));


159. Find Sum of an array.
function fun(){
const arr=[-1,2,1,-4];
let sum=0;

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;

while (arr.length > 0) {


stack += arr.pop();
}

console.log(stack);
}

fun([-1, 2, 1, -4]);

//Queue
function fun(arr) {
let stack = 0;

while (arr.length > 0) {


stack += arr.shift();
}

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

if (Math.abs(currentSum - target) <


Math.abs(closestSum - target)) {
closestSum = currentSum;
closestTriplet = [nums[i], nums[j], nums[k]];
}
}
}
}

console.log(closestTriplet);
}

fun();

161. Letter Combinations of a Phone Number.


function fun() {
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'],
};

let digits = '23';


let result = [];

let newDigits = digits.split('');


let one = newDigits[0];
let two = newDigits[1];

let arrOne = arr[one];


let arrTwo = arr[two];
if (arrOne && arrTwo) {
for (let i = 0; i < arrOne.length; i++) {
for (let j = 0; j < arrTwo.length; j++) {
result.push(arrOne[i] + arrTwo[j]);
}
}
}

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 = [];

function insert(combination, nextDigits, result) {


if (nextDigits.length === 0) {
return result.push(combination);
}

const currentLetters = arr[nextDigits[0]];

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


insert(combination + currentLetters[i],
nextDigits.slice(1), result);
}
}

insert('', digits, result);


console.log(result);
}

fun('23');

162. Valid Parentheses.


function fun(){
let left='(';
let right=')';
const result=[];

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


if (i % 2 === 0) {
result.push(left);
} else {
result.push(right);
}
}

console.log(result.join(''));
}

fun();

163. Generate Parentheses.


Given n pairs of parentheses, write a function to generate all combinations of
well-formed parentheses.
function fun(n) {
const result = [];
const stack = [['', 0, 0]];

while (stack.length > 0) {


const [current, open, close] = stack.pop();

if (current.length === 2 * n) {
result.push(current);
} else {
if (open < n) {
stack.push([current + '(', open + 1, close]);
}

if (close < open) {


stack.push([current + ')', open, close + 1]);
}
}
}

return console.log(result);
}

fun(3);

You might also like