2022-04-09
347. Top K Frequent Elements
Topic: Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect
Difficulty: Medium
Problem:
Given an integer array
Example 1:
Example 2:
Constraints:
•
•
• It is guaranteed that the answer is unique.
Follow up: Your algorithm's time complexity must be better than
347. Top K Frequent Elements
Topic: Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect
Difficulty: Medium
Problem:
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 <= 10^5•
k is in the range [1, the number of unique elements in the array].• It is guaranteed that the answer is unique.
Follow up: Your algorithm's time complexity must be better than
O(n log n), where n is the array's size.2022-04-10
682. Baseball Game
Topic: Array, Stack, Simulation
Difficulty: Easy
Problem:
You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.
At the beginning of the game, you start with an empty record. You are given a list of strings
1. An integer
2.
3.
4.
Return the sum of all the scores on the record.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
• For operation
• For operations
682. Baseball Game
Topic: Array, Stack, Simulation
Difficulty: Easy
Problem:
You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.
At the beginning of the game, you start with an empty record. You are given a list of strings
ops, where ops[i] is the i^th operation you must apply to the record and is one of the following:1. An integer
x - Record a new score of x.2.
"+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.3.
"D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.4.
"C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.Return the sum of all the scores on the record.
Example 1:
Input: ops = ["5","2","C","D","+"]
Output: 30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.
Example 2:
Input: ops = ["5","-2","4","C","D","9","+","+"]
Output: 27
Explanation:
"5" - Add 5 to the record, record is now [5].
"-2" - Add -2 to the record, record is now [5, -2].
"4" - Add 4 to the record, record is now [5, -2, 4].
"C" - Invalidate and remove the previous score, record is now [5, -2].
"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
"9" - Add 9 to the record, record is now [5, -2, -4, 9].
"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.
Example 3:
Input: ops = ["1"]
Output: 1
Constraints:
•
1 <= ops.length <= 1000•
ops[i] is "C", "D", "+", or a string representing an integer in the range [-3 * 10^4, 3 * 10^4].• For operation
"+", there will always be at least two previous scores on the record.• For operations
"C" and "D", there will always be at least one previous score on the record.2022-04-11
1260. Shift 2D Grid
Topic: Array, Matrix, Simulation
Difficulty: Easy
Problem:
Given a 2D
In one shift operation:
• Element at
• Element at
• Element at
Return the 2D grid after applying shift operation
Example 1:
Image: https://assets.leetcode.com/uploads/2019/11/05/e1.png
Example 2:
Image: https://assets.leetcode.com/uploads/2019/11/05/e2.png
Example 3:
Constraints:
•
•
•
•
•
•
1260. Shift 2D Grid
Topic: Array, Matrix, Simulation
Difficulty: Easy
Problem:
Given a 2D
grid of size m x n and an integer k. You need to shift the grid k times.In one shift operation:
• Element at
grid[i][j] moves to grid[i][j + 1].• Element at
grid[i][n - 1] moves to grid[i + 1][0].• Element at
grid[m - 1][n - 1] moves to grid[0][0].Return the 2D grid after applying shift operation
k times.Example 1:
Image: https://assets.leetcode.com/uploads/2019/11/05/e1.png
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
Example 2:
Image: https://assets.leetcode.com/uploads/2019/11/05/e2.png
Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
Example 3:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]
Constraints:
•
m == grid.length•
n == grid[i].length•
1 <= m <= 50•
1 <= n <= 50•
-1000 <= grid[i][j] <= 1000•
0 <= k <= 1002022-04-12
289. Game of Life
Topic: Array, Matrix, Simulation
Difficulty: Medium
Problem:
According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
The board is made up of an
1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the
Example 1:
Image: https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg
Constraints:
•
•
•
•
Follow up:
• Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
• In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
289. Game of Life
Topic: Array, Matrix, Simulation
Difficulty: Medium
Problem:
According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
The board is made up of an
m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the
m x n grid board, return the next state.Example 1:
Image: https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg
Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
Example 2:
Image: https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg
Input: board = [[1,1],[1,0]]
Output: [[1,1],[1,1]]
Constraints:
•
m == board.length•
n == board[i].length•
1 <= m, n <= 25•
board[i][j] is 0 or 1.Follow up:
• Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
• In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
2022-04-13
59. Spiral Matrix II
Topic: Array, Matrix, Simulation
Difficulty: Medium
Problem:
Given a positive integer
Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg
Example 2:
Constraints:
•
59. Spiral Matrix II
Topic: Array, Matrix, Simulation
Difficulty: Medium
Problem:
Given a positive integer
n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
•
1 <= n <= 202022-04-14
700. Search in a Binary Search Tree
Topic: Tree, Binary Search Tree, Binary Tree
Difficulty: Easy
Problem:
You are given the
Find the node in the BST that the node's value equals
Example 1:
Image: https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg
Constraints:
• The number of nodes in the tree is in the range
•
•
•
700. Search in a Binary Search Tree
Topic: Tree, Binary Search Tree, Binary Tree
Difficulty: Easy
Problem:
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.Example 1:
Image: https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
Example 2:
Image: https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg
Input: root = [4,2,7,1,3], val = 5
Output: []
Constraints:
• The number of nodes in the tree is in the range
[1, 5000].•
1 <= Node.val <= 10^7•
root is a binary search tree.•
1 <= val <= 10^72022-04-15
669. Trim a Binary Search Tree
Topic: Tree, Depth-First Search, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
Given the
Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg
Constraints:
• The number of nodes in the tree in the range
•
• The value of each node in the tree is unique.
•
•
669. Trim a Binary Search Tree
Topic: Tree, Depth-First Search, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
Given the
root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg
Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]
Example 2:
Image: https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg
Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Output: [3,2,null,1]
Constraints:
• The number of nodes in the tree in the range
[1, 10^4].•
0 <= Node.val <= 10^4• The value of each node in the tree is unique.
•
root is guaranteed to be a valid binary search tree.•
0 <= low <= high <= 10^42022-04-16
538. Convert BST to Greater Tree
Topic: Tree, Depth-First Search, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
Given the
As a reminder, a binary search tree is a tree that satisfies these constraints:
• The left subtree of a node contains only nodes with keys less than the node's key.
• The right subtree of a node contains only nodes with keys greater than the node's key.
• Both the left and right subtrees must also be binary search trees.
Example 1:
Image: https://assets.leetcode.com/uploads/2019/05/02/tree.png
Example 2:
Constraints:
• The number of nodes in the tree is in the range
•
• All the values in the tree are unique.
•
Note: This question is the same as 1038: <https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/>
538. Convert BST to Greater Tree
Topic: Tree, Depth-First Search, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
Given the
root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.As a reminder, a binary search tree is a tree that satisfies these constraints:
• The left subtree of a node contains only nodes with keys less than the node's key.
• The right subtree of a node contains only nodes with keys greater than the node's key.
• Both the left and right subtrees must also be binary search trees.
Example 1:
Image: https://assets.leetcode.com/uploads/2019/05/02/tree.png
Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Example 2:
Input: root = [0,null,1]
Output: [1,null,1]
Constraints:
• The number of nodes in the tree is in the range
[0, 10^4].•
-10^4 <= Node.val <= 10^4• All the values in the tree are unique.
•
root is guaranteed to be a valid binary search tree.Note: This question is the same as 1038: <https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/>
2022-04-17
897. Increasing Order Search Tree
Topic: Stack, Tree, Depth-First Search, Binary Search Tree, Binary Tree
Difficulty: Easy
Problem:
Given the
Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg
Constraints:
• The number of nodes in the given tree will be in the range
•
897. Increasing Order Search Tree
Topic: Stack, Tree, Depth-First Search, Binary Search Tree, Binary Tree
Difficulty: Easy
Problem:
Given the
root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg
Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
Example 2:
Image: https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg
Input: root = [5,1,7]
Output: [1,null,5,null,7]
Constraints:
• The number of nodes in the given tree will be in the range
[1, 100].•
0 <= Node.val <= 10002022-04-18
230. Kth Smallest Element in a BST
Topic: Tree, Depth-First Search, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
Given the
Example 1:
Image: https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg
Constraints:
• The number of nodes in the tree is
•
•
Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
230. Kth Smallest Element in a BST
Topic: Tree, Depth-First Search, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
Given the
root of a binary search tree, and an integer k, return the k^th smallest value (1-indexed) of all the values of the nodes in the tree.Example 1:
Image: https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg
Input: root = [3,1,4,null,2], k = 1
Output: 1
Example 2:
Image: https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Constraints:
• The number of nodes in the tree is
n.•
1 <= k <= n <= 10^4•
0 <= Node.val <= 10^4Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
2022-04-19
99. Recover Binary Search Tree
Topic: Tree, Depth-First Search, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
You are given the
Example 1:
Image: https://assets.leetcode.com/uploads/2020/10/28/recover1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2020/10/28/recover2.jpg
Constraints:
• The number of nodes in the tree is in the range
•
Follow up: A solution using
99. Recover Binary Search Tree
Topic: Tree, Depth-First Search, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
You are given the
root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.Example 1:
Image: https://assets.leetcode.com/uploads/2020/10/28/recover1.jpg
Input: root = [1,3,null,null,2]
Output: [3,1,null,null,2]
Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.
Example 2:
Image: https://assets.leetcode.com/uploads/2020/10/28/recover2.jpg
Input: root = [3,1,4,null,null,2]
Output: [2,1,4,null,null,3]
Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.
Constraints:
• The number of nodes in the tree is in the range
[2, 1000].•
-2^31 <= Node.val <= 2^31 - 1Follow up: A solution using
O(n) space is pretty straight-forward. Could you devise a constant O(1) space solution?2022-04-20
173. Binary Search Tree Iterator
Topic: Stack, Tree, Design, Binary Search Tree, Binary Tree, Iterator
Difficulty: Medium
Problem:
Implement the
•
•
•
Notice that by initializing the pointer to a non-existent smallest number, the first call to
You may assume that
Example 1:
Image: https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png
Constraints:
• The number of nodes in the tree is in the range
•
• At most
Follow up:
• Could you implement
173. Binary Search Tree Iterator
Topic: Stack, Tree, Design, Binary Search Tree, Binary Tree, Iterator
Difficulty: Medium
Problem:
Implement the
BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):•
BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.•
boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.•
int next() Moves the pointer to the right, then returns the number at the pointer.Notice that by initializing the pointer to a non-existent smallest number, the first call to
next() will return the smallest element in the BST.You may assume that
next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.Example 1:
Image: https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png
Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]
Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
Constraints:
• The number of nodes in the tree is in the range
[1, 10^5].•
0 <= Node.val <= 10^6• At most
10^5 calls will be made to hasNext, and next.Follow up:
• Could you implement
next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?2022-04-21
705. Design HashSet
Topic: Array, Hash Table, Linked List, Design, Hash Function
Difficulty: Easy
Problem:
Design a HashSet without using any built-in hash table libraries.
Implement
•
•
•
Example 1:
Constraints:
•
• At most
705. Design HashSet
Topic: Array, Hash Table, Linked List, Design, Hash Function
Difficulty: Easy
Problem:
Design a HashSet without using any built-in hash table libraries.
Implement
MyHashSet class:•
void add(key) Inserts the value key into the HashSet.•
bool contains(key) Returns whether the value key exists in the HashSet or not.•
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.Example 1:
Input
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
Output
[null, null, null, true, false, null, true, null, false]
Explanation
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(1); // return True
myHashSet.contains(3); // return False, (not found)
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(2); // return True
myHashSet.remove(2); // set = [1]
myHashSet.contains(2); // return False, (already removed)
Constraints:
•
0 <= key <= 10^6• At most
10^4 calls will be made to add, remove, and contains.2022-04-22
706. Design HashMap
Topic: Array, Hash Table, Linked List, Design, Hash Function
Difficulty: Easy
Problem:
Design a HashMap without using any built-in hash table libraries.
Implement the
•
•
•
•
Example 1:
Constraints:
•
• At most
706. Design HashMap
Topic: Array, Hash Table, Linked List, Design, Hash Function
Difficulty: Easy
Problem:
Design a HashMap without using any built-in hash table libraries.
Implement the
MyHashMap class:•
MyHashMap() initializes the object with an empty map.•
void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.•
int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.•
void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.Example 1:
Input
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
Output
[null, null, null, 1, -1, null, 1, null, -1]
Explanation
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // The map is now [[1,1]]
myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]
myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]
myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]
myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)
myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]
myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]
Constraints:
•
0 <= key, value <= 10^6• At most
10^4 calls will be made to put, get, and remove.2022-04-23
535. Encode and Decode TinyURL
Topic: Hash Table, String, Design, Hash Function
Difficulty: Medium
Problem:
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as
There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Implement the
•
•
•
Example 1:
Constraints:
•
•
535. Encode and Decode TinyURL
Topic: Hash Table, String, Design, Hash Function
Difficulty: Medium
Problem:
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as
https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL.There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Implement the
Solution class:•
Solution() Initializes the object of the system.•
String encode(String longUrl) Returns a tiny URL for the given longUrl.•
String decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object.Example 1:
Input: url = "https://leetcode.com/problems/design-tinyurl"
Output: "https://leetcode.com/problems/design-tinyurl"
Explanation:
Solution obj = new Solution();
string tiny = obj.encode(url); // returns the encoded tiny url.
string ans = obj.decode(tiny); // returns the original url after deconding it.
Constraints:
•
1 <= url.length <= 10^4•
url is guranteed to be a valid URL.2022-04-24
1396. Design Underground System
Topic: Hash Table, String, Design
Difficulty: Medium
Problem:
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.
Implement the
•
• A customer with a card ID equal to
• A customer can only be checked into one place at a time.
•
• A customer with a card ID equal to
•
• Returns the average time it takes to travel from
• The average time is computed from all the previous traveling times from
• The time it takes to travel from
• There will be at least one customer that has traveled from
You may assume all calls to the
Example 1:
Constraints:
•
•
• All strings consist of uppercase and lowercase English letters and digits.
• There will be at most
• Answers within
1396. Design Underground System
Topic: Hash Table, String, Design
Difficulty: Medium
Problem:
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.
Implement the
UndergroundSystem class:•
void checkIn(int id, string stationName, int t)• A customer with a card ID equal to
id, checks in at the station stationName at time t.• A customer can only be checked into one place at a time.
•
void checkOut(int id, string stationName, int t)• A customer with a card ID equal to
id, checks out from the station stationName at time t.•
double getAverageTime(string startStation, string endStation)• Returns the average time it takes to travel from
startStation to endStation.• The average time is computed from all the previous traveling times from
startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.• The time it takes to travel from
startStation to endStation may be different from the time it takes to travel from endStation to startStation.• There will be at least one customer that has traveled from
startStation to endStation before getAverageTime is called.You may assume all calls to the
checkIn and checkOut methods are consistent. If a customer checks in at time t_1 then checks out at time t_2, then t_1 < t_2. All events happen in chronological order.Example 1:
Input
["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]
Output
[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]
Explanation
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(45, "Leyton", 3);
undergroundSystem.checkIn(32, "Paradise", 8);
undergroundSystem.checkIn(27, "Leyton", 10);
undergroundSystem.checkOut(45, "Waterloo", 15); // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12
undergroundSystem.checkOut(27, "Waterloo", 20); // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10
undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14
undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11
undergroundSystem.checkIn(10, "Leyton", 24);
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000
undergroundSystem.checkOut(10, "Waterloo", 38); // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12
Constraints:
•
1 <= id, t <= 10^6•
1 <= stationName.length, startStation.length, endStation.length <= 10• All strings consist of uppercase and lowercase English letters and digits.
• There will be at most
2 * 10^4 calls in total to checkIn, checkOut, and getAverageTime.• Answers within
10^-5 of the actual value will be accepted.2022-04-25
284. Peeking Iterator
Topic: Array, Design, Iterator
Difficulty: Medium
Problem:
Design an iterator that supports the
Implement the
•
•
•
•
Note: Each language may have a different implementation of the constructor and
Example 1:
Constraints:
•
•
• All the calls to
• At most
Follow up: How would you extend your design to be generic and work with all types, not just integer?
284. Peeking Iterator
Topic: Array, Design, Iterator
Difficulty: Medium
Problem:
Design an iterator that supports the
peek operation on an existing iterator in addition to the hasNext and the next operations.Implement the
PeekingIterator class:•
PeekingIterator(Iterator<int> nums) Initializes the object with the given integer iterator iterator.•
int next() Returns the next element in the array and moves the pointer to the next element.•
boolean hasNext() Returns true if there are still elements in the array.•
int peek() Returns the next element in the array without moving the pointer.Note: Each language may have a different implementation of the constructor and
Iterator, but they all support the int next() and boolean hasNext() functions.Example 1:
Input
["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 2, 2, 3, false]
Explanation
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].
peekingIterator.peek(); // return 2, the pointer does not move [1,2,3].
peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]
peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]
peekingIterator.hasNext(); // return False
Constraints:
•
1 <= nums.length <= 1000•
1 <= nums[i] <= 1000• All the calls to
next and peek are valid.• At most
1000 calls will be made to next, hasNext, and peek.Follow up: How would you extend your design to be generic and work with all types, not just integer?
2022-04-26
1584. Min Cost to Connect All Points
Topic: Array, Union Find, Minimum Spanning Tree
Difficulty: Medium
Problem:
You are given an array
The cost of connecting two points
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/08/26/d.png
Example 2:
Constraints:
•
•
• All pairs
1584. Min Cost to Connect All Points
Topic: Array, Union Find, Minimum Spanning Tree
Difficulty: Medium
Problem:
You are given an array
points representing integer coordinates of some points on a 2D-plane, where points[i] = [x_i, y_i].The cost of connecting two points
[x_i, y_i] and [x_j, y_j] is the manhattan distance between them: |x_i - x_j| + |y_i - y_j|, where |val| denotes the absolute value of val.Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/08/26/d.png
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:
Image: [https://assets.leetcode.com/uploads/2020/08/26/c.png](https://assets.leetcode.com/uploads/2020/08/26/c.png)
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
Example 2:
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
Constraints:
•
1 <= points.length <= 1000•
-10^6 <= x_i, y_i <= 10^6• All pairs
(x_i, y_i) are distinct.2022-04-27
1202. Smallest String With Swaps
Topic: Hash Table, String, Depth-First Search, Breadth-First Search, Union Find
Difficulty: Medium
Problem:
You are given a string
You can swap the characters at any pair of indices in the given
Return the lexicographically smallest string that
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
•
1202. Smallest String With Swaps
Topic: Hash Table, String, Depth-First Search, Breadth-First Search, Union Find
Difficulty: Medium
Problem:
You are given a string
s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.You can swap the characters at any pair of indices in the given
pairs any number of times.Return the lexicographically smallest string that
s can be changed to after using the swaps.Example 1:
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
Constraints:
•
1 <= s.length <= 10^5•
0 <= pairs.length <= 10^5•
0 <= pairs[i][0], pairs[i][1] < s.length•
s only contains lower case English letters.2022-04-28
1631. Path With Minimum Effort
Topic: Array, Binary Search, Depth-First Search, Breadth-First Search, Union Find, Heap (Priority Queue), Matrix
Difficulty: Medium
Problem:
You are a hiker preparing for an upcoming hike. You are given
A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/10/04/ex1.png
Example 2:
Image: https://assets.leetcode.com/uploads/2020/10/04/ex2.png
Example 3:
Image: https://assets.leetcode.com/uploads/2020/10/04/ex3.png
Constraints:
•
•
•
•
1631. Path With Minimum Effort
Topic: Array, Binary Search, Depth-First Search, Breadth-First Search, Union Find, Heap (Priority Queue), Matrix
Difficulty: Medium
Problem:
You are a hiker preparing for an upcoming hike. You are given
heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/10/04/ex1.png
Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
Example 2:
Image: https://assets.leetcode.com/uploads/2020/10/04/ex2.png
Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
Example 3:
Image: https://assets.leetcode.com/uploads/2020/10/04/ex3.png
Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.
Constraints:
•
rows == heights.length•
columns == heights[i].length•
1 <= rows, columns <= 100•
1 <= heights[i][j] <= 10^6