Categories
Leetcode

Two Sum

function twoSum(nums, target) {
    let result = [],
        cache = {};
    for (let i = 0; i < nums.length; i++) {
        let x = target - nums[i];
        if (cache[x] !== undefined) {
            result.push([cache[x], i]);
        }
        cache[nums[i]] = i;
    }

    return result;
};
Categories
Leetcode Parenthesis String

Valid Parenthesis

function validParenthesis(str) {

let closingMap = {
')' : '(',
']' : '[',
'}' : '{'
}

let chars = [];
for(let i = 0; i < str.length; i++) {
if (str[i] === '(' || str[i] === '[' || str[i] === '{') {
chars.push(str[i]);
}
else {
let compare = chars.pop();
if (closingMap[str[i]] !== compare) return false;
}
}
return chars.length === 0;
}
Categories
Binary Search Recursion

Binary Search

function binarySearch(arr, n, start = 0, end = arr.length) {
let mid = Math.floor((end + start) / 2);
if (arr[mid] === n) return mid;

if (start < end - 1) {
if (n > arr[mid]) {
return binarySearch(arr, n, mid, end);
} else {
return binarySearch(arr, n, start, mid);
}
}
return -1;
}
Categories
Binary Tree Leetcode Recursion

Is Same Tree

let isSameTree = function(p, q) {

if (p === q) return true;
if (p?.val !== q?.val) return false;

return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};
Categories
Binary Tree Leetcode Recursion

Invert a Binary Tree

let invertTree = function(root) {

    if (root) {
        const right = root.right;
        root.right = invertTree(root.left)
        root.left = invertTree(right)
        return root;
    }
    return null;
};