Categories
Array Loop Matrix

Spiral Matrix

function spiralMatrix(dimension) {

    let matrix = [];
    // create blank matrix based from given dimension
    for (let i = 0; i < dimension; i++) {
        matrix.push(new Array(dimension).fill(0))
    }

    let counter = 1;
    let startRow = 0, endRow = dimension, startColumn = 0, endColumn = dimension;


    while (startRow < endRow && startColumn < endColumn) {

        // top left -> top right
        for (let i = startColumn; i < endColumn; i++) {
            matrix[startRow][i] = counter++;
        }
        startRow++

        // top right -> bottom right
        for (let i = startRow; i < endRow; i++) {
            matrix[i][endColumn - 1] = counter++;
        }
        endColumn--;

        // bottom right -> bottom left
        for (let i = endColumn - 1; i >= startColumn; i--) {
            matrix[endRow - 1][i] = counter++;
        }
        endRow--;


        // bottom left -> top left
        for (let i = endRow; i > startRow; i--) {
            matrix[i - 1][startColumn] = counter++;
        }
        startColumn++;

    }

     return matrix;
}

Categories
Array Loop Matrix

Game Of Life (Optimized)

let gameOfLife = function(board) {

    if (!board) return [];

    let LIVE = 1,
        DEAD = 0,
        ALIVE_TO_DEAD = 0b01, // [next state, current state]
        ALIVE_TO_ALIVE = 0b11,
        DEAD_TO_ALIVE = 0b10,
        DEAD_TO_DEAD = 0b00,
        maxRow = board.length - 1,
        maxCol = board[0].length - 1;

    function getAdjacentCount(row, col, valueToCompare) {
        let sum = 0;
        for (let i = Math.max(row - 1, 0); i <= Math.min(row + 1, maxRow); i++) {
            for (let j = Math.max(col - 1, 0); j <= Math.min(col + 1, maxCol); j++) {
                if (i === row && j === col) continue;
                if (board[i][j] & 1 === valueToCompare) sum = sum + 1;
            }
        }
        return sum;
    }

    function getNextValue(row, col) {
        const val = board[row][col];
        let liveNeighbors = getAdjacentCount(row, col, LIVE);
        if (val === LIVE) {

            // Any live cell with fewer than two live neighbors dies, as if caused by under-population.
            // Any live cell with more than three live neighbors dies, as if by over-population..
            if (liveNeighbors < 2 || liveNeighbors > 3) {
                return ALIVE_TO_DEAD;
            }
            // Any live cell with two or three live neighbors lives on to the next generation.
            return ALIVE_TO_ALIVE;
        }
        // cell is DEAD
        else {
            // Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
            if (liveNeighbors === 3) {
                return DEAD_TO_ALIVE;
            }
            // no condition
            return DEAD_TO_DEAD;
        }
    }

    for (let row = 0; row <= maxRow; row++) {
        for (let col = 0; col <= maxCol;col++) {
            board[row][col] = getNextValue(row, col);
        }
    }

    for (let row = 0; row <= maxRow; row++) {
        for (let col = 0; col <= maxCol;col++) {
            board[row][col] = board[row][col] >> 1;
        }
    }

};
Categories
Array Loop Matrix

Game Of Life

let gameOfLife = function(board) {

if (!board) return [];

let copy = [],
LIVE = 1,
DEAD = 0,
maxRow = board.length - 1,
maxCol = board[0].length - 1;

function getAdjacentCount(row, col, valueToCompare) {
let sum = 0;
for (let i = Math.max(row - 1, 0); i <= Math.min(row + 1, maxRow); i++) {
for (let j = Math.max(col - 1, 0); j <= Math.min(col + 1, maxCol); j++) {
if (i === row && j === col) continue;
if (copy[i] && copy[i][j] !== undefined) {
if (copy[i][j] === valueToCompare) sum = sum + 1; //?
}
else {
if (board[i][j] === valueToCompare) sum = sum + 1; //?
}
}
}
return sum;
}

function getNextValue(row, col) {
const val = board[row][col];
let liveNeighbors = getAdjacentCount(row, col, LIVE);
if (val === LIVE) {

// Any live cell with fewer than two live neighbors dies, as if caused by under-population.
if (liveNeighbors < 2) {
return DEAD;
}
// Any live cell with more than three live neighbors dies, as if by over-population..
else if (liveNeighbors > 3) {
return DEAD;
}
// Any live cell with two or three live neighbors lives on to the next generation.
return LIVE;
}
// cell is DEAD
else {
// Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
if (liveNeighbors === 3) {
return LIVE;
}
// no condition
return DEAD;
}
}

for (let row = 0; row <= maxRow; row++) {
copy[row] = [];
for (let col = 0; col <= maxCol;col++) {
copy[row][col] = board[row][col];
board[row][col] = getNextValue(row, col);
}
}

};
Categories
Leetcode Loop

LinkedList Palindrome

let isPalindrome = function(head) {

let slow = head, fast = head, val = [slow.val];

while (fast.next) {
if (fast.next.next) {
fast = fast.next.next;
slow = slow.next;
val.push(slow.val);
}
else {
fast = fast.next;
slow = slow.next;
}
}

while (slow) {
if (slow.val !== val.pop()) {
return false;
}
slow = slow.next;
}

return val.length === 0;
};
Categories
Array Loop

Fizz Buzz

let fizzBuzz = function(n) {

let result = [];
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
result.push("FizzBuzz");
}
else if (i % 3 === 0) {
result.push("Fizz");
}
else if (i % 5 === 0) {
result.push("Buzz");
}
else {
result.push('' + i);
}
}

return result;
};
Categories
Array Leetcode Loop

Pascal Triangle

let generate = function(numRows) {

if (numRows === 0) return [];

let result = [];
for (let i = 1; i <= numRows;i++) {
let row = [];
for (let j = 0; j < i; j++) {
if (j === 0 || j === i - 1) {
row[j] = 1;
}
else {
row[j] = result[i - 2][j - 1] + result[i - 2][j];
}
}
result.push(row);
}

return result;
};
Categories
Leetcode Loop String

Roman To Int

let romanToInt = function(s) {
if (!s) return 0;

let mapping = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}

let result = 0;
for (let i = s.length - 1; i >= 0;) {
if (mapping[s[i]] > mapping[s[i - 1]]) {
result += mapping[s[i]] - mapping[s[i - 1]];
i -= 2;
}
else {
result += mapping[s[i]];
i -= 1;
}
}

return result;
}
Categories
Dynamic Programming Leetcode Loop

Unique Paths (Iterative)

let uniquePaths = function(m, n) {

let getKey = (row, col) => `${row}${col}`;

let cache = { }
for (let row = 1; row <= m; row++) {
for (let col = 1; col <= n; col++) {
if (row === 1) {
cache[getKey(row, col)] = 1;
}
else if (col === 1) {
cache[getKey(row, col)] = 1;
}
else {
cache[getKey(row, col)] = cache[getKey(row-1, col)] + cache[getKey(row, col - 1)];
}
}
}

return cache[getKey(m,n)];
};
Categories
Array Leetcode Loop

Two Sum Less Than K

let twoSumLessThanK = function(A, K) {
let max = -1, start = 0, end = A.length - 1;
A.sort((a, b) => b - a); //?

while (start < end) {
let sum = A[start] + A[end];
if (sum < K) {
max = Math.max(sum, max);
end--;
}
else {
start++;
}
}

return max;
};
Categories
Array Leetcode Loop String

Reorganize String

let reorganizeString = function(S) {
let chars = {}, max = 0;
for(let i = 0; i < S.length;i++) {
if (chars[S[i]]) {
chars[S[i]] = chars[S[i]] + 1;
max = Math.max(chars[S[i]], max);
}
else {
chars[S[i]] = 1;
}
}

console.log(max, Math.floor((S.length + 1) / 2));
if (max > (S.length + 1) / 2) {
return "";
}

let result = [], index = 0;
const keys = Object.keys(chars).sort((a, b) => chars[b] - chars[a]); //?
while (keys.length) { //?
const key = keys.shift(); //?
result[index] = key;

if (chars[key] - 1 > 0) {
chars[key] = chars[key] - 1;
keys.unshift(key); //?
}

index += 2; //?
if (index >= S.length) {
index = 1;
}
}

return result.join('');
};