Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Js solutions #63

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
8 changes: 8 additions & 0 deletions 01_Fizz Buzz/Ideal Solutions/fizzBuzz.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const fizzBuzz = (N) => {
for (let i = 1; i <= N; i++) {
if (i % 3 == 0 && i % 5 == 0) console.log("FizzBuzz " + i);
else if (i % 3 === 0) console.log("Fizz " + i);
else if (i % 5 === 0) console.log("Buzz " + i);
}
};
fizzBuzz(15);
12 changes: 12 additions & 0 deletions 02_Check for prime/Ideal Solutions/checkPrime.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const checkPrime = (N) => {
if (N <= 0) return 0;
for (let i = 2; i ** 2 < N; i++) {
if (N % i === 0) {
return false;
}
}
return true;
};
console.log(checkPrime(-1));


Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const binaryRepresentation = (N) => {
let i;
process.stdout.write("0");
for (i = 1 << 30; i > 0; i = Math.floor(i / 2)) {
if ((N & i) != 0) {
process.stdout.write("1");
} else {
process.stdout.write("0");
}
}
};
binaryRepresentation(7);
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const binaryToNumber = (str) => {
let base = 1,
ans = 0;
for (let i = str.length - 1; i >= 0; i--) {
if (str[i] == "1") {
ans += base;
base *= 2;
}
}
return ans;
};
console.log(binaryToNumber("00000000000000000000000000000111"));
14 changes: 14 additions & 0 deletions 05_Check for anagram/Ideal Solutions/checkAnagram.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* input: N = 4, X = abcd, M = 4, Y = dacb */
const checkAnagram = (str1, str2) => {
if (str1.length !== str2.length) return false;
str1.sort();
str2.sort();
for (let i in str1) {
if (str1[i] !== str2[i]) {
return false;
}
}
return true;
};

console.log(checkAnagram("cdab".split(""), "dacb".split("")));
12 changes: 12 additions & 0 deletions 06_Check for palindrome/Ideal Solutions/checkPalindrome.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/* input: N = 9, string: malayalam */
const checkPalindrome = (str) => {
let i = 0,
j = str.length - 1;
while (i < j) {
if (str[i] !== str[j]) return false;
i++;
j--;
}
return true;
};
console.log(checkPalindrome("malayalam"));
12 changes: 12 additions & 0 deletions 07_Power of two/Ideal Solutions/powerOfTwo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
Given a positive integer N.
Check if it is a power of two or not.
*/

const powerOfTwo = (N) => {
while (N % 2 == 0) {
N /= 2;
}
return N === 1 ? true : false;
};
console.log(powerOfTwo(18));
20 changes: 20 additions & 0 deletions 08_Bubble sort/Ideal Solutions/bubbleSort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* Given an array A having N positive integers. Sort the array A using bubble sort.
*/
const swap = (arr, i, j) => {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
};

const bubbleSort = (arr) => {
if (!arr.length) return 0;
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
return arr;
};
console.log(bubbleSort([83, 4, 5, 2, 1, 6, 7]));
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/* Given an input array, sort the array using Quick Sort */

function swap(arr, i, j) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

/* Divide and rule 1946 16 aug*/
function partition(arr, low, high) {
let pivot = arr[high];
let i = low - 1;
for (let j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}

function sortUsingQuicksort(arr, low, high) {
if (low < high) {
let pi = partition(arr, low, high);
sortUsingQuicksort(arr, low, pi - 1);
sortUsingQuicksort(arr, pi + 1, high);
}
}
let arr = [10, 7, 8, 9, 1, 5];
let n = arr.length;

sortUsingQuicksort(arr, 0, n - 1);
console.log(arr);
20 changes: 20 additions & 0 deletions 10_Balanced Parenthesis/Ideal Solutions/balancedParenthesis.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* Given a string S having N characters. Any of the characters of the string are either of '(', '{', '[', ')', '}', ']'. Check whether the pairs and the orders of '{', '}', '(', ')', '[', ']' are correct or not.
*/
const balancedParenthesis = (str) => {
const stack = [];
for (let curr of str) {
const top = stack[stack.length - 1];
if (top === "(" && curr === ")") {
stack.pop();
} else if (top === "[" && curr === "]") {
stack.pop();
} else if (top === "{" && curr === "}") {
stack.pop();
} else {
stack.push(curr);
}
}
return stack.length === 0;
};

console.log(balancedParenthesis("[()]{}".split("")));
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const findDuplicatesInArray = (arr) => {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
let end = arr.length - 1;
let value = (end * (end + 1)) / 2;
return Math.abs(value - sum);
};

console.log(findDuplicatesInArray([1, 1, 3, 2, 4]));
53 changes: 53 additions & 0 deletions 12_Infix-Postfix/Ideal Solutions/infixPostfix.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
Infix Expression-
Operators are written in-between their operands. This is the usual way we write expressions.
example : a + b * c + d

Postfix Expression- If the operator appears in the expression after the operands.
example : abc * + d+

*/

const isalnum = (value) => {
const regex = /^[a-zA-Z0-9]+$/;
return value.match(regex) ? true : false;
};

const priority = (char) => {
if (char == "^") return 3;
else if (char == "/" || char == "*") return 2;
else if (char == "+" || char == "-") return 1;
else return -1;
};

function infixPostfix(s) {
let st = [];
let result = "";

for (let i = 0; i < s.length; i++) {
let c = s[i];
if (isalnum(c)) result += c;
else if (c == "(") st.push("(");
else if (c == ")") {
while (st[st.length - 1] != "(") {
result += st[st.length - 1];
st.pop();
}
st.pop();
} else {
while (st.length != 0 && priority(s[i]) <= priority(st[st.length - 1])) {
result += st[st.length - 1];
st.pop();
}
st.push(c);
}
}

while (st.length != 0) {
result += st[st.length - 1];
st.pop();
}

return result;
}
console.log(infixPostfix("a+b-c+d*(e-f)/g+(h*(i/j))".split("")));
28 changes: 28 additions & 0 deletions 13_Min Stack/Ideal Solutions/minStack.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Stack {
_stack = [];

push(val) {
const min = Math.min(val, this.getMin());
this._stack.push([val, min]);
}
top() {
return this.peek()[0];
}
pop() {
return this._stack.pop();
}

peek() {
return this._stack[this._stack.length - 1] || 0;
}
getMin() {
return this.peek()[1] ?? Infinity;
}
}

const stack = new Stack();
stack.push(2);
stack.push(6);
stack.push(0);
stack.push(10);
console.log(stack.getMin()); //0
38 changes: 38 additions & 0 deletions 14_Queue Using Two Stacks/Ideal Solutions/queueUsingStacks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Queue {
constructor() {
this.stack1 = [];
this.stack2 = [];
}

enqueue(value) {
this.stack1.push(value);
}

dequeue() {
if (!this.stack2.length)
while (this.stack1.length !== 0) {
this.stack2.push(this.stack1.pop());
}
return this.stack2[this.stack2.length - 1] === undefined
? "empty"
: this.stack2.pop();
}
isEmpty() {
return this.stack1.length === 0 && this.stack2.length === 0;
}
peek() {
if (this.isEmpty()) return "empty queue";
return this.stack2.length === 0
? this.stack1[0]
: this.stack2[this.stack2.length - 1];
}
}
const queue = new Queue();

queue.enqueue(0);
queue.enqueue(2);

console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.peek());
29 changes: 29 additions & 0 deletions 15_Stacksusing two Queues/Ideal Solutions/stackUsingTwoQueues.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Stack {
#Q1 = [];
#Q2 = [];

push(value) {
if (this.#Q1.length !== 0) {
while (this.#Q1.length) {
this.#Q2.push(this.#Q1.shift());
}
this.#Q1.push(value);
while (this.#Q2.length) {
this.#Q1.push(this.#Q2.shift());
}
} else {
this.#Q1.push(value);
}
}
pop() {
return this.#Q1.length ? this.#Q1.shift() : "empty";
}
}

const stack = new Stack();
/* stack.push(9);
console.log(stack.pop());
console.log(stack.pop());
stack.push(10);
console.log(stack.pop());
*/
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/* Given an array A having N positive integers. Find the nearest smaller number for every element such that the smaller element is on left side.

Note - If any element doesn't have any smaller element that it to it's left, print -1 for it.
*/

/* **Sample Input**
input: N = 5
A : 1 2 5 3 5

**Sample Output**
A: -1 1 2 2 3

*/

const input = `1 2 5 3 5`.split(" ").map(Number);

function nearestsmallernumber(arr) {
let stack = [];
let res = [];
for (let i in arr) {
while (stack.length && stack[stack.length - 1] >= arr[i]) {
stack.pop();
}
if (stack.length) {
res.push(stack[stack.length - 1]);
} else res.push(-1);
stack.push(arr[i]);
}
return res.join(" ");
}

console.log(nearestsmallernumber(input)); //-1 1 2 2 3
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
let arr = [0, 1, 2, 0, 1, 2];

const sortAnArrayOf012 = (arr) => {
let mid = 0;
let left = 0;
let end = arr.length - 1;
while (mid <= end) {
if (arr[mid] === 0) {
let tmp = arr[mid];
arr[mid] = arr[left];
arr[left] = tmp;
left++;
mid++;
} else if (arr[mid] === 1) {
mid++;
} else if (arr[mid] === 2) {
let tmp = arr[mid];
arr[mid] = arr[end];
arr[end] = tmp;
end--;
}
}
return arr;
};
console.log(sortAnArrayOf012(arr));
Loading