0% found this document useful (0 votes)
17 views36 pages

String Manipulation Algorithms in JavaScript

The document contains various JavaScript functions that solve different algorithmic problems, such as merging strings, finding the greatest common divisor of strings, checking if kids can have the most candies, and more. Each function is designed to perform a specific task efficiently, often using techniques like two-pointer approaches, sliding windows, and array manipulations. The document showcases a range of problems, including string manipulation, array processing, and mathematical computations.

Uploaded by

Manish Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views36 pages

String Manipulation Algorithms in JavaScript

The document contains various JavaScript functions that solve different algorithmic problems, such as merging strings, finding the greatest common divisor of strings, checking if kids can have the most candies, and more. Each function is designed to perform a specific task efficiently, often using techniques like two-pointer approaches, sliding windows, and array manipulations. The document showcases a range of problems, including string manipulation, array processing, and mathematical computations.

Uploaded by

Manish Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

You are given two strings word1 and word2.

Merge the strings by adding letters in alternating


order, starting with word1. If a string is longer than the other, append the additional letters onto
the end of the merged string.

Return the merged string.

var mergeAlternately = function(word1, word2) {


let result = '';
let i = 0;
let j = 0;

// Loop through both strings and add characters alternately


while (i < [Link] && j < [Link]) {
result += word1[i++];
result += word2[j++];
}

// If there are remaining characters in word1


while (i < [Link]) {
result += word1[i++];
}

// If there are remaining characters in word2


while (j < [Link]) {
result += word2[j++];
}

return result;
};

For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t (i.e., t is
concatenated with itself one or more times).

Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

function gcdOfStrings(str1, str2) {


// Helper function to compute the GCD of two numbers
function gcd(a, b) {
if (b === 0) return a;
return gcd(b, a % b);
}

// If str1 + str2 is not equal to str2 + str1, no common divisor exists


if (str1 + str2 !== str2 + str1) return '';

// Calculate the GCD of the lengths of the strings


const gcdLength = gcd([Link], [Link]);

// The largest common divisor string is the substring of str1 of length gcdLength
return [Link](0, gcdLength);
}

There are n kids with candies. You are given an integer array candies, where
each candies[i] represents the number of candies the i kid has, and an integer extraCandies,
th

denoting the number of extra candies that you have.

Return a boolean array result of length n, where result[i] is true if, after giving the i kid all
th

the extraCandies, they will have the greatest number of candies among all the kids,
or false otherwise.

var kidsWithCandies = function(candies, extraCandies) {


const maxCandies = [Link](...candies); // Find the maximum number of candies any kid has
return [Link](candy => candy + extraCandies >= maxCandies); // Check for each kid
};

You have a long flowerbed in which some of the plots are planted, and some are not. However,
flowers cannot be planted in adjacent plots.

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not
empty, and an integer n, return true if n new flowers can be planted in the flowerbed without
violating the no-adjacent-flowers rule and false otherwise.

var canPlaceFlowers = function(flowerbed, n) {


let count = 0; // To count how many flowers can be planted

for (let i = 0; i < [Link]; i++) {


// Check if current plot is empty and it can be planted
if (flowerbed[i] === 0 &&
(i === 0 || flowerbed[i - 1] === 0) &&
(i === [Link] - 1 || flowerbed[i + 1] === 0)) {
flowerbed[i] = 1; // Plant a flower
count++; // Increment the count of planted flowers
if (count >= n) return true; // If we've planted enough flowers, return true
}
}

return count >= n; // Return true if we managed to plant enough flowers


};

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more
than once.

var reverseVowels = function(s) {


const vowels = new Set('aeiouAEIOU'); // Set of vowels for quick lookup
let left = 0;
let right = [Link] - 1;
let arr = [Link](''); // Convert string to array for easier manipulation

while (left < right) {


// Move left pointer to the next vowel
while (left < right && ![Link](arr[left])) {
left++;
}

// Move right pointer to the previous vowel


while (left < right && ![Link](arr[right])) {
right--;
}

// If both pointers are at vowels, swap them


if (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
}

// Join the array back into a string and return


return [Link]('');
};

Given an input string s, reverse the order of the words.


A word is defined as a sequence of non-space characters. The words in s will be separated by at
least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The
returned string should only have a single space separating the words. Do not include any extra
spaces.

var reverseWords = function(s) {


// Step 1: Trim leading/trailing spaces, and split by any whitespace
const words = [Link]().split(/\s+/); // This splits on one or more spaces

// Step 2: Reverse the array of words


const reversedWords = [Link]();

// Step 3: Join the reversed words with a single space


return [Link](' ');
};

Given an integer array nums, return an array answer such that answer[i] is equal to the product of
all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

var productExceptSelf = function(nums) {


const n = [Link];
const answer = new Array(n).fill(1); // Initialize the result array with 1s

// Step 1: Calculate the left products and store them in `answer`


let left = 1;
for (let i = 0; i < n; i++) {
answer[i] = left;
left *= nums[i];
}

// Step 2: Calculate the right products and multiply them with `answer`
let right = 1;
for (let i = n - 1; i >= 0; i--) {
answer[i] *= right;
right *= nums[i];
}

return answer;
};

Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j <
k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.

var increasingTriplet = function(nums) {


let n = [Link];
if (n < 3) return false; // If there are fewer than 3 elements, no triplet is possible

let min_left = new Array(n).fill(Infinity);


let max_right = new Array(n).fill(-Infinity);

// Fill the min_left array (minimum to the left of each index)


min_left[0] = nums[0];
for (let i = 1; i < n; i++) {
min_left[i] = [Link](min_left[i - 1], nums[i]);
}

// Fill the max_right array (maximum to the right of each index)


max_right[n - 1] = nums[n - 1];
for (let i = n - 2; i >= 0; i--) {
max_right[i] = [Link](max_right[i + 1], nums[i]);
}

// Check for a valid triple


for (let i = 1; i < n - 1; i++) {
if (min_left[i - 1] < nums[i] && nums[i] < max_right[i + 1]) {
return true;
}
}

return false;
};

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s. For each group of consecutive repeating characters in chars:

 If the group's length is 1, append the character to s.


 Otherwise, append the character followed by the group's length.

The compressed string s should not be returned separately, but instead, be stored in the
input character array chars. Note that group lengths that are 10 or longer will be split into
multiple characters in chars.

After you are done modifying the input array, return the new length of the array.

You must write an algorithm that uses only constant extra space.

var compress = function(chars) {


let write = 0; // Pointer for where to write the compressed characters
let read = 0; // Pointer to traverse the original array

while (read < [Link]) {


let currentChar = chars[read];
let count = 0;

// Count the number of consecutive characters


while (read < [Link] && chars[read] === currentChar) {
read++;
count++;
}

// Write the character itself


chars[write++] = currentChar;

// If there are more than 1 consecutive characters, write the count


if (count > 1) {
for (let digit of [Link]()) {
chars[write++] = digit;
}
}
}

// Return the new length of the array


return write;
};

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of
the non-zero elements.

Note that you must do this in-place without making a copy of the array.

var moveZeroes = function(nums) {


let currentIndex = 0; // Pointer to track the position for non-zero elements
for (let i = 0; i < [Link]; i++) {
if (nums[i] !== 0) {
// Swap non-zero element with the currentIndex position
[nums[i], nums[currentIndex]] = [nums[currentIndex], nums[i]];
currentIndex++; // Move to the next position
}
}
return nums;
};

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some
(can be none) of the characters without disturbing the relative positions of the remaining
characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

var isSubsequence = function(s, t) {


if([Link] < [Link]) return false;

let i = 0;
let j = 0;

while(j < [Link]){


const tChar = t[j];
const sChar = s[i];

if(tChar === sChar){


i++;
}

j++;
}

if(i >= [Link]){


return true;
}

return false;
};

You are given an integer array height of length n. There are n vertical lines drawn such that the
two endpoints of the i line are (i, 0) and (i, height[i]).
th

Find two lines that together with the x-axis form a container, such that the container contains the
most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

var maxArea = function(height) {


let i = 0;
let j = [Link] - 1;
let max = 0;
while(j > i){
const currentHeight = [Link](height[j], height[i]);
max = [Link](max, currentHeight * [Link](j - i));
if(height[j] < height[i]){
j--;
}
else{
i++;
}
}
return max;
};

You are given an integer array nums and an integer k.

In one operation, you can pick two numbers from the array whose sum equals k and remove them
from the array.

Return the maximum number of operations you can perform on the array.

var maxOperations = function(nums, k) {


[Link]((a, b) => a - b); // Sort the array to make the two-pointer approach work
let i = 0;
let j = [Link] - 1;
let count = 0;

while (i < j) {
const sum = nums[i] + nums[j];

if (sum === k) {
count++;
i++;
j--;
} else if (sum < k) {
i++; // Increment left pointer if the sum is less than k
} else {
j--; // Decrement right pointer if the sum is greater than k
}
}

return count;
};

You are given an integer array nums consisting of n elements, and an integer k.

Find a contiguous subarray whose length is equal to k that has the maximum average value and
return this value. Any answer with a calculation error less than 10 will be accepted.
-5

Example 1:

Input: nums = [1,12,-5,-6,50,3], k = 4


Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75

var findMaxAverage = function(nums, k) {


let currentSum = 0;
// Calculate the sum of the first 'k' elements
for (let i = 0; i < k; i++) {
currentSum += nums[i];
}
let maxSum = currentSum;

// Slide the window across the rest of the array


for (let i = k; i < [Link]; i++) {
// Add the new element and subtract the old element
currentSum += nums[i] - nums[i - k];
maxSum = [Link](maxSum, currentSum); // Update max sum if needed
}

// Return the maximum average


return maxSum / k;
};

Given a string s and an integer k, return the maximum number of vowel letters in any substring
of s with length k.

Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.

var maxVowels = function(s, k) {


let currentCount = 0;
const vowels = ['a', 'e', 'i', 'o', 'u'];
for(let i = 0; i < k; i++){
if([Link](s[i]) >= 0){
currentCount++;
}
}
let max = currentCount;
for(let i = k; i < [Link]; i++){
if([Link](s[i-k]) >= 0){
currentCount--;
}
if([Link](s[i]) >= 0){
currentCount++;
}
max = [Link](max, currentCount);
}

return max;
};

Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the
array if you can flip at most k 0's.

Example 1:

Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2


Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.

Example 2:

Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3


Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
var longestOnes = function(nums, k) {
let i = 0; // Left pointer
let j = 0; // Right pointer
let curr = 0; // Count of zeros in the current window
let max = 0; // Max length of the subarray

while (j < [Link]) {


// If the current element is zero, increase the zero count
if (nums[j] === 0) {
curr++;
}

// If the number of zeros exceeds k, move the left pointer to the right
while (curr > k) {
if (nums[i] === 0) {
curr--;
}
i++; // Move the left pointer
}

// Calculate the max length of valid subarray


max = [Link](max, j - i + 1);

j++; // Move the right pointer


}

return max;
};

Given a binary array nums, you should delete one element from it.

Return the size of the longest non-empty subarray containing only 1's in the resulting array.
Return 0 if there is no such subarray.

var longestSubarray = function(nums) {


let left = 0;
let maxLength = 0;
let zeroCount = 0;

for (let right = 0; right < [Link]; right++) {


// If we encounter a 0, increment the zero count
if (nums[right] === 0) {
zeroCount++;
}

// If zero count exceeds 1, move the left pointer to shrink the window
while (zeroCount > 1) {
if (nums[left] === 0) {
zeroCount--;
}
left++;
}

// Calculate the maximum length of the window that contains at most one zero
maxLength = [Link](maxLength, right - left + 1);
}

// We need to delete one element, so subtract 1 from the result


return maxLength - 1;
};

There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes.
The biker starts his trip on point 0 with altitude equal 0.
You are given an integer array gain of length n where gain[i] is the net gain in altitude between
points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point.

var largestAltitude = function(gain) {


let max = 0;
let prev = 0;
for(let i = 0; i < [Link]; i++){
prev += gain[i];
max = [Link](max, prev);
}
return max;
};

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is
equal to the sum of all the numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements
to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

var pivotIndex = function(nums) {


let totalSum = 0;
let leftSum = 0;

// Calculate the total sum of the array


for (let num of nums) {
totalSum += num;
}

// Iterate through the array to find the pivot index


for (let i = 0; i < [Link]; i++) {
// Check if the left sum equals the right sum
if (leftSum === totalSum - leftSum - nums[i]) {
return i;
}
leftSum += nums[i]; // Update the left sum for the next index
}

return -1; // If no pivot index is found, return -1


};

Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:

 answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
 answer[1] is a list of all distinct integers in nums2 which are not present in nums1.

Note that the integers in the lists may be returned in any order.

var findDifference = function(nums1, nums2) {


const set1 = new Set(nums1);
const set2 = new Set(nums2);

const result1 = [Link](num => ![Link](num)); // Elements in nums1 but not in nums2
const result2 = [Link](num => ![Link](num)); // Elements in nums2 but not in nums1

return [[Link](new Set(result1)), [Link](new Set(result2))];


};
Given an array of integers arr, return true if the number of occurrences of each value in the array
is unique or false otherwise.

var uniqueOccurrences = function(arr) {


const map = new Map();
let result = true;
for(let i = 0; i < [Link]; i++){
if([Link](arr[i])){
[Link](arr[i], ([Link](arr[i])) + 1);
}
else{
[Link](arr[i], 1);
}
}
const set = new Set();
const occurences = [Link]([Link]());
for(let i = 0; i < [Link]; i++){
if([Link](occurences[i])) {
result = false;
break;
}
[Link](occurences[i]);
}

return result;
};

Two strings are considered close if you can attain one from the other using the following
operations:

 Operation 1: Swap any two existing characters.


 For example, abcde -> aecdb
 Operation 2: Transform every occurrence of one existing character into
another existing character, and do the same with the other character.
 For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)

You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close,
and false otherwise.

var closeStrings = function(word1, word2) {


if([Link] !== [Link]){
return false;
}

const freq1 = new Map();


const freq2 = new Map();

for(let i = 0; i < [Link]; i++){


[Link](word1[i], ([Link](word1[i]) || 0) + 1);
[Link](word2[i], ([Link](word2[i]) || 0) + 1);
}

if([Link]([Link]()).sort().join('') !== [Link]([Link]()).sort().join('')){


return false;
}

if([Link]([Link]()).sort().join('') !== [Link]([Link]()).sort().join('')){


return false;
}
return true;
};

Given a 0-indexed n x n integer matrix grid, return the number of pairs (r , c ) such that
i j

row r and column c are equal.


i j

A row and column pair is considered equal if they contain the same elements in the same order
(i.e., an equal array).

var equalPairs = function(grid) {


const rows = new Set();
let result = 0;

// Store all rows as strings in a set


for (let i = 0; i < [Link]; i++) {
[Link](grid[i].join(''));
}

// Check each column against the stored rows


for (let col = 0; col < grid[0].length; col++) {
let curCol = [];
for (let row = 0; row < [Link]; row++) {
[Link](grid[row][col]);
}

// Check if the column matches any row in the set


if ([Link]([Link](''))) {
result++;
}
}

return result;
};

You are given a string s, which contains stars *.

In one operation, you can:

 Choose a star in s.
 Remove the closest non-star character to its left, as well as remove the star itself.

Return the string after all stars have been removed.

Note:

 The input will be generated such that the operation is always possible.
 It can be shown that the resulting string will always be unique.

var removeStars = function(s) {


const stack = [];
for(let char of s){
if(char === "*"){
[Link]();
continue;
}
[Link](char);
}
return [Link]('')
};

We are given an array asteroids of integers representing asteroids in a row. The indices of the
asteriod in the array represent their relative position in space.
For each asteroid, the absolute value represents its size, and the sign represents its direction
(positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will
explode. If both are the same size, both will explode. Two asteroids moving in the same direction
will never meet.

var asteroidCollision = function(asteroids) {


let stack = [];

for (let ast of asteroids) {


// Process the current asteroid
let isDestroyed = false;
while ([Link] > 0 && ast < 0 && stack[[Link] - 1] > 0) {
let topAsteroid = stack[[Link] - 1];
if ([Link](topAsteroid) > [Link](ast)) {
// Current asteroid is destroyed
isDestroyed = true;
break;
} else if ([Link](topAsteroid) === [Link](ast)) {
// Both asteroids are destroyed
[Link]();
isDestroyed = true;
break;
} else {
// Top asteroid is destroyed
[Link]();
}
}
if (!isDestroyed) {
[Link](ast);
}
}

return stack;
};

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is
being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; there are no extra white spaces, square
brackets are well-formed, etc. Furthermore, you may assume that the original data does not
contain any digits and that digits are only for those repeat numbers, k. For example, there will not
be input like 3a or 2[4].

The test cases are generated so that the length of the output will never exceed 10 . 5

var decodeString = function(s) {


let stack = [];
let currentNum = 0;
let currentStr = '';

for (let char of s) {


if (char === '[') {
// Push the current number and string onto the stack
[Link]([currentNum, currentStr]);
// Reset current number and string
currentNum = 0;
currentStr = '';
} else if (char === ']') {
// Pop the last number and string from the stack
let [prevNum, prevStr] = [Link]();
// Repeat the current string 'prevNum' times and concatenate with the previous string
currentStr = prevStr + [Link](prevNum);
} else if (/\d/.test(char)) {
// Build the current number (handle multi-digit numbers)
currentNum = currentNum * 10 + parseInt(char);
} else {
// Append the current character to the current string
currentStr += char;
}
}

return currentStr;
};

You have a RecentCounter class which counts the number of recent requests within a certain time
frame.

Implement the RecentCounter class:

 RecentCounter() Initializes the counter with zero recent requests.


 int ping(int t) Adds a new request at time t, where t represents some time in milliseconds,
and returns the number of requests that has happened in the past 3000 milliseconds
(including the new request). Specifically, return the number of requests that have
happened in the inclusive range [t - 3000, t].

It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.

var RecentCounter = function() {


[Link] = [];
};

/**
* @param {number} t
* @return {number}
*/
[Link] = function(t) {
[Link](t);
// Remove pings that are outside the 3000ms window
while ([Link][0] < t - 3000) {
[Link](); // O(n) operation
}
return [Link];
};

In the world of Dota2, there are two parties: the Radiant and the Dire.

The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide
on a change in the Dota2 game. The voting for this change is a round-based procedure. In each
round, each senator can exercise one of the two rights:

 Ban one senator's right: A senator can make another senator lose all his rights in this
and all the following rounds.
 Announce the victory: If this senator found the senators who still have rights to vote are
all from the same party, he can announce the victory and decide on the change in the
game.

Given a string senate representing each senator's party belonging. The


character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators,
the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This
procedure will last until the end of voting. All the senators who have lost their rights will be
skipped during the procedure.

Suppose every senator is smart enough and will play the best strategy for his own party. Predict
which party will finally announce the victory and change the Dota2 game. The output should
be "Radiant" or "Dire".

var predictPartyVictory = function(senate) {


const n = [Link];
const radiantQueue = [];
const direQueue = [];

// Initialize the queues with the indices of 'R' and 'D' senators
for (let i = 0; i < n; i++) {
if (senate[i] === 'R') {
[Link](i);
} else {
[Link](i);
}
}

// Simulate the voting process


while ([Link] > 0 && [Link] > 0) {
const radiantIndex = [Link]();
const direIndex = [Link]();

if (radiantIndex < direIndex) {


[Link](radiantIndex + n); // Re-enqueue with updated index
} else {
[Link](direIndex + n); // Re-enqueue with updated index
}
}

// Determine the winner


return [Link] > 0 ? 'Radiant' : 'Dire';
};

You are given the head of a linked list. Delete the middle node, and return the head of the
modified linked list.

The middle node of a linked list of size n is the ⌊n / 2⌋ node from the start using 0-based
th

indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.

 For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.

var deleteMiddle = function(head) {


// Edge case: if the list is empty or has only one node
if (!head || ![Link]) {
return null;
}

let slow = head;


let fast = head;
let slowPrev = null;

// Traverse the list to find the middle node


while (fast && [Link]) {
fast = [Link];
slowPrev = slow;
slow = [Link];
}
// Delete the middle node
if (slowPrev) {
[Link] = [Link];
}

return head;
};

Given the head of a singly linked list, group all the nodes with odd indices together followed by the
nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the
input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

var oddEvenList = function(head) {


if (!head || ![Link]) {
return head;
}

let odd = head;


let even = [Link];
let evenHead = even;

while (even && [Link]) {


[Link] = [Link];
odd = [Link];
[Link] = [Link];
even = [Link];
}

[Link] = evenHead;
return head;
};

Given the head of a singly linked list, reverse the list, and return the reversed list.

var reverseList = function(head) {


let prev = null;
let cur = head;
while (cur) {
let nextTemp = [Link]; // Store next node
[Link] = prev; // Reverse current node's pointer
prev = cur; // Move prev and cur one step forward
cur = nextTemp;
}
return prev; // New head of the reversed list
};

In a linked list of size n, where n is even, the i node (0-indexed) of the linked list is known as
th

the twin of the (n-1-i) node, if 0 <= i <= (n / 2) - 1.


th

 For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2.
These are the only nodes with twins for n = 4.

The twin sum is defined as the sum of a node and its twin.
Given the head of a linked list with even length, return the maximum twin sum of the linked list.

var pairSum = function(head) {


let cur = head;
let values = [];
let maxTwinSum = 0;

// First, calculate the size of the list and store the first half values.
while (cur) {
[Link]([Link]);
cur = [Link];
}

let n = [Link];
// Find the twin sum and calculate the maximum.
for (let i = 0; i < n / 2; i++) {
let twinSum = values[i] + values[n - 1 - i];
maxTwinSum = [Link](maxTwinSum, twinSum);
}

return maxTwinSum;
};

A binary tree's maximum depth is the number of nodes along the longest path from the root
node down to the farthest leaf node.

var maxDepth = function(root) {


let max = 0;
const setDepth = (node, count) => {
if(!node){
max = [Link](max, count);
return;
}
setDepth([Link], count + 1);
setDepth([Link], count + 1);
}
setDepth(root, 0);
return max;
};

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form
a leaf value sequence.

var leafSimilar = function(root1, root2) {


const seq1 = [];
const seq2 = [];

const iterate = (node, seq) => {


if (!node) return;

if (![Link] && ![Link]) {


[Link]([Link]);
}

iterate([Link], seq);
iterate([Link], seq);
}

iterate(root1, seq1);
iterate(root2, seq2);
return [Link]() === [Link](); // Directly comparing arrays as strings
};

Given a binary tree root, a node X in the tree is named good if in the path from root to X there are
no nodes with a value greater than X.

Return the number of good nodes in the binary tree.

var goodNodes = function(root) {


let count = 0;
const traverse = (node, maxSoFar) => {
if(!node) return;
if(maxSoFar <= [Link]){
count++;
maxSoFar = [Link];
}
traverse([Link], maxSoFar);
traverse([Link], maxSoFar);
}

traverse(root, -Infinity);
return count;
};

Given the root of a binary tree and an integer targetSum, return the number of paths where the
sum of the values along the path equals targetSum.

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e.,
traveling only from parent nodes to child nodes).

Example 1:

var pathSum = function(root, targetSum) {


let count = 0;

// Helper function to count the number of paths that sum to targetSum


const findPaths = (node, sum) => {
if (!node) return;

sum += [Link]; // Add the current node's value to the running sum

if (sum === targetSum) {


count++; // If sum matches targetSum, increment the count
}

// Explore both the left and right children


findPaths([Link], sum);
findPaths([Link], sum);
};

// Helper function to traverse the tree and call findPaths for each node
const traverse = (node) => {
if (!node) return;

// For each node, start searching for paths starting from that node
findPaths(node, 0);

// Recursively check left and right subtrees


traverse([Link]);
traverse([Link]);
};

// Start the traversal from the root


traverse(root);
return count;
};

You are given the root of a binary tree.

A ZigZag path for a binary tree is defined as follow:

 Choose any node in the binary tree and a direction (right or left).
 If the current direction is right, move to the right child of the current node; otherwise, move
to the left child.
 Change the direction from right to left or from left to right.
 Repeat the second and third steps until you can't move in the tree.

Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).

Return the longest ZigZag path contained in that tree.

var longestZigZag = function(root) {


let max = 0;

// Helper function to perform DFS traversal


const dfs = (node, left, right) => {
if (!node) return;

// Update the maximum length of zigzag path


max = [Link](max, left, right);

// Move to left child, update the counts


dfs([Link], right + 1, 0); // Moving left from this node
// Move to right child, update the counts
dfs([Link], 0, left + 1); // Moving right from this node
};

// Start DFS traversal from root, starting with counts of 0


dfs(root, 0, 0);

return max;
};

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between
two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a
node to be a descendant of itself).”

var lowestCommonAncestor = function(root, p, q) {


// Base case: if the root is null or root is either p or q, return root
if (root === null || root === p || root === q) {
return root;
}

// Recur for the left and right subtrees


const left = lowestCommonAncestor([Link], p, q);
const right = lowestCommonAncestor([Link], p, q);

// If both left and right are non-null, root is the LCA


if (left !== null && right !== null) {
return root;
}

// Otherwise, return whichever side is non-null (if one is null)


return left !== null ? left : right;
};

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values
of the nodes you can see ordered from top to bottom.

var rightSideView = function(root) {


if (!root) return [];

const result = [];


const queue = [root];

while ([Link] > 0) {


let levelSize = [Link];

for (let i = 0; i < levelSize; i++) {


const node = [Link]();

// If it's the rightmost node of this level, add to result


if (i === levelSize - 1) {
[Link]([Link]);
}

// Add children to the queue for the next level


if ([Link]) [Link]([Link]);
if ([Link]) [Link]([Link]);
}
}

return result;
};

Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

Return the smallest level x such that the sum of all the values of nodes at level x is maximal.

var maxLevelSum = function(root) {


if (!root) return 0;

const levelQueue = [root];


let max = -Infinity;
let count = 1;
let result = 1;

while ([Link] > 0) {


let levelSize = [Link];
let sum = 0;

for (let i = 0; i < levelSize; i++) {


const node = [Link]();
sum += [Link];

if ([Link]) [Link]([Link]);
if ([Link]) [Link]([Link]);
}

if (sum > max) {


max = sum;
result = count;
}

count++;
}

return result;
};

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node's value equals val and return the subtree rooted with that
node. If such a node does not exist, return null.

var searchBST = function(root, val) {


const traverse = (node) => {
if(!node) return null;
if([Link] === val) return node;
if([Link] < val) return traverse([Link]);
if([Link] > val) return traverse([Link]);
}

return traverse(root);
};

Given a root node reference of a BST and a key, delete the node with the given key in the BST.
Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

1. Search for a node to remove.


2. If the node is found, delete the node.

var deleteNode = function(root, key) {


// Helper function to find the minimum value node in a subtree
const findMin = (node) => {
while ([Link]) {
node = [Link];
}
return node;
};

// Base case: if the root is null, just return null


if (!root) return null;

// If the key to be deleted is smaller than the root's value, search in the left subtree
if (key < [Link]) {
[Link] = deleteNode([Link], key);
}
// If the key to be deleted is larger than the root's value, search in the right subtree
else if (key > [Link]) {
[Link] = deleteNode([Link], key);
}
// If we found the node with the key
else {
// Case 1: Node has no children (leaf node)
if (![Link] && ![Link]) {
return null;
}
// Case 2: Node has one child
else if (![Link]) {
return [Link];
} else if (![Link]) {
return [Link];
}
// Case 3: Node has two children
else {
// Find the in-order successor (smallest node in the right subtree)
let minNode = findMin([Link]);
// Replace the value of the current node with the in-order successor's value
[Link] = [Link];
// Delete the in-order successor
[Link] = deleteNode([Link], [Link]);
}
}

return root;
};

Given an integer array nums and an integer k, return the k largest element in the array.
th

Note that it is the k largest element in the sorted order, not the k distinct element.
th th

Can you solve it without sorting?

class MinHeap {
constructor() {
[Link] = [];
}

// Helper function to get the index of the left child


leftChild(index) {
return 2 * index + 1;
}

// Helper function to get the index of the right child


rightChild(index) {
return 2 * index + 2;
}

// Helper function to get the index of the parent


parent(index) {
return [Link]((index - 1) / 2);
}

// Function to swap two elements in the heap


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

// Function to heapify the min-heap


heapify(index) {
let smallest = index;
const left = [Link](index);
const right = [Link](index);

if (left < [Link] && [Link][left] < [Link][smallest]) {


smallest = left;
}

if (right < [Link] && [Link][right] < [Link][smallest]) {


smallest = right;
}

if (smallest !== index) {


[Link](index, smallest);
[Link](smallest);
}
}

// Function to insert an element into the heap


insert(value) {
[Link](value);
let index = [Link] - 1;

while (index > 0 && [Link][[Link](index)] > [Link][index]) {


[Link](index, [Link](index));
index = [Link](index);
}
}

// Function to remove the smallest (root) element


extractMin() {
if ([Link] === 0) return null;
if ([Link] === 1) return [Link]();

const min = [Link][0];


[Link][0] = [Link]();
[Link](0);

return min;
}

// Function to return the smallest element (root)


peek() {
return [Link][0];
}

// Function to return the size of the heap


size() {
return [Link];
}
}

var findKthLargest = function(nums, k) {


const minHeap = new MinHeap();

// Build a min-heap of size k


for (let num of nums) {
[Link](num);
if ([Link]() > k) {
[Link](); // Remove the smallest element
}
}

return [Link](); // The root of the heap is the k-th largest element
};
You have a set which contains all positive integers [1, 2, 3, 4, 5, ...].

Implement the SmallestInfiniteSet class:

 SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive


integers.
 int popSmallest() Removes and returns the smallest integer contained in the infinite set.
 void addBack(int num) Adds a positive integer num back into the infinite set, if it
is not already in the infinite set.

class SmallestInfiniteSet {
constructor() {
[Link] = 1; // The smallest number that has not been popped yet
[Link] = []; // Min-heap to store the numbers added back
[Link] = new Set(); // A set to keep track of numbers already in the heap
}

// Helper function to maintain the heap property


heapifyUp() {
let index = [Link] - 1;
while (index > 0) {
const parent = [Link]((index - 1) / 2);
if ([Link][index] < [Link][parent]) {
[[Link][index], [Link][parent]] = [[Link][parent], [Link][index]];
index = parent;
} else {
break;
}
}
}

// Helper function to pop the smallest element from the heap


heapifyDown() {
let index = 0;
const n = [Link];
while (index * 2 + 1 < n) {
let leftChild = index * 2 + 1;
let rightChild = index * 2 + 2;
let smallest = index;

if ([Link][leftChild] < [Link][smallest]) smallest = leftChild;


if (rightChild < n && [Link][rightChild] < [Link][smallest]) smallest = rightChild;

if (smallest !== index) {


[[Link][index], [Link][smallest]] = [[Link][smallest],
[Link][index]];
index = smallest;
} else {
break;
}
}
}

// Function to pop the smallest number


popSmallest() {
if ([Link] > 0) {
// If the heap is not empty, pop the smallest element
const smallest = [Link][0];
[Link][0] = [Link][[Link] - 1];
[Link]();
[Link]();
return smallest;
} else {
// If the heap is empty, return the current smallest from the infinite set and increment current
return [Link]++;
}
}

// Function to add a number back into the set


addBack(num) {
if (num < [Link] && ![Link](num)) {
[Link](num); // Add num to the heap
[Link](num); // Mark num as seen
[Link](); // Maintain the heap property
}
}
}

You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive
integer k. You must choose a subsequence of indices from nums1 of length k.

For chosen indices i , i , ..., i , your score is defined as:


0 1 k-1

 The sum of the selected elements from nums1 multiplied with the minimum of the selected
elements from nums2.
 It can defined simply as: (nums1[i ] + nums1[i ] +...+ nums1[i ]) * min(nums2[i ] ,
0 1 k-1 0

nums2[i ], ... ,nums2[i ]).


1 k-1

Return the maximum possible score.

A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} by
deleting some or no elements.

var maxScore = function(nums1, nums2, k) {


//START of heap class
class Heap{
constructor(type){
[Link] = type;
[Link] = [];
[Link][0] = undefined;
}
print(){
for(let i=1;i<[Link];i++){
[Link]([Link][i])
}
}
getSize(){
return [Link]-1;
}
insert(value){
[Link](value);
if([Link]==2){
return ;
}
let lastIndex = [Link]-1;
while([Link][[Link](lastIndex/2)]!==undefined &&
[Link]([Link][lastIndex],[Link][[Link](lastIndex/2)])>0){
let temp = [Link][[Link](lastIndex/2)];
[Link][[Link](lastIndex/2)] = [Link][lastIndex];
[Link][lastIndex] = temp;
lastIndex = [Link](lastIndex/2);
}
}
//This returns a positive number if a is greater than b. Here meaing of being greater depends on
the type of heap. For max heap it will return positive number if a>b and for min heap it will return
positive number if a<b .
compare(a,b){
if([Link]==="min"){
if([Link](a) && [Link](b)){
return b[0]-a[0];
}else{
return b-a;
}
}else{
if([Link](a) && [Link](b)){
return a[0]-b[0];
}else{
return a-b;
}
}
}
removeTop(){
let max = [Link][1];
if([Link]()>1){
[Link][1] = [Link]();
[Link](1);
}else{//If the size is 0 then just remove the element, no shifting and hipify will be applicable
[Link]();
}
return max;
}
getTop(){
let max = null;
if([Link]()>=1){
max = [Link][1];
}
return max;
}
heapify(pos){
if(pos*2>[Link]-1){
//That means element at index 'pos' is not having any child
return;
}
if(
([Link][pos*2]!==undefined && [Link]([Link][pos*2],[Link][pos])>0)
|| ([Link][pos*2+1]!==undefined && [Link]([Link][pos*2+1],[Link][pos])>0)
){
if([Link][pos*2+1]===undefined ||
[Link]([Link][pos*2+1],[Link][pos*2])<=0){
let temp = [Link][pos*2];
[Link][pos*2] = [Link][pos];
[Link][pos] = temp;
[Link](pos*2);
}else{
let temp = [Link][pos*2+1];
[Link][pos*2+1] = [Link][pos];
[Link][pos] = temp;
[Link](pos*2+1);
}
}
}
}
//END of heap class

let arr2=[];
for(let i=0;i<[Link];i++){
[Link]([i,nums2[i]]);
}
[Link](function(a,b){return b[1]-a[1]});
let currentRate,sum=0,max=0;
let minHeap = new Heap('min');
for(let i=0;i<[Link];i++){
let index = arr2[i][0];
currentRate = nums2[index];//This is the minimum number from nums2 so far
sum += nums1[index];
[Link](nums1[index]);
if([Link]()>k){
let top = [Link]();
sum -= top;
}
if([Link]()===k){//We have choosen k elements
max = [Link](max,sum*currentRate);
}
}
return max;
};

You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the i worker.
th

You are also given two integers k and candidates. We want to hire exactly k workers according to
the following rules:

 You will run k sessions and hire exactly one worker in each session.
 In each hiring session, choose the worker with the lowest cost from either the
first candidates workers or the last candidates workers. Break the tie by the smallest index.
 For example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring
session, we will choose the 4 worker because they have the lowest
th

cost [3,2,7,7,1,2].
 In the second hiring session, we will choose 1 worker because they have the same
st

lowest cost as 4 worker but they have the smallest index [3,2,7,7,2]. Please note
th

that the indexing may be changed in the process.


 If there are fewer than candidates workers remaining, choose the worker with the lowest
cost among them. Break the tie by the smallest index.
 A worker can only be chosen once.

Return the total cost to hire exactly k workers.

var totalCost = function(costs, k, candidates) {


const n = [Link];

// Min-heaps for the front and back candidates


const frontHeap = [];
const backHeap = [];

// Fill the frontHeap with the first `candidates` workers


for (let i = 0; i < [Link](candidates, n); i++) {
[Link]([costs[i], i]);
}

// Fill the backHeap with the last `candidates` workers


for (let i = n - 1; i >= [Link](n - candidates, 0); i--) {
[Link]([costs[i], i]);
}

// Function to extract the minimum element from the heap


const extractMin = (heap) => {
if ([Link] === 0) return null;
[Link]((a, b) => a[0] - b[0]); // Sort by cost, then by index
return [Link]();
};
let total = 0;
for (let i = 0; i < k; i++) {
let selectedWorker;

// Choose from the front heap


const frontWorker = extractMin(frontHeap);

// Choose from the back heap


const backWorker = extractMin(backHeap);

// Compare frontWorker and backWorker, select the one with the lower cost
if (frontWorker && backWorker) {
if (frontWorker[0] < backWorker[0]) {
selectedWorker = frontWorker;
} else if (frontWorker[0] > backWorker[0]) {
selectedWorker = backWorker;
} else {
selectedWorker = frontWorker[1] < backWorker[1] ? frontWorker : backWorker;
}
}
else if (frontWorker) {
selectedWorker = frontWorker;
}
else {
selectedWorker = backWorker;
}

total += selectedWorker[0]; // Add the cost to the total


}

return total;
};

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I will tell you whether the number I picked is higher or lower than
your guess.

You call a pre-defined API int guess(int num), which returns three possible results:

 -1: Your guess is higher than the number I picked (i.e. num > pick).
 1: Your guess is lower than the number I picked (i.e. num < pick).
 0: your guess is equal to the number I picked (i.e. num == pick).

Return the number that I picked.

var guessNumber = function(n) {


let start = 1;
let end = n;

while (start <= end) {


const mid = [Link]((start + end) / 2); // Guess the middle number

const result = guess(mid); // Call the guess API

if (result === 0) {
return mid; // Correct guess
} else if (result === -1) {
end = mid - 1; // The picked number is smaller, adjust the range
} else {
start = mid + 1; // The picked number is larger, adjust the range
}
}

return -1; // In case something goes wrong, but shouldn't reach here
};

You are given two positive integer arrays spells and potions, of length n and m respectively,
where spells[i] represents the strength of the i spell and potions[j] represents the strength of
th

the j potion.
th

You are also given an integer success. A spell and potion pair is considered successful if
the product of their strengths is at least success.

Return an integer array pairs of length n where pairs[i] is the number of potions that will form a
successful pair with the i [Link]

function successfulPairs(spells, potions, success) {


// Sort the potions array to use binary search
[Link]((a, b) => a - b);

const result = [];

// Function to find the first potion that will form a successful pair
const binarySearch = (spell) => {
let left = 0;
let right = [Link];

while (left < right) {


let mid = [Link]((left + right) / 2);
if (spell * potions[mid] >= success) {
right = mid;
} else {
left = mid + 1;
}
}
return left; // The index of the first valid potion
};

// For each spell, find the number of successful pairs using binary search
for (let spell of spells) {
const index = binarySearch(spell);
[Link]([Link] - index);
}

return result;
}

A peak element is an element that is strictly greater than its neighbors.

Given a 0-indexed integer array nums, find a peak element, and return its index. If the array
contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to
be strictly greater than a neighbor that is outside the array.

You must write an algorithm that runs in O(log n) time.

var findPeakElement = function(nums) {


let left = 0;
let right = [Link] - 1;

while (left < right) {


const mid = [Link]((left + right) / 2);
if (nums[mid] > nums[mid + 1]) {
// Peak is on the left half
right = mid;
} else {
// Peak is on the right half
left = mid + 1;
}
}

return left; // The peak element will be at the 'left' index


};

Koko loves to eat bananas. There are n piles of bananas, the i pile has piles[i] bananas. The
th

guards have gone and will come back in h hours.

Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of
bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them
instead and will not eat any more bananas during this hour.

Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.

Return the minimum integer k such that she can eat all the bananas within h hours.

var minEatingSpeed = function(piles, h) {


// Helper function to calculate the total hours needed for a given eating speed k
const canEatAllInTime = (k) => {
let hours = 0;
for (let pile of piles) {
hours += [Link](pile / k); // Hours needed for this pile
}
return hours <= h; // Check if hours required is within the limit
};

// Binary search for the minimum k


let left = 1; // Minimum possible speed (1 banana per hour)
let right = [Link](...piles); // Maximum possible speed (largest pile)

while (left < right) {


let mid = [Link]((left + right) / 2);
if (canEatAllInTime(mid)) {
right = mid; // Try a smaller k
} else {
left = mid + 1; // Increase k
}
}

return left; // The smallest k that satisfies the condition


};

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the
number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does
not map to any letters.

var letterCombinations = function(digits) {


// Mapping of digits to letters as on a telephone keypad
const phoneMap = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']
};

// If the input string is empty, return an empty array


if ([Link] === 0) return [];

const result = [];

// Backtracking function to build the combinations


const backtrack = (index, currentCombination) => {
// If the current combination is the same length as digits, add it to the result
if ([Link] === [Link]) {
[Link](currentCombination);
return;
}

// Get the letters for the current digit


const letters = phoneMap[digits[index]];

// Iterate through the letters for the current digit


for (const letter of letters) {
// Recurse with the next digit
backtrack(index + 1, currentCombination + letter);
}
};

// Start backtracking from the first digit


backtrack(0, "");

return result;
};

Find all valid combinations of k numbers that sum up to n such that the following conditions are
true:

 Only numbers 1 through 9 are used.


 Each number is used at most once.

Return a list of all possible valid combinations. The list must not contain the same combination
twice, and the combinations may be returned in any order.

var combinationSum3 = function(k, n) {


const result = [];

// Backtracking function
const backtrack = (start, currentCombination, currentSum) => {
// If we have chosen k numbers and the sum is n, we have a valid combination
if ([Link] === k && currentSum === n) {
[Link]([...currentCombination]);
return;
}

// If the combination is too long or the sum exceeds n, stop searching


if ([Link] > k || currentSum > n) {
return;
}

// Try each number starting from `start` to 9


for (let i = start; i <= 9; i++) {
[Link](i); // Add the current number to the combination
backtrack(i + 1, currentCombination, currentSum + i); // Recurse with the next number
[Link](); // Backtrack by removing the current number
}
};

// Start backtracking from number 1


backtrack(1, [], 0);

return result;
};

Given an array of intervals intervals where intervals[i] = [start , end ], return the minimum number
i i

of intervals you need to remove to make the rest of the intervals non-overlapping.

Note that intervals which only touch at a point are non-overlapping. For example, [1, 2] and [2,
3] are non-overlapping.

var eraseOverlapIntervals = function(intervals) {


// If no intervals are given, return 0
if ([Link] === 0) return 0;

// Sort intervals by their end times


[Link]((a, b) => a[1] - b[1]);

let count = 0; // To count the number of intervals to remove


let lastEnd = intervals[0][1]; // End time of the last selected interval

// Iterate through the intervals starting from the second interval


for (let i = 1; i < [Link]; i++) {
// If the current interval starts before the last selected interval ends, it's overlapping
if (intervals[i][0] < lastEnd) {
count++; // We need to remove the current interval
} else {
lastEnd = intervals[i][1]; // Update the last selected interval's end time
}
}

return count;
};

There are some spherical balloons taped onto a flat wall that represents the XY-plane. The
balloons are represented as a 2D integer array points where points[i] = [x , x ] denotes a balloon
start end

whose horizontal diameter stretches between x and x . You do not know the exact y-
start end

coordinates of the balloons.

Arrows can be shot up directly vertically (in the positive y-direction) from different points along
the x-axis. A balloon with x and x is burst by an arrow shot at x if x <= x <= x . There is no
start end start end

limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting
any balloons in its path.

Given the array points, return the minimum number of arrows that must be shot to burst all
balloons.

var findMinArrowShots = function(points) {


if ([Link] === 0) return 0;

// Step 1: Sort the intervals by their xend value


[Link]((a, b) => a[1] - b[1]);

let arrows = 1; // We need at least one arrow to start


let lastShot = points[0][1]; // Shoot the first arrow at the end of the first balloon

// Step 2: Iterate through the remaining intervals


for (let i = 1; i < [Link]; i++) {
// If the current balloon starts after the last shot, we need a new arrow
if (points[i][0] > lastShot) {
arrows++; // Shoot a new arrow
lastShot = points[i][1]; // Update last shot to the end of the current balloon
}
}

return arrows; // Return the total number of arrows needed


};

Here are the answers to all the questions in JavaScript:

2. Find all the possible pivot elements in an unsorted array.

 A pivot element is an element that has all smaller elements to its left and all greater elements to its
right.

function findPivots(arr) {
let pivots = [];
for (let i = 0; i < [Link]; i++) {
let left = [Link](0, i);
let right = [Link](i + 1);
if ([Link](...left) < arr[i] && [Link](...right) > arr[i]) {
[Link](arr[i]);
}
}
return pivots;
}

3. Sorting subarrays to find the given maximum sum.


function maxSubarraySum(arr, targetSum) {
[Link]((a, b) => a - b);
let maxSum = 0;
for (let i = 0; i < [Link] - 2; i++) {
let currentSum = arr[i] + arr[i + 1] + arr[i + 2];
if (currentSum <= targetSum) {
maxSum = [Link](maxSum, currentSum);
}
}
return maxSum;
}

4. Find a subarray when adding 3 elements equals a target value from the given array.
function findSubarrayWithTargetSum(arr, target) {
for (let i = 0; i < [Link] - 2; i++) {
for (let j = i + 1; j < [Link] - 1; j++) {
for (let k = j + 1; k < [Link]; k++) {
if (arr[i] + arr[j] + arr[k] === target) {
return [arr[i], arr[j], arr[k]];
}
}
}
}
return null;
}

5. Design a rate limiter system.


class RateLimiter {
constructor(limit, interval) {
[Link] = limit;
[Link] = interval;
[Link] = [];
}

isRequestAllowed() {
const now = [Link]();
[Link] = [Link](timestamp => now - timestamp <
[Link]);
if ([Link] < [Link]) {
[Link](now);
return true;
}
return false;
}
}

6. Calculating the occurrence of a number in an array using a hashmap.


function countOccurrences(arr) {
const map = new Map();
[Link](num => {
[Link](num, ([Link](num) || 0) + 1);
});
return map;
}

7. How do you use function components in React?


const MyComponent = (props) => {
return <div>{[Link]}</div>;
};

8. Array sorting and algorithms.


let arr = [5, 2, 9, 1];
[Link]((a, b) => a - b); // Ascending order

9. Sort the table of league scores based on their scores.


let leagues = [
{ team: 'A', score: 100 },
{ team: 'B', score: 80 }
];
[Link]((a, b) => [Link] - [Link]); // Sort descending by score

10. Find the target string permutation match among target strings.
function isPermutation(str1, str2) {
if ([Link] !== [Link]) return false;
let sortedStr1 = [Link]('').sort().join('');
let sortedStr2 = [Link]('').sort().join('');
return sortedStr1 === sortedStr2;
}

11. Most frequent digit value in a number (maximum sum of subarray).


function mostFrequentDigit(num) {
const str = [Link]();
const freqMap = {};
let maxCount = 0;
let mostFreqDigit = null;
for (let digit of str) {
freqMap[digit] = (freqMap[digit] || 0) + 1;
if (freqMap[digit] > maxCount) {
maxCount = freqMap[digit];
mostFreqDigit = digit;
}
}

return mostFreqDigit;
}

12. Find duplicates in an array and print the results.


function findDuplicates(arr) {
const seen = new Set();
const duplicates = [];
for (let num of arr) {
if ([Link](num)) {
[Link](num);
} else {
[Link](num);
}
}
return duplicates;
}

13. Merge two sorted number arrays into a single sorted array, removing any duplicates.
function mergeSortedArrays(arr1, arr2) {
const merged = [...arr1, ...arr2];
const uniqueMerged = [...new Set(merged)];
[Link]((a, b) => a - b);
return uniqueMerged;
}

14. Reimplement the Levenshtein distance algorithm.


function levenshtein(a, b) {
let tmp;
if ([Link] === 0) { return [Link]; }
if ([Link] === 0) { return [Link]; }

if ([Link] > [Link]) { tmp = a; a = b; b = tmp; }

let i, j, alen = [Link], blen = [Link], row = Array(alen);


for (i = 0; i < alen; i++) { row[i] = i; }

for (i = 1; i <= blen; i++) {


let lastValue = i;
for (j = 1; j <= alen; j++) {
tmp = row[j - 1];
row[j - 1] = [Link](row[j - 1] + 1, [Link](lastValue + 1, b[i - 1] ===
a[j - 1] ? tmp : tmp + 1));
lastValue = tmp;
}
}

return row[alen - 1];


}

15. Maximum sum contiguous subarray.


function maxSubarraySum(arr) {
let maxSum = -Infinity;
let currentSum = 0;
for (let num of arr) {
currentSum = [Link](num, currentSum + num);
maxSum = [Link](maxSum, currentSum);
}
return maxSum;
}

16. Write a program to calculate the sum of a list of integers, the partial integer sum could
overflow, but the sum is guaranteed to fit into a 32-bit int type.
function calculateSum(arr) {
let sum = 0;
for (let num of arr) {
sum += num;
}
return sum;
}

17. Find the first non-repeating character in the string.


function firstNonRepeatingCharacter(str) {
const charCount = {};
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (let char of str) {
if (charCount[char] === 1) return char;
}
return null;
}

18. How is hash implemented?

 Hashing is typically implemented using hash functions and a hash table (or map). A hash function
converts a key into an index in an array, where the corresponding value is stored.

19. Shuffle an array.


function shuffleArray(arr) {
for (let i = [Link] - 1; i > 0; i--) {
const j = [Link]([Link]() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]]; // Swap elements
}
return arr;
}

20. How can you manage thousands of requests at the same time?

 You can manage thousands of requests by implementing a load balancer and using queues.
Requests can be handled in a queue, processed in batches, or distributed across multiple servers.

21. Find a loop in a singly linked list.


function hasCycle(head) {
let slow = head, fast = head;
while (fast !== null && [Link] !== null) {
slow = [Link];
fast = [Link];
if (slow === fast) {
return true;
}
}
return false;
}

22. Implement a queue using an array.


class Queue {
constructor() {
[Link] = [];
}

enqueue(element) {
[Link](element);
}

dequeue() {
return [Link]();
}

front() {
return [Link][0];
}

isEmpty() {
return [Link] === 0;
}
}

23. How would you distribute and limit incoming traffic between several API endpoints?

 You could use rate limiting and implement load balancing techniques using API gateways that
manage the traffic distribution and set a threshold on the rate of requests to each endpoint.

24. Write an algorithm to reverse an array.


function reverseArray(arr) {
let start = 0, end = [Link] - 1;
while (start < end) {
[arr[start], arr[end]] = [arr[end], arr[start]]; // Swap elements
start++;
end--;
}
return arr;
}

You might also like