Skip to content

Instantly share code, notes, and snippets.

View RP-3's full-sized avatar

Rohan Rogers RP-3

  • San Francisco Bay Area
View GitHub Profile
/**
* @param {number} num
* @return {boolean}
*/
/*
Idea: A power of four is just a non-negative int
with one bit set in at an even index.
So we need to make sure that the given int is:
- non-negative
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
const validChar = (c) => c.match(/[a-zA-Z0-9]/);
let [l, r] = [0, s.length-1];
while(l < r){
if(!validChar(s[l])){
/**
* Initialize your data structure here.
*/
var MyHashSet = function(size=10_000) {
this.size = size;
this.storage = new Array(size).fill(0).map(() => []);
};
/**
* @param {number} key
/**
* @param {number} n
* @return {number}
*/
// brute force backtracking
// O(2^n) time and O(n) space
var climbStairs = function(n) {
const r = (step) => {
if(step > n) return 0;
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} inorder
/**
* @param {number[]} nums
* @return {number[]}
*/
var singleNumber = function(nums) {
// for simplicity, let's say our two results are x and y.
// if we xor the entire list, we'll be left with only the bits
let diff = 0; // that differ between x and y. This is because
nums.forEach((n) => diff ^= n); // XORing cancels out numbers
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} val
/*
Sort-of brute force... I know there's a cleverer way to
do this with XORs and bit tricks but if the answer doesn't
fit into 53-bit int I'd be hosed so I'm sticking to what
I know will work =P
O(max(a.length, b.length))
*/
var addBinary = function(a, b) {
/*
Idea:
1. Find the worst-rated children and start with them
2. For Each worst child, give them just one candy (c)
3. For each neighbour,
- If they have a higher rating, give them c + 1 candies
- Otherwise give them 1 candy
4. If ever there is a conflict, round up.
The code ends up being a straightforward breadth-first search. O(n) space and time.
/**
* @param {number[]} arr
* @param {number} d
* @return {number}
*/
var maxJumps = function(arr, d) {
const getVisitable = (i) => {
const options = [];
for(let j=i+1; j<arr.length && j <= i+d; j++){