Algorithm review
twoSum - Array, Object
brute force1
2
3
4
5
6
7const twoSum = (nums, target) => {
for(let i = 0; i < nums.length - 1; i++)
for(let j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target)
return [i, j];
}
}use object - better performance
1
2
3
4
5
6
7
8
9const twoSum = (nums, target) => {
let obj = {};
for(let i = 0; i < nums.length; i++){
let num = nums[i];
if(obj.hasOwnProperty(target-num))
return [obj[target-num], i];
obj[num] = i; // stores number and its original index
}
}Object
1
2
3let car = {};
car.size = 1;
car.color = "red"; // size and color are properties of carLongest Substring Without Repeating Characters - String, Set
1
2
3
4
5
6
7
8
9
10
11
12
13const lengthOfLongestSubstring = s => {
let strSet = new Set();
let i = 0, j = 0, res = 0;
while(i < s.length && j < s.length) {
if(!strSet.has(s[j])){
strSet.add(s[j++]);
res = Math.max(res, j - i);
}else {
strSet.delete(s[i++]);
}
}
return res;
}Set - store unique value of any type
1
2
3
4let s = new Set([1, 2, 3, 4, 5]);
s.has(5) // true;
s.has(6) // false;
s.delete(2);Reverse Integer
1
2
3
4
5
6const reverse = x => {
let rev = Math.abs(x).toString().split('').reverse().join('') * Math.sign(x);
if( rev > Math.pow(2, 31) - 1 || rev < Math.pow(2, 31))
return 0;
return rev;
}1
2
3
4
5
6
7
8
9
10
11
12const reverse = x => {
let abs = Math.abs(x);
let rev;
while(abs > 0) {
let lastDigi = abs % 10;
rev = rev * 10 + lastDigi;
abs = Math.floor(abs / 10);
}
if( rev > Math.pow(2, 31) - 1 || rev < Math.pow(2, 31))
return 0;
return rev;
}Letter Combinations of a Phone Number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20const letterCombinations = (digits, current = "", res = []) => {
if(digits.length == 0 && current == "") return res;
if(digits.length < 1) res.push(current);
const Numbers = {
2: "abc",
3: "def",
4: "ghi",
5: "jkl",
6: "mno",
7: "pqrs",
8: "tuv",
9: "wxyz"
};
let numStr = Numbers[digits[0]];
for(let i = 0; i < numStr.length; i++) {
let letter = numStr[i];
letterCombinations(digits.slice(1), current + letter, res);
}
return res;
}Missing Number
1
2
3
4
5
6
7const missingNumber = nums => {
let xor = 0, i = 0;
for(; i < nums.length; i++){
xor = xor ^ i ^ nums[i];
}
return xor ^ i;
}1
2
3
4
5
6
7
8const missingNumber = nums => {
let expected = nums.length, sum = 0;
for(let i = 0; i < nums.length; i++){
sum += nums[i];
expected += i;
}
return expected - sum;
}Single Number
1
2
3
4
5
6
7const singleNumber = nums => {
let res = 0;
for(let i = 0; i < nums.length; i++){
res ^= nums[i];
}
return res;
}^ is super needed when dealing with finding a unique one.
Valid Anagram - Hash Table
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18const isAnagram = (s, t) => {
if(s.length != t.length) return false;
let dic = new Array(26);
dic.fill(0);
for(let i = 0; i < s.length; i++) {
let index = s.charCodeAt(i) - 97;
dic[index]++;
}
for(let i = 0; i < t.length; i++) {
let index = t.charCodeAt(i) - 97;
dic[index]--;
if(dic[index] < 0) return false;
}
return dic.every(val => val == 0);
}Largest Number
1
2
3
4
5const largestNumber = nums => {
return nums.sort((a,b) => {
return (b+''+a) - (a+''+b);
}).join('').replace(/^0*/, '') || '0';
}The math in this function is that, when compare two numbers we want to have the number with larger starting number. So we concatenate two numbers to compare to see which kind of concatenation is better.(a+b or b+a)
Count word frequency in a paragraph
1
2
3
4
5
6
7
8
9
10
11const countWord = s => {
let dic = {};
let wordArr = s.split(" ");
for (let i = 0; i < wordArr.length; i++) {
let word = wordArr[i];
if (!dic[word]) dic[word] = 1;
else dic[word]++;
}
for (word in dic)
console.log("word: " + word + " Count: " + dic[word]);
}for loop
for (x in person)
x means keyfor( y of preson)
y means a item of personSum of a number array
1
2
3
4
5
6const sum = nums => {
let sumArr = 0
for(let i = 0; i < nums.length; i++)
sumArr += nums[i];
return sumArr;
}Remove duplicates in a number array
1
2
3
4
5
6
7
8
9
10
11
12
13const deleteDu = nums => {
if(nums.length == 1 || nums.length == 0) return nums;
//sort it
nums = nums.sort((a, b) => {
return a-b;
});
let index = 1;
for(let i = 1; i < nums.length; i++) {
if(nums[i] != nums[i-1])
nums[index++] = nums[i];
}
return nums.slice(0, index);
}Remove duplicates in a number array II (appear at most twice)
1
2
3
4
5
6
7
8
9
10
11
12
13const removeDu = nums => {
if(nums.length < 3) return nums;
nums.sort((a, b) => {
return a-b;
});
let index = 2;
for(let i = 2; i < nums.length; i++){
//actually compare it with the 'new' array
if(nums[i] > nums[index-2])
nums[index++] = nums[i];
}
return nums.slice(0, index)
}Bubble sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14const bubbleSort = nums => {
let n = nums.length;
if (n < 2) return nums;
while (n > 0) {
for (let j = 0; j < n - 1; j++)
if (nums[j] > nums[j + 1]) {
let temp = nums[j + 1];
nums[j + 1] = nums[j];
nums[j] = temp;
}
n--;
}
return nums;
}Factorial
1
2
3
4
5
6
7
8
9const factorial = n => {
if(n > 1)
return n * factorial(n-1);
else if(n == 0 || n == 1)
return 1;
else
return -1;
}Get median of an array
1
2
3
4
5
6
7
8
9
10
11
12const getMedian = nums => {
let n = nums.length;
if(n < 2) return nums[0];
nums = nums.sort((a,b) => {
return a-b;
});
if(n % 2 == 0) {
return (nums[n/2] + nums[n/2 - 1]) / 2;
} else {
return nums[Math.floor(n/2)];
}
}Kangaroo
1
2
3
4
5
6
7const kangaroo = (x1, v1, x2, v2) => {
if(v1 < v2) return "NO";
else {
if((x1 - x2) % (v2 - v1) == 0) return "YES";
else return "NO";
}
}Super Reduced String
1
2
3
4
5
6
7
8
9
10
11const superReducedString = s => {
let charArr = [...s];
for(let i = 0; i < charArr.length; i++){
if(charArr[i] == charArr[i+1]){
charArr.splice(i, 2);
return superReducedString(charArr.join(""));
}
}
s = charArr.join("");
return s == "" ? "Empty String" : s;
}Closest Numbers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17const closestNumbers = arr => {
arr = arr.sort((a, b) => {
return a-b;
});
let min = Number.MAX_SAFE_INTEGER;
let res = [];
for(let i = 1; i < arr.length; i++){
let dif = arr[i] - arr[i-1];
if(dif <= min) {
if(dif < min) res = [];
res.push(arr[i-1]);
res.push(arr[i]);
min = dif;
}
}
return res;
}