🤖
@qwertyvipul | code
  • Code
  • DSA
    • Disjoint Set
    • Segment Tree
    • Bit Operations
    • Binary Exponential
    • Kadane's Algorithm
    • Modulus Multiplicative Inverse
  • Quick Notes
    • Design Patterns
    • System Design
    • React.js
  • LeetCode With JavaScript
Powered by GitBook
On this page
  • Basic data structures
  • Hash map
  • Numbers
  • Extreme values of maxi-mini
  • Use BigInt
  • Arrays
  • Create an array of some size with default values
  • Strings
  • Unicode
  • Bitwise
  • Sorting
  • Custom sort

LeetCode With JavaScript

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

# py
d = dict()
// js
d = new Map();
d.set(key, value);
d.get(key);

Numbers

  • Max safe integer in Python = 2 ** 32 - 1

  • Max safe integer in JS = 2 ** 53 - 1

Extreme values of maxi-mini

# py
maxi = -inf
mini = inf
//js
const maxi = Number.MIN_SAFE_INTEGER;
const mini = Number.MAX_SAFE_INTEGER;

Use BigInt

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.

Arrays

Create an array of some size with default values

# py
arr = [0] * n
// js
const arr = Array(n).fill(0);

Strings

Unicode

# py
uni = ord(ch)
// js
const uni = ch.charCodeAt(0);

Bitwise

# py
(mask >> i) & 1 == 1 # Will either give true or false
//js
(mask >> i) & 1 === 1 // Will always evaluate to 0
(mask >> i) & 1 === 0 // Will also always evaluate to 0

// Instead use
((mask >> i) & 1) === 0 // To get the order of execution right

Sorting

Custom sort

# py
tasks.sort(key = lambda x: x[0] - x[1])
// js
tasks.sort((task1, task2) => {
    const a = task1[0] - task1[1];
    const b = task2[0] - task2[1];
    return (b < a) - (a < b)
})
PreviousReact.js

Last updated 1 year ago