├── 1.array-and-strings ├── 1.move-zeroes.md ├── 2.add-binary.md ├── 3.intersection-of-two-arrays-II.md ├── 5-valid-palindrome.md ├── 6-valid-palindrome-II.md └── 7-valid-number.md ├── 2.linked-list ├── 1.reverse-linked-list.md ├── 2.add-two-numbers.md ├── 3.remove-nth-node-from-end-of-list.md ├── 4.intersection-of-two-linked-lists.md └── 6.linked-list-cycle.md ├── 3.trees-and-graphs ├── 1.same-tree.md ├── 104.maximum-depth-of-binary-tree.md ├── 2.validate-binary-search-tree.md ├── 3.binary-tree-paths.md ├── 4.diameter-of-binary-tree.md └── 8.number-of-Islands.md ├── 4.backtracking ├── 3.permutations.md └── 93.restore-IP-addresses.md ├── 5.sorting-and-searching ├── 215.kth-largest-element-in-an-array.md ├── 3.merge-sorted-array.md ├── 4.merge-two-sorted-lists.md └── 5.merge-k-sorted-lists.md ├── 6.dynamic-programming └── 3.decode-ways.md ├── 7.algorithms ├── 1.merge-sort.md └── 2.quicksort.md └── README.md /1.array-and-strings/1.move-zeroes.md: -------------------------------------------------------------------------------- 1 | ### Move Zeroes 2 | 3 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 4 | 5 | #### Example: 6 | 7 | ``` 8 | Input: [0,1,0,3,12] 9 | Output: [1,3,12,0,0] 10 | ``` 11 | 12 | #### Note: 13 | 14 | 1. You must do this in-place without making a copy of the array. 15 | 2. Minimize the total number of operations. 16 | 17 | #### Solutions: 18 | 19 | ##### JavaScript 20 | 21 | ```JavaScript 22 | /** 23 | * @param {number[]} nums 24 | * @return {void} Do not return anything, modify nums in-place instead. 25 | */ 26 | var moveZeroes = function(nums) { 27 | var zeroes = 0; 28 | for (var i = 0; i < nums.length; i++) { 29 | if (nums[i] === 0) { 30 | nums.splice(i, 1); 31 | i--; 32 | zeroes++; 33 | } 34 | } 35 | while (zeroes) { 36 | nums.push(0); 37 | zeroes--; 38 | } 39 | }; 40 | ``` 41 | 42 | ##### PHP 43 | 44 | ```PHP 45 | Given two binary strings, return their sum (also a binary string).
4 |The input strings are both `non-empty` and contains only characters `1` or `0`.
5 | 6 | #### Example 1: 7 | 8 | ``` 9 | Input: a = "11", b = "1" 10 | Output: "100" 11 | ``` 12 | 13 | #### Example 2: 14 | 15 | ``` 16 | Input: a = "1010", b = "1011" 17 | Output: "10101" 18 | ``` 19 | 20 | ##### JavaScript 21 | 22 | ```JavaScript 23 | /** 24 | * @param {string} a 25 | * @param {string} b 26 | * @return {string} 27 | */ 28 | var addBinary = function (a, b) { 29 | var aLength = a.length; 30 | var bLength = b.length; 31 | 32 | if (aLength < bLength) { 33 | var dif = bLength - aLength; 34 | var concatString = ""; 35 | while (dif) { 36 | --dif; 37 | concatString += "0"; 38 | } 39 | a = concatString + a; 40 | } else if (aLength > bLength) { 41 | var dif = aLength - bLength; 42 | var concatString = ""; 43 | while (dif) { 44 | --dif; 45 | concatString += "0"; 46 | } 47 | b = concatString + b; 48 | } 49 | 50 | var length = a.length; 51 | var result = ''; 52 | var rememeber = 0; 53 | 54 | for (var i = length - 1; i >= 0; --i) { 55 | var slug = ((+a[i]) + (+b[i]) + rememeber); 56 | if (slug >= 2) { 57 | slug = slug - 2; 58 | rememeber = 1; 59 | } else { 60 | rememeber = 0; 61 | } 62 | result = slug + result; 63 | } 64 | 65 | if (rememeber === 1) { 66 | result = "1" + result; 67 | } 68 | 69 | return result; 70 | }; 71 | ``` 72 | 73 | ##### PHP 74 | 75 | ```PHP 76 | $bCount) { 91 | $diff = $aCount - $bCount; 92 | $concatString = ''; 93 | while ($diff) { 94 | $concatString = '0' . $concatString; 95 | --$diff; 96 | } 97 | $b = $concatString . $b; 98 | } 99 | 100 | $count = strlen($a); 101 | $remember = 0; 102 | $result = ''; 103 | 104 | for ($i = $count - 1; $i >= 0; --$i) { 105 | $slug = $a[$i] + $b[$i] + $remember; 106 | if ($slug >= 2) { 107 | $slug = $slug - 2; 108 | $remember = 1; 109 | } else { 110 | $remember = 0; 111 | } 112 | $result = $slug . $result; 113 | } 114 | 115 | if ($remember === 1) { 116 | $result = '1' . $result; 117 | } 118 | 119 | return $result; 120 | } 121 | 122 | var_dump(addBinary('11','1')); 123 | 124 | 125 | ``` -------------------------------------------------------------------------------- /1.array-and-strings/3.intersection-of-two-arrays-II.md: -------------------------------------------------------------------------------- 1 | ### Intersection of Two Arrays II 2 | 3 |Given two arrays, write a function to compute their intersection.
4 | 5 | #### Example 1: 6 | 7 | ``` 8 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 9 | Output: [2,2] 10 | ``` 11 | 12 | #### Example 2: 13 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 14 | Output: [4,9] 15 | 16 | #### Note: 17 | 18 | - Each element in the result should appear as many times as it shows in both arrays. 19 | - The result can be in any order. 20 | 21 | #### Follow up: 22 | 23 | - What if the given array is already sorted? How would you optimize your algorithm? 24 | - What if nums1's size is small compared to nums2's size? Which algorithm is better? 25 | - What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? 26 | 27 | ```JavaScript 28 | /** 29 | * @param {number[]} nums1 30 | * @param {number[]} nums2 31 | * @return {number[]} 32 | */ 33 | var intersect = function(nums1, nums2) { 34 | var result = []; 35 | var searched = []; 36 | for(var i =0; iYou are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
4 | 5 |You may assume the two numbers do not contain any leading zero, except the number 0 itself.
6 | 7 | #### Example: 8 | 9 | ``` 10 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 11 | Output: 7 -> 0 -> 8 12 | Explanation: 342 + 465 = 807. 13 | 14 | ``` 15 | 16 | ##### JavaScript 17 | 18 | ```JavaScript 19 | /** 20 | * Definition for singly-linked list. 21 | * function ListNode(val) { 22 | * this.val = val; 23 | * this.next = null; 24 | * } 25 | */ 26 | /** 27 | * @param {ListNode} l1 28 | * @param {ListNode} l2 29 | * @return {ListNode} 30 | */ 31 | var addTwoNumbers = function(l1, l2) { 32 | const before = new ListNode(); 33 | let tail = before; 34 | let c = 0; 35 | 36 | while (l1 || l2 || c) { 37 | const v1 = l1 ? l1.val : 0; 38 | const v2 = l2 ? l2.val : 0; 39 | const v = v1+v2+c; 40 | 41 | tail.next = new ListNode(v%10); 42 | tail = tail.next; 43 | c = v >= 10 ? 1 : 0; 44 | l1 = l1!==null ? l1.next : null; 45 | l2 = l2!==null ? l2.next : null; 46 | } 47 | 48 | return before.next; 49 | }; 50 | ``` 51 | -------------------------------------------------------------------------------- /2.linked-list/3.remove-nth-node-from-end-of-list.md: -------------------------------------------------------------------------------- 1 | ### Remove Nth Node From End of List 2 | 3 |Given a linked list, remove the n-th node from the end of list and return its head.
4 | 5 | #### Example: 6 | 7 | ``` 8 | Given linked list: 1->2->3->4->5, and n = 2. 9 | 10 | After removing the second node from the end, the linked list becomes 1->2->3->5. 11 | ``` 12 | 13 | #### Note: 14 | 15 | Given n will always be valid. 16 | 17 | #### Follow up: 18 | 19 | Could you do this in one pass? 20 | 21 | ##### JavaScript 22 | 23 | ```JavaScript 24 | /** 25 | * Definition for singly-linked list. 26 | * function ListNode(val) { 27 | * this.val = val; 28 | * this.next = null; 29 | * } 30 | */ 31 | /** 32 | * @param {ListNode} head 33 | * @param {number} n 34 | * @return {ListNode} 35 | */ 36 | var removeNthFromEnd = function(head, n) { 37 | 38 | if (!head) return head; 39 | 40 | let prev = head; 41 | let curr = head.next; 42 | 43 | while (curr) { 44 | if (n > 0) { 45 | n -= 1; 46 | } else { 47 | prev = prev.next; 48 | } 49 | 50 | curr = curr.next; 51 | } 52 | 53 | if (n === 1) return head.next; 54 | 55 | prev.next = prev.next.next || null; 56 | return head; 57 | }; 58 | ``` -------------------------------------------------------------------------------- /2.linked-list/4.intersection-of-two-linked-lists.md: -------------------------------------------------------------------------------- 1 | ### Intersection of Two Linked Lists 2 | 3 | Write a program to find the node at which the intersection of two singly linked lists begins. 4 | 5 | 6 | #### For example, the following two linked lists: 7 | 8 | ``` 9 | A: a1 → a2 10 | ↘ 11 | c1 → c2 → c3 12 | ↗ 13 | B: b1 → b2 → b3 14 | ``` 15 | begin to intersect at node c1. 16 | 17 | 18 | #### Notes: 19 | 20 | - If the two linked lists have no intersection at all, return null. 21 | - The linked lists must retain their original structure after the function returns. 22 | - You may assume there are no cycles anywhere in the entire linked structure. 23 | - Your code should preferably run in O(n) time and use only O(1) memory. 24 | 25 | ##### JavaScript 26 | 27 | ```JavaScript 28 | /** 29 | * Definition for singly-linked list. 30 | * function ListNode(val) { 31 | * this.val = val; 32 | * this.next = null; 33 | * } 34 | */ 35 | 36 | /** 37 | * @param {ListNode} headA 38 | * @param {ListNode} headB 39 | * @return {ListNode} 40 | */ 41 | var getIntersectionNode = function(headA, headB) { 42 | if (!headA || !headB) return null; 43 | var p1 = headA; 44 | var p2 = headB; 45 | while (p1 && p2 && p1 !== p2) { 46 | p1 = p1.next; 47 | p2 = p2.next; 48 | 49 | if (p1 == p2) return p1; 50 | if (!p1) p1 = headB; 51 | if (!p2) p2 = headA; 52 | } 53 | return p1; 54 | }; 55 | ``` -------------------------------------------------------------------------------- /2.linked-list/6.linked-list-cycle.md: -------------------------------------------------------------------------------- 1 | ### Linked List Cycle 2 | 3 | Given a linked list, determine if it has a cycle in it. 4 | 5 | #### Follow up: 6 | Can you solve it without using extra space? 7 | 8 | ##### JavaScript 9 | 10 | ```JavaScript 11 | /** 12 | * Definition for singly-linked list. 13 | * function ListNode(val) { 14 | * this.val = val; 15 | * this.next = null; 16 | * } 17 | */ 18 | 19 | /** 20 | * @param {ListNode} head 21 | * @return {boolean} 22 | */ 23 | var hasCycle = function (head) { 24 | 25 | if (head === null || head.next === null) { 26 | return false; 27 | } 28 | var tail1 = head.next; 29 | var tail2 = head.next.next; 30 | while (tail1 && tail2) { 31 | if (tail1 === tail2) { 32 | return true; 33 | } 34 | tail1 = tail1.next; 35 | if (tail2.next) { 36 | tail2 = tail2.next.next; 37 | } 38 | else { 39 | return false; 40 | } 41 | } 42 | 43 | return false; 44 | }; 45 | ``` -------------------------------------------------------------------------------- /3.trees-and-graphs/1.same-tree.md: -------------------------------------------------------------------------------- 1 | ### Same Tree 2 | 3 |Given two binary trees, write a function to check if they are the same or not.
4 | 5 |Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
6 | 7 | #### Example 1: 8 | 9 | ``` 10 | Input: 1 1 11 | / \ / \ 12 | 2 3 2 3 13 | 14 | [1,2,3], [1,2,3] 15 | 16 | Output: true 17 | ``` 18 | 19 | #### Example 2: 20 | 21 | ``` 22 | Input: 1 1 23 | / \ 24 | 2 2 25 | 26 | [1,2], [1,null,2] 27 | 28 | Output: false 29 | ``` 30 | 31 | #### Example 3: 32 | 33 | ``` 34 | Input: 1 1 35 | / \ / \ 36 | 2 1 1 2 37 | 38 | [1,2,1], [1,1,2] 39 | 40 | Output: false 41 | ``` 42 | 43 | ##### JavaScript 44 | 45 | ```JavaScript 46 | /** 47 | * Definition for a binary tree node. 48 | * function TreeNode(val) { 49 | * this.val = val; 50 | * this.left = this.right = null; 51 | * } 52 | */ 53 | /** 54 | * @param {TreeNode} p 55 | * @param {TreeNode} q 56 | * @return {boolean} 57 | */ 58 | var isSameTree = function(p, q) { 59 | if(!p||!q)return p===q 60 | return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)&&p.val===q.val 61 | }; 62 | ``` -------------------------------------------------------------------------------- /3.trees-and-graphs/104.maximum-depth-of-binary-tree.md: -------------------------------------------------------------------------------- 1 | ### 104. Maximum Depth of Binary Tree 2 | 3 |Given a binary tree, find its maximum depth.
4 | 5 |The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
6 | 7 | #### Note: 8 | 9 | A leaf is a node with no children. 10 | 11 | #### Example: 12 | 13 | ``` 14 | Given binary tree [3,9,20,null,null,15,7], 15 | 16 | 3 17 | / \ 18 | 9 20 19 | / \ 20 | 15 7 21 | return its depth = 3. 22 | ``` 23 | 24 | ##### JavaScript 25 | 26 | ```JavaScript 27 | /** 28 | * Definition for a binary tree node. 29 | * function TreeNode(val) { 30 | * this.val = val; 31 | * this.left = this.right = null; 32 | * } 33 | */ 34 | /** 35 | * @param {TreeNode} root 36 | * @return {number} 37 | */ 38 | var maxDepth = function(root) { 39 | return maxDepthHelper(root,0); 40 | 41 | }; 42 | 43 | var maxDepthHelper = function(root, depth){ 44 | if(root !==null){ 45 | depth = 1 + depth; 46 | }else{ 47 | return depth; 48 | } 49 | let leftDepth = maxDepthHelper(root.left,depth); 50 | let rigthDepth = maxDepthHelper(root.right,depth); 51 | 52 | 53 | if(leftDepth > rigthDepth){ 54 | return leftDepth; 55 | } 56 | return rigthDepth; 57 | } 58 | ``` -------------------------------------------------------------------------------- /3.trees-and-graphs/2.validate-binary-search-tree.md: -------------------------------------------------------------------------------- 1 | ### Validate Binary Search Tree 2 | 3 |Given a binary tree, determine if it is a valid binary search tree (BST).
4 | 5 | #### Assume a BST is defined as follows: 6 | 7 | - The left subtree of a node contains only nodes with keys less than the node's key. 8 | - The right subtree of a node contains only nodes with keys greater than the node's key. 9 | - Both the left and right subtrees must also be binary search trees. 10 | 11 | #### Example 1: 12 | 13 | ``` 14 | Input: 15 | 2 16 | / \ 17 | 1 3 18 | Output: true 19 | ``` 20 | 21 | #### Example 2: 22 | 23 | ``` 24 | 5 25 | / \ 26 | 1 4 27 | / \ 28 | 3 6 29 | Output: false 30 | Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value 31 | is 5 but its right child's value is 4. 32 | ``` 33 | 34 | ##### JavaScript 35 | 36 | ```JavaScript 37 | /** 38 | * Definition for a binary tree node. 39 | * function TreeNode(val) { 40 | * this.val = val; 41 | * this.left = this.right = null; 42 | * } 43 | */ 44 | /** 45 | * @param {TreeNode} root 46 | * @return {boolean} 47 | */ 48 | var isValidBST = function (root) { 49 | 50 | return isValidBSTHelper(root, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); 51 | }; 52 | 53 | var isValidBSTHelper = function (root, min, max) { 54 | if (root === null) { 55 | return true; 56 | } 57 | 58 | if (root.val < min || root.val > max) { 59 | return false; 60 | } 61 | 62 | if (!isValidBSTHelper(root.left, min, root.val - 1) || !isValidBSTHelper(root.right, root.val + 1, max)) { 63 | return false; 64 | } 65 | 66 | return true; 67 | } 68 | ``` -------------------------------------------------------------------------------- /3.trees-and-graphs/3.binary-tree-paths.md: -------------------------------------------------------------------------------- 1 | ### Binary Tree Paths 2 | 3 | Given a binary tree, return all root-to-leaf paths. 4 | 5 | #### Note: 6 | A leaf is a node with no children. 7 | 8 | #### Example: 9 | 10 | ``` 11 | Input: 12 | 13 | 1 14 | / \ 15 | 2 3 16 | \ 17 | 5 18 | 19 | Output: ["1->2->5", "1->3"] 20 | 21 | Explanation: All root-to-leaf paths are: 1->2->5, 1->3 22 | 23 | ``` 24 | 25 | ##### JavaScript 26 | 27 | ```JavaScript 28 | /** 29 | * Definition for a binary tree node. 30 | * function TreeNode(val) { 31 | * this.val = val; 32 | * this.left = this.right = null; 33 | * } 34 | */ 35 | /** 36 | * @param {TreeNode} root 37 | * @return {string[]} 38 | */ 39 | var binaryTreePaths = function (root) { 40 | if (root === null) { 41 | return []; 42 | } 43 | 44 | var result = []; 45 | result[0] = [root.val]; 46 | 47 | runNext(root, result, 0); 48 | 49 | return transformation(result); 50 | }; 51 | 52 | var search = function (node, stackMarix, oldStackIndex, isNew) { 53 | if (node === null) { 54 | return; 55 | } 56 | 57 | let stackIndex = oldStackIndex; 58 | if (isNew) { 59 | stackMarix[stackMarix.length] = stackMarix[stackIndex].slice(); 60 | stackIndex = stackMarix.length - 1; 61 | } 62 | 63 | stackMarix[stackIndex].push(node.val); 64 | runNext(node, stackMarix, stackIndex); 65 | }; 66 | 67 | var runNext = function (node, stackMarix, stackIndex) { 68 | if (node.left !== null && node.right !== null) { 69 | search(node.right, stackMarix, stackIndex, true); 70 | search(node.left, stackMarix, stackIndex, false); 71 | } else if (node.left === null) { 72 | search(node.right, stackMarix, stackIndex, false); 73 | } else { 74 | search(node.left, stackMarix, stackIndex, false); 75 | } 76 | }; 77 | 78 | 79 | var transformation = function (matrix) { 80 | var result = []; 81 | for (var i = 0; i < matrix.length; ++i) { 82 | result.push(matrix[i].join('->')); 83 | } 84 | 85 | return result; 86 | }; 87 | ``` -------------------------------------------------------------------------------- /3.trees-and-graphs/4.diameter-of-binary-tree.md: -------------------------------------------------------------------------------- 1 | ### Diameter of Binary Tree 2 | 3 | Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 4 | 5 | #### Example: 6 | ``` 7 | Given a binary tree 8 | 1 9 | / \ 10 | 2 3 11 | / \ 12 | 4 5 13 | Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 14 | ``` 15 | 16 | #### Note: 17 | The length of path between two nodes is represented by the number of edges between them. 18 | 19 | ##### JavaScript 20 | 21 | ```JavaScript 22 | /** 23 | * Definition for a binary tree node. 24 | * function TreeNode(val) { 25 | * this.val = val; 26 | * this.left = this.right = null; 27 | * } 28 | */ 29 | /** 30 | * @param {TreeNode} root 31 | * @return {number} 32 | */ 33 | var diameterOfBinaryTree = function (root) { 34 | return diameter(root, 0); 35 | }; 36 | 37 | var diameter = function (node, diameterVal) { 38 | if (node === null) { 39 | return diameterVal; 40 | } 41 | let leftHeigth = heigth(node.left, 0); 42 | let rigthHeigth = heigth(node.right, 0); 43 | 44 | var diameter1 = leftHeigth + rigthHeigth; 45 | var maxDiameter = Math.max(diameter1, diameterVal); 46 | 47 | var leftDiameter = diameter(node.left, 0); 48 | var rigthDiameter = diameter(node.right, 0); 49 | 50 | return Math.max(leftDiameter, rigthDiameter, maxDiameter); 51 | }; 52 | 53 | var heigth = function (node, heigthV) { 54 | if (node === null) { 55 | return heigthV; 56 | } 57 | ++heigthV; 58 | let left = heigth(node.left, heigthV); 59 | let rigth = heigth(node.right, heigthV); 60 | 61 | return Math.max(left, rigth); 62 | }; 63 | 64 | ``` -------------------------------------------------------------------------------- /3.trees-and-graphs/8.number-of-Islands.md: -------------------------------------------------------------------------------- 1 | ### Number of Islands 2 | 3 | Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 4 | 5 | #### Example 1: 6 | 7 | ``` 8 | Input: 9 | 11110 10 | 11010 11 | 11000 12 | 00000 13 | 14 | Output: 1 15 | ``` 16 | 17 | #### Example 2: 18 | 19 | ``` 20 | Input: 21 | 11000 22 | 11000 23 | 00100 24 | 00011 25 | 26 | Output: 3 27 | ``` 28 | 29 | #### JavaScript 30 | 31 | ```JavaScript 32 | /** 33 | * @param {character[][]} grid 34 | * @return {number} 35 | */ 36 | var numIslands = function (grid) { 37 | var newVisitingGrid = []; 38 | var result = 0; 39 | for (let i = 0; i < grid.length; ++i) { 40 | for (let j = 0; j < grid[i].length; ++j) { 41 | result += numIslandsHalper(grid, newVisitingGrid, i, j); 42 | } 43 | } 44 | 45 | return result; 46 | }; 47 | 48 | var numIslandsHalper = function (grid, newVisitingGrid, x, y) { 49 | if (typeof(grid[x]) === 'undefined') { 50 | return 0; 51 | } 52 | if (typeof(newVisitingGrid[x]) === 'undefined') { 53 | newVisitingGrid[x] = []; 54 | } 55 | if (newVisitingGrid[x][y] === 1) { 56 | return 0; 57 | } 58 | if (typeof(newVisitingGrid[x]) === 'undefined') { 59 | newVisitingGrid[x] = []; 60 | } 61 | newVisitingGrid[x][y] = 1; 62 | 63 | 64 | if (grid[x][y] == 1) { 65 | numIslandsHalper(grid, newVisitingGrid, x + 1, y); 66 | numIslandsHalper(grid, newVisitingGrid, x, y + 1); 67 | numIslandsHalper(grid, newVisitingGrid, x - 1, y); 68 | numIslandsHalper(grid, newVisitingGrid, x, y - 1); 69 | 70 | return 1; 71 | } 72 | 73 | return 0; 74 | } 75 | ``` -------------------------------------------------------------------------------- /4.backtracking/3.permutations.md: -------------------------------------------------------------------------------- 1 | ### Permutations 2 | 3 | Given a collection of distinct integers, return all possible permutations. 4 | 5 | #### Example: 6 | 7 | ``` 8 | Input: [1,2,3] 9 | Output: 10 | [ 11 | [1,2,3], 12 | [1,3,2], 13 | [2,1,3], 14 | [2,3,1], 15 | [3,1,2], 16 | [3,2,1] 17 | ] 18 | ``` 19 | 20 | ##### JavaScript 21 | 22 | ```JavaScript 23 | function Lexico(nums) { 24 | this._array = nums.sort(); 25 | } 26 | 27 | Lexico.prototype.next = function () { 28 | 29 | for (var i = this._array.length - 1; i > 0; --i) { 30 | if (this._array[i] > this._array[i - 1]) { 31 | var pivot = i - 1; 32 | for (var j = this._array.length - 1; j > pivot; --j) { 33 | if (this._array[j] > this._array[pivot]) { 34 | //swap 35 | let c = this._array[j]; 36 | this._array[j] = this._array[pivot]; 37 | this._array[pivot] = c; 38 | 39 | let newArray = this._array.slice(0); 40 | let firstPart = newArray.slice(0, pivot + 1); 41 | let secondPart = newArray.slice(pivot + 1, this._array.length).reverse(); 42 | newArray = firstPart.concat(secondPart); 43 | this._array = newArray; 44 | console.log(this._array); 45 | 46 | return newArray.slice(0); 47 | } 48 | } 49 | } 50 | } 51 | 52 | return false; 53 | 54 | } 55 | 56 | Lexico.prototype.value = function () { 57 | return this._array.slice(0); 58 | } 59 | 60 | /** 61 | * @param {number[]} nums 62 | * @return {number[][]} 63 | */ 64 | var permute = function (nums) { 65 | var result = []; 66 | 67 | if (nums.length === 1) { 68 | return [nums]; 69 | } 70 | 71 | let lexico = new Lexico(nums); 72 | 73 | result.push(lexico.value()); 74 | console.log(); 75 | while (true) { 76 | if (val = lexico.next()) { 77 | result.push(val); 78 | } else { 79 | break; 80 | } 81 | } 82 | 83 | return result; 84 | }; 85 | ``` -------------------------------------------------------------------------------- /4.backtracking/93.restore-IP-addresses.md: -------------------------------------------------------------------------------- 1 | ### Restore IP Addresses 2 | 3 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 4 | 5 | #### Example: 6 | 7 | ``` 8 | Input: "25525511135" 9 | Output: ["255.255.11.135", "255.255.111.35"] 10 | ``` 11 | 12 | #### JavaScript 13 | 14 | ```JavaScript 15 | /** 16 | * @param {string} s 17 | * @return {string[]} 18 | */ 19 | var restoreIpAddresses = function (s) { 20 | if (s.length < 4 || s.length > 12) { 21 | return []; 22 | } 23 | 24 | let result = []; 25 | 26 | IpAddresses(s, result, [], 1, 0); 27 | IpAddresses(s, result, [], 2, 0); 28 | IpAddresses(s, result, [], 3, 0); 29 | 30 | return result; 31 | }; 32 | 33 | function IpAddresses(s, result, arrayLocalResult, count, iteration) { 34 | 35 | let startSubstring = arrayLocalResult.join('').length; 36 | let endSubsctring = startSubstring + count; 37 | if (endSubsctring > s.length) { 38 | return; 39 | } 40 | var newArray = arrayLocalResult.slice(0); 41 | var substring = s.substring(startSubstring, endSubsctring); 42 | if (+substring > 255 || substring.length !== ('' + +substring).length) { 43 | return; 44 | } 45 | newArray.push(substring); 46 | 47 | if (iteration === 3) { 48 | if (s.length === endSubsctring) { 49 | result.push(newArray.join('.')); 50 | } 51 | return; 52 | } 53 | IpAddresses(s, result, newArray, 1, iteration + 1); 54 | IpAddresses(s, result, newArray, 2, iteration + 1); 55 | IpAddresses(s, result, newArray, 3, iteration + 1); 56 | } 57 | 58 | restoreIpAddresses('25525511135'); 59 | ``` -------------------------------------------------------------------------------- /5.sorting-and-searching/215.kth-largest-element-in-an-array.md: -------------------------------------------------------------------------------- 1 | ### Kth Largest Element in an Array 2 | 3 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 4 | 5 | #### Example 1: 6 | 7 | ``` 8 | Input: [3,2,1,5,6,4] and k = 2 9 | Output: 5 10 | 11 | ``` 12 | 13 | #### Example 2: 14 | ``` 15 | Input: [3,2,3,1,2,4,5,5,6] and k = 4 16 | Output: 4 17 | ``` 18 | 19 | #### Note: 20 | You may assume k is always valid, 1 ≤ k ≤ array's length. 21 | 22 | #### JavaScript 23 | 24 | ```JavaScript 25 | /** 26 | * @param {number[]} nums 27 | * @param {number} k 28 | * @return {number} 29 | */ 30 | var findKthLargest = function (nums, k) { 31 | let start = 0; 32 | let end = k - 1; 33 | debugger; 34 | return quickSort(nums, 0, nums.length - 1, nums.length - k); 35 | }; 36 | 37 | function swap(items, firstIndex, secondIndex) { 38 | const temp = items[firstIndex]; 39 | items[firstIndex] = items[secondIndex]; 40 | items[secondIndex] = temp; 41 | } 42 | 43 | var partition = function (nums, start, end) { 44 | let pivot = nums[Math.floor((start + end) / 2)]; 45 | let i = start; 46 | let j = end; 47 | 48 | while (i <= j) { 49 | while (nums[i] < pivot) { 50 | ++i; 51 | } 52 | while (nums[j] > pivot) { 53 | --j; 54 | } 55 | 56 | if (i <= j) { 57 | swap(nums, i, j); 58 | ++i; 59 | --j; 60 | } 61 | } 62 | 63 | return i; 64 | }; 65 | 66 | var quickSort = function (nums, start, end, findIndex) { 67 | if (nums.length > 1) { 68 | let index = partition(nums, start, end); 69 | if (findIndex >= start && findIndex <= index - 1) { 70 | if (start < index - 1) { 71 | quickSort(nums, start, index - 1, findIndex); 72 | } 73 | } else { 74 | if (index < end) { 75 | quickSort(nums, index, end, findIndex); 76 | } 77 | } 78 | } 79 | 80 | console.log(nums); 81 | 82 | return nums[findIndex] 83 | }; 84 | 85 | findKthLargest([3, 2, 1, 5, 6, 4], 2); 86 | ``` -------------------------------------------------------------------------------- /5.sorting-and-searching/3.merge-sorted-array.md: -------------------------------------------------------------------------------- 1 | ### Merge Sorted Array 2 | 3 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 4 | 5 | #### Note: 6 | 7 |The number of elements initialized in nums1 and nums2 are m and n respectively.
8 |You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
9 | 10 | #### Example: 11 | 12 | ``` 13 | Input: 14 | nums1 = [1,2,3,0,0,0], m = 3 15 | nums2 = [2,5,6], n = 3 16 | 17 | Output: [1,2,2,3,5,6] 18 | ``` 19 | 20 | ##### JavaScript 21 | 22 | ```JavaScript 23 | /** 24 | * @param {number[]} nums1 25 | * @param {number} m 26 | * @param {number[]} nums2 27 | * @param {number} n 28 | * @return {void} Do not return anything, modify nums1 in-place instead. 29 | */ 30 | var merge = function (nums1, m, nums2, n) { 31 | var firstIndex = 0; 32 | var secondIndex = 0; 33 | while (secondIndex !== n && firstIndex - secondIndex < m) { 34 | if (nums1[firstIndex] > nums2[secondIndex]) { 35 | for (let i = nums1.length - 1; i !== firstIndex; --i) { 36 | nums1[i] = nums1[i - 1]; 37 | } 38 | nums1[firstIndex] = nums2[secondIndex]; 39 | console.log(nums1); 40 | ++firstIndex; 41 | ++secondIndex; 42 | } else { 43 | ++firstIndex; 44 | } 45 | } 46 | 47 | if (secondIndex !== n) { 48 | for (secondIndex; secondIndex < n; ++secondIndex) { 49 | nums1[firstIndex++] = nums2[secondIndex]; 50 | } 51 | } 52 | }; 53 | ``` -------------------------------------------------------------------------------- /5.sorting-and-searching/4.merge-two-sorted-lists.md: -------------------------------------------------------------------------------- 1 | ### Merge Two Sorted Lists 2 | 3 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 4 | 5 | #### Example: 6 | 7 | ``` 8 | Input: 1->2->4, 1->3->4 9 | Output: 1->1->2->3->4->4 10 | ``` 11 | 12 | 13 | ##### JavaScript 14 | 15 | ```JavaScript 16 | /** 17 | * Definition for singly-linked list. 18 | * function ListNode(val) { 19 | * this.val = val; 20 | * this.next = null; 21 | * } 22 | */ 23 | /** 24 | * @param {ListNode} l1 25 | * @param {ListNode} l2 26 | * @return {ListNode} 27 | */ 28 | var mergeTwoLists = function (l1, l2) { 29 | let res = new ListNode(); 30 | let cur = res; 31 | while (l1 && l2) { 32 | if (l1.val <= l2.val) { 33 | cur.next = new ListNode(l1.val); 34 | l1 = l1.next; 35 | cur = cur.next; 36 | continue; 37 | } 38 | else { 39 | cur.next = new ListNode(l2.val); 40 | l2 = l2.next; 41 | cur = cur.next; 42 | continue; 43 | } 44 | } 45 | cur.next = l1 ? l1 : l2; 46 | return res.next; 47 | }; 48 | ``` -------------------------------------------------------------------------------- /5.sorting-and-searching/5.merge-k-sorted-lists.md: -------------------------------------------------------------------------------- 1 | ### Merge k Sorted Lists 2 | 3 | Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 4 | 5 | #### Example: 6 | 7 | ``` 8 | Input: 9 | [ 10 | 1->4->5, 11 | 1->3->4, 12 | 2->6 13 | ] 14 | Output: 1->1->2->3->4->4->5->6 15 | ``` 16 | 17 | 18 | ##### JavaScript 19 | 20 | ```JavaScript 21 | /** 22 | * Definition for singly-linked list. 23 | * function ListNode(val) { 24 | * this.val = val; 25 | * this.next = null; 26 | * } 27 | */ 28 | /** 29 | * @param {ListNode[]} lists 30 | * @return {ListNode} 31 | */ 32 | var mergeKLists = function (lists) { 33 | normalize(lists); 34 | var head = new ListNode(); 35 | var taill = head; 36 | 37 | while (lists.length) { 38 | let min = lists[0].val; 39 | let minINdex = 0; 40 | 41 | for (let i = 0; i < lists.length; ++i) { 42 | if (lists[i].val < min) { 43 | min = lists[i].val; 44 | minINdex = i; 45 | } 46 | } 47 | taill.next = new ListNode(min); 48 | taill = taill.next; 49 | if (lists[minINdex].next === null) { 50 | lists.splice(minINdex, 1); 51 | } else { 52 | lists[minINdex] = lists[minINdex].next; 53 | } 54 | 55 | } 56 | 57 | return head.next; 58 | 59 | }; 60 | 61 | function normalize(lists) { 62 | for (var i = 0; i < lists.length; ++i) { 63 | if (lists[i] === null) { 64 | lists.splice(i, 1); 65 | --i; 66 | } 67 | } 68 | } 69 | ``` -------------------------------------------------------------------------------- /6.dynamic-programming/3.decode-ways.md: -------------------------------------------------------------------------------- 1 | ### Decode Ways 2 | 3 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 4 | 5 | ``` 6 | 'A' -> 1 7 | 'B' -> 2 8 | ... 9 | 'Z' -> 26 10 | ``` 11 | Given a non-empty string containing only digits, determine the total number of ways to decode it. 12 | 13 | #### Example 1: 14 | 15 | ``` 16 | Input: "12" 17 | Output: 2 18 | Explanation: It could be decoded as "AB" (1 2) or "L" (12). 19 | ``` 20 | 21 | #### Example 2: 22 | 23 | ``` 24 | Input: "226" 25 | Output: 3 26 | Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 27 | ``` 28 | 29 | ##### JavaScript 30 | 31 | ```JavaScript 32 | /** 33 | * @param {string} s 34 | * @return {number} 35 | */ 36 | var numDecodings = function (s) { 37 | 38 | let resultValue = 0; 39 | let substringValues = []; 40 | 41 | calculate(0, 1); 42 | calculate(0, 2); 43 | 44 | return resultValue; 45 | 46 | function calculate(startIndex, count) { 47 | let startSubstring = startIndex; 48 | let endSubstring = startSubstring + count; 49 | if (endSubstring > s.length) { 50 | return; 51 | } 52 | let substring = getSubstringValues(startSubstring, endSubstring); 53 | 54 | if (false === substring) { 55 | return; 56 | } 57 | 58 | if (s.length === endSubstring) { 59 | ++resultValue; 60 | return; 61 | } 62 | 63 | calculate(endSubstring, 1); 64 | calculate(endSubstring, 2); 65 | } 66 | 67 | function getSubstringValues(start, end) { 68 | if (typeof substringValues[start] === 'undefined') { 69 | substringValues[start] = []; 70 | } 71 | 72 | if (typeof substringValues[start][end] === 'undefined') { 73 | let substring = s.substring(start, end); 74 | if (+substring > 26 || +substring < 1 || substring.length !== ('' + +substring).length) { 75 | substring = false; 76 | } 77 | substringValues[start][end] = substring; 78 | } 79 | 80 | return substringValues[start][end]; 81 | } 82 | }; 83 | 84 | console.log(numDecodings('123')); 85 | ``` -------------------------------------------------------------------------------- /7.algorithms/1.merge-sort.md: -------------------------------------------------------------------------------- 1 | ### Merge Sort 2 | 3 | #### Links 4 | - https://hackernoon.com/programming-with-js-merge-sort-deb677b777c0 5 | - https://en.wikipedia.org/wiki/Merge_sort 6 | 7 | ```JavaScript 8 | // Split the array into halves and merge them recursively 9 | function mergeSort (arr) { 10 | if (arr.length === 1) { 11 | // return once we hit an array with a single item 12 | return arr 13 | } 14 | 15 | const middle = Math.floor(arr.length / 2) // get the middle item of the array rounded down 16 | const left = arr.slice(0, middle) // items on the left side 17 | const right = arr.slice(middle) // items on the right side 18 | 19 | return merge( 20 | mergeSort(left), 21 | mergeSort(right) 22 | ) 23 | } 24 | 25 | // compare the arrays item by item and return the concatenated result 26 | function merge (left, right) { 27 | let result = [] 28 | let indexLeft = 0 29 | let indexRight = 0 30 | 31 | while (indexLeft < left.length && indexRight < right.length) { 32 | if (left[indexLeft] < right[indexRight]) { 33 | result.push(left[indexLeft]) 34 | indexLeft++ 35 | } else { 36 | result.push(right[indexRight]) 37 | indexRight++ 38 | } 39 | } 40 | 41 | return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight)) 42 | } 43 | 44 | const list = [2, 5, 1, 3, 7, 2, 3, 8, 6, 3] 45 | console.log(mergeSort(list)) // [ 1, 2, 2, 3, 3, 3, 5, 6, 7, 8 ] 46 | ``` 47 | 48 | ```PHP 49 | pivot) { 26 | j--; 27 | } 28 | if (i <= j) { 29 | swap(items, i, j); 30 | i++; 31 | j--; 32 | } 33 | } 34 | return i; 35 | } 36 | 37 | function quickSort(items, left, right) { 38 | var index; 39 | if (items.length > 1) { 40 | index = partition(items, left, right); 41 | if (left < index - 1) { 42 | quickSort(items, left, index - 1); 43 | } 44 | if (index < right) { 45 | quickSort(items, index, right); 46 | } 47 | } 48 | return items; 49 | } 50 | 51 | var items = [2, 5, 1, 3, 7, 2, 3, 8, 6, 3]; 52 | // first call 53 | console.log(quickSort(items, 0, items.length - 1)); 54 | ``` 55 | 56 | ```PHP 57 | $pivot) { 80 | --$j; 81 | } 82 | 83 | if ($i <= $j) { 84 | swap($arr, $i, $j); 85 | ++$i; 86 | --$j; 87 | } 88 | } 89 | 90 | return $i; 91 | 92 | } 93 | 94 | function quickSort(array &$arr, int $start, int $end) 95 | { 96 | if (\count($arr) > 1) { 97 | $index = partition($arr, $start, $end); 98 | 99 | if ($start < $index - 1) { 100 | quickSort($arr, $start, $index - 1); 101 | } 102 | 103 | if ($index < $end) { 104 | quickSort($arr, $index, $end); 105 | } 106 | } 107 | 108 | return $arr; 109 | } 110 | 111 | return quickSort($arr, 0, \count($arr) - 1); 112 | } 113 | 114 | var_dump(merge([2, 5, 1, 3, 7, 2, 3, 8, 6, 3])); 115 | 116 | ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # facebook-interview-preparing 2 | 3 | ### 1. Array and strings 4 | - [Move Zeroes](1.array-and-strings/1.move-zeroes.md) 5 | - [Add Binary](1.array-and-strings/2.add-binary.md) 6 | - [Intersection of Two Arrays II](1.array-and-strings/3.intersection-of-two-arrays-II.md) 7 | - [Valid Palindrome](1.array-and-strings/5-valid-palindrome.md) 8 | - [Valid Palindrome II](1.array-and-strings/6-valid-palindrome-II.md) 9 | - [Valid Number](1.array-and-strings/7-valid-number.md) 10 | 11 | ### 2. Linked List 12 | - [Reverse Linked List](2.linked-list/1.reverse-linked-list.md) 13 | - [Add Two Numbers](./2.linked-list/2.add-two-numbers.md) 14 | - [Remove Nth Node From End of List](./2.linked-list/3.remove-nth-node-from-end-of-list.md) 15 | - [Intersection of Two Linked Lists](./2.linked-list/4.intersection-of-two-linked-lists.md) 16 | - [Linked List Cycle](./2.linked-list/6.linked-list-cycle.md) 17 | 18 | ### 3. Trees and Graphs 19 | - [Same Tree](./3.trees-and-graphs/1.same-tree.md) 20 | - [Validate Binary Search Tree](./3.trees-and-graphs/2.validate-binary-search-tree.md) 21 | - [Binary Tree Paths](./3.trees-and-graphs/3.binary-tree-paths.md) 22 | - [Diameter of Binary Tree](./3.trees-and-graphs/4.diameter-of-binary-tree.md) 23 | - [Number of Islands](./3.trees-and-graphs/8.number-of-Islands.md) 24 | - [Maximum Depth of Binary Tree](./3.trees-and-graphs/104.maximum-depth-of-binary-tree.md) 25 | 26 | ### 4. Backtracking 27 | - [Permutations](./4.backtracking/3.permutations.md) 28 | - [Restore IP Addresses](./4.backtracking/93.restore-IP-addresses.md) 29 | 30 | ### 5. Sorting and Searching 31 | - [Merge Sorted Array](./5.sorting-and-searching/3.merge-sorted-array.md) 32 | - [Merge Two Sorted Lists](./5.sorting-and-searching/4.merge-two-sorted-lists.md) 33 | - [Merge k Sorted Lists](./5.sorting-and-searching/5.merge-k-sorted-lists.md) 34 | - [Kth Largest Element in an Array](5.sorting-and-searching/215.kth-largest-element-in-an-array.md) 35 | 36 | ### 6. Dynamic Programming 37 | - [Decode Ways](./6.dynamic-programming/3.decode-ways.md) 38 | 39 | ### TODO: 40 | 41 | | Data Structures | Algorithms | Concepts | 42 | | :------------------: | :----------------------: | :----------------------: | 43 | | Linked Lists | Breadth First Search | Bit Manipulation | 44 | | Binary Trees | Depth First Search | Singleton Design Pattern | 45 | | Tries | Binary Search | Factory Design Pattern | 46 | | Stacks | Tree Insert / Find / etc | Memory (Stack vs Heap) | 47 | | Queues | | Recursion | 48 | | Vectors / ArrayLists | | Big-O Time | 49 | | Hash Tables | | | 50 | 51 | ### TODO from Facebook 52 | 53 | #### Algorithms to study: 54 | - [Merge Sort](7.algorithms/1.merge-sort.md) 55 | - [Quick Sort](7.algorithms/2.quicksort.md) 56 | - Breadth-first search 57 | - Depth-first search 58 | - Binary Search 59 | - [lexicographic order](./4.backtracking/3.permutations.md) 60 | 61 | #### Data Structures to study: 62 | - Arrays/ArrayLists 63 | - Hash Tables 64 | - Trees 65 | - Graphs 66 | - Stacks/Queues 67 | - Heaps 68 | 69 | #### Concepts to know: 70 | - Big O 71 | - Recursion 72 | - Memoization/Dynamic Programming 73 | --------------------------------------------------------------------------------