Leetcode JS Flashcards
for…of loop
iterates over iterable objects like String, Array, Map, Set, etc…
let sharks = [ "great white", "tiger", "hammerhead" ]; // Print out each type of shark for (let shark of sharks) { console.log(shark); }
- can only be used for iterables (will NOT work on objects)
- gives you access to each element
- you can use w/objects by calling Object.entries(myObj)
if you need access to both element and index, you can do this:
~~~
for (let [index, shark] of sharks.entries()) {
console.log(index, shark);
}
~~~
New in ES6
for…in loop
iterates over the properties of an object
vinsByFrequency: { 77: 1, 89: 3, 123: 4, 456: 1 } for (let key in vinsByFrequency) { // key is each vin }
Set
- lets you store unique values of any type
- A value in the set may only occur once
-methods: add(), delete(), size(), has()
const mySet1 = new Set() mySet1.add(1) mySet1.add(5) mySet1.add(5) mySet1.size; // 2 mySet1.has(1); // true mySet1.delete(5); // removes 5 from the set
new Map()
holds key-value pairs and remembers the original insertion order of the keys
Methods: set(), delete(), size(), has()
const map1 = new Map(); map1.set('a', 1); map1.set('b', 2); map1.set('c', 3); console.log(map1.get('a')); // Expected output: 1 map1.set('a', 97); console.log(map1.get('a')); // Expected output: 97 console.log(map1.size); // Expected output: 3 map1.delete('b'); console.log(map1.size); // Expected output: 2
Premature Optimization Quote
“premature optimization is the root of all evil”
Check if element in array
myArray.includes(element)
How to reverse a string
myStr.split("").reverse().join("")
split(“”) - splits a string into an array of elements
reverse() - reverses an array
join(“”) - joins an array of elements into a string
How to create regular expression
Regular Expression Literal
~~~
const re = /ab+c/;
~~~
Calling constructor function of RegExp obj
~~~
const re = new RegExp(“ab+c”);
~~~
Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don’t know the pattern and are getting it from another source, such as user input.
Given a string, how to create a new string that only includes alphanumeric characters
const str = "#ABCabc123?%"; const re = /[^a-z0-9]/gi; // use the replace() method to match and remove all the non-alphanumeric characters const newStr = str.replace(re, ""); console.log(newStr); // ABCabc123
How to mutate str to all lowercase
myStr.toLowerCase()
RegEx syntax
let re = /[^a-z0-9]/gi
The forward slash character is used to denote the boundaries of the regular expression:
/this_is_my_regular_expression/
^ negates
[a-z0-9] chars between a-z or between 1-9
[^a-z0-9] chars that are not a-z or 1-9
/g (global) - will catch all of the matching chars
/gi (global & case insensitive)
Math.max()
returns the largest of the numbers given as input parameters
console.log(Math.max(1, 3, 2)); // Expected output: 3 console.log(Math.max(-1, -3, -2)); // Expected output: -1 const array1 = [1, 3, 2]; console.log(Math.max(...array1)); // Expected output: 3
When to use for loop vs while loop
For Loop: best used when you know the number of iterations ahead of time
While Loop: best used when you don’t know the number of iterations ahead of time
Valid Parentheses
Stack
function isValid(s) { let stack = [] for(let i=0; i<s.length; i++) { if(s[i] === '(') { stack.push(')') } else if (s[i] === '{') { stack.push('}') } else if (s[i] === '[') { stack.push(']') } else if (s[i] !== stack.pop()) { return false } } if(stack.length > 0) { return false } return true };
Best Time to Buy and Sell Stock
Two Pointer
const maxProfit = function(prices) { let profit = 0 let maxProfit = 0 let left = 0 for(let right=1; right<prices.length; right++) { if(prices[left] < prices[right]) { profit = prices[right] - prices[left] maxProfit = Math.max(maxProfit, profit) } else { left = right } } return maxProfit };