Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions TypeScript/Problem1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
4. MEDIAN OF TWO SORTED ARAYS

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Go to LeetCode and look for the problem #4, and read the examples for a better understanding.
*/

function findMedianSortedArrays(nums1: number[], nums2: number[]): number {
const totalLength = nums1.length + nums2.length;
const isEven = totalLength % 2 === 0;
const medianIndex = Math.floor(totalLength / 2);

let i = 0;
let j = 0;
let current = 0;
let previous = 0;

for (let k = 0; k <= medianIndex; k++) { // itera hasta alcanzar ell índice del elemento medio
previous = current; // guarda el valor actual en previous
if (i < nums1.length && (j >= nums2.length || nums1[i] < nums2[j])) { // compara los elementos de los arrays y selecciona el menor
current = nums1[i]; // asigna el index de nums1 a current
i++; // y avanza el index i
} else {
current = nums2[j]; // asigna el valor de nums2 a current
j++; // y avanza index j
}
}

return isEven ? (previous + current) / 2 : current; // si isEven resulta true, devuelve la division
// entre 2 de la suma de previous y current.
// Si isEven es false, devuelve current.
};
56 changes: 56 additions & 0 deletions TypeScript/Problem2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
146. LRU CACHE
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Go to LeetCodde and look for the problem #146, and read the instructions to understand this better.
*/

class LRUCache {
private capacity: number;
private cache: Map<number, number>;

constructor(capacity: number) {
if (capacity < 1 || capacity > 3000) {
throw new Error("Capacity must be between 1 and 3k");
}
this.capacity = capacity;
this.cache = new Map();
}

get(key: number): number {
if (!this.cache.has(key)) {//si no existe, -1
return -1;
}

//En caso de sí tenerla, la mueve al final (más reciente)
const temp = this.cache.get(key)!;
this.cache.delete(key);
this.cache.set(key, temp);
return temp;
}

put(key: number, value: number): void {
if (key < 0 || key > 10000) {
throw new Error("Key must be between 0 and 10k");
}

if (value < 0 || value > 100000) {
throw new Error("Value must be between 0 and 100k");
}

if (this.cache.has(key)) { //si ya existe, lo elimina
this.cache.delete(key);
} else if (this.cache.size == this.capacity) { //si no existía y no hay más memoria
//elimina la clave mas vieja
const [oldestKey] = this.cache.keys();
this.cache.delete(oldestKey);
}
this.cache.set(key, value); //vuelve a insertar la key preexistente para actualizarla al lugar mas reciente
}
}

/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
22 changes: 22 additions & 0 deletions TypeScript/Problem3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
3. LONGEST SUBSTRING WITHOUT REPEATING CHARACTERS
Given a string s, find the length of the longest substring without duplicate characters.
Go to LeetCode and look for the problem #3, and read the instructions for a better understanding.
*/

function lengthOfLongestSubstring(s: string): number {
let characterIndexList: Map<string, number> = new Map(); //aqui se almacenan los strings con su valor
let maxLength: number = 0; //maxima longitud histórica
let left: number = 0; //limite izquierdo indica a partir de dónde no hay caracteres repetidos

for (let index = 0; index < s.length; index++) {
if (characterIndexList.has(s[index])) { //si el caracter ya existe en map
left = Math.max(left, characterIndexList.get(s[index])!+1); //mueve left delante de la posicion repetida
}

characterIndexList.set(s[index], index); //agrega el caracter al map. En caso de ya existir, actualiza su valor
maxLength = Math.max(maxLength, index - left + 1); //evalua qué valor es mayor: la longitud maxima registrada o la actual respecto a left
}

return maxLength;
};
37 changes: 37 additions & 0 deletions TypeScript/Problem4.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
10. REGULAR EXPRESSION MATCHING
Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.​​​​
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).

Go to LeetCode and look for the problem #10. Read the examples for a better understanding.
*/

function isMatch(s: string, p: string): boolean {
const dp: boolean[][] = Array(s.length + 1).fill(null).map(() => Array(p.length + 1).fill(false)); //crea matriz en false
dp[0][0] = true; //true porque las cadenas al inicio coinciden al estar vacias

for (let j = 2; j <= p.length; j += 2) { //maneja patrones como "a*" o ".*" al inicio
if (p[j - 1] === '*') {
dp[0][j] = dp[0][j - 2];
}
}

//compara cada caracter de la cadena con el patron
for (let i = 1; i <= s.length; i++) {
for (let j = 1; j <= p.length; j++) {
if (p[j - 1] === s[i - 1] || p[j - 1] === '.') { //si coinciden exactamente o es "."
dp[i][j] = dp[i - 1][j - 1];
} else if (p[j - 1] === '*') { //en caso de encontrar "*"
dp[i][j] = dp[i][j - 2]; //opcion 1: no se usa el caracter previo

if (p[j - 2] === s[i - 1] || p[j - 2] === '.') {
dp[i][j] = dp[i][j] || dp[i - 1][j]; //opcion 2: se usa el carácter previo si coincide con el actual de s
}
}
}
}

return dp[s.length][p.length]; //se comparan las cadenas
}