Week 1
Plus Minus
Use toFixed() function in JavaScript to print required number of decimal
places.
Mini-Max Sum
Sort function sorts strings, by default. To sort numbers, pass a function.
let sortedArr = arr.sort((a, b) => a - b);Time Conversion
Use endsWith() string method
let amOrPm = s.endsWith("AM") ? "AM" : "PM";Convert string to number
hour = parseInt(hour, 10);Sparse Arrays
Map constructor takes array of arrays
let map = new Map(queries.map((query) => [query, 0]));Array.prototype.map() returns a new array
queries.map((query) => map.get(query));Lonely Integer
In a given array, each element occurs twice, except one. Find the unique element.
// relevant Set functions
Set.prototype.has();
Set.prototype.add();
Set.prototype.delete();Flipping Bits
- 32-bit Maximum Value: The maximum value for a 32-bit unsigned integer is
0xFFFFFFFF, which is4294967295in decimal. This value has all 32 bits set to1. - Flipping the Bits: By using the XOR (
^) operation with0xFFFFFFFF, you effectively flip all the bits in the numbern. XOR with1flips the bit, so this operation inverts all bits ofn. - Handling Large Integer Values: JavaScript can handle large integers using
the
BigInttype. To ensure compatibility with the problem statement while usingBigInt
function flippingBits(n) {
// Define the maximum 32-bit unsigned integer as a BigInt
const MAX_32BIT_UNSIGNED = BigInt(0xffffffff);
// Convert n to BigInt and XOR with the maximum 32-bit unsigned integer to flip all bits
return BigInt(n) ^ MAX_32BIT_UNSIGNED;
}Diagonal Difference
/*
* Complete the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*/
function diagonalDifference(arr) {
// Write your code here
let length = arr[0].length;
let left = 0,
right = 0;
for (let i = 0; i < length; i++) {
left += arr[i][i];
right += arr[i][length - 1 - i];
console.log(left, right);
}
return Math.abs(left - right);
}Counting Sort 1
Array.prototype.fill() method
let sortingArray = new Array(100).fill(0);Pangrams
Set usage
function pangrams(s) {
// Write your code here
let set = new Set();
for (let c of s.toLowerCase().split(" ").join("")) {
if (!set.has(c)) set.add(c);
}
return [...set].length === 26 ? "pangram" : "not pangram";
}Permuting Two Arrays
The key insight is that we don’t actually need to check all permutations. Here’s why:
- We’re looking for any permutation where A[i] + B[i] >= k for all i.
- To maximize our chances of satisfying this condition, we want to pair the smallest elements of A with the largest elements of B.
- By sorting A in ascending order and B in descending order, we create the optimal pairing.
- If this optimal pairing doesn’t work, no other permutation will work either.
function canPermute(A, B, k) {
// Sort array A in ascending order
A.sort((a, b) => a - b);
// Sort array B in descending order
B.sort((a, b) => b - a);
// Check if the sum of corresponding elements is at least k
for (let i = 0; i < A.length; i++) {
if (A[i] + B[i] < k) {
return false;
}
}
return true;
}
// Example usage
const A = [2, 1, 3];
const B = [7, 8, 9];
const k = 10;
console.log(canPermute(A, B, k)); // Output: trueSubarray Division 1
Sliding window problem
function birthday(s, d, m) {
let count = 0;
let currentSum = 0;
// Calculate the sum of the first subarray of length m
for (let i = 0; i < m; i++) {
currentSum += s[i];
}
// Check if the first subarray matches the target sum
if (currentSum === d) {
count++;
}
// Slide the window across the array
for (let i = m; i < s.length; i++) {
// Add the new element and remove the element that is left out
currentSum += s[i] - s[i - m];
// Check if the updated sum matches the target sum
if (currentSum === d) {
count++;
}
}
return count;
}Week 2
Drawing Book
Insight: how do we find the number of turns taken to reach a page - from the front and the back?
function pageCount(n, p) {
// Write your code here
const frontTurns = Math.floor(p / 2);
// Calculate the number of page turns from the back
const backTurns = Math.floor(n / 2 - Math.floor(p / 2));
// Return the minimum of the two
return Math.min(frontTurns, backTurns);
}Tower Breakers
Insight: start with simplest cases
function towerBreakers(n, m) {
// If the height of each tower is 1, Player 2 wins by default
if (m === 1) {
return 2;
}
// If the number of towers is even, Player 2 can mirror Player 1's moves
if (n % 2 === 0) {
return 2;
}
// Otherwise, Player 1 can force a win
return 1;
}Ceaser Cipher
String functions
// create string
String.fromCharCode(newCharCode)
// covert to char code
'z'.charCodeAt(0)Dynamic Array
Initialize an array of length n where each element is an empty array
let seqList = Array.from({ length: n }, () => []);SHerlock and Array
JavaScript array reduce function
let totalSum = arr.reduce((a, b) => a + b, 0); // Calculate the total sum of the array