diff --git a/set-matrix-zeroes/nhistory.js b/set-matrix-zeroes/nhistory.js new file mode 100644 index 000000000..732313900 --- /dev/null +++ b/set-matrix-zeroes/nhistory.js @@ -0,0 +1,24 @@ +var setZeroes = function (matrix) { + let rows = new Set(); + let cols = new Set(); + + for (let row = 0; row < matrix.length; row++) { + for (let col = 0; col < matrix[0].length; col++) { + if (matrix[row][col] === 0) { + rows.add(row); + cols.add(col); + } + } + } + + for (let row = 0; row < matrix.length; row++) { + for (let col = 0; col < matrix[0].length; col++) { + if (rows.has(row) || cols.has(col)) { + matrix[row][col] = 0; + } + } + } +}; + +// TC: O(m*n) +// SC: O(m+n) diff --git a/spiral-matrix/nhistory.js b/spiral-matrix/nhistory.js new file mode 100644 index 000000000..3f4f28808 --- /dev/null +++ b/spiral-matrix/nhistory.js @@ -0,0 +1,45 @@ +var spiralOrder = function (matrix) { + // Edge case + if (matrix.length === 0) return []; + + let result = []; + let rowStart = 0, + rowEnd = matrix.length - 1; + let colStart = 0, + colEnd = matrix[0].length - 1; + + while (rowStart <= rowEnd && colStart <= colEnd) { + // Traverse right + for (let col = colStart; col <= colEnd; col++) { + result.push(matrix[rowStart][col]); + } + rowStart++; + + // Traverse down + for (let row = rowStart; row <= rowEnd; row++) { + result.push(matrix[row][colEnd]); + } + colEnd--; + + // Traverse left (check if rowStart <= rowEnd to avoid duplicates) + if (rowStart <= rowEnd) { + for (let col = colEnd; col >= colStart; col--) { + result.push(matrix[rowEnd][col]); + } + rowEnd--; + } + + // Traverse up (check if colStart <= colEnd to avoid duplicates) + if (colStart <= colEnd) { + for (let row = rowEnd; row >= rowStart; row--) { + result.push(matrix[row][colStart]); + } + colStart++; + } + } + + return result; +}; + +// TC: O(m*n) +// SC: O(m*n) diff --git a/sum-of-two-integers/nhistory.js b/sum-of-two-integers/nhistory.js new file mode 100644 index 000000000..c4e381479 --- /dev/null +++ b/sum-of-two-integers/nhistory.js @@ -0,0 +1,16 @@ +var getSum = function (a, b) { + while (b !== 0) { + if (b > 0) { + a++; + b--; + } else { + b++; + a--; + } + } + return a; +}; + +// |b| is absolute value of b +// TC: O(|b|) +// SC: O(1)