JAVASCRIPT - rs-hash/Senior GitHub Wiki
Algorithmic Problem Solving:
Write a function to check if a string is a palindrome.
function isPalindrome(str) {
return str === str.split('').reverse().join('');
}
Implement a function to reverse a linked list.
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
reverse() {
let prev = null;
let current = this.head;
let next = null;
while (current !== null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
this.head = prev;
}
}
Solve the classic FizzBuzz problem efficiently.
function fizzBuzz(n) {
for (let i = 1; i <= n; i++) {
let output = '';
if (i % 3 === 0) output += 'Fizz';
if (i % 5 === 0) output += 'Buzz';
console.log(output || i);
}
}
Implement a binary search algorithm.
function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1; // Not found
}
Write a function to find the factorial of a number.
function factorial(n) {
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
}
Data Structures:
Implement a stack data structure in JavaScript.
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
if (this.isEmpty()) return null;
return this.items.pop();
}
peek() {
return this.isEmpty() ? null : this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
clear() {
this.items = [];
}
}
Create a queue using arrays and demonstrate its functionalities.
class Queue {
constructor() {
this.items = [];
}
enqueue(item) {
this.items.push(item);
}
dequeue() {
if (this.isEmpty()) return null;
return this.items.shift();
}
front() {
return this.isEmpty() ? null : this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
clear() {
this.items = [];
}
}
Implement a binary tree and write functions for traversal (in-order, pre-order, post-order).
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinaryTree {
constructor() {
this.root = null;
}
inOrderTraversal(node = this.root) {
if (node !== null) {
this.inOrderTraversal(node.left);
console.log(node.value);
this.inOrderTraversal(node.right);
}
}
preOrderTraversal(node = this.root) {
if (node !== null) {
console.log(node.value);
this.preOrderTraversal(node.left);
this.preOrderTraversal(node.right);
}
}
postOrderTraversal(node = this.root) {
if (node !== null) {
this.postOrderTraversal(node.left);
this.postOrderTraversal(node.right);
console.log(node.value);
}
}
}
Solve a problem using a hash table or dictionary.
function countCharacters(str) {
const charCount = {};
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
return charCount;
}
Design and implement a priority queue.
class PriorityQueue {
constructor() {
this.items = [];
}
enqueue(item, priority) {
this.items.push({ item, priority });
this.items.sort((a, b) => a.priority - b.priority);
}
dequeue() {
if (this.isEmpty()) return null;
return this.items.shift().item;
}
front() {
return this.isEmpty() ? null : this.items[0].item;
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
clear() {
this.items = [];
}
}
String Manipulation:
Write a function to remove duplicate characters from a string.
function removeDuplicates(str) {
return Array.from(new Set(str)).join('');
}
Implement a function to check if two strings are anagrams of each other.
function areAnagrams(str1, str2) {
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
Reverse words in a sentence without using built-in functions.
function reverseWords(sentence) {
return sentence.split(' ').map(word => {
let reversed = '';
for (let i = word.length - 1; i >= 0; i--) {
reversed += word[i];
}
return reversed;
}).join(' ');
}
Find the longest common substring between two strings.
function longestCommonSubstring(str1, str2) {
let longest = '';
for (let i = 0; i < str1.length; i++) {
for (let j = i + 1; j <= str1.length; j++) {
const substr = str1.substring(i, j);
if (str2.includes(substr) && substr.length > longest.length) {
longest = substr;
}
}
}
return longest;
}
Write a function to convert a string to Title Case.
function toTitleCase(str) {
return str.toLowerCase().split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
}
Array Operations:
Find the maximum and minimum elements in an array.
function findMinMax(arr) {
return {
max: Math.max(...arr),
min: Math.min(...arr)
};
}
Remove duplicates from an array without using additional data structures.
function removeDuplicates(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
Implement a function to rotate an array by a given number of steps.
function rotateArray(arr, steps) {
const rotated = [...arr];
for (let i = 0; i < steps; i++) {
rotated.unshift(rotated.pop());
}
return rotated;
}
Find the intersection of two arrays.
function intersection(arr1, arr2) {
return arr1.filter(item => arr2.includes(item));
}
Implement a function to shuffle an array.
function shuffleArray(arr) {
const shuffled = [...arr];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
Sorting and Searching:
Implement a sorting algorithm (e.g., bubble sort, insertion sort, quicksort).
function bubbleSort(arr) {
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]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
Write a function to perform a binary search in a sorted array.
function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1; // Not found
}
Sort an array of objects based on a specific property.
function sortByProperty(arr, property) {
return arr.sort((a, b) => a[property] - b[property]);
}
Find the kth smallest/largest element in an array.
function kthSmallest(arr, k) {
return arr.sort((a, b) => a - b)[k - 1];
}
function kthLargest(arr, k) {
return arr.sort((a, b) => b - a)[k - 1];
}
Implement a searching algorithm (e.g., linear search, binary search).
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1; // Not found
}
Dynamic Programming:
Solve the Fibonacci sequence using dynamic programming.
function fibonacci(n) {
const fib = [0, 1];
for (let i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
Implement a function to calculate the nth Fibonacci number efficiently.
function fibonacci(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 1) return n;
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
return memo[n];
}
Solve a problem using memoization or tabulation techniques.
Memoization Example:
function factorial(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 1) return 1;
memo[n] = n * factorial(n - 1, memo);
return memo[n];
}
Write a function to find the longest increasing subsequence in an array.
function longestIncreasingSubsequence(arr) {
const dp = new Array(arr.length).fill(1);
let maxLength = 1;
for (let i = 1; i < arr.length; i++) {
for (let j = 0; j < i; j++) {
if (arr[i] > arr[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
maxLength = Math.max(maxLength, dp[i]);
}
}
}
return maxLength;
}
Solve the 0/1 Knapsack problem using dynamic programming.
function knapsack(weights, values, capacity) {
const n = weights.length;
const dp = Array.from(Array(n + 1), () => Array(capacity + 1).fill(0));
for (let i = 1; i <= n; i++) {
for (let w = 1; w <= capacity; w++) {
if (weights[i - 1] <= w) {
dp[i][w] = Math.max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
return dp[n][capacity];
}
Problem-Solving Scenarios:
Given an array of numbers, find pairs that sum up to a specific target.
function findPairs(arr, target) {
const pairs = [];
const seen = new Set();
for (let num of arr) {
const complement = target - num;
if (seen.has(complement)) {
pairs.push([num, complement]);
}
seen.add(num);
}
return pairs;
}
Implement a function to validate a credit card number.
function validateCreditCard(cardNumber) {
const sanitized = cardNumber.replace(/\D/g, '');
if (sanitized.length !== 16) return false;
const sum = sanitized.split('').reduce((acc, digit) => acc + parseInt(digit), 0);
return sum % 10 === 0;
}
### Solve a problem related to calculating discounts or taxes based on certain conditions.
```jsx
function calculateDiscount(price, discountPercent, threshold) {
if (price >= threshold) {
return price * (1 - discountPercent / 100);
}
return price;
}
Design and implement an algorithm to handle pagination efficiently.
function paginate(items, pageNumber, pageSize) {
const startIndex = (pageNumber - 1) * pageSize;
return items.slice(startIndex, startIndex + pageSize);
}