Tools
I do most of my LeetCoding in Python, so I will basically discuss here how to go from Python to equivalent JavaScript.
Basic data structures
// Hash map
hmap = new Map();
hmap.set(key, value);
hmap.get(key);
// key values
const keyValues = hmap.entries();
Numbers
- Max safe integer in Python =
2 ** 32 - 1
- Max safe integer in JS =
2 ** 53 - 1
As a rule of thumb, anything that's gonna fit in Python would fit in JS.
Anything that overflows in Python, assume it overflows in JS. In JS use BigInt
to handle big numbers.
const mini = Number.MIN_SAFE_INTEGER;
const maxi = Number.MAX_SAFE_INTEGER;
const inf = Infinity;
const negInf = -Infinity;
const bigNum = BigInt(someNum);
// Another way to declare a big int
// Suffix with `n`
// https://leetcode.com/problems/count-good-numbers/solutions/4836032/js-solution-by-bharadwaj/
const bigNum = 1n;
Math
// Get sign of a number
const sign = Math.sign(num);
Math.ceil();
Math.floor();
// Get integer part of a number
const num = Math.trunc(dec);
const num = ~~dec;
// Max and min of two numbers
const mini = Math.min(num1, num2);
const maxi = Math.max(num1, num2);
// Max and min of an array of number
const mini = Math.min(...nums);
const maxi = Math.max(...nums);
Math.abs(num);
Math.sqrt(num);
Math.log2(num);
// Some more methods
// https://leetcode.com/problems/minimum-time-to-complete-trips/solutions/4985204/js/
Math.min.apply();
Arrays
Array().fill();
Array.from();
const arr = [];
arr.sort((a, b) => a - b);
arr.reduce((val, item) => {});
// Returns new copy
arr.slice(startIdx, endIdx);
// Modifies original array
arr.splice(startIdx, count);
const hset = new Set();
// Add element
hset.add(num);
// Check element
hset.has(num);
// Delete element
hset.delete(num);
// Create array from hset
const arr = Array.from(hset);
// Create an array of some size with default values
const arr = Array(n).fill(0);
// Sum of array elements
const sum = nums.reduce((acu, num) => acu + num);
// Queue
const q = [];
q.push(num);
const frontEle = q.shift();
// Add to front
nums.unshift(num);
// Remove from front
const num = nums.shift();
Strings
const s = "some string";
s.split();
s.join();
s.match(/expr/ || []);
s.replace(/expr/, "");
// Get unicode of a character
const uni = ch.charCodeAt(0);
const chr = String.fromCharCode(uni);
// Character to integer
const num = parseInt(ch);
// String to number
const num = Number(str);
// If string includes sub string
const exists = s.includes(ss);
// The index of sub string
const idx = s.indexOf(ss);
const lastIdx = s.lastIndexOf(ss);
// Extract substring
const ss = s.substring(startIdx, endIdx);
// Replace all
const s2 = s1.replaceAll(ss1, ss2);
Objects
// Keys
const keys = Object.keys(obj);
// Key values
const keyValues = Object.entries(obj);
Functions
// Working with prototypes
// https://leetcode.com/problems/finding-pairs-with-a-certain-sum/solutions/4824403/js-soution-by-bharadwaj/
Bitwise
# py
(mask >> i) & 1 == 1 # Will either give true or false
// JS
((mask >> i) & 1) === 0; // To get the order of execution right
// Unit32Array
// https://leetcode.com/problems/find-the-sum-of-the-power-of-all-subsequences/solutions/4884324/js/
// https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/solutions/4793480/js-solution-by-bharadwaj/
// https://leetcode.com/problems/maximize-consecutive-elements-in-an-array-after-modification/solutions/4742629/js-solution-by-bharadwaj/
// Unit8Array
// https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/solutions/4857399/js-solution-by-bharadwaj/
// https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/solutions/4857399/js-solution-by-bharadwaj/
// https://leetcode.com/problems/apply-operations-to-make-string-empty/solutions/4742568/js-solution-by-bharadwaj/
Sorting
// Custom sort
nums.sort((a, b) => a - b);
// Using comparator function
tasks.sort((task1, task2) => {
const a = task1[0] - task1[1];
const b = task2[0] - task2[1];
return (b < a) - (a < b);
});
Priority Queue
// Create the heap
const heap = new PriorityQueue();
const minHeap = new MinPriorityQueue();
const maxHeap = new MaxPriorityQueue();
// Insert elements
minHeap.enqueue(nums[i], nums[i]);
// Peek
minHeap.front();
// Pop elements
const { element, priority } = minHeap.dequeue();
// Just get the element
const ele = minHeap.dequeue().element;
// Heap to array
const arr = minHeap.toArray();
const minHeap = new Heap((a, b) => a - b); // Min Heap
const maxHeap = new Heap((a, b) => b - a); // Max heap
// Priority queue with priority function
// https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/solutions/4844549/js-solution-by-bharadwaj/
const heap = new MinPriorityQueue({ priority: (x) => x[1] });
// With compare function
const heap = new MinPriorityQueue({
compare: (a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]),
});
// Multi-level comparison
const heap = new Heap((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]));