Press "Enter" to skip to content

Posts tagged as “Guide”

List some handy functions in Javascript

Array.isArray()

The isArray() method checks if the specified parameter is an array. Returns a true if is an array.

Array.isArray('string'); // false
Array.isArray(123); // false
Array.isArray(['I am Array']); // true
Array.isArray({key: value}); // false

Array.find()

The find() method is used to get the value of the first element in the array that satisfies the provided condition.

array.find(function(currentValue, index, arr),thisValue)
['apple','bannna','pear'].find(function(name) {
    return name === 'apple';
});

// or ES6 arrow functions
['apple','bannna','pear'].find(name => name === 'apple');

const people = [
  { name: 'Tom', username: 'tom2020' },
  { name: 'Jason', username: 'jason009' },
  { name: 'Rose', username: 'rose123' },
];
people.find(person => person.name === 'Tom');
// output: { name: 'Tom', username: 'tom2020' }

// find array item with index of 3
const atIndex = items.find(function(element, index){
  return index === 3
})

// display array item found
console.log(atIndex)

Array.filter()

The filter() method returns an array containing elements of the target array that match the set test. The callback function containing a test is passed as an argument to the filter method.

const filteredArray = targetArray.filter(callbackFunction(element[,index[,array]])[, thisArg])
const names = ['Kevin', 'Peter', 'Jason', 'Epso', 'Hang'];

// Filter the array for names having 'o'
const nameHasO = names.filter(name => name.includes('o'));

Another good example: Boolean() is also a function that returnstrue when true,

or false when if the value is omitted or is 0-0nullfalseNaNundefined, or the empty string ("").

var array = [1, 2, "b", 0, {}, "", NaN, 3, undefined, null, 5];

var newArray = array.filter(Boolean);  // [1, 2, "b", {}, 3, 5]; 

Array.every()

The every method checks that each element in an array passes a set test. This method will return true if all the elements pass the test. Otherwise returns false.

array.every(callback(element[, index[, array]])[, thisArg])
const students = [{name: 'Tom', score: 70} , {name: 'Jason', score: 80}, {name: 'King', score: 95}];

// Test callback function
const studentsPassed = students.every(student => student.score >= 60);

console.log(studentsPassed) // Output: true

Array.some()

This method checks if any of the elements contained in an array passes a set test. If at least one of the elements passes this test, true is returned. This method only returns a Boolean.

const bool = array.some(callback(element[, index[, array]])[, thisArg])
const cities = [{city: 'Oakland', zipCode: '94602'}, {city: 'San Francisco'}];

// Verify properties of an object
let hasZipCode = cities.some(function(city){
  return !!city.zipCode;
})
console.log(hasZipCode); // Output: true

Array.toString() 

This method returns a String representation of the elements within the calling array. This method is somewhat similar to the join(',') method.

['Hello', 'World!'].toString()
// 'Hello,World!'
['1', '2', '3', '4'].toString()
// '1,2,3,4'

Array slice() vs. splice() vs. split()

According to the documentation: The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.

Argument 2: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

let array = [1,2,3,4,5]
console.log(array.slice(2));
// output: [3, 4, 5], returned selected element(s).
 
console.log(array.slice(-2));
// output: [4, 5], returned selected element(s).
console.log(array);
// output: [1, 2, 3, 4, 5], original array remains intact.
 
           -5 -4 -3 -2 -1
            |  |  |  |  |
let array2=[6, 7, 8, 9, 10];
             |  |  |  |  |
             0  1  2  3  4
console.log(array2.slice(2,4));
// output: [8, 9]
 
console.log(array2.slice(-2,4));
// output: [9]
 
console.log(array2.slice(-3,-1));
// output [8, 9]

The splice() method changes an existing array by removing, adding and/or replacing specified elements from it. The method mutates the original array and returns an array of all elements removed from the array. An empty array is returned if no elements are removed.

  • The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.
  • The splice() method changes the original array and slice() method doesn’t change the original array.
  • The splice() method can take n number of arguments:
let array = [1,2,3,4,5];
console.log(array.splice(2));
// output: [3, 4, 5], returned removed item(s) as a new array object.
 
console.log(array);
// output: [1, 2], original array altered.
 
var array2 = [6,7,8,9,10];
console.log(array2.splice(2,1));
// output: [8]
 
console.log(array2.splice(2,0));
// output: [] , no item(s) selected means no item(s) removed.
 
console.log(array2);
// output: [6,7,9,10]
 
let array3 = [11,12,13,14,15];
console.log(array3.splice(2,1,"apple","banana"));
// output: [13]
 
console.log(array3);
// output: [11, 12, "apple", "banana", 14, 15]
 
           -5 -4 -3 -2 -1
            |  |  |  |  |
var array4=[16,17,18,19,20];
             |  |  |  |  |
             0  1  2  3  4
 
console.log(array4.splice(-2,1,"string"));
// output:  [19]
 
console.log(array4);
// output: [16, 17, 18, "string", 20]

Split ( )

Slice( ) and splice( ) methods are for arrays. The split( ) method is used for strings. It divides a string into substrings and returns them as an array. Syntax:

string.split(separator, limit);

  • Separator: Defines how to split a string… by a comma, character etc.
  • Limit: Limits the number of splits with a given number
let str = "How are you doing today?";
let newStr = str.split(" ", 3);
// newStr: ['How','are','you']

This page will be updated every time if I find something interesting.

LeetCode Beginner to Expert Road Path 2

Tree

129. Sum Root to Leaf Numbers

112. Path Sum

814. Binary Tree Pruning

Divide and conquer

912. Sort an Array Merge Sort

153. Find Minimum in Rotated Sorted Array Binary Search

169. Majority Element

Linked List

148. Sort List

206. Reverse Linked List

24. Swap Nodes in Pairs

Binary Search Tree (BST)

108. Convert Sorted Array to Binary Search Tree Recursion + Divide and Conquer

230. Kth Smallest Element in a BST

700. Search in a Binary Search Tree

Graph

841. Keys and Rooms (DFS)

200. Number of Islands Traverse connected components (DFS)

133. Clone Graph Queue + Hashtable

Search / Backtracking (DFS/BFS)

79. Search Word (DFS)

17. Letter Combinations of a Phone Number Combination

37. Sudoku Solver (DFS)

Binary Search

99. Recover Binary Search Tree

74. Search a 2D Matrix

35. Search Insert Position

Two Pointers

977. Squares of a Sorted Array (QuickSort/MergeSort)

167. Two Sum II – Input array is sorted

917. Reverse Only Letters

Dynamic Programing

279. Perfect Squares

198. House Robber

85. Maximal Rectangle (Hard)

To be continue…

How to write good clean code? 我们应该怎样写代码?

  • Good Naming of variables – Easy to read for other programmers
  • Have enough documentation – Good for you or other when revisit this code
  • Doesn’t has duplicate code – Think about writing a function/method for it
  • Less code less maintenance – Less bugs, more reliable
  • Code can pass all test cases
  • Facing outdate code/project communicate with Team members first
  • Refactoring the code when adding a new feature, fixing a bug, or during a code review

Algorithm Template Cheat Sheet

DFS Template

Use on Binary Tree, Permutation or Combination problems

  • Time complexity:
    • Tree traversal: O(n)
    • Permutation: O(n! * n)
    • Combination: O(2n * n)
function dfs(nums, n, start, cur, res...) {
    if (exit recursive condition) {
        // record answer
        return;
    }
    for (possible solution) {
        // modify current state
        dfs(nums, n, i + 1, cur, res...);
        // recover current state

    }
    return something if need // option
};

BFS Template

Use on Topological Sorting, Level Traversal, Shortest path in graph, Union Find problems

  • Time complexity:O(n + m) // n is node, m is edge
  • Space complexity: O(n)
// 1. No level:
function bfs(node) {
    const queue = [];
    queue.push(node);
    
    while(queue.length !== 0) {
        ...
        let cur = queue.shift();
        for (neighbor in cur\'s neighbors) {
             if (neighbor is valid but not visit)
                queue.push(neighbor)
        }
    }
}
             
// 2. Has level traversal: depends on the questions
// Level could be a number or array
function bfs(node) {
    const queue = [];
    queue.push(node);
    // (1) let level = 0; // level as a number for tracking
    while(queue.length !== 0) {
        let size = queue.length;
        // (2) let level = []; // level could be storing data
        while(size--) {
            let cur = queue.shift();
            for (neighbor in cur\'s neighbors) {
                 if (neighbor is valid but not visit)
                    queue.push(neighbor)
            }
        }
        //(1) level++;
        //(2) res.push(level.concat()); // adding to the result
    }
}
                 
// 3. BFS - finding the shortest path in graph
function bfs(node) {
    const queue = [];
    let distance = new Map(); // avoid duplicate, track startNode
    queue.push(startNode);
    distance.set(startNode, 0); // or 1 depends on the question
    
    while(queue.length !== 0) {
        let cur = queue.shift();
        if (node is destination) {
            break or return something;
        }
        for (neighbor in cur\'s neighbors) {
             if (distance.has(neighbor)) continue;
             queue.push(neighbor);
             distance.set(neighbor, distance.get(node) + 1);
        }
    }
    // possible return:
    return distance;
    return distance.keys();
    return distnace.get(endNode);
    ...
}

Topological Sorting (BFS) Template:

function topologicalSort(nodes) {
    const queue = [];
    let indegrees = getIndegrees(nodes); // 统计所有点的入度信息 as hashmap
    // add those indegree === 0 nodes into queue
    for (node of nodes) {
        if (indegrees.get(node) === 0)
            queue.push(node);
    }
    
    let topoOrder = [];
    while(queue.length !== 0) {
        let cur = queue.shift();
        topoOrder.push(cur);
        for (neighbor in cur\'s neighbors) {
             indegrees.set(neighbor, indegrees.get(neighbor) - 1);
             // when indegree is 0, no more depends on any node, add to queue
             if (indegrees.get(neighbor) === 0) {
                queue.push(neighbor);
        }
    }
    if (topoOrder.length !== nodes.length)
        return "No topoOrder!";
    
    return topoOrder;
}

Binary Search Template

  • Time complexity O(logn)
  • Space complexity O(1)
function binarySearch(nums, target) {
    let l = 0;
    let r = nums.length;
    
    while (l < r) {
        let mid = l + Math.floor((r - l) / 2);
        if (nums[mid] === target) {
            // most case: just return target
            return mid;
            // --- if searching leftBound
            // leftBound = mid;
            // r = mid;
            // --- if searching rightBound
            // rightBound = mid;
            // l = mid + 1;
        } else if (nums[mid] > target) {
            r = mid;
        } else {
            l = mid + 1;
        }
    }
}

Merge Sort Template

var sortArray = function(nums) {
    if (nums === null || nums.length === 0) return;
    let temp = [];
    mergeSort(nums, 0, nums.length - 1, temp);
    return nums;
};

function mergeSort(nums, start, end, temp) {
    if (start >= end) return;
    // deal with first half
    mergeSort(nums, start, Math.floor((start + end) / 2), temp);
    // deal with second half
    mergeSort(nums, Math.floor((start +end) / 2) + 1, end, temp);
    // merge
    merge(nums, start, end, temp);
}

function merge(nums, start, end, temp) {
    let mid = Math.floor((start + end) / 2);
    let l_index = start;
    let r_index = mid + 1;
    let index = start;
    while (l_index <= mid && r_index <= end) {
        if (nums[l_index] < nums[r_index]) {
            temp[index++] = nums[l_index++];
        } else {
            temp[index++] = nums[r_index++];
        }
    }
    while (l_index <= mid)
        temp[index++] = nums[l_index++];
    while (r_index <= end)
        temp[index++] = nums[r_index++];
    for (let i = start; i <= end; i++) {
        nums[i] = temp[i];
    }
}

Quick Sort Template

var sortArray = function(nums) {
    if (nums === null || nums.length === 0) return;
    quickSort(nums, 0, nums.length - 1)
    return nums;
};

function quickSort(nums, left, right) {
    let index;
    if (nums.length > 1) {
        // index returned from partition
        index = partition(nums, left, right);
        // more elements on the left side of the pivot
        if (left < index - 1)
            quickSort(nums, left, index - 1);
        // more elements on the right side of the pivot
        if (index < right)
            quickSort(nums, index, right);
    }
    // you can return or not return, 
    // since we change nums, no need to return
    // return nums;
}

function partition(nums, start, end) {
    let l = start, r = end;
    let mid = Math.floor((start + end) / 2);
    let pivot = nums[mid];
    // Important: l <= r not l < r
    while (l <= r) {
        while(nums[l] < pivot)
            l++;
        while(nums[r] > pivot)
            r--;
        if (l <= r) {
            // swap
            [nums[l], nums[r]] = [nums[r], nums[l]];
            l++;
            r--;
        }
    }
    return l;
}

To be continue…