319 challenges in the catalogue. Browse freely; sign in to open the editor and submit.
You are given the root node of a binary search tree (BST) and a val to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
There may exist multiple valid ways to do the insertion. As long as the tree remains a valid BST after insertion, any is accepted.
Example 1:
Input: root = [4,2,7,1,3], val = 5
Output: [4,2,7,1,3,5]
Explanation: Another accepted tree is [5,2,7,1,3,null,null,null,null,null,4].
Example 2:
Input: root = [40,20,60,10,30,50,70], val = 25
Output: [40,20,60,10,30,50,70,null,null,25]
Example 3:
Input: root = [], val = 5
Output: [5]
[0, 10^4].-10^8 <= Node.val <= 10^8val is guaranteed not to exist in the original BST.Given a string s, find the length of the longest substring without repeating characters.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
0 <= s.length <= 5 * 10^4s consists of English letters, digits, symbols and spaces.Simulate water molecule formation. There are two kinds of threads: hydrogen and oxygen. Your goal is to group these threads to form water molecules (H2O). Each molecule needs exactly 2 hydrogen atoms and 1 oxygen atom.
A barrier mechanism must ensure that all three atoms of a molecule are released together before any atom from the next molecule proceeds.
class H2O {
hydrogen(releaseHydrogen: () => void): Promise<void>;
oxygen(releaseOxygen: () => void): Promise<void>;
}
Input: atoms = "OOHHHH"
Output: molecules = ["HHO", "HHO"]
Explanation: 4 H atoms and 2 O atoms form 2 water molecules.
Each molecule has exactly 2 H and 1 O.
Design and implement a fully RESTful API for a blog platform. The API should support creating, reading, updating, and deleting blog posts and comments, following REST best practices including proper HTTP methods, status codes, and resource naming conventions.
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | /api/posts | Create a new post |
| GET | /api/posts | List all posts (with pagination) |
| GET | /api/posts/:id | Get a single post |
| PUT | /api/posts/:id | Update a post |
| DELETE | /api/posts/:id | Delete a post |
| POST | /api/posts/:id/comments | Add a comment to a post |
| GET | /api/posts/:id/comments | List comments for a post |
Post:
interface Post {
id: number;
title: string; // Required, 1-200 chars
content: string; // Required, 1-10000 chars
author: string; // Required
tags: string[]; // Optional
createdAt: string; // ISO 8601
updatedAt: string; // ISO 8601
}
Comment:
interface Comment {
id: number;
postId: number;
author: string; // Required
content: string; // Required, 1-2000 chars
createdAt: string; // ISO 8601
}
Input:
POST /api/posts
Content-Type: application/json
{
"title": "Getting Started with REST",
"content": "REST is an architectural style...",
"author": "jane",
"tags": ["rest", "api", "tutorial"]
}
Implement a Disjoint Set Union (DSU) data structure, also known as Union-Find.
The DSU should support the following operations efficiently:
find(i): Determine which set an element i belongs to. Return the "representative" or "root" of that set. Implement path compression to optimize future queries.union(i, j): Join two subsets into a single subset. Implement union by rank (or height/size) to keep the tree flat.Implement a class DSU that initializes with n elements (from 0 to n-1) and has the methods find(i) and union(i, j).
const dsu = new DSU(5);
dsu.union(0, 1);
dsu.union(1, 2);
console.log(dsu.find(0) === dsu.find(2)); // true
console.log(dsu.find(0) === dsu.find(3)); // false
dsu.union(2, 4);
console.log(dsu.find(4) === dsu.find(0)); // true
1 <= n <= 10^50 <= i, j < n10^5 operations.The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.
Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
Input: nums1 = [2,4], nums2 = [1,2,3,4]
Output: [3,-1]
1 <= nums1.length <= nums2.length <= 10000 <= nums1[i], nums2[i] <= 10^4nums1 and nums2 are unique.nums1 also appear in nums2.Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
Example 1:
Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]
Example 2:
Input: root = []
Output: []
[0, 10^4].-1000 <= Node.val <= 1000You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
Example 1:
Input: coins = [1,5,11], amount = 11
Output: 1
Explanation: 11 = 11
Example 2:
Input: coins = [2], amount = 3
Output: -1
Explanation: Cannot make 3 with only coins of value 2.
Example 3:
Input: coins = [1], amount = 0
Output: 0
Explanation: No coins needed for amount 0.
1 <= coins.length <= 121 <= coins[i] <= 2^31 - 10 <= amount <= 10^4Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity) Initialize the LRU cache with positive size capacity.int get(int key) Return the value of the key if the key exists, otherwise return -1.void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.The functions get and put must each run in O(1) average time complexity.
Example 1:
Input:
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output:
[null, null, null, 1, null, -1, null, -1, 3, 4]
Explanation:
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
1 <= capacity <= 30000 <= key <= 10^40 <= value <= 10^52 * 10^5 calls will be made to get and put.Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1]
Output: [[1]]
1 <= nums.length <= 6-10 <= nums[i] <= 10nums are unique.A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.
Given a tree of n nodes labeled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).
Return a list of all MHTs' root labels. You can return the answer in any order.
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
Example 1:
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
Example 2:
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
Output: [3,4]
1 <= n <= 2 * 10^4edges.length == n - 10 <= ai, bi < nai != bi(ai, bi) are distinct.Implement a drag-and-drop list reordering system. Build a DragDropList class that manages list items and supports reordering through drag-and-drop operations.
Your implementation should handle:
interface DragDropList<T> {
getItems(): T[];
moveItem(fromIndex: number, toIndex: number): void;
swap(indexA: number, indexB: number): void;
undo(): void;
reset(): void;
}
function createDragDropList<T>(items: T[]): DragDropList<T>
getItems() — Returns the current ordered list.moveItem(from, to) — Removes item at from and inserts it at to.swap(a, b) — Swaps items at indices a and b.undo() — Reverts the last operation.reset() — Restores the original order.const list = createDragDropList(['A', 'B', 'C', 'D']);
list.moveItem(0, 2);
list.getItems(); // ['B', 'C', 'A', 'D']
const list = createDragDropList([1, 2, 3]);
list.swap(0, 2);
list.getItems(); // [3, 2, 1]
const list = createDragDropList(['X', 'Y', 'Z']);
list.moveItem(0, 2);
list.getItems(); // ['Y', 'Z', 'X']
list.undo();
list.getItems(); // ['X', 'Y', 'Z']
1 <= items.length <= 10000Output:
{
"id": 1,
"title": "Getting Started with REST",
"content": "REST is an architectural style...",
"author": "jane",
"tags": ["rest", "api", "tutorial"],
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:30:00Z"
}
Status: 201 Created
Input:
GET /api/posts?page=1&limit=10&author=jane
Output:
{
"data": [...],
"pagination": {
"page": 1,
"limit": 10,
"total": 25,
"totalPages": 3
}
}
Status: 200 OK
Input:
GET /api/posts/999
Output:
{
"error": "Post not found",
"statusCode": 404
}
Status: 404 Not Found