Algorithms in Coding Interviws Flashcards
https://www.youtube.com/@NeetCode/playlists
arrays
zero based index
contiguous memory (one next to each other, in order)
memory, good for read (slower to insert, delete)
links list
has a pointer
es desordenado para inserts/delete
memory, good for inset/delete. slow for read
hash maps are dictionaries. With key and values
unordered
good for searching
stacks and 3 methods can be used.
In JS arrays can funciotn as stack
of pancakes!!
LIFO (last in, first out)
you can:
-push
-pop
-peek (at the top element)
trees –> real virtual dom
tiene nodos conectados
el root
con parent-child direction (react virtual dom)
binary search trees.
se hace con clases en js
graphs
son modelos
Search Algoritm: binary search
-guess game
-complejidad es O(log n).
- ordenado en orden ascendente
- busqueda es un número objetivo
binary search
-si la lista esta ordenada
-empezas en el medio, mejor la eficiencia que una linear search
-eficiencia mejor que la linear search
Sorting: insertion sort
Ex: order an array
get first compare with second
Sorting: merge sort
related to recursion algorimn
https://www.youtube.com/watch?v=DjYZk8nrXVY&ab_channel=AshishPratapSingh
prefixSum
function prefixSum(arr) {
const prefixSums = [0]; // Inicializamos con 0 para manejar el caso de sumar desde el inicio
for (let i = 0; i < arr.length; i++) {
prefixSums[i + 1] = prefixSums[i] + arr[i]; // Guardamos la suma acumulada hasta el índice i
}
return prefixSums;
}
const prefixSums = prefixSum(arr);
console.log(prefixSums); // [0, 1, 3, 6, 10, 15]
prefixSum.
Problem 303 in javascript.
Tell me:
how to create a class
how to inialize a number in a constructor
how to sumInRange (this is a method/function)
class NumArray {
constructor(nums) {
this.nums = nums; // Initialize the nums array
}
sumRange(left, right) { let c = 0; for (let i = left; i <= right; i++) { c += this.nums[i]; // Access the stored array using this.nums } return c; } }
largo spelling
length
prefixSum
525. Contiguous Array
Explain el problema y como encararlo.
https://www.youtube.com/watch?v=9ZyLjjk536U&ab_channel=Techdose
Pensar que pide buscar en numeros binearios es decir 0,1. Te da un array de eso. Hay que buscar la mayor cantidad de 0,0,1,1 (es decir misma cantidad presente en un subarray) y devolver el largo.
Por lo cual hay que pensar como recorrer el array original en un loop y conseguir ese subarray length.
Una forma de pensarlo:
es que la suma se tiene que mantener igual en un momento, significando que no hay modificacion.
cantiad de 1 y 0 es igual es el subarray == subarray valido.
Los counters tienen que ser iguales.
Count 1 - count 0 = 0
prefixSum
525. Contiguous Array
Explain el problema y como encararlo.
https://www.youtube.com/watch?v=VtC__J8G8Tw&ab_channel=AryanMittal
prefixSum
560. Subarray Sum Equals K
concepto de for… of
objecto {}
map[sum - k]
let nums = [1, 2, 3];
for (let num of nums) {
console.log(num);
}
objecto con key: value
let map = {0: 1};
buscar en el objecto por key:
map[sum - k]
if (map[sum - k] !== undefined)
Check if sum - k exists in the map
Concepto de suma acumulada:
La clave de la fórmula sum - k es que nos permite verificar si hubo una suma acumulada previa que, al restarle k, nos da la suma acumulada actual.
Entonces, si la suma acumulada en el índice actual menos k ya ha aparecido en el mapa, significa que existe un subarreglo entre un índice anterior y el índice actual cuya suma es igual a k.
var subarraySum = function(nums, k) {
let map = {0: 1}; // This accounts for the case where the sum itself equals k from the beginning.
let count = 0;
let sum = 0;
for (let num of nums) { sum += num; // Update the running sum if (map[sum - k] !== undefined) { count += map[sum - k]; // If sum - k exists in the map, it means there's a subarray that sums to k } // Update the map with the current running sum map[sum] = (map[sum] || 0) + 1; } return count; };
Suma Acumulada | 3 ejercicios
Prefix Sum
303. Range Sum Query - Immutable
525. Contiguous Array
560. Subarray Sum Equals K
Two Pointers
167. Two Sum II - Input Array is Sorted
15. 3 Sum
11. Container with most water
isPalindrome with TwoPointers pattern
function isPalindrome(s) {
let left = 0, right = s.length - 1;
while (left < right) { if (s[left] !== s[right]) { return false; } left++; right--; } return true; }
Sliding Window
643. Maximum Average Subarray I
3. Longest Substring without Repeating Characters
76. Minimum Window Substring
Sliding Window
para que sirve?
Encontrar arrays con good time complexity
function findSubarrayWithSum(arr, target) {
let left = 0, sum = 0;
for (let right = 0; right < arr.length; right++) { sum += arr[right]; // Reducimos el tamaño de la ventana si la suma es mayor al target while (sum > target) { sum -= arr[left]; left++; } // Si encontramos la suma exacta, retornamos el subarray if (sum === target) { return arr.slice(left, right + 1); } } return []; // No se encontró subarray }
// Ejemplo de uso
console.log(findSubarrayWithSum([1, 2, 3, 7, 5], 12)); // [2, 3, 7]
console.log(findSubarrayWithSum([1, 4, 20, 3, 10, 5], 33)); // [20, 3, 10]