Skip to main content

DSA Tips & Tricks

Swap Function

function swap(arr, i, j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
}

Reverse Array

function reverseArray(arr) {
return arr.reverse();
}

Check for Duplicates

function hasDuplicates(arr) {
return new Set(arr).size !== arr.length;
}

Find Maximum/Minimum

function findMax(arr) {
return Math.max(...arr);
}

function findMin(arr) {
return Math.min(...arr);
}

Sum of Elements

function sumArray(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}

Generate Range

function range(start, end) {
return Array.from({ length: end - start + 1 }, (_, i) => start + i);
}

Creating Visited Array for 2D Matrix Graph Problems on LC

const rows = 3
const cols = 3
const visited = Array.from({ length: rows }, () => Array(cols).fill(false));

/*
[
[ false, false, false ],
[ false, false, false ],
[ false, false, false ]
]
*/
  • Use Case: Keep track of visited nodes when traversing or searching through 2D grids.
  • Common Problem: BFS, DFS in grid-based questions.

Traversing 2D Matrix

const directions = [
[0, 1], // right
[1, 0], // down
[0, -1], // left
[-1, 0], // up
[1, 1], // down-right (diagonal)
[1, -1], // down-left (diagonal)
[-1, 1], // up-right (diagonal)
[-1, -1] // up-left (diagonal)
];

for (let [dr, dc] of directions) {
const newRow = row + dr;
const newCol = col + dc;
//do something
}
  • Use Case: Move in all possible directions in a matrix, especially for flood-fill, path-finding, or connected components problems.

Creating DP Dynamic Array

const n=4
const dp = Array(n).fill(1)
//[1,1,1,1]
  • Use Case: Useful for dynamic programming problems where you need to store solutions to subproblems, e.g., dp[i] could represent the solution for the first i elements.

Using Multi-Dimensional DP Arrays

const rows = 3;
const cols = 3;
const dp = Array.from({ length: rows }, () => Array(cols).fill(0));

/*
[
[ 0, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 0 ]
]
*/
  • Use Case: Useful in problems like finding paths in a grid, calculating the maximum/minimum path sums, or handling subproblems that depend on two indices.

DFS/BFS Queue for Matrix

const queue = [[startRow, startCol]];
const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; // 4-directional movement

while (queue.length) {
const [row, col] = queue.shift();

for (let [dr, dc] of directions) {
const newRow = row + dr;
const newCol = col + dc;
// Add boundary check here and then enqueue
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {
queue.push([newRow, newCol]);
}
}
}
  • Use Case: For BFS (level-order) or DFS (depth-first) traversals on a 2D grid.

Boundary Check for Matrix Traversals

const isValid = (row, col, rows, cols) => {
return row >= 0 && row < rows && col >= 0 && col < cols;
};
  • Use Case: Avoid index out-of-bound errors when traversing a matrix.

Alphanumeric Check for Strings

function isAlphanumeric(str) {
return /^[a-zA-Z0-9]+$/.test(str);
}

//OR

function isAlphanumeric(char) {
return (('A' <= char && char <= 'Z') ||
('a' <= char && char <= 'z') ||
('0' <= char && char <= '9'));
}

// Test cases
console.log(isAlphanumeric("abc123")); // true
console.log(isAlphanumeric("abc")); // true
console.log(isAlphanumeric("123")); // true
console.log(isAlphanumeric("abc 123")); // false (contains space)
console.log(isAlphanumeric("abc!123")); // false (contains special character)
console.log(isAlphanumeric("")); // false (empty string)

Rectangle Area (Coordinates)

Area = |x2 - x1| × |y2 - y1|
  • Points to Remember:
    • (x1, y1) and (x2, y2) are the coordinates of opposite corners.
    • The result is in square units.

Square Area (Coordinates)

Area = (|x2 - x1|)² or (|y2 - y1|)² 
  • Points to Remember:
    • Ensure the points form a square (check diagonals are equal and perpendicular).

Triangle Area (Coordinates)

Area = |x1(y2 - y3) + x2(y3 - y1) + x3(y1 - y2)| / 2
  • Points to Remember:
    • (x1, y1), (x2, y2), and (x3, y3) are the vertices of the triangle.
    • The result is in square units.