0% found this document useful (0 votes)
4 views10 pages

Algorithm Solutions

The document provides a collection of algorithm implementations in JavaScript, focusing on various dynamic programming, backtracking, and greedy algorithms. Each algorithm is presented with its function definition, including Fibonacci, climbing stairs, coin change, subset sum, knapsack, longest common subsequence, permutations, N-Queens, rat in a maze, tower of Hanoi, activity selection, fractional knapsack, job sequencing, minimum coins, and generating balanced parentheses. Example usage for each algorithm is also included to demonstrate their functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Algorithm Solutions

The document provides a collection of algorithm implementations in JavaScript, focusing on various dynamic programming, backtracking, and greedy algorithms. Each algorithm is presented with its function definition, including Fibonacci, climbing stairs, coin change, subset sum, knapsack, longest common subsequence, permutations, N-Queens, rat in a maze, tower of Hanoi, activity selection, fractional knapsack, job sequencing, minimum coins, and generating balanced parentheses. Example usage for each algorithm is also included to demonstrate their functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

FIBONACCI (DP - MEMOIZATION)

function fib(n, memo = {}) {

if (n <= 1) return n;

if (memo[n] !== undefined) return memo[n];

memo[n] = fib(n - 1, memo) + fib(n - 2, memo);

return memo[n];

2. CLIMBING STAIRS (DP)

function climbStairs(n) {

if (n <= 1) return 1;

const dp = new Array(n + 1).fill(0);

dp[0] = 1; dp[1] = 1;

for (let i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2];

return dp[n];

3. COIN CHANGE (DP - MIN COINS)

function coinChange(coins, amount) {

const dp = new Array(amount + 1).fill(Infinity);

dp[0] = 0;

for (const coin of coins) {

for (let i = coin; i <= amount; i++) {

dp[i] = [Link](dp[i], dp[i - coin] + 1);


}

return dp[amount] === Infinity ? -1 : dp[amount];

4. SUBSET SUM (DP)

function subsetSum(nums, target) {

const n = [Link];

const dp = [Link]({ length: n + 1 }, () => new Array(target + 1).fill(

for (let i = 0; i <= n; i++) dp[i][0] = true;

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

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

if (nums[i - 1] <= j) dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]

else dp[i][j] = dp[i - 1][j];

return dp[n][target];

5. 0/1 KNAPSACK (DP)

function knapsack(weights, values, W) {

const n = [Link];

const dp = [Link]({ length: n + 1 }, () => new Array(W + 1).fill(0));

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

for (let w = 1; w <= W; w++) {

if (weights[i - 1] <= w) {

dp[i][w] = [Link](values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i -

} else dp[i][w] = dp[i - 1][w];


}

return dp[n][W];

6. LONGEST COMMON SUBSEQUENCE (DP)

function lcs(a, b) {

const n = [Link], m = [Link];

const dp = [Link]({ length: n + 1 }, () => new Array(m + 1).fill(0));

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

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

if (a[i - 1] === b[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1];

else dp[i][j] = [Link](dp[i - 1][j], dp[i][j - 1]);

return dp[n][m];

7. PERMUTATIONS (BACKTRACKING)

function permute(nums) {

const res = [];

function backtrack(path, used) {

if ([Link] === [Link]) {

[Link]([Link]());

return;

for (let i = 0; i < [Link]; i++) {

if (used[i]) continue;
used[i] = true;

[Link](nums[i]);

backtrack(path, used);

[Link]();

used[i] = false;

backtrack([], new Array([Link]).fill(false));

return res;

8. N-QUEENS (BACKTRACKING)

function solveNQueens(n) {

const res = [];

const cols = new Set(), diag1 = new Set(), diag2 = new Set();

const board = Array(n).fill().map(() => Array(n).fill('.'));

function backtrack(r) {

if (r === n) {

[Link]([Link](row => [Link]('')).slice());

return;

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

if ([Link](c) || [Link](r - c) || [Link](r + c)) continue;

[Link](c); [Link](r - c); [Link](r + c);

board[r][c] = 'Q';

backtrack(r + 1);

board[r][c] = '.';

[Link](c); [Link](r - c); [Link](r + c);

}
}

backtrack(0);

return res;

9. RAT IN A MAZE (BACKTRACKING)

function ratInMaze(maze) {

const n = [Link];

const res = [];

const visited = [Link]({ length: n }, () => new Array(n).fill(false));

const dirs = [[1,0,'D'], [0,1,'R'], [-1,0,'U'], [0,-1,'L']];

function dfs(x, y, path) {

if (x === n - 1 && y === n - 1) {

[Link](path);

return;

for (const [dx, dy, move] of dirs) {

const nx = x + dx, ny = y + dy;

if (nx >= 0 && nx < n && ny >= 0 && ny < n && maze[nx][ny] === 1 && !visit

visited[nx][ny] = true;

dfs(nx, ny, path + move);

visited[nx][ny] = false;

if (maze[0][0] === 1) {

visited[0][0] = true;

dfs(0, 0, '');

}
return res;

10. TOWER OF HANOI (RECURSION)

function towerOfHanoi(n, from, to, aux, moves = []) {

if (n === 1) {

[Link](`Move disk 1 from ${from} to ${to}`);

return moves;

towerOfHanoi(n - 1, from, aux, to, moves);

[Link](`Move disk ${n} from ${from} to ${to}`);

towerOfHanoi(n - 1, aux, to, from, moves);

return moves;

11. ACTIVITY SELECTION (GREEDY)

function activitySelection(start, end) {

const acts = [Link]((s, i) => ({ s, e: end[i] }))

.sort((a, b) => a.e - b.e);

const res = [];

let lastEnd = -Infinity;

for (const a of acts) {

if (a.s >= lastEnd) {

[Link](a);

lastEnd = a.e;

return res;
}

12. FRACTIONAL KNAPSACK (GREEDY)

function fractionalKnapsack(weights, values, W) {

const items = [Link]((v, i) => ({ v, w: weights[i], idx: i }))

.sort((a, b) => (b.v / b.w) - (a.v / a.w));

let total = 0;

for (const it of items) {

if (W === 0) break;

if (it.w <= W) {

W -= it.w;

total += it.v;

} else {

total += it.v * (W / it.w);

W = 0;

return total;

13. JOB SEQUENCING (GREEDY)

function jobSequencing(jobs, deadlines, profits) {

const arr = [Link]((j, i) => ({ j, d: deadlines[i], p: profits[i] }))

.sort((a, b) => b.p - a.p);

const maxD = [Link](...deadlines);

const slot = new Array(maxD).fill(null);

let total = 0;

for (const job of arr) {


for (let t = job.d - 1; t >= 0; t--) {

if (slot[t] === null) {

slot[t] = job.j;

total += job.p;

break;

return total;

14. MINIMUM COINS (GREEDY - CANONICAL SETS)

function minCoins(coins, amount) {

[Link]((a,b)=>b-a);

let count = 0;

for (const c of coins) {

if (amount === 0) break;

const take = [Link](amount / c);

count += take;

amount -= take * c;

return amount === 0 ? count : -1;

15. GENERATE BALANCED PARENTHESES (BACKTRACKING)

function generateParentheses(n) {

const res = [];

function backtrack(s, open, close) {


if ([Link] === 2 * n) {

[Link](s);

return;

if (open < n) backtrack(s + '(', open + 1, close);

if (close < open) backtrack(s + ')', open, close + 1);

backtrack('', 0, 0);

return res;

EXAMPLE USAGE

[Link]('fib(10)=', fib(10));

[Link]('climbStairs(5)=', climbStairs(5));

[Link]('coinChange([1,2,5],11)=', coinChange([1,2,5], 11));

[Link]('subsetSum([3,34,4,12,5,2],9)=', subsetSum([3,34,4,12,5,2], 9))

[Link]('knapsack([1,3,4,5],[1,4,5,7],7)=', knapsack([1,3,4,5],[1,4,5,7

[Link]('lcs("abcde","ace")=', lcs('abcde', 'ace'));

[Link]('permute([1,2,3])=', permute([1,2,3]));

[Link]('solveNQueens(4).length=', solveNQueens(4).length);

[Link]('ratInMaze sample=', ratInMaze([[1,0,0,0],[1,1,0,1],[0,1,0,0],[


[Link]('towerOfHanoi(3)=', towerOfHanoi(3,'A','C','B'));

[Link]('activitySelection=', activitySelection([1,3,0,5,8,5],[2,4,6,7,

[Link]('fractionalKnapsack=', fractionalKnapsack([10,20,30],[60,100,12

[Link]('jobSequencing=', jobSequencing(['a','b','c','d'],[2,1,2,1],[10

[Link]('minCoins=', minCoins([1,2,5,10,20,50,100,500,2000],121));

[Link]('generateParentheses(3)=', generateParentheses(3));

You might also like