Skip to content

Instantly share code, notes, and snippets.

View Ramko9999's full-sized avatar
🎯
Focusing

Ramko9999

🎯
Focusing
View GitHub Profile
// counts all pairs in arr that sum up to target
function twoSumCountMap(arr, target){
let count = 0;
let map = new Map();
for(const num of arr){
if(map.has(target - num)){
count += map.get(target - num);
}
if(!map.has(num)){
map.set(num, 0)
// counts all pairs in arr that sum up to target
function twoSumCount(arr, target){
let count = 0;
let map = {};
for(const num of arr){
if((target - num) in map){
count += map[target - num];
}
if(!(num in map)){
map[num] = 0;
function StringBuilder(){
this.strings = [];
this.add = (s) => {
this.strings.push(s)
}
this.concat = () => {
return this.strings.join("");
}
<!DOCTYPE html>
<html lang="en">
<body>
<script>
let elems = ["A", "B"];
elems.forEach((v) => console.log("I ate", v));
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<body>
<script src="forEachPolyfill.js"></script>
<script>
let elems = ["A", "B"];
elems.forEach((v) => console.log("I ate", v));
</script>
</body>
const isForEachSupported = Array.prototype.forEach;
if(!isForEachSupported){
Array.prototype.forEach = function customForEach (callback){
if(typeof callback !== "function"){
throw Error(`${callback} is not of type function`);
}
from collections import defaultdict
# create an empty defaultdict with default value equal to []
default_list_d = defaultdict(list)
default_list_d['a'].append(1)
# default_list_d is now {"a": [1]}
# create a defaultdict with default value equal to 0
default_int_d = defaultdict(int)
# each entry is a tuple (age, height)
students = [(12,54),(18,78),(18,62),(17,67),(16,67),(21, 76)]
# since our student ages and heights are already tuples, no need to pre-process
heapq.heapify(students)
k = 4
kyoungest = []
for i in range(k):
kyoungest.append(heapq.heappop(students))
numbers = [4,1,24,2,1]
# invert numbers so that the largest values are now the smallest
numbers = [-1 * n for n in numbers]
# turn numbers into min heap
heapq.heapify(numbers)
# pop out 2 times
k = 2
# Approach 1: push new elements into the heap
numbers = [4,1,24,2,1]
heap = [] # our "heap"
for num in numbers:
heapq.heappush(heap, num)
smallest_num = heapq.heappop(heap)
# time complexity: O(NlogN)
# Approach 2: use heapify()