319 challenges in the catalogue. Browse freely; sign in to open the editor and submit.
Implement a minimal Observable class (inspired by RxJS) and a fromPromise factory function. The Observable should support subscribing with next/error/complete callbacks, and basic operators like map and filter.
interface Observer<T> {
next: (value: T) => void;
error?: (err: any) => void;
complete?: () => void;
}
interface Subscription {
unsubscribe: () => void;
}
class Observable<T> {
constructor(subscribeFn: (observer: Observer<T>) => void | (() => void));
subscribe(observer: Observer<T>): Subscription;
map<U>(transform: (value: T) => U): Observable<U>;
filter(predicate: (value: T) => boolean): Observable<T>;
}
function fromPromise<T>(promise: Promise<T>): Observable<T>
constructor(subscribeFn) — Takes a function that receives an observer and can return a cleanup function.subscribe(observer) — Starts the observable, returns a Subscription with unsubscribe.map(transform) — Returns a new Observable that transforms each emitted value.filter(predicate) — Returns a new Observable that only emits values passing the predicate.fromPromise(promise) — Creates an Observable that emits the promise result, then completes. On rejection, calls error.const obs = new Observable<number>(observer => {
observer.next(1);
observer.next(2);
observer.next(3);
observer.complete();
});
obs.subscribe({
next: v => console.log(v), // 1, 2, 3
complete: () => console.log('done')
});
const obs = fromPromise(Promise.resolve(42));
obs.subscribe({
next: v => console.log(v), // 42
complete: () => console.log('done')
});
const obs = new Observable<number>(observer => {
[1, 2, 3, 4, 5].forEach(n => observer.next(n));
observer.complete();
});
obs.filter(n => n % 2 === 0).map(n => n * 10).subscribe({
next: v => console.log(v) // 20, 40
});
complete() or error(), no more values should be emittedunsubscribe() should prevent further callbacksfromPromise must handle both resolved and rejected promisesFive philosophers sit at a round table with a fork between each pair. To eat, a philosopher needs both the left and right fork. Design a solution that prevents deadlock and allows all philosophers to eat.
Implement a deadlock-free solution using resource ordering: each philosopher always picks up the lower-numbered fork first.
function diningPhilosophers(
n: number,
rounds: number
): { actions: string[][]; deadlockFree: boolean }
n: Number of philosophers (seated in a circle)rounds: Number of eating rounds per philosopherInput: n = 5, rounds = 1
Output:
actions = [
["P0: pick fork 0", "P0: pick fork 1", "P0: eat", "P0: put fork 1", "P0: put fork 0"],
...
]
deadlockFree = true
A system logs failed and succeeded tasks in two separate tables. Write a solution to report the period of time in 2019 where tasks had the same status ('failed' or 'succeeded') continuously.
The result table should contain period_state, start_date, and end_date.
period_state is the status of the tasks during that period.start_date is the first date of that period.end_date is the last date of that period.Return the result table ordered by start_date.
| Column Name | Type | | :--- | :--- | | fail_date | date |
fail_date is the primary key for this table.
This table contains the days of failed tasks.
| Column Name | Type | | :--- | :--- | | success_date | date |
success_date is the primary key for this table.
This table contains the days of succeeded tasks.
Input: Failed table: | fail_date | | :--- | | 2018-12-28 | | 2018-12-29 | | 2019-01-04 | | 2019-01-05 |
Succeeded table: | success_date | | :--- | | 2018-12-30 | | 2018-12-31 | | 2019-01-01 | | 2019-01-02 | | 2019-01-03 | | 2019-01-06 |
Output: | period_state | start_date | end_date | | :--- | :--- | :--- | | succeeded | 2019-01-01 | 2019-01-03 | | failed | 2019-01-04 | 2019-01-05 | | succeeded | 2019-01-06 | 2019-01-06 |
Explanation:
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Implement the MyStack class:
void push(int x) Pushes element x to the top of the stack.int pop() Removes the element on the top of the stack and returns it.int top() Returns the element on the top of the stack.boolean empty() Returns true if the stack is empty, false otherwise.Notes:
push to back, peek/pop from front, size, and is empty operations are valid.Input:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
Output:
[null, null, null, 2, 2, false]
Explanation:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return false
1 <= x <= 9100 calls will be made to push, pop, top, and empty.pop and top are valid.Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j] is '0' or '1'.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]
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4k is in the range [1, the number of unique elements in the array].Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1
Output: []
1 <= candidates.length <= 302 <= candidates[i] <= 40candidates are distinct.1 <= target <= 40Implement a transaction manager that supports ACID properties with optimistic concurrency control. The system should handle concurrent transactions, detect conflicts using version numbers, support automatic retries, and ensure data consistency.
interface Record {
id: string;
data: any;
version: number;
updatedAt: string;
}
interface Transaction {
id: string;
status: 'active' | 'committed' | 'rolled_back' | 'conflict';
readSet: Map<string, number>; // key -> version read
writeSet: Map<string, any>; // key -> new value
startTimestamp: number;
}
const result = await txManager.withTransaction(async (tx) => {
const account = await tx.read('account:1');
await tx.write('account:1', { ...account.data, balance: account.data.balance - 100 });
return { transferred: 100 };
});
// result: { transferred: 100 }
// account:1 balance decreased by 100, version incremented
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4.
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1.
Example 3:
Input: nums = [5], target = 5
Output: 0
Explanation: Single element equals target.
1 <= nums.length <= 10^4-10^4 < nums[i], target < 10^4nums are unique.nums is sorted in ascending order.Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
1 <= nums.length <= 10-10 <= nums[i] <= 10nums are unique.Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
n == nums.length1 <= n <= 300nums[i] is either 0, 1, or 2.Could you come up with a one-pass algorithm using only constant extra space?
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
[0, 10^4].-10^5 <= Node.val <= 10^5pos is -1 or a valid index in the linked-list.Can you solve it using O(1) (i.e. constant) memory?
// T1 and T2 both read account:1 (version 1)
// T1 writes and commits -> version becomes 2
// T2 tries to commit -> CONFLICT (read version 1, current version 2)
// T2 is automatically retried with fresh data
await txManager.withTransaction(async (tx) => {
const from = await tx.read('account:A');
const to = await tx.read('account:B');
if (from.data.balance < 100) throw new Error('Insufficient funds');
await tx.write('account:A', { ...from.data, balance: from.data.balance - 100 });
await tx.write('account:B', { ...to.data, balance: to.data.balance + 100 });
});
// Both accounts updated atomically, or neither is updated