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
# First pass. Clunky but works in O(n)
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
i = 0
def insert(gt, lt):
nonlocal i
if i >= len(preorder): return None
const longestPath = (adjList) => {
const graph = {};
adjList.forEach(([from, to]) => {
if(!graph[from]) graph[from] = new Set();
graph[from].add(to);
});
const memo = {}; // node -> longestPathLength starting at node
let result = 0;
/**
* @param {number[]} stones
* @return {number}
*/
// O(n^2) worst case
// Could've used a heap but it's late in my day
// and I didn't want to have to paste one in JS.
// Heap would be O(n*log(n))
var lastStoneWeight = function(stones) {
stones.sort((a, b) => a-b); // asc order
/*
IDEA:
- There are four letters, which can be represented
by two bits.
- The sequence we're looking for is 10 chars long,
so can fit inside 20 bits, which in turn fits in
a single int quite comfortably.
APPROACH:
- Traverse the sequence a single time, starting with
the first 10 chars
// O(32 * nums.length^2)
var totalHammingDistance = function(nums) {
let result = 0;
const bits = new Array(32).fill(0);
nums.forEach((n) => {
for(let i=0; i<bits.length; i++)
});
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
const left = new Array(nums.length).fill(1);
for(let i=1; i<nums.length; i++){
left[i] = left[i-1]*nums[i-1];
var stringShift = function(s, shift) {
const net = shift.reduce((acc, [direction, magnitude]) => {
return acc + (direction === 1 ? magnitude : -magnitude);
}, 0) % s.length;
if(net === 0) return s;
if(net > 0){
class Solution:
def numIslands(self, grid):
seen = []
for row in grid:
seen.append(list(row))
return self.solution(grid, seen)
def solution(self, grid, seen):
islandCount = 0
for y, row in enumerate(grid):
class Solution {
func isVisited(_ grid: [[Character]], _ i: Int, _ j: Int) -> Bool {
return grid[i][j] == Character("2")
}
func markVisited(_ grid: inout [[Character]], _ i: Int, _ j: Int) {
guard i >= 0, j >= 0, i < grid.count, j < grid[i].count, !isVisited(grid, i, j), grid[i][j] == "1" else {
return
}