leetcode roadmap Flashcards

1
Q

Contains Duplicate (easy)

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:

Input: nums = [1,2,3,1]
Output: true
Example 2:

Input: nums = [1,2,3,4]
Output: false
Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Constraints:

1 <= nums.length <= 105
-109 <= nums[i] <= 109

A

Arrays & Hashing

var containsDuplicate = function(nums) {
    const numsSet = new Set();

    for (let i = 0; i < nums.length; i++) {
        if (numsSet.has(nums[i])) {
            return true;
        }
        numsSet.add(nums[i]);
    }

    return false;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Valid Anagram (easy)

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: s = “anagram”, t = “nagaram”
Output: true
Example 2:

Input: s = “rat”, t = “car”
Output: false

Constraints:

1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters.

A

Arrays & Hashing

var isAnagram = function(s, t) {
    if (s.length !== t.length) {
        return false;
    }

    const map = new Map();

    for (let i = 0; i < s.length; i++) {
        map.set(s[i], (map.get(s[i]) || 0) + 1);
        map.set(t[i], (map.get(t[i]) || 0) - 1);
    }

    for ([char, count] of map) {
        if (count !== 0) {
            return false;
        }
    }

    return true;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Two Sum (easy)

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

A

Arrays & Hashing

var twoSum = function(nums, target) {
    const hash = {};

    for (let i = 0; i < nums.length; i++) {
        const diff = target - nums[i];

        if (diff in hash) {
            return [i, hash[diff]];
        }

        hash[nums[i]] = i;
    }

    return [];
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Group Anagrams (med)

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]
Example 2:

Input: strs = [””]
Output: [[””]]
Example 3:

Input: strs = [“a”]
Output: [[“a”]]

Constraints:

1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.

A

Arrays & Hashing

var groupAnagrams = function(strs) {
    if (strs.length === 1) {
        return [strs];
    }

    const anagramMap = new Map();

    for (let i = 0; i < strs.length; i++) {
        const str = strs[i];
        
        const frequency = new Array(26).fill(0);

        for (let j = 0; j < str.length; j++) {
            const charCode = (str[j].charCodeAt() - 97);

            frequency[charCode]++;
        }

        let key = frequency.join('_');

        if (anagramMap.get(key)) {
            anagramMap.get(key).push(str);
        } else {
            anagramMap.set(key, [str]);
        }
    }

    return [...anagramMap.values()];
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Top K Frequent Elements (med)

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:

Input: nums = [1], k = 1
Output: [1]

Constraints:

1 <= nums.length <= 105
-104 <= nums[i] <= 104
k is in the range [1, the number of unique elements in the array].
It is guaranteed that the answer is unique.

A

Arrays & Hashing

var topKFrequent = function(nums, k) {
    const res = [];
    const map = {};
    const bucket = [];

    nums.forEach(num => {
        map[num] = (map[num] || 0) + 1;
    });

    Object.entries(map).forEach(([num, freq]) => {
        if (bucket[freq]) {
            bucket[freq].push(num);
        } else {
            bucket[freq] = [num];
        }
    });

    for (let i = bucket.length - 1; i >= 0; i--) {
        if (bucket[i]) {
            res.push(...bucket[i]);
            if (res.length === k) {
                return res;
            }
        }
    }

    return res;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Product of Array Except Self (med)

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.

Example 1:

Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Constraints:

2 <= nums.length <= 105
-30 <= nums[i] <= 30
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

A

Arrays & Hashing

var productExceptSelf = function(nums) {
    const res = [];
    let prefix = 1;
    let postfix = 1;

    for (let i = 0; i < nums.length; i++) {
        res[i] = prefix;
        prefix *= nums[i];
    }

    for (let i = nums.length - 2; i >= 0; i--) {
        postfix *= nums[i + 1];
        res[i] *= postfix;
    }

    return res;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Valid Sudoku (med)

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Note:

A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.

Example 1:

Input: board =
[[“5”,”3”,”.”,”.”,”7”,”.”,”.”,”.”,”.”]
,[“6”,”.”,”.”,”1”,”9”,”5”,”.”,”.”,”.”]
,[”.”,”9”,”8”,”.”,”.”,”.”,”.”,”6”,”.”]
,[“8”,”.”,”.”,”.”,”6”,”.”,”.”,”.”,”3”]
,[“4”,”.”,”.”,”8”,”.”,”3”,”.”,”.”,”1”]
,[“7”,”.”,”.”,”.”,”2”,”.”,”.”,”.”,”6”]
,[”.”,”6”,”.”,”.”,”.”,”.”,”2”,”8”,”.”]
,[”.”,”.”,”.”,”4”,”1”,”9”,”.”,”.”,”5”]
,[”.”,”.”,”.”,”.”,”8”,”.”,”.”,”7”,”9”]]
Output: true
Example 2:

Input: board =
[[“8”,”3”,”.”,”.”,”7”,”.”,”.”,”.”,”.”]
,[“6”,”.”,”.”,”1”,”9”,”5”,”.”,”.”,”.”]
,[”.”,”9”,”8”,”.”,”.”,”.”,”.”,”6”,”.”]
,[“8”,”.”,”.”,”.”,”6”,”.”,”.”,”.”,”3”]
,[“4”,”.”,”.”,”8”,”.”,”3”,”.”,”.”,”1”]
,[“7”,”.”,”.”,”.”,”2”,”.”,”.”,”.”,”6”]
,[”.”,”6”,”.”,”.”,”.”,”.”,”2”,”8”,”.”]
,[”.”,”.”,”.”,”4”,”1”,”9”,”.”,”.”,”5”]
,[”.”,”.”,”.”,”.”,”8”,”.”,”.”,”7”,”9”]]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8’s in the top left 3x3 sub-box, it is invalid.

Constraints:

board.length == 9
board[i].length == 9
board[i][j] is a digit 1-9 or ‘.’.

A

Arrays & Hashing

const addToSetIfNotPresent = (set, value) => {
    if (set.has(value)) {
        return false;
    } else {
        set.add(value);
        return true;
    }
}

var isValidSudoku = function(board) {
    const seen = new Set();

    for (let i = 0; i < 9; i++) {
        for (let j = 0; j < 9; j++) {
            const number = board[i][j];

            if (number !== '.') {
                if (
                    !addToSetIfNotPresent(seen, `${number} in row ${i}`) ||
                    !addToSetIfNotPresent(seen, `${number} in column ${j}`) ||
                    !addToSetIfNotPresent(seen, `${number} in block ${Math.floor(i / 3)} - ${Math.floor(j / 3)}`)
                ) {
                    return false;
                }
            }
        }
    }

    return true;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Encode and Decode Strings (med)

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings. Please implement encode and decode

Example(s):

Example1

Input: [“lint”,“code”,“love”,“you”] Output: [“lint”,“code”,“love”,“you”] Explanation: One possible encode method is: “lint:;code:;love:;you”

Example2

Input: [“we”, “say”, “:”, “yes”] Output: [“we”, “say”, “:”, “yes”] Explanation: One possible encode method is: “we:;say:;:::;yes”

A

Arrays & Hashing

const encode = (arr) => {
  let res = '';
  
  arr.forEach(str => {
  	res += `${str.length}#${str}`;
  });
  
  return res;
}

const delimitWord = (str, index) => {
  const delimeterIndex = str.indexOf('#', index);
  const length = Number(str.slice(index, delimeterIndex));
  const start = delimeterIndex + 1;
  const end = start + length;
  const word = str.slice(start, end);
  
  return [word, end];
}

const decode = (str) => {
  const res = [];
  
  let i = 0;
  
  while (i < str.length) {
    const [word, nextIndex] = delimitWord(str, i);
    
    res.push(word);
    i = nextIndex;
  }
  
  return res;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Longest Consecutive Sequence (med)

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

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

Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Constraints:

0 <= nums.length <= 105
-109 <= nums[i] <= 109

A

Arrays & Hashing

var longestConsecutive = function(nums) {
    if (nums.length === 0) {
        return 0;
    }

    let res = 1;

    const set = new Set(nums);

    for (let num of set) {
        if (set.has(num + 1) && !set.has(num - 1)) {
            let length = 2;
            let i = num + 2;

            while (set.has(i)) {
                length++;
                i++;
            }

            res = Math.max(res, length);
        }
    }

    return res;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Valid Palindrome (easy)

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input: s = “A man, a plan, a canal: Panama”
Output: true
Explanation: “amanaplanacanalpanama” is a palindrome.
Example 2:

Input: s = “race a car”
Output: false
Explanation: “raceacar” is not a palindrome.
Example 3:

Input: s = “ “
Output: true
Explanation: s is an empty string “” after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

Constraints:

1 <= s.length <= 2 * 105
s consists only of printable ASCII characters.

A

Two Pointers

const isAlphaNumeric = (char) => ((char >= '0' && char <= '9') || (char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z'));

var isPalindrome = function(s) {
    let left = 0;
    let right = s.length - 1;

    while (left < right) {
        if (!isAlphaNumeric(s[left])) {
            left++;
        } else if (!isAlphaNumeric(s[right])) {
            right--;
        } else {
            if (s[left].toLowerCase() !== s[right].toLowerCase()) {
                return false;
            }
            left++;
            right--;
        }
    }

    return true;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Two Sum II - Input Array Is Sorted (med)

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 < numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Your solution must use only constant extra space.

Example 1:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Example 2:

Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
Example 3:

Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].

A

Two Pointers

var twoSum = function(numbers, target) {
    if (numbers.length == 2) {
        return [1, 2];
    }

    let left = 0;
    let right = numbers.length - 1;

    while (left < right) {
        const sum = numbers[left] + numbers[right];

        if (sum === target) {
            return [left + 1, right + 1];
        }
        if (sum > target) {
            right--;
        } else {
            left++;
        }
    }
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

3Sum (med)

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.

Constraints:

3 <= nums.length <= 3000
-105 <= nums[i] <= 105

A

Two Pointers

var threeSum = function(nums) {
    nums.sort((a, b) => a - b);

    const res = [];

    for (let i = 0; i < nums.length - 2; i++) {
        if (i > 0 && nums[i] === nums[i - 1]) {
            continue;
        }
        let left = i + 1;
        let right = nums.length - 1;

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

            if (sum === 0) {
                res.push([nums[i], nums[left], nums[right]]);

                while (nums[left] === nums[left + 1]) {
                    left ++;
                }
                left++;
                
                while (nums[right] === nums[right - 1]) {
                    right --;
                }
                right --;
            } else if (sum > 0) {
                right --;
            } else {
                left ++;
            }
        }
    }

    return res;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Container With Most Water (med)

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

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.

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example 2:

Input: height = [1,1]
Output: 1

Constraints:

n == height.length
2 <= n <= 105
0 <= height[i] <= 104

A

Two Pointers

var maxArea = function(height) {
    let max = 0;
    let left = 0;
    let right = height.length - 1;
    let maxHeight = 0;

    while (left < right) {
        const isLeftMin = height[left] < height[right];
        const currentHeight = isLeftMin ? height[left] : height[right];
        if (currentHeight > maxHeight) {
            maxHeight = currentHeight;
            max = Math.max(max, currentHeight * (right - left));
        }
        if (isLeftMin) {
            left++;
        } else {
            right--;
        }
    }

    return max;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Trapping Rain Water (hard)

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9

Constraints:

n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105

A

Two Pointers

var trap = function(height) {
    if (height.length < 3) {
        return 0;
    }

    let res = 0;
    
    let l = 0;
    let r = height.length - 1;
    let lMax = 0;
    let rMax = 0;

    while (l < r) {
        if (height[l] < lMax) {
            res += lMax - height[l];
        } else {
            lMax = height[l];
        }

        if (height[r] < rMax) {
            res += rMax - height[r];
        } else {
            rMax = height[r];
        }

        if (height[l] < height[r]) {
            l++;
        } else {
            r--;
        }
    }

    return res;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Valid Parentheses (easy)

Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = “()”
Output: true
Example 2:

Input: s = “()[]{}”
Output: true
Example 3:

Input: s = “(]”
Output: false

Constraints:

1 <= s.length <= 104
s consists of parentheses only ‘()[]{}’.

A

Stack

const pairs = {
    '{': '}',
    '(': ')',
    '[': ']',
}

var isValid = function(s) {
    const opened = [];

    for (let i = 0; i < s.length; i++) {
        if (pairs[s[i]]) {
            opened.push(s[i]);
        } else if (s[i] !== pairs[opened.pop()]) {
            return false;
        }
    }

    return opened.length === 0;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Min Stack (med)

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

MinStack() initializes the stack object.
void push(int val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.

Example 1:

Input
[“MinStack”,”push”,”push”,”push”,”getMin”,”pop”,”top”,”getMin”]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2

Constraints:

-231 <= val <= 231 - 1
Methods pop, top and getMin operations will always be called on non-empty stacks.
At most 3 * 104 calls will be made to push, pop, top, and getMin.

A

Stack

var MinStack = function() {
    this.val = [];
};

/** 
 * @param {number} val
 * @return {void}
 */
MinStack.prototype.push = function(val) {
    let min = null;

    if (this.val.length === 0) {
        min = val;
    } else {
        min = Math.min(this.val.at(-1)[1], val);
    }

    this.val.push([val, min]);
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    this.val.pop();
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
    return this.val.at(-1)[0];
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    return this.val.at(-1)[1];
};
17
Q

Evaluate Reverse Polish Notation (med)

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Evaluate the expression. Return an integer that represents the value of the expression.

Note that:

The valid operators are ‘+’, ‘-‘, ‘*’, and ‘/’.
Each operand may be an integer or another expression.
The division between two integers always truncates toward zero.
There will not be any division by zero.
The input represents a valid arithmetic expression in a reverse polish notation.
The answer and all the intermediate calculations can be represented in a 32-bit integer.

Example 1:

Input: tokens = [“2”,”1”,”+”,”3”,”*”]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:

Input: tokens = [“4”,”13”,”5”,”/”,”+”]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:

Input: tokens = [“10”,”6”,”9”,”3”,”+”,”-11”,””,”/”,””,”17”,”+”,”5”,”+”]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

A

Stack

const operandsSet = new Set(["+", "-", "*", "/"]);

const operators = {
    "+": (a, b) => a + b,
    "-": (a, b) => a - b,
    "*": (a, b) => a * b,
    "/": (a, b) => Math.trunc(a / b),
}

/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function(tokens) {
    let stack = [];

    for (let i = 0; i < tokens.length; i++) {
        if (!(tokens[i] in operators)) {
            stack.push(tokens[i]);
        } else {
            const b = Number(stack.pop());
            const a = Number(stack.pop());

            stack.push(operators[tokens[i]](a, b));
        }
    }

    return Number(stack[0]);
};
18
Q

Generate Parentheses (med)

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

Input: n = 3
Output: [”((()))”,”(()())”,”(())()”,”()(())”,”()()()”]
Example 2:

Input: n = 1
Output: [”()”]

Constraints:

1 <= n <= 8

A

Stack

var generateParenthesis = function(n) {
    const res = [];

    const go = (s, l, r) => {
        if (s.length === n * 2) {
            res.push(s);
            return;
        }

        if (l < n) {
            go(s + '(', l + 1, r);
        }
        if (r < l) {
            go(s + ')', l, r + 1);
        }
    }

    go('', 0, 0);

    return res;
};
19
Q

Daily Temperatures (med)

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

Example 1:

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:

Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:

Input: temperatures = [30,60,90]
Output: [1,1,0]

Constraints:

1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100

A

Stack

var dailyTemperatures = function(temperatures) {
    const res = new Array(temperatures.length).fill(0);
    const stack = [];

    for (let i = 0; i < temperatures.length; i++) {
        while (stack.length > 0 && temperatures[stack.at(-1)] < temperatures[i]) {
            const temp = stack.pop();
            res[temp] = i - temp;
        }
        stack.push(i);
    }

    return res;
};
20
Q

Car Fleet (med)

There are n cars going to the same destination along a one-lane road. The destination is target miles away.

You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour).

A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car’s speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position).

A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet.

If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.

Return the number of car fleets that will arrive at the destination.

Example 1:

Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output: 3
Explanation:
The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12.
The car starting at 0 does not catch up to any other car, so it is a fleet by itself.
The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.
Note that no other cars meet these fleets before the destination, so the answer is 3.
Example 2:

Input: target = 10, position = [3], speed = [3]
Output: 1
Explanation: There is only one car, hence there is only one fleet.
Example 3:

Input: target = 100, position = [0,2,4], speed = [4,2,1]
Output: 1
Explanation:
The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2.
Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.

Constraints:

n == position.length == speed.length
1 <= n <= 105
0 < target <= 106
0 <= position[i] < target
All the values of position are unique.
0 < speed[i] <= 106

A

Stack?

const getTime = (car, target) => {
    const dist = target - car.pos;

    return dist / car.speed;
}

var carFleet = function(target, position, speed) {
    let res = 0;
    const cars = position.map((pos, i) => ({ pos, speed: speed[i] }));

    cars.sort((a, b) => b.pos - a.pos);

    let lastTime = -1;

    for (let i = 0; i < cars.length; i++) {
        const time = getTime(cars[i], target);

        if (lastTime < time) {
            res++;
            lastTime = time;
        }
    }

    return res;
};