Leetcode JS Flashcards

1
Q

for…of loop

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

for…in loop

A

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
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Set

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

new Map()

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Premature Optimization Quote

A

“premature optimization is the root of all evil”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Check if element in array

A

myArray.includes(element)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to reverse a string

A
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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to create regular expression

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Given a string, how to create a new string that only includes alphanumeric characters

A
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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to mutate str to all lowercase

A
myStr.toLowerCase()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

RegEx syntax

A
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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Math.max()

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

When to use for loop vs while loop

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Valid Parentheses

A

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
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Best Time to Buy and Sell Stock

A

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
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Reverse a linked list

A
var reverseList = function(head) {
    let prev = null
    let curr = head
    let next = null
    
    while(curr!== null){
        // save next
        next = curr.next
        // reverse pointer
        curr.next = prev
        // advance prev and curr
        prev = curr
        curr = next
    }
    return prev;
};
17
Q

Object.entries(myObj)

A

returns array of arrays (with key/value pairs)

[['honda', 3], ['bmw', 1], ['toyota': 15]]