Day 23 - LeetCode Hard
Screenshot:-
1. Median of Two Sorted Arrays
Problem: Given two sorted arrays, find the median of the two arrays combined.
Explanation: The median is the middle value of a sorted list. If the total number of elements is odd, it’s the middle element. If even, it’s the average of the two middle elements.
Script:
function findMedianSortedArrays(nums1, nums2) {
const merged = [...nums1, ...nums2].sort((a, b) => a - b);
const len = merged.length;
const mid = Math.floor(len / 2);
return len % 2 === 0 ? (merged[mid - 1] + merged[mid]) / 2 : merged[mid];
}
// Test cases
console.log(findMedianSortedArrays([1, 3], [2])); // Output: 2
console.log(findMedianSortedArrays([1, 2], [3, 4])); // Output: 2.5
2. Merge k Sorted Lists
Problem: Merge k sorted linked lists into one sorted linked list.
Explanation: Use a priority queue (min-heap) to efficiently merge k sorted linked lists.
Script:
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
function mergeKLists(lists) {
const heap = new MinHeap();
lists.forEach(list => {
while (list) {
heap.insert(list.val);
list = list.next;
}
});
let dummy = new ListNode(0);
let current = dummy;
while (!heap.isEmpty()) {
current.next = new ListNode(heap.extractMin());
current = current.next;
}
return dummy.next;
}
3. Trapping Rain Water
Problem: Compute how much water can be trapped after raining based on elevation map.
Explanation: Use two pointers to calculate the trapped water, considering the heights of the bars from both ends.
Script:
function trap(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0;
let water = 0;
while (left <= right) {
if (height[left] <= height[right]) {
leftMax = Math.max(leftMax, height[left]);
water += Math.max(0, leftMax - height[left]);
left++;
} else {
rightMax = Math.max(rightMax, height[right]);
water += Math.max(0, rightMax - height[right]);
right--;
}
}
return water;
}
// Test cases
console.log(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])); // Output: 6
4. N-Queens
Problem: Solve the N-Queens problem by placing n queens on an n x n chessboard so that no two queens attack each other.
Explanation: Use backtracking to place queens one by one and ensure they don’t threaten each other.
Script:
function solveNQueens(n) {
const result = [];
const board = Array(n).fill().map(() => Array(n).fill('.'));
function isSafe(row, col) {
for (let i = 0; i < row; i++) {
if (board[i][col] === 'Q') return false;
if (col - (row - i) >= 0 && board[i][col - (row - i)] === 'Q') return false;
if (col + (row - i) < n && board[i][col + (row - i)] === 'Q') return false;
}
return true;
}
function placeQueens(row) {
if (row === n) {
result.push(board.map(r => r.join('')));
return;
}
for (let col = 0; col < n; col++) {
if (isSafe(row, col)) {
board[row][col] = 'Q';
placeQueens(row + 1);
board[row][col] = '.';
}
}
}
placeQueens(0);
return result;
}
// Test cases
console.log(solveNQueens(4)); // Output: All distinct solutions for 4-Queens
5. Word Ladder
Problem: Find the shortest transformation sequence from a begin word to an end word using a dictionary.
Explanation: Use BFS to find the shortest path from the begin word to the end word by changing one letter at a time.
Script:
function ladderLength(beginWord, endWord, wordList) {
if (!wordList.includes(endWord)) return 0;
const wordSet = new Set(wordList);
const queue = [[beginWord, 1]];
while (queue.length) {
const [word, length] = queue.shift();
if (word === endWord) return length;
for (let i = 0; i < word.length; i++) {
for (let c = 'a'.charCodeAt(0); c <= 'z'.charCodeAt(0); c++) {
const newWord = word.slice(0, i) + String.fromCharCode(c) + word.slice(i + 1);
if (wordSet.has(newWord)) {
wordSet.delete(newWord);
queue.push([newWord, length + 1]);
}
}
}
}
return 0;
}
// Test cases
console.log(ladderLength("hit", "cog", ["hot", "dot", "dog", "cog"])); // Output: 5
Achievement
By working through these problems, you'll gain valuable experience in solving complex algorithmic challenges and handling edge cases. Each problem helps improve your problem-solving skills and understanding of advanced algorithms.
Happy Coding!!!!